minor improvements and bug-fixes
[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.HashSet;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Locale;
51 import java.util.Set;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
54
55 import javax.imageio.IIOImage;
56 import javax.imageio.ImageIO;
57 import javax.imageio.ImageWriteParam;
58 import javax.imageio.ImageWriter;
59 import javax.imageio.stream.ImageOutputStream;
60 import javax.swing.JApplet;
61 import javax.swing.JOptionPane;
62 import javax.swing.text.MaskFormatter;
63
64 import org.forester.io.parsers.PhylogenyParser;
65 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
66 import org.forester.io.parsers.nhx.NHXParser;
67 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
68 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
69 import org.forester.io.parsers.tol.TolParser;
70 import org.forester.io.parsers.util.ParserUtils;
71 import org.forester.phylogeny.Phylogeny;
72 import org.forester.phylogeny.PhylogenyMethods;
73 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
74 import org.forester.phylogeny.PhylogenyNode;
75 import org.forester.phylogeny.data.BranchWidth;
76 import org.forester.phylogeny.data.Confidence;
77 import org.forester.phylogeny.data.Taxonomy;
78 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
79 import org.forester.util.AsciiHistogram;
80 import org.forester.util.DescriptiveStatistics;
81 import org.forester.util.ForesterUtil;
82
83 public final class AptxUtil {
84
85     public static enum GraphicsExportType {
86         BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
87
88         private final String _suffix;
89
90         private GraphicsExportType( final String suffix ) {
91             _suffix = suffix;
92         }
93
94         @Override
95         public String toString() {
96             return _suffix;
97         }
98     }
99     private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
100             .getAvailableFontFamilyNames();
101     static {
102         Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
103     }
104
105     final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
106         final String my_str = str.toUpperCase();
107         char first = my_str.charAt( 0 );
108         char second = ' ';
109         char third = ' ';
110         if ( my_str.length() > 1 ) {
111             if ( is_taxonomy ) {
112                 second = my_str.charAt( 1 );
113             }
114             else {
115                 second = my_str.charAt( my_str.length() - 1 );
116             }
117             if ( is_taxonomy ) {
118                 if ( my_str.length() > 2 ) {
119                     if ( my_str.indexOf( " " ) > 0 ) {
120                         third = my_str.charAt( my_str.indexOf( " " ) + 1 );
121                     }
122                     else {
123                         third = my_str.charAt( 2 );
124                     }
125                 }
126             }
127             else if ( my_str.length() > 2 ) {
128                 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
129             }
130         }
131         first = normalizeCharForRGB( first );
132         second = normalizeCharForRGB( second );
133         third = normalizeCharForRGB( third );
134         if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
135             first = 0;
136         }
137         else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
138             second = 255;
139         }
140         return new Color( first, second, third );
141     }
142
143     public static MaskFormatter createMaskFormatter( final String s ) {
144         MaskFormatter formatter = null;
145         try {
146             formatter = new MaskFormatter( s );
147         }
148         catch ( final ParseException e ) {
149             throw new IllegalArgumentException( e );
150         }
151         return formatter;
152     }
153
154     final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
155         final PhylogenyNodeIterator it = phy.iteratorPostorder();
156         while ( it.hasNext() ) {
157             if ( it.next().getNodeData().isHasEvent() ) {
158                 return true;
159             }
160         }
161         return false;
162     }
163
164     /**
165      * Returns true if at least one branch has a length larger than zero.
166      *
167      *
168      * @param phy
169      */
170     final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
171         final PhylogenyNodeIterator it = phy.iteratorPostorder();
172         while ( it.hasNext() ) {
173             if ( it.next().getDistanceToParent() > 0.0 ) {
174                 return true;
175             }
176         }
177         return false;
178     }
179     
180     final static public boolean isHasNoBranchLengthSmallerThanZero( final Phylogeny phy ) {
181         final PhylogenyNodeIterator it = phy.iteratorPostorder();
182         while ( it.hasNext() ) {
183             final PhylogenyNode n = it.next(); 
184             if ( n.getDistanceToParent() < 0.0 && !n.isRoot() ) {
185                 return false;
186             }
187         }
188         return true;
189     }
190
191     final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
192         final PhylogenyNodeIterator it = phy.iteratorPostorder();
193         while ( it.hasNext() ) {
194             final PhylogenyNode n = it.next();
195             if ( n.getBranchData().isHasConfidences() ) {
196                 final List<Confidence> c = n.getBranchData().getConfidences();
197                 for( final Confidence confidence : c ) {
198                     if ( confidence.getStandardDeviation() > 0 ) {
199                         return true;
200                     }
201                 }
202             }
203         }
204         return false;
205     }
206
207     final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
208         final PhylogenyNodeIterator it = phy.iteratorPostorder();
209         while ( it.hasNext() ) {
210             if ( it.next().getBranchData().isHasConfidences() ) {
211                 return true;
212             }
213         }
214         return false;
215     }
216
217     final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
218         final PhylogenyNodeIterator it = phy.iteratorPostorder();
219         while ( it.hasNext() ) {
220             final PhylogenyNode n = it.next();
221             if ( n.getNodeData().isHasTaxonomy()
222                     && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
223                 return true;
224             }
225         }
226         return false;
227     }
228
229     final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
230         final PhylogenyNodeIterator it = phy.iteratorPostorder();
231         while ( it.hasNext() ) {
232             final PhylogenyNode n = it.next();
233             if ( n.getNodeData().isHasSequence()
234                     && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
235                 return true;
236             }
237         }
238         return false;
239     }
240
241     final public static void launchWebBrowser( final URI uri,
242                                                final boolean is_applet,
243                                                final JApplet applet,
244                                                final String frame_name ) throws IOException {
245         if ( is_applet ) {
246             applet.getAppletContext().showDocument( uri.toURL(), frame_name );
247         }
248         else {
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[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
746         int i = 0;
747         for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
748             if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
749                 str_array[ i++ ] = e;
750             }
751         }
752         return str_array;
753     }
754
755     final static String[] getAllRanks( final Phylogeny tree ) {
756         final SortedSet<String> ranks = new TreeSet<String>();
757         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
758             final PhylogenyNode n = it.next();
759             if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
760                 ranks.add( n.getNodeData().getTaxonomy().getRank() );
761             }
762         }
763         return ForesterUtil.stringSetToArray( ranks );
764     }
765
766     final static String[] getAvailableFontFamiliesSorted() {
767         return AVAILABLE_FONT_FAMILIES_SORTED;
768     }
769
770     final static boolean isUsOrCanada() {
771         try {
772             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
773                 return true;
774             }
775         }
776         catch ( final Exception e ) {
777             return false;
778         }
779         return false;
780     }
781     final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t,
782                                                                      final ControlPanel cp ) {
783         if ( ( t != null ) && !t.isEmpty() ) {
784             final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
785              
786             if ( !has_bl ) {
787                 cp.setDrawPhylogram( false );
788                 cp.setDrawPhylogramEnabled( false );
789             }
790             else {
791                 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
792                 cp.setDrawPhylogram(  has_all_bl );
793                 if ( cp.getDisplayAsPhylogramCb() != null ) {
794                     cp.setDrawPhylogramEnabled( true );
795                 }
796             }
797         }
798     }
799     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
800                                                                       final ControlPanel atv_control,
801                                                                       final Configuration configuration ) {
802         if ( ( t != null ) && !t.isEmpty() ) {
803             final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
804             if ( !has_bl ) {
805                 atv_control.setDrawPhylogram( false );
806                 atv_control.setDrawPhylogramEnabled( false );
807             }
808             if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
809                     && atv_control.getUseVisualStylesCb() != null ) {
810                 atv_control.getUseVisualStylesCb().setSelected( true );
811             }
812             if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
813                     && t.getFirstExternalNode().getBranchData().getBranchWidth().getValue()
814                     != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
815                     && atv_control.getUseBranchWidthsCb() != null ) {
816                 atv_control.getUseBranchWidthsCb().setSelected( true );
817             }
818             
819             
820             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
821                 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
822                     if ( has_bl ) {
823                         final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
824                         
825                         atv_control.setDrawPhylogram( has_all_bl );
826                         atv_control.setDrawPhylogramEnabled( true );
827                     }
828                     else {
829                         atv_control.setDrawPhylogram( false );
830                     }
831                 }
832             }
833             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
834                 if ( atv_control.getWriteConfidenceCb() != null ) {
835                     if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
836                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
837                     }
838                     else {
839                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
840                     }
841                 }
842             }
843             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
844                 if ( atv_control.getShowEventsCb() != null ) {
845                     if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
846                         atv_control.setCheckbox( Configuration.write_events, true );
847                     }
848                     else {
849                         atv_control.setCheckbox( Configuration.write_events, false );
850                     }
851                 }
852             }
853         }
854     }
855
856     final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
857         try {
858             AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, AptxConstants.PRG_NAME );
859         }
860         catch ( final Exception e ) {
861             throw new IOException( e );
862         }
863     }
864
865     final static void outOfMemoryError( final OutOfMemoryError e ) {
866         System.err.println();
867         System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
868         System.err.println();
869         e.printStackTrace();
870         System.err.println();
871         JOptionPane.showMessageDialog( null,
872                                        "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
873                                                + "\n\nError: " + e.getLocalizedMessage(),
874                                                "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
875                                                JOptionPane.ERROR_MESSAGE );
876         System.exit( -1 );
877     }
878
879     final static void printAppletMessage( final String applet_name, final String message ) {
880         System.out.println( "[" + applet_name + "] > " + message );
881     }
882
883     final static void removeBranchColors( final Phylogeny phy ) {
884         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
885             it.next().getBranchData().setBranchColor( null );
886         }
887     }
888
889     final static void removeVisualStyles( final Phylogeny phy ) {
890         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
891             it.next().getNodeData().setNodeVisualData( null );
892         }
893     }
894
895     final static void unexpectedError( final Error e ) {
896         System.err.println();
897         e.printStackTrace( System.err );
898         System.err.println();
899         final StringBuffer sb = new StringBuffer();
900         for( final StackTraceElement s : e.getStackTrace() ) {
901             sb.append( s + "\n" );
902         }
903         JOptionPane
904         .showMessageDialog( null,
905                             "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
906                                     + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
907                                     + sb,
908                                     "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
909                                     JOptionPane.ERROR_MESSAGE );
910         System.exit( -1 );
911     }
912
913     final static void unexpectedException( final Exception 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.showMessageDialog( null,
922                                        "An unexpected exception has occured. \nPlease contact: "
923                                                + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
924                                                + "\n" + sb,
925                                                "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
926                                                JOptionPane.ERROR_MESSAGE );
927     }
928
929     final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
930                                                                        int width,
931                                                                        int height,
932                                                                        final TreePanel tree_panel,
933                                                                        final ControlPanel ac,
934                                                                        final GraphicsExportType type,
935                                                                        final Options options ) throws IOException {
936         
937         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
938                                                                    RenderingHints.VALUE_RENDER_QUALITY );
939         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
940         if ( options.isAntialiasPrint() ) {
941             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
942             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
943         }
944         else {
945             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
946             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
947         }
948         final Phylogeny phylogeny = tree_panel.getPhylogeny();
949         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
950             return "";
951         }
952         Rectangle visible = null;
953 //        if ( !options.isGraphicsExportUsingActualSize() ) {
954 //            width = options.getPrintSizeX();
955 //            height = options.getPrintSizeY();
956 //        }
957        /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
958             visible = tree_panel.getVisibleRect();
959             width = visible.width;
960             height = visible.height;
961         }
962         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
963         Graphics2D g2d = buffered_img.createGraphics();
964         g2d.setRenderingHints( rendering_hints );
965         int x = 0;
966         int y = 0;
967         if ( options.isGraphicsExportVisibleOnly() ) {
968             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
969             g2d.setClip( null );
970             x = visible.x;
971             y = visible.y;
972         }
973         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
974         ImageIO.write( buffered_img, type.toString(), baos );
975         g2d.dispose();
976         System.gc();
977         if ( !options.isGraphicsExportUsingActualSize() ) {
978             tree_panel.getMainPanel().getControlPanel().showWhole();
979         }
980         String msg = baos.toString();
981         if ( ( width > 0 ) && ( height > 0 ) ) {
982             msg += " [size: " + width + ", " + height + "]";
983         }
984         return msg;
985     }
986
987     final static String writePhylogenyToGraphicsFile( final String file_name,
988                                                       int width,
989                                                       int height,
990                                                       final TreePanel tree_panel,
991                                                       final ControlPanel ac,
992                                                       final GraphicsExportType type,
993                                                       final Options options ) throws IOException {
994        
995         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
996                                                                    RenderingHints.VALUE_RENDER_QUALITY );
997         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
998         if ( options.isAntialiasPrint() ) {
999             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1000             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1001         }
1002         else {
1003             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1004             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1005         }
1006         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1007         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1008             return "";
1009         }
1010         final File file = new File( file_name );
1011         if ( file.isDirectory() ) {
1012             throw new IOException( "\"" + file_name + "\" is a directory" );
1013         }
1014         Rectangle visible = null;
1015 //        if ( !options.isGraphicsExportUsingActualSize() ) {
1016 //            width = options.getPrintSizeX();
1017 //            height = options.getPrintSizeY();
1018 //        }
1019         /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1020             visible = tree_panel.getVisibleRect();
1021             width = visible.width;
1022             height = visible.height;
1023         }
1024         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1025         Graphics2D g2d = buffered_img.createGraphics();
1026         g2d.setRenderingHints( rendering_hints );
1027         int x = 0;
1028         int y = 0;
1029         if ( options.isGraphicsExportVisibleOnly() ) {
1030             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1031             g2d.setClip( null );
1032             x = visible.x;
1033             y = visible.y;
1034         }
1035         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1036         if ( type == GraphicsExportType.TIFF ) {
1037             writeToTiff( file, buffered_img );
1038         }
1039         else {
1040             ImageIO.write( buffered_img, type.toString(), file );
1041         }
1042         g2d.dispose();
1043         System.gc();
1044         if ( !options.isGraphicsExportUsingActualSize() ) {
1045             tree_panel.getMainPanel().getControlPanel().showWhole();
1046         }
1047         String msg = file.toString();
1048         if ( ( width > 0 ) && ( height > 0 ) ) {
1049             msg += " [size: " + width + ", " + height + "]";
1050         }
1051         return msg;
1052     }
1053
1054     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1055         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1056         ImageWriter writer = null;
1057         ImageOutputStream ios = null;
1058         // Find an appropriate writer:
1059         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1060         if ( it.hasNext() ) {
1061             writer = it.next();
1062         }
1063         else {
1064             throw new IOException( "failed to get TIFF image writer" );
1065         }
1066         // Setup writer:
1067         ios = ImageIO.createImageOutputStream( file );
1068         writer.setOutput( ios );
1069         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1070         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1071         // see writeParam.getCompressionTypes() for available compression type
1072         // strings.
1073         image_write_param.setCompressionType( "PackBits" );
1074         final String t[] = image_write_param.getCompressionTypes();
1075         for( final String string : t ) {
1076             System.out.println( string );
1077         }
1078         // Convert to an IIOImage:
1079         final IIOImage iio_image = new IIOImage( image, null, null );
1080         writer.write( null, iio_image, image_write_param );
1081     }
1082 }