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