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