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