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.JOptionPane;
63 import javax.swing.text.MaskFormatter;
65 import org.forester.io.parsers.PhylogenyParser;
66 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
67 import org.forester.io.parsers.nhx.NHXParser;
68 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
69 import org.forester.io.parsers.tol.TolParser;
70 import org.forester.io.parsers.util.ParserUtils;
71 import org.forester.phylogeny.Phylogeny;
72 import org.forester.phylogeny.PhylogenyMethods;
73 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
74 import org.forester.phylogeny.PhylogenyNode;
75 import org.forester.phylogeny.data.BranchWidth;
76 import org.forester.phylogeny.data.Confidence;
77 import org.forester.phylogeny.data.Taxonomy;
78 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
79 import org.forester.util.AsciiHistogram;
80 import org.forester.util.DescriptiveStatistics;
81 import org.forester.util.ForesterUtil;
82 import org.forester.util.TaxonomyUtil;
84 public final class AptxUtil {
86 public static enum GraphicsExportType {
94 private final String _suffix;
96 private GraphicsExportType( final String suffix ) {
101 public String toString() {
105 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
106 .getAvailableFontFamilyNames();
108 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
111 final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
112 final String my_str = str.toUpperCase();
113 char first = my_str.charAt( 0 );
116 if ( my_str.length() > 1 ) {
118 second = my_str.charAt( 1 );
121 second = my_str.charAt( my_str.length() - 1 );
124 if ( my_str.length() > 2 ) {
125 if ( my_str.indexOf( " " ) > 0 ) {
126 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
129 third = my_str.charAt( 2 );
133 else if ( my_str.length() > 2 ) {
134 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
137 first = normalizeCharForRGB( first );
138 second = normalizeCharForRGB( second );
139 third = normalizeCharForRGB( third );
140 if ( ( first > 200 ) && ( second > 200 ) && ( third > 200 ) ) {
143 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
146 else if ( Math.abs( first - second ) < 40 && Math.abs( second - third ) < 40 ) {
149 return new Color( first, second, third );
152 public static MaskFormatter createMaskFormatter( final String s ) {
153 MaskFormatter formatter = null;
155 formatter = new MaskFormatter( s );
157 catch ( final ParseException e ) {
158 throw new IllegalArgumentException( e );
163 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
164 final PhylogenyNodeIterator it = phy.iteratorPostorder();
165 while ( it.hasNext() ) {
166 if ( it.next().getNodeData().isHasEvent() ) {
174 * Returns true if at least one branch has a length larger than zero.
179 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
180 final PhylogenyNodeIterator it = phy.iteratorPostorder();
181 while ( it.hasNext() ) {
182 if ( it.next().getDistanceToParent() > 0.0 ) {
189 final static public boolean isHasAtLeast50PercentBranchLengthLargerThanZero( final Phylogeny phy ) {
190 final PhylogenyNodeIterator it = phy.iteratorPostorder();
193 while ( it.hasNext() ) {
194 if ( it.next().getDistanceToParent() > 0.0 ) {
202 return (((( double ) positive) / total) >= 0.5 );
205 final static public boolean isHasNoBranchLengthSmallerThanZero( final Phylogeny phy ) {
206 final PhylogenyNodeIterator it = phy.iteratorPostorder();
207 while ( it.hasNext() ) {
208 final PhylogenyNode n = it.next();
209 if ( n.getDistanceToParent() < 0.0 && !n.isRoot() ) {
216 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
217 final PhylogenyNodeIterator it = phy.iteratorPostorder();
218 while ( it.hasNext() ) {
219 final PhylogenyNode n = it.next();
220 if ( n.getBranchData().isHasConfidences() ) {
221 final List<Confidence> c = n.getBranchData().getConfidences();
222 for( final Confidence confidence : c ) {
223 if ( confidence.getStandardDeviation() > 0 ) {
232 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
233 final PhylogenyNodeIterator it = phy.iteratorPostorder();
234 while ( it.hasNext() ) {
235 if ( it.next().getBranchData().isHasConfidences() ) {
242 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
243 final PhylogenyNodeIterator it = phy.iteratorPostorder();
244 while ( it.hasNext() ) {
245 final PhylogenyNode n = it.next();
246 if ( n.getNodeData().isHasTaxonomy()
247 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
254 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
255 final PhylogenyNodeIterator it = phy.iteratorPostorder();
256 while ( it.hasNext() ) {
257 final PhylogenyNode n = it.next();
258 if ( n.getNodeData().isHasSequence()
259 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
266 final public static void launchWebBrowser( final URI uri, final String frame_name ) throws IOException {
267 // This requires Java 1.6:
268 // =======================
269 // boolean no_desktop = false;
271 // if ( Desktop.isDesktopSupported() ) {
272 // System.out.println( "desktop supported" );
273 // final Desktop dt = Desktop.getDesktop();
277 // no_desktop = true;
280 // catch ( final Exception ex ) {
281 // ex.printStackTrace();
282 // no_desktop = true;
284 // catch ( final Error er ) {
285 // er.printStackTrace();
286 // no_desktop = true;
288 // if ( no_desktop ) {
289 // System.out.println( "desktop not supported" );
291 openUrlInWebBrowser( uri.toString() );
293 catch ( final Exception e ) {
294 throw new IOException( e );
299 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
300 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
301 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
302 for( final PhylogenyNode n : descs ) {
303 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
304 tax_set.add( n.getNodeData().getTaxonomy() );
310 public final static void printWarningMessage( final String name, final String message ) {
311 System.out.println( "[" + name + "] > " + message );
314 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
315 final boolean phyloxml_validate_against_xsd,
316 final boolean replace_underscores,
317 final boolean internal_numbers_are_confidences,
318 final TAXONOMY_EXTRACTION taxonomy_extraction,
319 final boolean midpoint_reroot )
320 throws FileNotFoundException, IOException {
321 final PhylogenyParser parser;
322 boolean nhx_or_nexus = false;
323 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
324 parser = new TolParser();
327 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
328 if ( parser instanceof NHXParser ) {
330 final NHXParser nhx = ( NHXParser ) parser;
331 nhx.setReplaceUnderscores( replace_underscores );
332 nhx.setIgnoreQuotes( false );
333 nhx.setTaxonomyExtraction( taxonomy_extraction );
335 else if ( parser instanceof NexusPhylogeniesParser ) {
337 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
338 nex.setReplaceUnderscores( replace_underscores );
339 nex.setIgnoreQuotes( false );
342 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
343 Phylogeny[] phys = null;
345 phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
347 catch ( final KeyManagementException e ) {
348 throw new IOException( e.getMessage() );
350 catch ( final NoSuchAlgorithmException e ) {
351 throw new IOException( e.getMessage() );
353 if ( phys != null ) {
354 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
355 for( final Phylogeny phy : phys ) {
356 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
359 if ( midpoint_reroot ) {
360 for( final Phylogeny phy : phys ) {
361 PhylogenyMethods.midpointRoot( phy );
362 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
369 final public static void showErrorMessage( final Component parent, final String error_msg ) {
370 printAppletMessage( AptxConstants.PRG_NAME, error_msg );
371 JOptionPane.showMessageDialog( parent,
373 "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "] Error",
374 JOptionPane.ERROR_MESSAGE );
377 public static void writePhylogenyToGraphicsFile( final File intree,
381 final GraphicsExportType type,
382 final Configuration config )
384 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
385 Phylogeny[] phys = null;
386 phys = PhylogenyMethods.readPhylogenies( parser, intree );
387 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
390 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
394 final GraphicsExportType type,
395 final Configuration config )
397 final Phylogeny[] phys = new Phylogeny[ 1 ];
399 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
400 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile,
403 mf.getMainPanel().getCurrentTreePanel(),
404 mf.getMainPanel().getControlPanel(),
410 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
413 final TreePanel tree_panel,
414 final ControlPanel ac,
415 final GraphicsExportType type,
416 final Options options )
418 tree_panel.calcParametersForPainting( width, height );
419 tree_panel.resetPreferredSize();
420 tree_panel.repaint();
421 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
422 RenderingHints.VALUE_RENDER_QUALITY );
423 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
424 if ( options.isAntialiasPrint() ) {
425 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
426 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
429 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
430 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
432 final Phylogeny phylogeny = tree_panel.getPhylogeny();
433 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
436 if ( outfile.isDirectory() ) {
437 throw new IOException( "\"" + outfile + "\" is a directory" );
439 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
440 final Graphics2D g2d = buffered_img.createGraphics();
441 g2d.setRenderingHints( rendering_hints );
442 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
443 if ( type == GraphicsExportType.TIFF ) {
444 writeToTiff( outfile, buffered_img );
447 ImageIO.write( buffered_img, type.toString(), outfile );
452 final private static char normalizeCharForRGB( char c ) {
455 c = c > 255 ? 255 : c;
460 final private static void openUrlInWebBrowser( final String url )
461 throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException,
462 IllegalArgumentException, IllegalAccessException, InvocationTargetException, InterruptedException {
463 final String os = System.getProperty( "os.name" );
464 final Runtime runtime = Runtime.getRuntime();
465 if ( os.toLowerCase().startsWith( "win" ) ) {
466 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
468 else if ( ForesterUtil.isMac() ) {
469 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
470 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
471 open_url.invoke( null, new Object[] { url } );
474 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
475 String browser = null;
476 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
477 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
478 browser = browsers[ i ];
481 if ( browser == null ) {
482 throw new IOException( "could not find a web browser to open [" + url + "] in" );
485 runtime.exec( new String[] { browser, url } );
490 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
491 final String default_name,
492 final String full_path,
493 final Configuration configuration,
494 final MainPanel main_panel ) {
495 if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
496 JOptionPane.showMessageDialog( main_panel,
497 "Attempt to load " + phys.length
498 + " phylogenies,\ngoing to load only the first "
499 + AptxConstants.MAX_TREES_TO_LOAD,
500 AptxConstants.PRG_NAME + " more than " + AptxConstants.MAX_TREES_TO_LOAD
502 JOptionPane.WARNING_MESSAGE );
505 for( final Phylogeny phy : phys ) {
506 if ( !phy.isEmpty() ) {
507 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
509 String my_name_for_file = "";
510 if ( phys.length > 1 ) {
511 if ( !ForesterUtil.isEmpty( default_name ) ) {
512 my_name = new String( default_name );
514 if ( !ForesterUtil.isEmpty( full_path ) ) {
515 my_name_for_file = new String( full_path );
517 else if ( !ForesterUtil.isEmpty( default_name ) ) {
518 my_name_for_file = new String( default_name );
521 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
522 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
523 my_name_for_file.length() );
524 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
526 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
527 my_name_for_file += "_";
529 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
530 my_name_for_file += phy.getName().replaceAll( " ", "_" );
532 else if ( phy.getIdentifier() != null ) {
533 final StringBuffer sb = new StringBuffer();
534 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
535 sb.append( phy.getIdentifier().getProvider() );
538 sb.append( phy.getIdentifier().getValue() );
539 my_name_for_file += sb;
542 my_name_for_file += i;
544 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
545 && ( phy.getIdentifier() == null ) ) {
546 my_name = my_name + " [" + i + "]";
548 if ( !ForesterUtil.isEmpty( suffix ) ) {
549 my_name_for_file += suffix;
553 if ( !ForesterUtil.isEmpty( default_name ) ) {
554 my_name = new String( default_name );
556 my_name_for_file = "";
557 if ( !ForesterUtil.isEmpty( full_path ) ) {
558 my_name_for_file = new String( full_path );
560 else if ( !ForesterUtil.isEmpty( default_name ) ) {
561 my_name_for_file = new String( default_name );
563 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
564 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
565 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
567 else if ( phy.getIdentifier() != null ) {
568 final StringBuffer sb = new StringBuffer();
569 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
570 sb.append( phy.getIdentifier().getProvider() );
573 sb.append( phy.getIdentifier().getValue() );
574 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
578 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
579 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
580 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
587 final static void addPhylogenyToPanel( final Phylogeny[] phys,
588 final Configuration configuration,
589 final MainPanel main_panel ) {
590 final Phylogeny phy = phys[ 0 ];
591 main_panel.addPhylogenyInPanel( phy, configuration );
592 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
595 // Returns true if the specified format name can be written
596 final static boolean canWriteFormat( final String format_name ) {
597 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
598 return iter.hasNext();
601 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
602 final StringBuilder desc = new StringBuilder();
603 if ( ( phy != null ) && !phy.isEmpty() ) {
605 if ( treefile != null ) {
607 f = treefile.getCanonicalPath();
609 catch ( final IOException e ) {
610 //Not important, ignore.
612 if ( !ForesterUtil.isEmpty( f ) ) {
613 desc.append( "Path: " );
618 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
619 desc.append( "Name: " );
620 desc.append( phy.getName() );
623 if ( phy.getIdentifier() != null ) {
624 desc.append( "Id: " );
625 desc.append( phy.getIdentifier().toString() );
628 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
629 desc.append( "Description: " );
630 desc.append( phy.getDescription() );
633 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
634 desc.append( "Distance Unit: " );
635 desc.append( phy.getDistanceUnit() );
638 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
639 desc.append( "Type: " );
640 desc.append( phy.getType() );
643 desc.append( "Rooted: " );
644 desc.append( phy.isRooted() );
646 desc.append( "Rerootable: " );
647 desc.append( phy.isRerootable() );
649 desc.append( "Nodes: " );
650 desc.append( phy.getNodeCount() );
652 desc.append( "External nodes: " );
653 desc.append( phy.getNumberOfExternalNodes() );
655 desc.append( "Internal nodes: " );
656 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
658 desc.append( "Internal nodes with polytomies: " );
659 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
661 desc.append( "Branches: " );
662 desc.append( phy.getNumberOfBranches() );
664 desc.append( "Depth: " );
665 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
667 desc.append( "Maximum distance to root: " );
668 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
670 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
671 if ( taxs != null ) {
672 desc.append( "Distinct external taxonomies: " );
673 desc.append( taxs.size() );
675 for( final Taxonomy t : taxs ) {
676 System.out.println( t.toString() );
679 final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
680 if ( bs.getN() > 3 ) {
682 desc.append( "Branch-length statistics: " );
684 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
686 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
688 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
689 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
691 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
693 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
695 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
697 final AsciiHistogram histo = new AsciiHistogram( bs );
698 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
701 final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
702 if ( ds.getN() > 2 ) {
704 desc.append( "Descendants per node statistics: " );
706 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
708 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
709 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
711 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
713 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
716 List<DescriptiveStatistics> css = null;
718 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
720 catch ( final IllegalArgumentException e ) {
721 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
723 if ( ( css != null ) && ( css.size() > 0 ) ) {
725 for( int i = 0; i < css.size(); ++i ) {
726 final DescriptiveStatistics cs = css.get( i );
727 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
728 if ( css.size() > 1 ) {
729 desc.append( "Support statistics " + ( i + 1 ) + ": " );
732 desc.append( "Support statistics: " );
734 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
736 desc.append( " Type: " + cs.getDescription() );
739 desc.append( " Branches with support: " + cs.getN() );
741 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
743 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
744 if ( cs.getN() > 2 ) {
745 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
748 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
750 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
756 return desc.toString();
764 * to message to be printed
766 final static void dieWithSystemError( final String message ) {
767 System.out.println();
768 System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
769 System.out.println( "Please contact the authors." );
770 System.out.println( AptxConstants.PRG_NAME + " needs to close." );
771 System.out.println();
775 final static String[] getAllPossibleRanks() {
776 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
778 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
779 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
780 str_array[ i++ ] = e;
786 final static String[] getAllPossibleRanks( final Map<String, Integer> present_ranks ) {
787 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
789 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
790 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
791 if ( present_ranks != null && present_ranks.containsKey( e ) ) {
792 str_array[ i++ ] = e + " (" + present_ranks.get( e ) + ")";
795 str_array[ i++ ] = e;
802 final static String[] getAllRanks( final Phylogeny tree ) {
803 final SortedSet<String> ranks = new TreeSet<String>();
804 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
805 final PhylogenyNode n = it.next();
806 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
807 ranks.add( n.getNodeData().getTaxonomy().getRank() );
810 return ForesterUtil.stringSetToArray( ranks );
813 final static String[] getAvailableFontFamiliesSorted() {
814 return AVAILABLE_FONT_FAMILIES_SORTED;
817 final static boolean isUsOrCanada() {
819 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
823 catch ( final Exception e ) {
829 final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t, final ControlPanel cp ) {
830 if ( ( t != null ) && !t.isEmpty() ) {
831 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
833 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
834 cp.setDrawPhylogramEnabled( false );
837 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
839 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
841 if ( cp.getDisplayAsUnalignedPhylogramRb() != null ) {
842 cp.setDrawPhylogramEnabled( true );
848 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
849 final ControlPanel cp,
850 final Configuration configuration ) {
851 if ( ( t != null ) && !t.isEmpty() ) {
852 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
854 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
855 cp.setDrawPhylogramEnabled( false );
857 if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
858 && cp.getUseVisualStylesCb() != null ) {
859 cp.getUseVisualStylesCb().setSelected( true );
861 if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
862 && t.getFirstExternalNode().getBranchData().getBranchWidth()
863 .getValue() != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
864 && cp.getUseBranchWidthsCb() != null ) {
865 cp.getUseBranchWidthsCb().setSelected( true );
867 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
868 if ( cp.getDisplayAsAlignedPhylogramRb() != null ) {
870 final boolean has_mostly_bl = AptxUtil.isHasAtLeast50PercentBranchLengthLargerThanZero( t );
871 if ( has_mostly_bl ) {
872 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
874 cp.setDrawPhylogramEnabled( true );
877 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
881 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
882 if ( cp.getWriteConfidenceCb() != null ) {
883 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
884 cp.setCheckbox( Configuration.write_confidence_values, true );
887 cp.setCheckbox( Configuration.write_confidence_values, false );
891 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
892 if ( cp.getShowEventsCb() != null ) {
893 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
894 cp.setCheckbox( Configuration.write_events, true );
897 cp.setCheckbox( Configuration.write_events, false );
904 final static void openWebsite( final String url ) throws IOException {
906 AptxUtil.launchWebBrowser( new URI( url ), AptxConstants.PRG_NAME );
908 catch ( final Exception e ) {
909 throw new IOException( e );
913 final static void outOfMemoryError( final OutOfMemoryError e ) {
914 System.err.println();
915 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
916 System.err.println();
918 System.err.println();
919 JOptionPane.showMessageDialog( null,
920 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
921 + "\n\nError: " + e.getLocalizedMessage(),
922 "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
924 JOptionPane.ERROR_MESSAGE );
928 final static void printAppletMessage( final String applet_name, final String message ) {
929 System.out.println( "[" + applet_name + "] > " + message );
932 final static void removeBranchColors( final Phylogeny phy ) {
933 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
934 it.next().getBranchData().setBranchColor( null );
938 final static void removeVisualStyles( final Phylogeny phy ) {
939 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
940 it.next().getNodeData().setNodeVisualData( null );
944 final static void unexpectedError( final Error e ) {
945 System.err.println();
946 e.printStackTrace( System.err );
947 System.err.println();
948 final StringBuffer sb = new StringBuffer();
949 for( final StackTraceElement s : e.getStackTrace() ) {
950 sb.append( s + "\n" );
952 JOptionPane.showMessageDialog( null,
953 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
954 + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage()
956 "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " "
957 + AptxConstants.VERSION + "]",
958 JOptionPane.ERROR_MESSAGE );
962 final static void unexpectedException( final Exception e ) {
963 System.err.println();
964 e.printStackTrace( System.err );
965 System.err.println();
966 final StringBuffer sb = new StringBuffer();
967 for( final StackTraceElement s : e.getStackTrace() ) {
968 sb.append( s + "\n" );
970 JOptionPane.showMessageDialog( null,
971 "An unexpected exception has occured. \nPlease contact: "
972 + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
974 "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
975 JOptionPane.ERROR_MESSAGE );
978 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
981 final TreePanel tree_panel,
982 final ControlPanel ac,
983 final GraphicsExportType type,
984 final Options options )
986 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
987 RenderingHints.VALUE_RENDER_QUALITY );
988 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
989 if ( options.isAntialiasPrint() ) {
990 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
991 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
994 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
995 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
997 final Phylogeny phylogeny = tree_panel.getPhylogeny();
998 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1001 Rectangle visible = null;
1002 // if ( !options.isGraphicsExportUsingActualSize() ) {
1003 // width = options.getPrintSizeX();
1004 // height = options.getPrintSizeY();
1006 /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1007 visible = tree_panel.getVisibleRect();
1008 width = visible.width;
1009 height = visible.height;
1011 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1012 Graphics2D g2d = buffered_img.createGraphics();
1013 g2d.setRenderingHints( rendering_hints );
1016 if ( options.isGraphicsExportVisibleOnly() ) {
1017 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1018 g2d.setClip( null );
1022 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1023 ImageIO.write( buffered_img, type.toString(), baos );
1026 if ( !options.isGraphicsExportUsingActualSize() ) {
1027 tree_panel.getMainPanel().getControlPanel().showWhole();
1029 String msg = baos.toString();
1030 if ( ( width > 0 ) && ( height > 0 ) ) {
1031 msg += " [size: " + width + ", " + height + "]";
1036 final static String writePhylogenyToGraphicsFile( final String file_name,
1039 final TreePanel tree_panel,
1040 final ControlPanel ac,
1041 final GraphicsExportType type,
1042 final Options options )
1043 throws IOException {
1044 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1045 RenderingHints.VALUE_RENDER_QUALITY );
1046 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1047 if ( options.isAntialiasPrint() ) {
1048 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1049 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1052 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1053 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1055 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1056 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1059 final File file = new File( file_name );
1060 if ( file.isDirectory() ) {
1061 throw new IOException( "\"" + file_name + "\" is a directory" );
1063 Rectangle visible = null;
1064 // if ( !options.isGraphicsExportUsingActualSize() ) {
1065 // width = options.getPrintSizeX();
1066 // height = options.getPrintSizeY();
1068 /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1069 visible = tree_panel.getVisibleRect();
1070 width = visible.width;
1071 height = visible.height;
1073 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1074 Graphics2D g2d = buffered_img.createGraphics();
1075 g2d.setRenderingHints( rendering_hints );
1078 if ( options.isGraphicsExportVisibleOnly() ) {
1079 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1080 g2d.setClip( null );
1084 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1085 if ( type == GraphicsExportType.TIFF ) {
1086 writeToTiff( file, buffered_img );
1089 ImageIO.write( buffered_img, type.toString(), file );
1093 if ( !options.isGraphicsExportUsingActualSize() ) {
1094 tree_panel.getMainPanel().getControlPanel().showWhole();
1096 String msg = file.toString();
1097 if ( ( width > 0 ) && ( height > 0 ) ) {
1098 msg += " [size: " + width + ", " + height + "]";
1103 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1104 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1105 ImageWriter writer = null;
1106 ImageOutputStream ios = null;
1107 // Find an appropriate writer:
1108 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1109 if ( it.hasNext() ) {
1113 throw new IOException( "failed to get TIFF image writer" );
1116 ios = ImageIO.createImageOutputStream( file );
1117 writer.setOutput( ios );
1118 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1119 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1120 // see writeParam.getCompressionTypes() for available compression type
1122 image_write_param.setCompressionType( "PackBits" );
1123 final String t[] = image_write_param.getCompressionTypes();
1124 for( final String string : t ) {
1125 System.out.println( string );
1127 // Convert to an IIOImage:
1128 final IIOImage iio_image = new IIOImage( image, null, null );
1129 writer.write( null, iio_image, image_write_param );
1132 final static Map<String, Integer> getRankCounts( final Phylogeny tree ) {
1133 final Map<String, Integer> present_ranks = new HashMap<String, Integer>();
1134 if ( ( tree != null ) && !tree.isEmpty() ) {
1135 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
1136 final PhylogenyNode n = it.next();
1137 if ( !n.isExternal() && n.getNodeData().isHasTaxonomy()
1138 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) && !n.isRoot() ) {
1139 final String rank = n.getNodeData().getTaxonomy().getRank().toLowerCase();
1140 if ( present_ranks.containsKey( rank ) ) {
1141 present_ranks.put( rank, present_ranks.get( rank ) + 1 );
1144 present_ranks.put( rank, 1 );
1149 return present_ranks;