in progress
[jalview.git] / forester / java / src / org / forester / archaeopteryx / AptxUtil.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // All rights reserved
8 //
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.
13 //
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.
18 //
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
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
25
26 package org.forester.archaeopteryx;
27
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;
36 import java.io.File;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.lang.reflect.InvocationTargetException;
40 import java.lang.reflect.Method;
41 import java.net.URI;
42 import java.net.URL;
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;
52 import java.util.Map;
53 import java.util.Set;
54 import java.util.SortedSet;
55 import java.util.TreeSet;
56
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;
64
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;
83
84 public final class AptxUtil {
85
86     public static enum GraphicsExportType {
87         BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
88
89         private final String _suffix;
90
91         private GraphicsExportType( final String suffix ) {
92             _suffix = suffix;
93         }
94
95         @Override
96         public String toString() {
97             return _suffix;
98         }
99     }
100     private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
101             .getAvailableFontFamilyNames();
102     static {
103         Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
104     }
105
106     final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
107         final String my_str = str.toUpperCase();
108         char first = my_str.charAt( 0 );
109         char second = ' ';
110         char third = ' ';
111         if ( my_str.length() > 1 ) {
112             if ( is_taxonomy ) {
113                 second = my_str.charAt( 1 );
114             }
115             else {
116                 second = my_str.charAt( my_str.length() - 1 );
117             }
118             if ( is_taxonomy ) {
119                 if ( my_str.length() > 2 ) {
120                     if ( my_str.indexOf( " " ) > 0 ) {
121                         third = my_str.charAt( my_str.indexOf( " " ) + 1 );
122                     }
123                     else {
124                         third = my_str.charAt( 2 );
125                     }
126                 }
127             }
128             else if ( my_str.length() > 2 ) {
129                 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
130             }
131         }
132         first = normalizeCharForRGB( first );
133         second = normalizeCharForRGB( second );
134         third = normalizeCharForRGB( third );
135         if ( ( first > 200 ) && ( second > 200 ) && ( third > 200 ) ) {
136             first = 0;
137         }
138         else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
139             second = 255;
140         }
141         else if ( Math.abs( first - second ) < 40 && Math.abs( second - third ) < 40 ) {
142             third = 255;
143         }
144         return new Color( first, second, third );
145     }
146
147     public static MaskFormatter createMaskFormatter( final String s ) {
148         MaskFormatter formatter = null;
149         try {
150             formatter = new MaskFormatter( s );
151         }
152         catch ( final ParseException e ) {
153             throw new IllegalArgumentException( e );
154         }
155         return formatter;
156     }
157
158     final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
159         final PhylogenyNodeIterator it = phy.iteratorPostorder();
160         while ( it.hasNext() ) {
161             if ( it.next().getNodeData().isHasEvent() ) {
162                 return true;
163             }
164         }
165         return false;
166     }
167
168     /**
169      * Returns true if at least one branch has a length larger than zero.
170      *
171      *
172      * @param phy
173      */
174     final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
175         final PhylogenyNodeIterator it = phy.iteratorPostorder();
176         while ( it.hasNext() ) {
177             if ( it.next().getDistanceToParent() > 0.0 ) {
178                 return true;
179             }
180         }
181         return false;
182     }
183     
184     final static public boolean isHasNoBranchLengthSmallerThanZero( final Phylogeny phy ) {
185         final PhylogenyNodeIterator it = phy.iteratorPostorder();
186         while ( it.hasNext() ) {
187             final PhylogenyNode n = it.next(); 
188             if ( n.getDistanceToParent() < 0.0 && !n.isRoot() ) {
189                 return false;
190             }
191         }
192         return true;
193     }
194
195     final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
196         final PhylogenyNodeIterator it = phy.iteratorPostorder();
197         while ( it.hasNext() ) {
198             final PhylogenyNode n = it.next();
199             if ( n.getBranchData().isHasConfidences() ) {
200                 final List<Confidence> c = n.getBranchData().getConfidences();
201                 for( final Confidence confidence : c ) {
202                     if ( confidence.getStandardDeviation() > 0 ) {
203                         return true;
204                     }
205                 }
206             }
207         }
208         return false;
209     }
210
211     final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
212         final PhylogenyNodeIterator it = phy.iteratorPostorder();
213         while ( it.hasNext() ) {
214             if ( it.next().getBranchData().isHasConfidences() ) {
215                 return true;
216             }
217         }
218         return false;
219     }
220
221     final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
222         final PhylogenyNodeIterator it = phy.iteratorPostorder();
223         while ( it.hasNext() ) {
224             final PhylogenyNode n = it.next();
225             if ( n.getNodeData().isHasTaxonomy()
226                     && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
227                 return true;
228             }
229         }
230         return false;
231     }
232
233     final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
234         final PhylogenyNodeIterator it = phy.iteratorPostorder();
235         while ( it.hasNext() ) {
236             final PhylogenyNode n = it.next();
237             if ( n.getNodeData().isHasSequence()
238                     && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
239                 return true;
240             }
241         }
242         return false;
243     }
244
245     final public static void launchWebBrowser( final URI uri,
246                                              final String frame_name ) throws IOException {
247        
248             // This requires Java 1.6:
249             // =======================
250             // boolean no_desktop = false;
251             // try {
252             // if ( Desktop.isDesktopSupported() ) {
253             // System.out.println( "desktop supported" );
254             // final Desktop dt = Desktop.getDesktop();
255             // dt.browse( uri );
256             // }
257             // else {
258             // no_desktop = true;
259             // }
260             // }
261             // catch ( final Exception ex ) {
262             // ex.printStackTrace();
263             // no_desktop = true;
264             // }
265             // catch ( final Error er ) {
266             // er.printStackTrace();
267             // no_desktop = true;
268             // }
269             // if ( no_desktop ) {
270             // System.out.println( "desktop not supported" );
271             try {
272                 openUrlInWebBrowser( uri.toString() );
273             }
274             catch ( final Exception e ) {
275                 throw new IOException( e );
276             }
277             // }
278         
279     }
280
281     public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
282         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
283         final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
284         for( final PhylogenyNode n : descs ) {
285             if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
286                 tax_set.add( n.getNodeData().getTaxonomy() );
287             }
288         }
289         return tax_set;
290     }
291
292     public final static void printWarningMessage( final String name, final String message ) {
293         System.out.println( "[" + name + "] > " + message );
294     }
295
296     final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
297                                                             final boolean phyloxml_validate_against_xsd,
298                                                             final boolean replace_underscores,
299                                                             final boolean internal_numbers_are_confidences,
300                                                             final TAXONOMY_EXTRACTION taxonomy_extraction,
301                                                             final boolean midpoint_reroot )
302                                                                     throws FileNotFoundException, IOException {
303         final PhylogenyParser parser;
304         boolean nhx_or_nexus = false;
305         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
306             parser = new TolParser();
307         }
308         else {
309             parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
310             if ( parser instanceof NHXParser ) {
311                 nhx_or_nexus = true;
312                 final NHXParser nhx = ( NHXParser ) parser;
313                 nhx.setReplaceUnderscores( replace_underscores );
314                 nhx.setIgnoreQuotes( false );
315                 nhx.setTaxonomyExtraction( taxonomy_extraction );
316             }
317             else if ( parser instanceof NexusPhylogeniesParser ) {
318                 nhx_or_nexus = true;
319                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
320                 nex.setReplaceUnderscores( replace_underscores );
321                 nex.setIgnoreQuotes( false );
322             }
323         }
324         AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
325         Phylogeny[] phys = null;
326         try {
327             phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
328         }
329         catch ( final KeyManagementException e ) {
330             throw new IOException( e.getMessage() );
331         }
332         catch ( final NoSuchAlgorithmException e ) {
333             throw new IOException( e.getMessage() );
334         }
335         if ( phys != null ) {
336             if ( nhx_or_nexus && internal_numbers_are_confidences ) {
337                 for( final Phylogeny phy : phys ) {
338                     PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
339                 }
340             }
341             if ( midpoint_reroot ) {
342                 for( final Phylogeny phy : phys ) {
343                     PhylogenyMethods.midpointRoot( phy );
344                     PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
345                 }
346             }
347         }
348         return phys;
349     }
350
351     final public static void showErrorMessage( final Component parent, final String error_msg ) {
352         printAppletMessage( AptxConstants.PRG_NAME, error_msg );
353         JOptionPane.showMessageDialog( parent, error_msg, "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
354                                        + "] Error", JOptionPane.ERROR_MESSAGE );
355     }
356
357     public static void writePhylogenyToGraphicsFile( final File intree,
358                                                      final File outfile,
359                                                      final int width,
360                                                      final int height,
361                                                      final GraphicsExportType type,
362                                                      final Configuration config ) throws IOException {
363         final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
364         Phylogeny[] phys = null;
365         phys = PhylogenyMethods.readPhylogenies( parser, intree );
366         writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
367     }
368
369     public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
370                                                      final File outfile,
371                                                      final int width,
372                                                      final int height,
373                                                      final GraphicsExportType type,
374                                                      final Configuration config ) throws IOException {
375         final Phylogeny[] phys = new Phylogeny[ 1 ];
376         phys[ 0 ] = phy;
377         final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
378         AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
379                                                              .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
380         mf.end();
381     }
382
383     public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
384                                                                          final int width,
385                                                                          final int height,
386                                                                          final TreePanel tree_panel,
387                                                                          final ControlPanel ac,
388                                                                          final GraphicsExportType type,
389                                                                          final Options options ) throws IOException {
390         tree_panel.calcParametersForPainting( width, height );
391         tree_panel.resetPreferredSize();
392         tree_panel.repaint();
393         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
394                                                                    RenderingHints.VALUE_RENDER_QUALITY );
395         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
396         if ( options.isAntialiasPrint() ) {
397             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
398             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
399         }
400         else {
401             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
402             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
403         }
404         final Phylogeny phylogeny = tree_panel.getPhylogeny();
405         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
406             return;
407         }
408         if ( outfile.isDirectory() ) {
409             throw new IOException( "\"" + outfile + "\" is a directory" );
410         }
411         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
412         final Graphics2D g2d = buffered_img.createGraphics();
413         g2d.setRenderingHints( rendering_hints );
414         tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
415         if ( type == GraphicsExportType.TIFF ) {
416             writeToTiff( outfile, buffered_img );
417         }
418         else {
419             ImageIO.write( buffered_img, type.toString(), outfile );
420         }
421         g2d.dispose();
422     }
423
424     final private static char normalizeCharForRGB( char c ) {
425         c -= 65;
426         c *= 10.2;
427         c = c > 255 ? 255 : c;
428         c = c < 0 ? 0 : c;
429         return c;
430     }
431
432     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
433     SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
434     InvocationTargetException, InterruptedException {
435         final String os = System.getProperty( "os.name" );
436         final Runtime runtime = Runtime.getRuntime();
437         if ( os.toLowerCase().startsWith( "win" ) ) {
438             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
439         }
440         else if ( ForesterUtil.isMac() ) {
441             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
442             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
443             open_url.invoke( null, new Object[] { url } );
444         }
445         else {
446             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
447             String browser = null;
448             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
449                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
450                     browser = browsers[ i ];
451                 }
452             }
453             if ( browser == null ) {
454                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
455             }
456             else {
457                 runtime.exec( new String[] { browser, url } );
458             }
459         }
460     }
461
462     final static void addPhylogeniesToTabs( final Phylogeny[] phys,
463                                             final String default_name,
464                                             final String full_path,
465                                             final Configuration configuration,
466                                             final MainPanel main_panel ) {
467         if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
468             JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
469                                            + " phylogenies,\ngoing to load only the first " + AptxConstants.MAX_TREES_TO_LOAD, AptxConstants.PRG_NAME
470                                            + " more than " + AptxConstants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
471         }
472         int i = 1;
473         for( final Phylogeny phy : phys ) {
474             if ( !phy.isEmpty() ) {
475                 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
476                     String my_name = "";
477                     String my_name_for_file = "";
478                     if ( phys.length > 1 ) {
479                         if ( !ForesterUtil.isEmpty( default_name ) ) {
480                             my_name = new String( default_name );
481                         }
482                         if ( !ForesterUtil.isEmpty( full_path ) ) {
483                             my_name_for_file = new String( full_path );
484                         }
485                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
486                             my_name_for_file = new String( default_name );
487                         }
488                         String suffix = "";
489                         if ( my_name_for_file.indexOf( '.' ) > 0 ) {
490                             suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
491                                                                  my_name_for_file.length() );
492                             my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
493                         }
494                         if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
495                             my_name_for_file += "_";
496                         }
497                         if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
498                             my_name_for_file += phy.getName().replaceAll( " ", "_" );
499                         }
500                         else if ( phy.getIdentifier() != null ) {
501                             final StringBuffer sb = new StringBuffer();
502                             if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
503                                 sb.append( phy.getIdentifier().getProvider() );
504                                 sb.append( "_" );
505                             }
506                             sb.append( phy.getIdentifier().getValue() );
507                             my_name_for_file += sb;
508                         }
509                         else {
510                             my_name_for_file += i;
511                         }
512                         if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
513                                 && ( phy.getIdentifier() == null ) ) {
514                             my_name = my_name + " [" + i + "]";
515                         }
516                         if ( !ForesterUtil.isEmpty( suffix ) ) {
517                             my_name_for_file += suffix;
518                         }
519                     }
520                     else {
521                         if ( !ForesterUtil.isEmpty( default_name ) ) {
522                             my_name = new String( default_name );
523                         }
524                         my_name_for_file = "";
525                         if ( !ForesterUtil.isEmpty( full_path ) ) {
526                             my_name_for_file = new String( full_path );
527                         }
528                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
529                             my_name_for_file = new String( default_name );
530                         }
531                         if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
532                             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
533                                 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
534                             }
535                             else if ( phy.getIdentifier() != null ) {
536                                 final StringBuffer sb = new StringBuffer();
537                                 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
538                                     sb.append( phy.getIdentifier().getProvider() );
539                                     sb.append( "_" );
540                                 }
541                                 sb.append( phy.getIdentifier().getValue() );
542                                 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
543                             }
544                         }
545                     }
546                     main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
547                     main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
548                     lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
549                     ++i;
550                 }
551             }
552         }
553     }
554
555     final static void addPhylogenyToPanel( final Phylogeny[] phys,
556                                            final Configuration configuration,
557                                            final MainPanel main_panel ) {
558         final Phylogeny phy = phys[ 0 ];
559         main_panel.addPhylogenyInPanel( phy, configuration );
560         lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
561     }
562
563     // Returns true if the specified format name can be written
564     final static boolean canWriteFormat( final String format_name ) {
565         final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
566         return iter.hasNext();
567     }
568
569     final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
570         final StringBuilder desc = new StringBuilder();
571         if ( ( phy != null ) && !phy.isEmpty() ) {
572             String f = null;
573             if ( treefile != null ) {
574                 try {
575                     f = treefile.getCanonicalPath();
576                 }
577                 catch ( final IOException e ) {
578                     //Not important, ignore.
579                 }
580                 if ( !ForesterUtil.isEmpty( f ) ) {
581                     desc.append( "Path: " );
582                     desc.append( f );
583                     desc.append( "\n" );
584                 }
585             }
586             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
587                 desc.append( "Name: " );
588                 desc.append( phy.getName() );
589                 desc.append( "\n" );
590             }
591             if ( phy.getIdentifier() != null ) {
592                 desc.append( "Id: " );
593                 desc.append( phy.getIdentifier().toString() );
594                 desc.append( "\n" );
595             }
596             if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
597                 desc.append( "Description: " );
598                 desc.append( phy.getDescription() );
599                 desc.append( "\n" );
600             }
601             if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
602                 desc.append( "Distance Unit: " );
603                 desc.append( phy.getDistanceUnit() );
604                 desc.append( "\n" );
605             }
606             if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
607                 desc.append( "Type: " );
608                 desc.append( phy.getType() );
609                 desc.append( "\n" );
610             }
611             desc.append( "Rooted: " );
612             desc.append( phy.isRooted() );
613             desc.append( "\n" );
614             desc.append( "Rerootable: " );
615             desc.append( phy.isRerootable() );
616             desc.append( "\n" );
617             desc.append( "Nodes: " );
618             desc.append( phy.getNodeCount() );
619             desc.append( "\n" );
620             desc.append( "External nodes: " );
621             desc.append( phy.getNumberOfExternalNodes() );
622             desc.append( "\n" );
623             desc.append( "Internal nodes: " );
624             desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
625             desc.append( "\n" );
626             desc.append( "Internal nodes with polytomies: " );
627             desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
628             desc.append( "\n" );
629             desc.append( "Branches: " );
630             desc.append( phy.getNumberOfBranches() );
631             desc.append( "\n" );
632             desc.append( "Depth: " );
633             desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
634             desc.append( "\n" );
635             desc.append( "Maximum distance to root: " );
636             desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
637             desc.append( "\n" );
638             final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
639             if ( taxs != null ) {
640                 desc.append( "Distinct external taxonomies: " );
641                 desc.append( taxs.size() );
642             }
643             for( final Taxonomy t : taxs ) {
644                 System.out.println( t.toString() );
645             }
646             desc.append( "\n" );
647             final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
648             if ( bs.getN() > 3 ) {
649                 desc.append( "\n" );
650                 desc.append( "Branch-length statistics: " );
651                 desc.append( "\n" );
652                 desc.append( "    Number of branches with non-negative branch-lengths: " + bs.getN() );
653                 desc.append( "\n" );
654                 desc.append( "    Median: " + ForesterUtil.round( bs.median(), 6 ) );
655                 desc.append( "\n" );
656                 desc.append( "    Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
657                         + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
658                 desc.append( "\n" );
659                 desc.append( "    Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
660                 desc.append( "\n" );
661                 desc.append( "    Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
662                 desc.append( "\n" );
663                 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
664                     desc.append( "\n" );
665                     final AsciiHistogram histo = new AsciiHistogram( bs );
666                     desc.append( histo.toStringBuffer( 12, '#', 40, 7, "    " ) );
667                 }
668             }
669             final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
670             if ( ds.getN() > 2 ) {
671                 desc.append( "\n" );
672                 desc.append( "Descendants per node statistics: " );
673                 desc.append( "\n" );
674                 desc.append( "    Median: " + ForesterUtil.round( ds.median(), 6 ) );
675                 desc.append( "\n" );
676                 desc.append( "    Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
677                         + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
678                 desc.append( "\n" );
679                 desc.append( "    Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
680                 desc.append( "\n" );
681                 desc.append( "    Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
682                 desc.append( "\n" );
683             }
684             List<DescriptiveStatistics> css = null;
685             try {
686                 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
687             }
688             catch ( final IllegalArgumentException e ) {
689                 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
690             }
691             if ( ( css != null ) && ( css.size() > 0 ) ) {
692                 desc.append( "\n" );
693                 for( int i = 0; i < css.size(); ++i ) {
694                     final DescriptiveStatistics cs = css.get( i );
695                     if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
696                         if ( css.size() > 1 ) {
697                             desc.append( "Support statistics " + ( i + 1 ) + ": " );
698                         }
699                         else {
700                             desc.append( "Support statistics: " );
701                         }
702                         if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
703                             desc.append( "\n" );
704                             desc.append( "    Type: " + cs.getDescription() );
705                         }
706                         desc.append( "\n" );
707                         desc.append( "    Branches with support: " + cs.getN() );
708                         desc.append( "\n" );
709                         desc.append( "    Median: " + ForesterUtil.round( cs.median(), 6 ) );
710                         desc.append( "\n" );
711                         desc.append( "    Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
712                         if ( cs.getN() > 2 ) {
713                             desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
714                         }
715                         desc.append( "\n" );
716                         desc.append( "    Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
717                         desc.append( "\n" );
718                         desc.append( "    Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
719                         desc.append( "\n" );
720                     }
721                 }
722             }
723         }
724         return desc.toString();
725     }
726
727     /**
728      * Exits with -1.
729      *
730      *
731      * @param message
732      *            to message to be printed
733      */
734     final static void dieWithSystemError( final String message ) {
735         System.out.println();
736         System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
737         System.out.println( "Please contact the authors." );
738         System.out.println( AptxConstants.PRG_NAME + " needs to close." );
739         System.out.println();
740         System.exit( -1 );
741     }
742
743     final static String[] getAllPossibleRanks() {
744         final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
745         int i = 0;
746         for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
747             if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
748                 str_array[ i++ ] = e;
749             }
750         }
751         return str_array;
752     }
753     
754     final static String[] getAllPossibleRanks(final Map<String, Integer> present_ranks) {
755         final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
756         int i = 0;
757         for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
758             if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
759                 if ( present_ranks != null && present_ranks.containsKey( e ) ) {
760                     str_array[ i++ ] = e + " (" +  present_ranks.get(e) + ")";
761                 }
762                 else {
763                     str_array[ i++ ] = e;
764                 }
765             }
766         }
767         return str_array;
768     }
769
770     final static String[] getAllRanks( final Phylogeny tree ) {
771         final SortedSet<String> ranks = new TreeSet<String>();
772         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
773             final PhylogenyNode n = it.next();
774             if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
775                 ranks.add( n.getNodeData().getTaxonomy().getRank() );
776             }
777         }
778         return ForesterUtil.stringSetToArray( ranks );
779     }
780
781     final static String[] getAvailableFontFamiliesSorted() {
782         return AVAILABLE_FONT_FAMILIES_SORTED;
783     }
784
785     final static boolean isUsOrCanada() {
786         try {
787             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
788                 return true;
789             }
790         }
791         catch ( final Exception e ) {
792             return false;
793         }
794         return false;
795     }
796     final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t,
797                                                                      final ControlPanel cp ) {
798         if ( ( t != null ) && !t.isEmpty() ) {
799             final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
800              
801             if ( !has_bl ) {
802                 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
803                 cp.setDrawPhylogramEnabled( false );
804             }
805             else {
806                 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
807                 if (has_all_bl) {
808                     cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
809                 }
810                
811                 if ( cp.getDisplayAsUnalignedPhylogramRb() != null ) {
812                     cp.setDrawPhylogramEnabled( true );
813                 }
814             }
815         }
816     }
817     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
818                                                                       final ControlPanel atv_control,
819                                                                       final Configuration configuration ) {
820         if ( ( t != null ) && !t.isEmpty() ) {
821             final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
822             if ( !has_bl ) {
823                 atv_control.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
824                 atv_control.setDrawPhylogramEnabled( false );
825             }
826             if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
827                     && atv_control.getUseVisualStylesCb() != null ) {
828                 atv_control.getUseVisualStylesCb().setSelected( true );
829             }
830             if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
831                     && t.getFirstExternalNode().getBranchData().getBranchWidth().getValue()
832                     != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
833                     && atv_control.getUseBranchWidthsCb() != null ) {
834                 atv_control.getUseBranchWidthsCb().setSelected( true );
835             }
836             
837             
838             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
839                 if ( atv_control.getDisplayAsAlignedPhylogramRb() != null ) {
840                     if ( has_bl ) {
841                         final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
842                         if (has_all_bl) {
843                             atv_control.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
844                         }
845                        
846                         atv_control.setDrawPhylogramEnabled( true );
847                     }
848                     else {
849                         atv_control.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
850                     }
851                 }
852             }
853             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
854                 if ( atv_control.getWriteConfidenceCb() != null ) {
855                     if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
856                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
857                     }
858                     else {
859                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
860                     }
861                 }
862             }
863             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
864                 if ( atv_control.getShowEventsCb() != null ) {
865                     if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
866                         atv_control.setCheckbox( Configuration.write_events, true );
867                     }
868                     else {
869                         atv_control.setCheckbox( Configuration.write_events, false );
870                     }
871                 }
872             }
873         }
874     }
875
876     final static void openWebsite( final String url ) throws IOException {
877         try {
878             AptxUtil.launchWebBrowser( new URI( url ),  AptxConstants.PRG_NAME );
879         }
880         catch ( final Exception e ) {
881             throw new IOException( e );
882         }
883     }
884
885     final static void outOfMemoryError( final OutOfMemoryError e ) {
886         System.err.println();
887         System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
888         System.err.println();
889         e.printStackTrace();
890         System.err.println();
891         JOptionPane.showMessageDialog( null,
892                                        "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
893                                                + "\n\nError: " + e.getLocalizedMessage(),
894                                                "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
895                                                JOptionPane.ERROR_MESSAGE );
896         System.exit( -1 );
897     }
898
899     final static void printAppletMessage( final String applet_name, final String message ) {
900         System.out.println( "[" + applet_name + "] > " + message );
901     }
902
903     final static void removeBranchColors( final Phylogeny phy ) {
904         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
905             it.next().getBranchData().setBranchColor( null );
906         }
907     }
908
909     final static void removeVisualStyles( final Phylogeny phy ) {
910         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
911             it.next().getNodeData().setNodeVisualData( null );
912         }
913     }
914
915     final static void unexpectedError( final Error e ) {
916         System.err.println();
917         e.printStackTrace( System.err );
918         System.err.println();
919         final StringBuffer sb = new StringBuffer();
920         for( final StackTraceElement s : e.getStackTrace() ) {
921             sb.append( s + "\n" );
922         }
923         JOptionPane
924         .showMessageDialog( null,
925                             "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
926                                     + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
927                                     + sb,
928                                     "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
929                                     JOptionPane.ERROR_MESSAGE );
930         System.exit( -1 );
931     }
932
933     final static void unexpectedException( final Exception e ) {
934         System.err.println();
935         e.printStackTrace( System.err );
936         System.err.println();
937         final StringBuffer sb = new StringBuffer();
938         for( final StackTraceElement s : e.getStackTrace() ) {
939             sb.append( s + "\n" );
940         }
941         JOptionPane.showMessageDialog( null,
942                                        "An unexpected exception has occured. \nPlease contact: "
943                                                + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
944                                                + "\n" + sb,
945                                                "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
946                                                JOptionPane.ERROR_MESSAGE );
947     }
948
949     final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
950                                                                        int width,
951                                                                        int height,
952                                                                        final TreePanel tree_panel,
953                                                                        final ControlPanel ac,
954                                                                        final GraphicsExportType type,
955                                                                        final Options options ) throws IOException {
956         
957         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
958                                                                    RenderingHints.VALUE_RENDER_QUALITY );
959         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
960         if ( options.isAntialiasPrint() ) {
961             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
962             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
963         }
964         else {
965             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
966             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
967         }
968         final Phylogeny phylogeny = tree_panel.getPhylogeny();
969         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
970             return "";
971         }
972         Rectangle visible = null;
973 //        if ( !options.isGraphicsExportUsingActualSize() ) {
974 //            width = options.getPrintSizeX();
975 //            height = options.getPrintSizeY();
976 //        }
977        /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
978             visible = tree_panel.getVisibleRect();
979             width = visible.width;
980             height = visible.height;
981         }
982         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
983         Graphics2D g2d = buffered_img.createGraphics();
984         g2d.setRenderingHints( rendering_hints );
985         int x = 0;
986         int y = 0;
987         if ( options.isGraphicsExportVisibleOnly() ) {
988             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
989             g2d.setClip( null );
990             x = visible.x;
991             y = visible.y;
992         }
993         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
994         ImageIO.write( buffered_img, type.toString(), baos );
995         g2d.dispose();
996         System.gc();
997         if ( !options.isGraphicsExportUsingActualSize() ) {
998             tree_panel.getMainPanel().getControlPanel().showWhole();
999         }
1000         String msg = baos.toString();
1001         if ( ( width > 0 ) && ( height > 0 ) ) {
1002             msg += " [size: " + width + ", " + height + "]";
1003         }
1004         return msg;
1005     }
1006
1007     final static String writePhylogenyToGraphicsFile( final String file_name,
1008                                                       int width,
1009                                                       int height,
1010                                                       final TreePanel tree_panel,
1011                                                       final ControlPanel ac,
1012                                                       final GraphicsExportType type,
1013                                                       final Options options ) throws IOException {
1014        
1015         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1016                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1017         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1018         if ( options.isAntialiasPrint() ) {
1019             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1020             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1021         }
1022         else {
1023             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1024             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1025         }
1026         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1027         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1028             return "";
1029         }
1030         final File file = new File( file_name );
1031         if ( file.isDirectory() ) {
1032             throw new IOException( "\"" + file_name + "\" is a directory" );
1033         }
1034         Rectangle visible = null;
1035 //        if ( !options.isGraphicsExportUsingActualSize() ) {
1036 //            width = options.getPrintSizeX();
1037 //            height = options.getPrintSizeY();
1038 //        }
1039         /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1040             visible = tree_panel.getVisibleRect();
1041             width = visible.width;
1042             height = visible.height;
1043         }
1044         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1045         Graphics2D g2d = buffered_img.createGraphics();
1046         g2d.setRenderingHints( rendering_hints );
1047         int x = 0;
1048         int y = 0;
1049         if ( options.isGraphicsExportVisibleOnly() ) {
1050             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1051             g2d.setClip( null );
1052             x = visible.x;
1053             y = visible.y;
1054         }
1055         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1056         if ( type == GraphicsExportType.TIFF ) {
1057             writeToTiff( file, buffered_img );
1058         }
1059         else {
1060             ImageIO.write( buffered_img, type.toString(), file );
1061         }
1062         g2d.dispose();
1063         System.gc();
1064         if ( !options.isGraphicsExportUsingActualSize() ) {
1065             tree_panel.getMainPanel().getControlPanel().showWhole();
1066         }
1067         String msg = file.toString();
1068         if ( ( width > 0 ) && ( height > 0 ) ) {
1069             msg += " [size: " + width + ", " + height + "]";
1070         }
1071         return msg;
1072     }
1073
1074     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1075         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1076         ImageWriter writer = null;
1077         ImageOutputStream ios = null;
1078         // Find an appropriate writer:
1079         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1080         if ( it.hasNext() ) {
1081             writer = it.next();
1082         }
1083         else {
1084             throw new IOException( "failed to get TIFF image writer" );
1085         }
1086         // Setup writer:
1087         ios = ImageIO.createImageOutputStream( file );
1088         writer.setOutput( ios );
1089         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1090         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1091         // see writeParam.getCompressionTypes() for available compression type
1092         // strings.
1093         image_write_param.setCompressionType( "PackBits" );
1094         final String t[] = image_write_param.getCompressionTypes();
1095         for( final String string : t ) {
1096             System.out.println( string );
1097         }
1098         // Convert to an IIOImage:
1099         final IIOImage iio_image = new IIOImage( image, null, null );
1100         writer.write( null, iio_image, image_write_param );
1101     }
1102
1103     final static Map<String, Integer> getRankCounts(final Phylogeny tree) {
1104         final Map<String, Integer> present_ranks = new HashMap<String, Integer>();
1105     
1106         if ( ( tree != null ) && !tree.isEmpty() ) {
1107             for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
1108                 final PhylogenyNode n = it.next();
1109                 if ( !n.isExternal() && n.getNodeData().isHasTaxonomy()
1110                         && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) && !n.isRoot() ) {
1111                     final String rank = n.getNodeData().getTaxonomy().getRank().toLowerCase();
1112                     if (present_ranks.containsKey( rank ) ) {
1113                         present_ranks.put( rank, present_ranks.get( rank ) + 1 );
1114                     }
1115                     else {
1116                         present_ranks.put( rank, 1 );
1117                     }
1118                 }
1119             }
1120         }
1121         return present_ranks;
1122     }
1123 }