removed applet code
[jalview.git] / forester / java / src / org / forester / archaeopteryx / AptxUtil.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
25
26 package org.forester.archaeopteryx;
27
28 import java.awt.Color;
29 import java.awt.Component;
30 import java.awt.Graphics2D;
31 import java.awt.GraphicsEnvironment;
32 import java.awt.Rectangle;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.io.ByteArrayOutputStream;
36 import java.io.File;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.lang.reflect.InvocationTargetException;
40 import java.lang.reflect.Method;
41 import java.net.URI;
42 import java.net.URL;
43 import java.security.KeyManagementException;
44 import java.security.NoSuchAlgorithmException;
45 import java.text.ParseException;
46 import java.util.Arrays;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Locale;
52 import java.util.Map;
53 import java.util.Set;
54 import java.util.SortedSet;
55 import java.util.TreeSet;
56
57 import javax.imageio.IIOImage;
58 import javax.imageio.ImageIO;
59 import javax.imageio.ImageWriteParam;
60 import javax.imageio.ImageWriter;
61 import javax.imageio.stream.ImageOutputStream;
62 import javax.swing.JOptionPane;
63 import javax.swing.text.MaskFormatter;
64
65 import org.forester.archaeopteryx.ControlPanel.TreeDisplayType;
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 String frame_name ) throws IOException {
248        
249             // This requires Java 1.6:
250             // =======================
251             // boolean no_desktop = false;
252             // try {
253             // if ( Desktop.isDesktopSupported() ) {
254             // System.out.println( "desktop supported" );
255             // final Desktop dt = Desktop.getDesktop();
256             // dt.browse( uri );
257             // }
258             // else {
259             // no_desktop = true;
260             // }
261             // }
262             // catch ( final Exception ex ) {
263             // ex.printStackTrace();
264             // no_desktop = true;
265             // }
266             // catch ( final Error er ) {
267             // er.printStackTrace();
268             // no_desktop = true;
269             // }
270             // if ( no_desktop ) {
271             // System.out.println( "desktop not supported" );
272             try {
273                 openUrlInWebBrowser( uri.toString() );
274             }
275             catch ( final Exception e ) {
276                 throw new IOException( e );
277             }
278             // }
279         
280     }
281
282     public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
283         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
284         final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
285         for( final PhylogenyNode n : descs ) {
286             if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
287                 tax_set.add( n.getNodeData().getTaxonomy() );
288             }
289         }
290         return tax_set;
291     }
292
293     public final static void printWarningMessage( final String name, final String message ) {
294         System.out.println( "[" + name + "] > " + message );
295     }
296
297     final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
298                                                             final boolean phyloxml_validate_against_xsd,
299                                                             final boolean replace_underscores,
300                                                             final boolean internal_numbers_are_confidences,
301                                                             final TAXONOMY_EXTRACTION taxonomy_extraction,
302                                                             final boolean midpoint_reroot )
303                                                                     throws FileNotFoundException, IOException {
304         final PhylogenyParser parser;
305         boolean nhx_or_nexus = false;
306         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
307             parser = new TolParser();
308         }
309         else {
310             parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
311             if ( parser instanceof NHXParser ) {
312                 nhx_or_nexus = true;
313                 final NHXParser nhx = ( NHXParser ) parser;
314                 nhx.setReplaceUnderscores( replace_underscores );
315                 nhx.setIgnoreQuotes( false );
316                 nhx.setTaxonomyExtraction( taxonomy_extraction );
317             }
318             else if ( parser instanceof NexusPhylogeniesParser ) {
319                 nhx_or_nexus = true;
320                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
321                 nex.setReplaceUnderscores( replace_underscores );
322                 nex.setIgnoreQuotes( false );
323             }
324         }
325         AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
326         Phylogeny[] phys = null;
327         try {
328             phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
329         }
330         catch ( final KeyManagementException e ) {
331             throw new IOException( e.getMessage() );
332         }
333         catch ( final NoSuchAlgorithmException e ) {
334             throw new IOException( e.getMessage() );
335         }
336         if ( phys != null ) {
337             if ( nhx_or_nexus && internal_numbers_are_confidences ) {
338                 for( final Phylogeny phy : phys ) {
339                     PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
340                 }
341             }
342             if ( midpoint_reroot ) {
343                 for( final Phylogeny phy : phys ) {
344                     PhylogenyMethods.midpointRoot( phy );
345                     PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
346                 }
347             }
348         }
349         return phys;
350     }
351
352     final public static void showErrorMessage( final Component parent, final String error_msg ) {
353         printAppletMessage( AptxConstants.PRG_NAME, error_msg );
354         JOptionPane.showMessageDialog( parent, error_msg, "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
355                                        + "] Error", JOptionPane.ERROR_MESSAGE );
356     }
357
358     public static void writePhylogenyToGraphicsFile( final File intree,
359                                                      final File outfile,
360                                                      final int width,
361                                                      final int height,
362                                                      final GraphicsExportType type,
363                                                      final Configuration config ) throws IOException {
364         final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
365         Phylogeny[] phys = null;
366         phys = PhylogenyMethods.readPhylogenies( parser, intree );
367         writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
368     }
369
370     public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
371                                                      final File outfile,
372                                                      final int width,
373                                                      final int height,
374                                                      final GraphicsExportType type,
375                                                      final Configuration config ) throws IOException {
376         final Phylogeny[] phys = new Phylogeny[ 1 ];
377         phys[ 0 ] = phy;
378         final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
379         AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
380                                                              .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
381         mf.end();
382     }
383
384     public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
385                                                                          final int width,
386                                                                          final int height,
387                                                                          final TreePanel tree_panel,
388                                                                          final ControlPanel ac,
389                                                                          final GraphicsExportType type,
390                                                                          final Options options ) throws IOException {
391         tree_panel.calcParametersForPainting( width, height );
392         tree_panel.resetPreferredSize();
393         tree_panel.repaint();
394         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
395                                                                    RenderingHints.VALUE_RENDER_QUALITY );
396         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
397         if ( options.isAntialiasPrint() ) {
398             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
399             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
400         }
401         else {
402             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
403             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
404         }
405         final Phylogeny phylogeny = tree_panel.getPhylogeny();
406         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
407             return;
408         }
409         if ( outfile.isDirectory() ) {
410             throw new IOException( "\"" + outfile + "\" is a directory" );
411         }
412         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
413         final Graphics2D g2d = buffered_img.createGraphics();
414         g2d.setRenderingHints( rendering_hints );
415         tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
416         if ( type == GraphicsExportType.TIFF ) {
417             writeToTiff( outfile, buffered_img );
418         }
419         else {
420             ImageIO.write( buffered_img, type.toString(), outfile );
421         }
422         g2d.dispose();
423     }
424
425     final private static char normalizeCharForRGB( char c ) {
426         c -= 65;
427         c *= 10.2;
428         c = c > 255 ? 255 : c;
429         c = c < 0 ? 0 : c;
430         return c;
431     }
432
433     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
434     SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
435     InvocationTargetException, InterruptedException {
436         final String os = System.getProperty( "os.name" );
437         final Runtime runtime = Runtime.getRuntime();
438         if ( os.toLowerCase().startsWith( "win" ) ) {
439             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
440         }
441         else if ( ForesterUtil.isMac() ) {
442             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
443             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
444             open_url.invoke( null, new Object[] { url } );
445         }
446         else {
447             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
448             String browser = null;
449             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
450                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
451                     browser = browsers[ i ];
452                 }
453             }
454             if ( browser == null ) {
455                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
456             }
457             else {
458                 runtime.exec( new String[] { browser, url } );
459             }
460         }
461     }
462
463     final static void addPhylogeniesToTabs( final Phylogeny[] phys,
464                                             final String default_name,
465                                             final String full_path,
466                                             final Configuration configuration,
467                                             final MainPanel main_panel ) {
468         if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
469             JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
470                                            + " phylogenies,\ngoing to load only the first " + AptxConstants.MAX_TREES_TO_LOAD, AptxConstants.PRG_NAME
471                                            + " more than " + AptxConstants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
472         }
473         int i = 1;
474         for( final Phylogeny phy : phys ) {
475             if ( !phy.isEmpty() ) {
476                 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
477                     String my_name = "";
478                     String my_name_for_file = "";
479                     if ( phys.length > 1 ) {
480                         if ( !ForesterUtil.isEmpty( default_name ) ) {
481                             my_name = new String( default_name );
482                         }
483                         if ( !ForesterUtil.isEmpty( full_path ) ) {
484                             my_name_for_file = new String( full_path );
485                         }
486                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
487                             my_name_for_file = new String( default_name );
488                         }
489                         String suffix = "";
490                         if ( my_name_for_file.indexOf( '.' ) > 0 ) {
491                             suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
492                                                                  my_name_for_file.length() );
493                             my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
494                         }
495                         if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
496                             my_name_for_file += "_";
497                         }
498                         if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
499                             my_name_for_file += phy.getName().replaceAll( " ", "_" );
500                         }
501                         else if ( phy.getIdentifier() != null ) {
502                             final StringBuffer sb = new StringBuffer();
503                             if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
504                                 sb.append( phy.getIdentifier().getProvider() );
505                                 sb.append( "_" );
506                             }
507                             sb.append( phy.getIdentifier().getValue() );
508                             my_name_for_file += sb;
509                         }
510                         else {
511                             my_name_for_file += i;
512                         }
513                         if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
514                                 && ( phy.getIdentifier() == null ) ) {
515                             my_name = my_name + " [" + i + "]";
516                         }
517                         if ( !ForesterUtil.isEmpty( suffix ) ) {
518                             my_name_for_file += suffix;
519                         }
520                     }
521                     else {
522                         if ( !ForesterUtil.isEmpty( default_name ) ) {
523                             my_name = new String( default_name );
524                         }
525                         my_name_for_file = "";
526                         if ( !ForesterUtil.isEmpty( full_path ) ) {
527                             my_name_for_file = new String( full_path );
528                         }
529                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
530                             my_name_for_file = new String( default_name );
531                         }
532                         if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
533                             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
534                                 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
535                             }
536                             else if ( phy.getIdentifier() != null ) {
537                                 final StringBuffer sb = new StringBuffer();
538                                 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
539                                     sb.append( phy.getIdentifier().getProvider() );
540                                     sb.append( "_" );
541                                 }
542                                 sb.append( phy.getIdentifier().getValue() );
543                                 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
544                             }
545                         }
546                     }
547                     main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
548                     main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
549                     lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
550                     ++i;
551                 }
552             }
553         }
554     }
555
556     final static void addPhylogenyToPanel( final Phylogeny[] phys,
557                                            final Configuration configuration,
558                                            final MainPanel main_panel ) {
559         final Phylogeny phy = phys[ 0 ];
560         main_panel.addPhylogenyInPanel( phy, configuration );
561         lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
562     }
563
564     // Returns true if the specified format name can be written
565     final static boolean canWriteFormat( final String format_name ) {
566         final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
567         return iter.hasNext();
568     }
569
570     final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
571         final StringBuilder desc = new StringBuilder();
572         if ( ( phy != null ) && !phy.isEmpty() ) {
573             String f = null;
574             if ( treefile != null ) {
575                 try {
576                     f = treefile.getCanonicalPath();
577                 }
578                 catch ( final IOException e ) {
579                     //Not important, ignore.
580                 }
581                 if ( !ForesterUtil.isEmpty( f ) ) {
582                     desc.append( "Path: " );
583                     desc.append( f );
584                     desc.append( "\n" );
585                 }
586             }
587             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
588                 desc.append( "Name: " );
589                 desc.append( phy.getName() );
590                 desc.append( "\n" );
591             }
592             if ( phy.getIdentifier() != null ) {
593                 desc.append( "Id: " );
594                 desc.append( phy.getIdentifier().toString() );
595                 desc.append( "\n" );
596             }
597             if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
598                 desc.append( "Description: " );
599                 desc.append( phy.getDescription() );
600                 desc.append( "\n" );
601             }
602             if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
603                 desc.append( "Distance Unit: " );
604                 desc.append( phy.getDistanceUnit() );
605                 desc.append( "\n" );
606             }
607             if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
608                 desc.append( "Type: " );
609                 desc.append( phy.getType() );
610                 desc.append( "\n" );
611             }
612             desc.append( "Rooted: " );
613             desc.append( phy.isRooted() );
614             desc.append( "\n" );
615             desc.append( "Rerootable: " );
616             desc.append( phy.isRerootable() );
617             desc.append( "\n" );
618             desc.append( "Nodes: " );
619             desc.append( phy.getNodeCount() );
620             desc.append( "\n" );
621             desc.append( "External nodes: " );
622             desc.append( phy.getNumberOfExternalNodes() );
623             desc.append( "\n" );
624             desc.append( "Internal nodes: " );
625             desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
626             desc.append( "\n" );
627             desc.append( "Internal nodes with polytomies: " );
628             desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
629             desc.append( "\n" );
630             desc.append( "Branches: " );
631             desc.append( phy.getNumberOfBranches() );
632             desc.append( "\n" );
633             desc.append( "Depth: " );
634             desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
635             desc.append( "\n" );
636             desc.append( "Maximum distance to root: " );
637             desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
638             desc.append( "\n" );
639             final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
640             if ( taxs != null ) {
641                 desc.append( "Distinct external taxonomies: " );
642                 desc.append( taxs.size() );
643             }
644             for( final Taxonomy t : taxs ) {
645                 System.out.println( t.toString() );
646             }
647             desc.append( "\n" );
648             final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
649             if ( bs.getN() > 3 ) {
650                 desc.append( "\n" );
651                 desc.append( "Branch-length statistics: " );
652                 desc.append( "\n" );
653                 desc.append( "    Number of branches with non-negative branch-lengths: " + bs.getN() );
654                 desc.append( "\n" );
655                 desc.append( "    Median: " + ForesterUtil.round( bs.median(), 6 ) );
656                 desc.append( "\n" );
657                 desc.append( "    Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
658                         + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
659                 desc.append( "\n" );
660                 desc.append( "    Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
661                 desc.append( "\n" );
662                 desc.append( "    Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
663                 desc.append( "\n" );
664                 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
665                     desc.append( "\n" );
666                     final AsciiHistogram histo = new AsciiHistogram( bs );
667                     desc.append( histo.toStringBuffer( 12, '#', 40, 7, "    " ) );
668                 }
669             }
670             final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
671             if ( ds.getN() > 2 ) {
672                 desc.append( "\n" );
673                 desc.append( "Descendants per node statistics: " );
674                 desc.append( "\n" );
675                 desc.append( "    Median: " + ForesterUtil.round( ds.median(), 6 ) );
676                 desc.append( "\n" );
677                 desc.append( "    Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
678                         + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
679                 desc.append( "\n" );
680                 desc.append( "    Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
681                 desc.append( "\n" );
682                 desc.append( "    Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
683                 desc.append( "\n" );
684             }
685             List<DescriptiveStatistics> css = null;
686             try {
687                 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
688             }
689             catch ( final IllegalArgumentException e ) {
690                 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
691             }
692             if ( ( css != null ) && ( css.size() > 0 ) ) {
693                 desc.append( "\n" );
694                 for( int i = 0; i < css.size(); ++i ) {
695                     final DescriptiveStatistics cs = css.get( i );
696                     if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
697                         if ( css.size() > 1 ) {
698                             desc.append( "Support statistics " + ( i + 1 ) + ": " );
699                         }
700                         else {
701                             desc.append( "Support statistics: " );
702                         }
703                         if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
704                             desc.append( "\n" );
705                             desc.append( "    Type: " + cs.getDescription() );
706                         }
707                         desc.append( "\n" );
708                         desc.append( "    Branches with support: " + cs.getN() );
709                         desc.append( "\n" );
710                         desc.append( "    Median: " + ForesterUtil.round( cs.median(), 6 ) );
711                         desc.append( "\n" );
712                         desc.append( "    Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
713                         if ( cs.getN() > 2 ) {
714                             desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
715                         }
716                         desc.append( "\n" );
717                         desc.append( "    Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
718                         desc.append( "\n" );
719                         desc.append( "    Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
720                         desc.append( "\n" );
721                     }
722                 }
723             }
724         }
725         return desc.toString();
726     }
727
728     /**
729      * Exits with -1.
730      *
731      *
732      * @param message
733      *            to message to be printed
734      */
735     final static void dieWithSystemError( final String message ) {
736         System.out.println();
737         System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
738         System.out.println( "Please contact the authors." );
739         System.out.println( AptxConstants.PRG_NAME + " needs to close." );
740         System.out.println();
741         System.exit( -1 );
742     }
743
744     final static String[] getAllPossibleRanks() {
745         final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
746         int i = 0;
747         for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
748             if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
749                 str_array[ i++ ] = e;
750             }
751         }
752         return str_array;
753     }
754     
755     final static String[] getAllPossibleRanks(final Map<String, Integer> present_ranks) {
756         final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
757         int i = 0;
758         for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
759             if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
760                 if ( present_ranks != null && present_ranks.containsKey( e ) ) {
761                     str_array[ i++ ] = e + " (" +  present_ranks.get(e) + ")";
762                 }
763                 else {
764                     str_array[ i++ ] = e;
765                 }
766             }
767         }
768         return str_array;
769     }
770
771     final static String[] getAllRanks( final Phylogeny tree ) {
772         final SortedSet<String> ranks = new TreeSet<String>();
773         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
774             final PhylogenyNode n = it.next();
775             if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
776                 ranks.add( n.getNodeData().getTaxonomy().getRank() );
777             }
778         }
779         return ForesterUtil.stringSetToArray( ranks );
780     }
781
782     final static String[] getAvailableFontFamiliesSorted() {
783         return AVAILABLE_FONT_FAMILIES_SORTED;
784     }
785
786     final static boolean isUsOrCanada() {
787         try {
788             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
789                 return true;
790             }
791         }
792         catch ( final Exception e ) {
793             return false;
794         }
795         return false;
796     }
797     final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t,
798                                                                      final ControlPanel cp ) {
799         if ( ( t != null ) && !t.isEmpty() ) {
800             final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
801              
802             if ( !has_bl ) {
803                 cp.setTreeDisplayType( TreeDisplayType.CLADOGRAM );
804                 cp.setDrawPhylogramEnabled( false );
805             }
806             else {
807                 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
808                 if (has_all_bl) {
809                     cp.setTreeDisplayType( TreeDisplayType.UNALIGNED_PHYLOGRAM );
810                 }
811                
812                 if ( cp.getDisplayAsUnalignedPhylogramRb() != null ) {
813                     cp.setDrawPhylogramEnabled( true );
814                 }
815             }
816         }
817     }
818     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
819                                                                       final ControlPanel atv_control,
820                                                                       final Configuration configuration ) {
821         if ( ( t != null ) && !t.isEmpty() ) {
822             final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
823             if ( !has_bl ) {
824                 atv_control.setTreeDisplayType( TreeDisplayType.CLADOGRAM );
825                 atv_control.setDrawPhylogramEnabled( false );
826             }
827             if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
828                     && atv_control.getUseVisualStylesCb() != null ) {
829                 atv_control.getUseVisualStylesCb().setSelected( true );
830             }
831             if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
832                     && t.getFirstExternalNode().getBranchData().getBranchWidth().getValue()
833                     != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
834                     && atv_control.getUseBranchWidthsCb() != null ) {
835                 atv_control.getUseBranchWidthsCb().setSelected( true );
836             }
837             
838             
839             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
840                 if ( atv_control.getDisplayAsAlignedPhylogramRb() != null ) {
841                     if ( has_bl ) {
842                         final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
843                         if (has_all_bl) {
844                             atv_control.setTreeDisplayType( TreeDisplayType.UNALIGNED_PHYLOGRAM );
845                         }
846                        
847                         atv_control.setDrawPhylogramEnabled( true );
848                     }
849                     else {
850                         atv_control.setTreeDisplayType( TreeDisplayType.CLADOGRAM );
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 ) throws IOException {
878         try {
879             AptxUtil.launchWebBrowser( new URI( url ),  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 }