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