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