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