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