2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
26 package org.forester.archaeopteryx;
28 import java.awt.Color;
29 import java.awt.Component;
30 import java.awt.Graphics2D;
31 import java.awt.GraphicsEnvironment;
32 import java.awt.Rectangle;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.io.ByteArrayOutputStream;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.lang.reflect.InvocationTargetException;
40 import java.lang.reflect.Method;
43 import java.security.KeyManagementException;
44 import java.security.NoSuchAlgorithmException;
45 import java.text.ParseException;
46 import java.util.Arrays;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Locale;
54 import java.util.SortedSet;
55 import java.util.TreeSet;
57 import javax.imageio.IIOImage;
58 import javax.imageio.ImageIO;
59 import javax.imageio.ImageWriteParam;
60 import javax.imageio.ImageWriter;
61 import javax.imageio.stream.ImageOutputStream;
62 import javax.swing.JApplet;
63 import javax.swing.JOptionPane;
64 import javax.swing.text.MaskFormatter;
66 import org.forester.archaeopteryx.ControlPanel.TreeDisplayType;
67 import org.forester.io.parsers.PhylogenyParser;
68 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
69 import org.forester.io.parsers.nhx.NHXParser;
70 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
71 import org.forester.io.parsers.tol.TolParser;
72 import org.forester.io.parsers.util.ParserUtils;
73 import org.forester.phylogeny.Phylogeny;
74 import org.forester.phylogeny.PhylogenyMethods;
75 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
76 import org.forester.phylogeny.PhylogenyNode;
77 import org.forester.phylogeny.data.BranchWidth;
78 import org.forester.phylogeny.data.Confidence;
79 import org.forester.phylogeny.data.Taxonomy;
80 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
81 import org.forester.util.AsciiHistogram;
82 import org.forester.util.DescriptiveStatistics;
83 import org.forester.util.ForesterUtil;
84 import org.forester.util.TaxonomyUtil;
86 public final class AptxUtil {
88 public static enum GraphicsExportType {
89 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
91 private final String _suffix;
93 private GraphicsExportType( final String suffix ) {
98 public String toString() {
102 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
103 .getAvailableFontFamilyNames();
105 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
108 final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
109 final String my_str = str.toUpperCase();
110 char first = my_str.charAt( 0 );
113 if ( my_str.length() > 1 ) {
115 second = my_str.charAt( 1 );
118 second = my_str.charAt( my_str.length() - 1 );
121 if ( my_str.length() > 2 ) {
122 if ( my_str.indexOf( " " ) > 0 ) {
123 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
126 third = my_str.charAt( 2 );
130 else if ( my_str.length() > 2 ) {
131 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
134 first = normalizeCharForRGB( first );
135 second = normalizeCharForRGB( second );
136 third = normalizeCharForRGB( third );
137 if ( ( first > 200 ) && ( second > 200 ) && ( third > 200 ) ) {
140 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
143 else if ( Math.abs( first - second ) < 40 && Math.abs( second - third ) < 40 ) {
146 return new Color( first, second, third );
149 public static MaskFormatter createMaskFormatter( final String s ) {
150 MaskFormatter formatter = null;
152 formatter = new MaskFormatter( s );
154 catch ( final ParseException e ) {
155 throw new IllegalArgumentException( e );
160 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
161 final PhylogenyNodeIterator it = phy.iteratorPostorder();
162 while ( it.hasNext() ) {
163 if ( it.next().getNodeData().isHasEvent() ) {
171 * Returns true if at least one branch has a length larger than zero.
176 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
177 final PhylogenyNodeIterator it = phy.iteratorPostorder();
178 while ( it.hasNext() ) {
179 if ( it.next().getDistanceToParent() > 0.0 ) {
186 final static public boolean isHasNoBranchLengthSmallerThanZero( final Phylogeny phy ) {
187 final PhylogenyNodeIterator it = phy.iteratorPostorder();
188 while ( it.hasNext() ) {
189 final PhylogenyNode n = it.next();
190 if ( n.getDistanceToParent() < 0.0 && !n.isRoot() ) {
197 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
198 final PhylogenyNodeIterator it = phy.iteratorPostorder();
199 while ( it.hasNext() ) {
200 final PhylogenyNode n = it.next();
201 if ( n.getBranchData().isHasConfidences() ) {
202 final List<Confidence> c = n.getBranchData().getConfidences();
203 for( final Confidence confidence : c ) {
204 if ( confidence.getStandardDeviation() > 0 ) {
213 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
214 final PhylogenyNodeIterator it = phy.iteratorPostorder();
215 while ( it.hasNext() ) {
216 if ( it.next().getBranchData().isHasConfidences() ) {
223 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
224 final PhylogenyNodeIterator it = phy.iteratorPostorder();
225 while ( it.hasNext() ) {
226 final PhylogenyNode n = it.next();
227 if ( n.getNodeData().isHasTaxonomy()
228 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
235 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
236 final PhylogenyNodeIterator it = phy.iteratorPostorder();
237 while ( it.hasNext() ) {
238 final PhylogenyNode n = it.next();
239 if ( n.getNodeData().isHasSequence()
240 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
247 final public static void launchWebBrowser( final URI uri,
248 final boolean is_applet,
249 final JApplet applet,
250 final String frame_name ) throws IOException {
252 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
255 // This requires Java 1.6:
256 // =======================
257 // boolean no_desktop = false;
259 // if ( Desktop.isDesktopSupported() ) {
260 // System.out.println( "desktop supported" );
261 // final Desktop dt = Desktop.getDesktop();
265 // no_desktop = true;
268 // catch ( final Exception ex ) {
269 // ex.printStackTrace();
270 // no_desktop = true;
272 // catch ( final Error er ) {
273 // er.printStackTrace();
274 // no_desktop = true;
276 // if ( no_desktop ) {
277 // System.out.println( "desktop not supported" );
279 openUrlInWebBrowser( uri.toString() );
281 catch ( final Exception e ) {
282 throw new IOException( e );
288 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
289 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
290 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
291 for( final PhylogenyNode n : descs ) {
292 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
293 tax_set.add( n.getNodeData().getTaxonomy() );
299 public final static void printWarningMessage( final String name, final String message ) {
300 System.out.println( "[" + name + "] > " + message );
303 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
304 final boolean phyloxml_validate_against_xsd,
305 final boolean replace_underscores,
306 final boolean internal_numbers_are_confidences,
307 final TAXONOMY_EXTRACTION taxonomy_extraction,
308 final boolean midpoint_reroot )
309 throws FileNotFoundException, IOException {
310 final PhylogenyParser parser;
311 boolean nhx_or_nexus = false;
312 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
313 parser = new TolParser();
316 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
317 if ( parser instanceof NHXParser ) {
319 final NHXParser nhx = ( NHXParser ) parser;
320 nhx.setReplaceUnderscores( replace_underscores );
321 nhx.setIgnoreQuotes( false );
322 nhx.setTaxonomyExtraction( taxonomy_extraction );
324 else if ( parser instanceof NexusPhylogeniesParser ) {
326 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
327 nex.setReplaceUnderscores( replace_underscores );
328 nex.setIgnoreQuotes( false );
331 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
332 Phylogeny[] phys = null;
334 phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
336 catch ( final KeyManagementException e ) {
337 throw new IOException( e.getMessage() );
339 catch ( final NoSuchAlgorithmException e ) {
340 throw new IOException( e.getMessage() );
342 if ( phys != null ) {
343 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
344 for( final Phylogeny phy : phys ) {
345 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
348 if ( midpoint_reroot ) {
349 for( final Phylogeny phy : phys ) {
350 PhylogenyMethods.midpointRoot( phy );
351 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
358 final public static void showErrorMessage( final Component parent, final String error_msg ) {
359 printAppletMessage( AptxConstants.PRG_NAME, error_msg );
360 JOptionPane.showMessageDialog( parent, error_msg, "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
361 + "] Error", JOptionPane.ERROR_MESSAGE );
364 public static void writePhylogenyToGraphicsFile( final File intree,
368 final GraphicsExportType type,
369 final Configuration config ) throws IOException {
370 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
371 Phylogeny[] phys = null;
372 phys = PhylogenyMethods.readPhylogenies( parser, intree );
373 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
376 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
380 final GraphicsExportType type,
381 final Configuration config ) throws IOException {
382 final Phylogeny[] phys = new Phylogeny[ 1 ];
384 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
385 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
386 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
390 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
393 final TreePanel tree_panel,
394 final ControlPanel ac,
395 final GraphicsExportType type,
396 final Options options ) throws IOException {
397 tree_panel.calcParametersForPainting( width, height );
398 tree_panel.resetPreferredSize();
399 tree_panel.repaint();
400 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
401 RenderingHints.VALUE_RENDER_QUALITY );
402 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
403 if ( options.isAntialiasPrint() ) {
404 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
405 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
408 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
409 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
411 final Phylogeny phylogeny = tree_panel.getPhylogeny();
412 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
415 if ( outfile.isDirectory() ) {
416 throw new IOException( "\"" + outfile + "\" is a directory" );
418 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
419 final Graphics2D g2d = buffered_img.createGraphics();
420 g2d.setRenderingHints( rendering_hints );
421 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
422 if ( type == GraphicsExportType.TIFF ) {
423 writeToTiff( outfile, buffered_img );
426 ImageIO.write( buffered_img, type.toString(), outfile );
431 final private static char normalizeCharForRGB( char c ) {
434 c = c > 255 ? 255 : c;
439 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
440 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
441 InvocationTargetException, InterruptedException {
442 final String os = System.getProperty( "os.name" );
443 final Runtime runtime = Runtime.getRuntime();
444 if ( os.toLowerCase().startsWith( "win" ) ) {
445 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
447 else if ( ForesterUtil.isMac() ) {
448 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
449 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
450 open_url.invoke( null, new Object[] { url } );
453 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
454 String browser = null;
455 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
456 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
457 browser = browsers[ i ];
460 if ( browser == null ) {
461 throw new IOException( "could not find a web browser to open [" + url + "] in" );
464 runtime.exec( new String[] { browser, url } );
469 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
470 final String default_name,
471 final String full_path,
472 final Configuration configuration,
473 final MainPanel main_panel ) {
474 if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
475 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
476 + " phylogenies,\ngoing to load only the first " + AptxConstants.MAX_TREES_TO_LOAD, AptxConstants.PRG_NAME
477 + " more than " + AptxConstants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
480 for( final Phylogeny phy : phys ) {
481 if ( !phy.isEmpty() ) {
482 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
484 String my_name_for_file = "";
485 if ( phys.length > 1 ) {
486 if ( !ForesterUtil.isEmpty( default_name ) ) {
487 my_name = new String( default_name );
489 if ( !ForesterUtil.isEmpty( full_path ) ) {
490 my_name_for_file = new String( full_path );
492 else if ( !ForesterUtil.isEmpty( default_name ) ) {
493 my_name_for_file = new String( default_name );
496 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
497 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
498 my_name_for_file.length() );
499 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
501 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
502 my_name_for_file += "_";
504 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
505 my_name_for_file += phy.getName().replaceAll( " ", "_" );
507 else if ( phy.getIdentifier() != null ) {
508 final StringBuffer sb = new StringBuffer();
509 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
510 sb.append( phy.getIdentifier().getProvider() );
513 sb.append( phy.getIdentifier().getValue() );
514 my_name_for_file += sb;
517 my_name_for_file += i;
519 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
520 && ( phy.getIdentifier() == null ) ) {
521 my_name = my_name + " [" + i + "]";
523 if ( !ForesterUtil.isEmpty( suffix ) ) {
524 my_name_for_file += suffix;
528 if ( !ForesterUtil.isEmpty( default_name ) ) {
529 my_name = new String( default_name );
531 my_name_for_file = "";
532 if ( !ForesterUtil.isEmpty( full_path ) ) {
533 my_name_for_file = new String( full_path );
535 else if ( !ForesterUtil.isEmpty( default_name ) ) {
536 my_name_for_file = new String( default_name );
538 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
539 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
540 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
542 else if ( phy.getIdentifier() != null ) {
543 final StringBuffer sb = new StringBuffer();
544 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
545 sb.append( phy.getIdentifier().getProvider() );
548 sb.append( phy.getIdentifier().getValue() );
549 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
553 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
554 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
555 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
562 final static void addPhylogenyToPanel( final Phylogeny[] phys,
563 final Configuration configuration,
564 final MainPanel main_panel ) {
565 final Phylogeny phy = phys[ 0 ];
566 main_panel.addPhylogenyInPanel( phy, configuration );
567 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
570 // Returns true if the specified format name can be written
571 final static boolean canWriteFormat( final String format_name ) {
572 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
573 return iter.hasNext();
576 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
577 final StringBuilder desc = new StringBuilder();
578 if ( ( phy != null ) && !phy.isEmpty() ) {
580 if ( treefile != null ) {
582 f = treefile.getCanonicalPath();
584 catch ( final IOException e ) {
585 //Not important, ignore.
587 if ( !ForesterUtil.isEmpty( f ) ) {
588 desc.append( "Path: " );
593 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
594 desc.append( "Name: " );
595 desc.append( phy.getName() );
598 if ( phy.getIdentifier() != null ) {
599 desc.append( "Id: " );
600 desc.append( phy.getIdentifier().toString() );
603 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
604 desc.append( "Description: " );
605 desc.append( phy.getDescription() );
608 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
609 desc.append( "Distance Unit: " );
610 desc.append( phy.getDistanceUnit() );
613 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
614 desc.append( "Type: " );
615 desc.append( phy.getType() );
618 desc.append( "Rooted: " );
619 desc.append( phy.isRooted() );
621 desc.append( "Rerootable: " );
622 desc.append( phy.isRerootable() );
624 desc.append( "Nodes: " );
625 desc.append( phy.getNodeCount() );
627 desc.append( "External nodes: " );
628 desc.append( phy.getNumberOfExternalNodes() );
630 desc.append( "Internal nodes: " );
631 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
633 desc.append( "Internal nodes with polytomies: " );
634 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
636 desc.append( "Branches: " );
637 desc.append( phy.getNumberOfBranches() );
639 desc.append( "Depth: " );
640 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
642 desc.append( "Maximum distance to root: " );
643 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
645 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
646 if ( taxs != null ) {
647 desc.append( "Distinct external taxonomies: " );
648 desc.append( taxs.size() );
650 for( final Taxonomy t : taxs ) {
651 System.out.println( t.toString() );
654 final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
655 if ( bs.getN() > 3 ) {
657 desc.append( "Branch-length statistics: " );
659 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
661 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
663 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
664 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
666 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
668 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
670 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
672 final AsciiHistogram histo = new AsciiHistogram( bs );
673 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
676 final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
677 if ( ds.getN() > 2 ) {
679 desc.append( "Descendants per node statistics: " );
681 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
683 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
684 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
686 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
688 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
691 List<DescriptiveStatistics> css = null;
693 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
695 catch ( final IllegalArgumentException e ) {
696 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
698 if ( ( css != null ) && ( css.size() > 0 ) ) {
700 for( int i = 0; i < css.size(); ++i ) {
701 final DescriptiveStatistics cs = css.get( i );
702 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
703 if ( css.size() > 1 ) {
704 desc.append( "Support statistics " + ( i + 1 ) + ": " );
707 desc.append( "Support statistics: " );
709 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
711 desc.append( " Type: " + cs.getDescription() );
714 desc.append( " Branches with support: " + cs.getN() );
716 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
718 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
719 if ( cs.getN() > 2 ) {
720 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
723 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
725 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
731 return desc.toString();
739 * to message to be printed
741 final static void dieWithSystemError( final String message ) {
742 System.out.println();
743 System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
744 System.out.println( "Please contact the authors." );
745 System.out.println( AptxConstants.PRG_NAME + " needs to close." );
746 System.out.println();
750 final static String[] getAllPossibleRanks() {
751 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
753 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
754 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
755 str_array[ i++ ] = e;
761 final static String[] getAllPossibleRanks(final Map<String, Integer> present_ranks) {
762 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
764 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
765 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
766 if ( present_ranks != null && present_ranks.containsKey( e ) ) {
767 str_array[ i++ ] = e + " (" + present_ranks.get(e) + ")";
770 str_array[ i++ ] = e;
777 final static String[] getAllRanks( final Phylogeny tree ) {
778 final SortedSet<String> ranks = new TreeSet<String>();
779 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
780 final PhylogenyNode n = it.next();
781 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
782 ranks.add( n.getNodeData().getTaxonomy().getRank() );
785 return ForesterUtil.stringSetToArray( ranks );
788 final static String[] getAvailableFontFamiliesSorted() {
789 return AVAILABLE_FONT_FAMILIES_SORTED;
792 final static boolean isUsOrCanada() {
794 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
798 catch ( final Exception e ) {
803 final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t,
804 final ControlPanel cp ) {
805 if ( ( t != null ) && !t.isEmpty() ) {
806 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
809 cp.setTreeDisplayType( TreeDisplayType.CLADOGRAM );
810 cp.setDrawPhylogramEnabled( false );
813 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
815 cp.setTreeDisplayType( TreeDisplayType.UNALIGNED_PHYLOGRAM );
818 if ( cp.getDisplayAsUnalignedPhylogramRb() != null ) {
819 cp.setDrawPhylogramEnabled( true );
824 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
825 final ControlPanel atv_control,
826 final Configuration configuration ) {
827 if ( ( t != null ) && !t.isEmpty() ) {
828 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
830 atv_control.setTreeDisplayType( TreeDisplayType.CLADOGRAM );
831 atv_control.setDrawPhylogramEnabled( false );
833 if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
834 && atv_control.getUseVisualStylesCb() != null ) {
835 atv_control.getUseVisualStylesCb().setSelected( true );
837 if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
838 && t.getFirstExternalNode().getBranchData().getBranchWidth().getValue()
839 != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
840 && atv_control.getUseBranchWidthsCb() != null ) {
841 atv_control.getUseBranchWidthsCb().setSelected( true );
845 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
846 if ( atv_control.getDisplayAsAlignedPhylogramRb() != null ) {
848 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
850 atv_control.setTreeDisplayType( TreeDisplayType.UNALIGNED_PHYLOGRAM );
853 atv_control.setDrawPhylogramEnabled( true );
856 atv_control.setTreeDisplayType( TreeDisplayType.CLADOGRAM );
860 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
861 if ( atv_control.getWriteConfidenceCb() != null ) {
862 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
863 atv_control.setCheckbox( Configuration.write_confidence_values, true );
866 atv_control.setCheckbox( Configuration.write_confidence_values, false );
870 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
871 if ( atv_control.getShowEventsCb() != null ) {
872 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
873 atv_control.setCheckbox( Configuration.write_events, true );
876 atv_control.setCheckbox( Configuration.write_events, false );
883 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
885 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, AptxConstants.PRG_NAME );
887 catch ( final Exception e ) {
888 throw new IOException( e );
892 final static void outOfMemoryError( final OutOfMemoryError e ) {
893 System.err.println();
894 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
895 System.err.println();
897 System.err.println();
898 JOptionPane.showMessageDialog( null,
899 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
900 + "\n\nError: " + e.getLocalizedMessage(),
901 "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
902 JOptionPane.ERROR_MESSAGE );
906 final static void printAppletMessage( final String applet_name, final String message ) {
907 System.out.println( "[" + applet_name + "] > " + message );
910 final static void removeBranchColors( final Phylogeny phy ) {
911 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
912 it.next().getBranchData().setBranchColor( null );
916 final static void removeVisualStyles( final Phylogeny phy ) {
917 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
918 it.next().getNodeData().setNodeVisualData( null );
922 final static void unexpectedError( final Error e ) {
923 System.err.println();
924 e.printStackTrace( System.err );
925 System.err.println();
926 final StringBuffer sb = new StringBuffer();
927 for( final StackTraceElement s : e.getStackTrace() ) {
928 sb.append( s + "\n" );
931 .showMessageDialog( null,
932 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
933 + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
935 "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
936 JOptionPane.ERROR_MESSAGE );
940 final static void unexpectedException( final Exception e ) {
941 System.err.println();
942 e.printStackTrace( System.err );
943 System.err.println();
944 final StringBuffer sb = new StringBuffer();
945 for( final StackTraceElement s : e.getStackTrace() ) {
946 sb.append( s + "\n" );
948 JOptionPane.showMessageDialog( null,
949 "An unexpected exception has occured. \nPlease contact: "
950 + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
952 "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
953 JOptionPane.ERROR_MESSAGE );
956 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
959 final TreePanel tree_panel,
960 final ControlPanel ac,
961 final GraphicsExportType type,
962 final Options options ) throws IOException {
964 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
965 RenderingHints.VALUE_RENDER_QUALITY );
966 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
967 if ( options.isAntialiasPrint() ) {
968 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
969 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
972 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
973 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
975 final Phylogeny phylogeny = tree_panel.getPhylogeny();
976 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
979 Rectangle visible = null;
980 // if ( !options.isGraphicsExportUsingActualSize() ) {
981 // width = options.getPrintSizeX();
982 // height = options.getPrintSizeY();
984 /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
985 visible = tree_panel.getVisibleRect();
986 width = visible.width;
987 height = visible.height;
989 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
990 Graphics2D g2d = buffered_img.createGraphics();
991 g2d.setRenderingHints( rendering_hints );
994 if ( options.isGraphicsExportVisibleOnly() ) {
995 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1000 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1001 ImageIO.write( buffered_img, type.toString(), baos );
1004 if ( !options.isGraphicsExportUsingActualSize() ) {
1005 tree_panel.getMainPanel().getControlPanel().showWhole();
1007 String msg = baos.toString();
1008 if ( ( width > 0 ) && ( height > 0 ) ) {
1009 msg += " [size: " + width + ", " + height + "]";
1014 final static String writePhylogenyToGraphicsFile( final String file_name,
1017 final TreePanel tree_panel,
1018 final ControlPanel ac,
1019 final GraphicsExportType type,
1020 final Options options ) throws IOException {
1022 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1023 RenderingHints.VALUE_RENDER_QUALITY );
1024 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1025 if ( options.isAntialiasPrint() ) {
1026 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1027 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1030 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1031 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1033 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1034 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1037 final File file = new File( file_name );
1038 if ( file.isDirectory() ) {
1039 throw new IOException( "\"" + file_name + "\" is a directory" );
1041 Rectangle visible = null;
1042 // if ( !options.isGraphicsExportUsingActualSize() ) {
1043 // width = options.getPrintSizeX();
1044 // height = options.getPrintSizeY();
1046 /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1047 visible = tree_panel.getVisibleRect();
1048 width = visible.width;
1049 height = visible.height;
1051 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1052 Graphics2D g2d = buffered_img.createGraphics();
1053 g2d.setRenderingHints( rendering_hints );
1056 if ( options.isGraphicsExportVisibleOnly() ) {
1057 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1058 g2d.setClip( null );
1062 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1063 if ( type == GraphicsExportType.TIFF ) {
1064 writeToTiff( file, buffered_img );
1067 ImageIO.write( buffered_img, type.toString(), file );
1071 if ( !options.isGraphicsExportUsingActualSize() ) {
1072 tree_panel.getMainPanel().getControlPanel().showWhole();
1074 String msg = file.toString();
1075 if ( ( width > 0 ) && ( height > 0 ) ) {
1076 msg += " [size: " + width + ", " + height + "]";
1081 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1082 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1083 ImageWriter writer = null;
1084 ImageOutputStream ios = null;
1085 // Find an appropriate writer:
1086 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1087 if ( it.hasNext() ) {
1091 throw new IOException( "failed to get TIFF image writer" );
1094 ios = ImageIO.createImageOutputStream( file );
1095 writer.setOutput( ios );
1096 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1097 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1098 // see writeParam.getCompressionTypes() for available compression type
1100 image_write_param.setCompressionType( "PackBits" );
1101 final String t[] = image_write_param.getCompressionTypes();
1102 for( final String string : t ) {
1103 System.out.println( string );
1105 // Convert to an IIOImage:
1106 final IIOImage iio_image = new IIOImage( image, null, null );
1107 writer.write( null, iio_image, image_write_param );
1110 final static Map<String, Integer> getRankCounts(final Phylogeny tree) {
1111 final Map<String, Integer> present_ranks = new HashMap<String, Integer>();
1113 if ( ( tree != null ) && !tree.isEmpty() ) {
1114 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
1115 final PhylogenyNode n = it.next();
1116 if ( !n.isExternal() && n.getNodeData().isHasTaxonomy()
1117 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) && !n.isRoot() ) {
1118 final String rank = n.getNodeData().getTaxonomy().getRank().toLowerCase();
1119 if (present_ranks.containsKey( rank ) ) {
1120 present_ranks.put( rank, present_ranks.get( rank ) + 1 );
1123 present_ranks.put( rank, 1 );
1128 return present_ranks;