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