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