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