rio, lca, refactoring
[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: 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 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
55
56 import javax.imageio.IIOImage;
57 import javax.imageio.ImageIO;
58 import javax.imageio.ImageWriteParam;
59 import javax.imageio.ImageWriter;
60 import javax.imageio.stream.ImageOutputStream;
61 import javax.swing.JApplet;
62 import javax.swing.JOptionPane;
63 import javax.swing.text.MaskFormatter;
64
65 import org.forester.analysis.TaxonomyDataManager;
66 import org.forester.io.parsers.PhylogenyParser;
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.PhylogenyNode;
73 import org.forester.phylogeny.data.Accession;
74 import org.forester.phylogeny.data.BranchColor;
75 import org.forester.phylogeny.data.Distribution;
76 import org.forester.phylogeny.data.Sequence;
77 import org.forester.phylogeny.data.Taxonomy;
78 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
79 import org.forester.phylogeny.factories.PhylogenyFactory;
80 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
81 import org.forester.phylogeny.iterators.PreorderTreeIterator;
82 import org.forester.util.AsciiHistogram;
83 import org.forester.util.DescriptiveStatistics;
84 import org.forester.util.ForesterUtil;
85 import org.forester.ws.seqdb.UniProtTaxonomy;
86
87 public final class AptxUtil {
88
89     private final static Pattern  seq_identifier_pattern_1       = Pattern
90                                                                          .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
91     private final static Pattern  seq_identifier_pattern_2       = Pattern
92                                                                          .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
93     private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
94                                                                          .getAvailableFontFamilyNames();
95     static {
96         Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
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 = AptxUtil.normalizeCharForRGB( first );
217         second = AptxUtil.normalizeCharForRGB( second );
218         third = AptxUtil.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                     AptxUtil.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     private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
270         node.getBranchData().setBranchColor( c );
271         final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
272         for( final PhylogenyNode desc : descs ) {
273             desc.getBranchData().setBranchColor( c );
274         }
275     }
276
277     final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
278         double max_conf = 0.0;
279         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
280             final PhylogenyNode n = it.next();
281             n.getBranchData().setBranchColor( null );
282             if ( n.getBranchData().isHasConfidences() ) {
283                 final double conf = PhylogenyMethods.getConfidenceValue( n );
284                 if ( conf > max_conf ) {
285                     max_conf = conf;
286                 }
287             }
288         }
289         if ( max_conf > 0.0 ) {
290             final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
291             final Color br = tree_panel.getTreeColorSet().getBranchColor();
292             for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
293                 final PhylogenyNode n = it.next();
294                 if ( n.getBranchData().isHasConfidences() ) {
295                     final double conf = PhylogenyMethods.getConfidenceValue( n );
296                     final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
297                     colorizeSubtree( n, c );
298                 }
299             }
300         }
301     }
302
303     final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
304         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
305             it.next().getBranchData().setBranchColor( null );
306         }
307         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
308             final PhylogenyNode n = it.next();
309             if ( !n.getBranchData().isHasBranchColor() ) {
310                 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
311                 if ( tax != null ) {
312                     n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
313                     final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
314                     for( final PhylogenyNode desc : descs ) {
315                         desc.getBranchData()
316                                 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
317                     }
318                 }
319             }
320         }
321     }
322
323     final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
324         final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
325         int colorizations = 0;
326         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
327             final PhylogenyNode n = it.next();
328             if ( n.getNodeData().isHasTaxonomy()
329                     && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
330                             || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
331                                 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
332                 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
333                         && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
334                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
335                             .getTaxonomy() ) );
336                     colorizeSubtree( n, c );
337                     ++colorizations;
338                     if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
339                         true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
340                     }
341                 }
342             }
343         }
344         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
345             final PhylogenyNode node = it.next();
346             if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
347                     && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
348                 boolean success = false;
349                 if ( !true_lineage_to_color_map.isEmpty() ) {
350                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
351                         if ( true_lineage_to_color_map.containsKey( lin ) ) {
352                             colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
353                             ++colorizations;
354                             success = true;
355                             break;
356                         }
357                     }
358                 }
359                 if ( !success ) {
360                     final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
361                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
362                         final Taxonomy temp_tax = new Taxonomy();
363                         temp_tax.setScientificName( lin );
364                         if ( lineage_to_rank_map.containsKey( lin )
365                                 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
366                                 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
367                             final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
368                             colorizeSubtree( node, c );
369                             ++colorizations;
370                             true_lineage_to_color_map.put( lin, c.getValue() );
371                             break;
372                         }
373                         else {
374                             UniProtTaxonomy up = null;
375                             try {
376                                 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
377                             }
378                             catch ( final Exception e ) {
379                                 e.printStackTrace();
380                             }
381                             if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
382                                 lineage_to_rank_map.put( lin, up.getRank() );
383                                 if ( up.getRank().equalsIgnoreCase( rank ) ) {
384                                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
385                                     colorizeSubtree( node, c );
386                                     ++colorizations;
387                                     true_lineage_to_color_map.put( lin, c.getValue() );
388                                     break;
389                                 }
390                             }
391                         }
392                     }
393                 }
394             }
395         }
396         return colorizations;
397     }
398
399     final static String createBasicInformation( final Phylogeny phy ) {
400         final StringBuilder desc = new StringBuilder();
401         if ( ( phy != null ) && !phy.isEmpty() ) {
402             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
403                 desc.append( "Name: " );
404                 desc.append( phy.getName() );
405                 desc.append( "\n" );
406             }
407             if ( phy.getIdentifier() != null ) {
408                 desc.append( "Id: " );
409                 desc.append( phy.getIdentifier() );
410                 desc.append( "\n" );
411             }
412             desc.append( "Rooted: " );
413             desc.append( phy.isRooted() );
414             desc.append( "\n" );
415             desc.append( "Rerootable: " );
416             desc.append( phy.isRerootable() );
417             desc.append( "\n" );
418             desc.append( "Node sum: " );
419             desc.append( phy.getNodeCount() );
420             desc.append( "\n" );
421             desc.append( "External node sum: " );
422             desc.append( phy.getNumberOfExternalNodes() );
423             desc.append( "\n" );
424             desc.append( "Internal node sum: " );
425             desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
426             desc.append( "\n" );
427             desc.append( "Branche sum: " );
428             desc.append( phy.getNumberOfBranches() );
429             desc.append( "\n" );
430             desc.append( "Depth: " );
431             desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
432             desc.append( "\n" );
433             desc.append( "Maximum distance to root: " );
434             desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
435             desc.append( "\n" );
436             final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
437             if ( taxs != null ) {
438                 desc.append( "Distinct external taxonomies: " );
439                 desc.append( taxs.size() );
440             }
441             desc.append( "\n" );
442             final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
443             if ( bs.getN() > 3 ) {
444                 desc.append( "\n" );
445                 desc.append( "Branch-length statistics: " );
446                 desc.append( "\n" );
447                 desc.append( "    Number of branches with non-negative branch-lengths: " + bs.getN() );
448                 desc.append( "\n" );
449                 desc.append( "    Median: " + ForesterUtil.round( bs.median(), 6 ) );
450                 desc.append( "\n" );
451                 desc.append( "    Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
452                 desc.append( "\n" );
453                 desc.append( "    SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
454                 desc.append( "\n" );
455                 desc.append( "    Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
456                 desc.append( "\n" );
457                 desc.append( "    Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
458                 desc.append( "\n" );
459                 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
460                     desc.append( "\n" );
461                     final AsciiHistogram histo = new AsciiHistogram( bs );
462                     desc.append( histo.toStringBuffer( 12, '#', 40, 7, "    " ) );
463                 }
464             }
465             final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
466             if ( ds.getN() > 2 ) {
467                 desc.append( "\n" );
468                 desc.append( "Descendants per node statistics: " );
469                 desc.append( "\n" );
470                 desc.append( "    Median: " + ForesterUtil.round( ds.median(), 2 ) );
471                 desc.append( "\n" );
472                 desc.append( "    Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
473                 desc.append( "\n" );
474                 desc.append( "    SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
475                 desc.append( "\n" );
476                 desc.append( "    Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
477                 desc.append( "\n" );
478                 desc.append( "    Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
479                 desc.append( "\n" );
480             }
481             List<DescriptiveStatistics> css = null;
482             try {
483                 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
484             }
485             catch ( final IllegalArgumentException e ) {
486                 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
487             }
488             if ( ( css != null ) && ( css.size() > 0 ) ) {
489                 desc.append( "\n" );
490                 for( int i = 0; i < css.size(); ++i ) {
491                     final DescriptiveStatistics cs = css.get( i );
492                     if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
493                         if ( css.size() > 1 ) {
494                             desc.append( "Support statistics " + ( i + 1 ) + ": " );
495                         }
496                         else {
497                             desc.append( "Support statistics: " );
498                         }
499                         if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
500                             desc.append( "\n" );
501                             desc.append( "    Type: " + cs.getDescription() );
502                         }
503                         desc.append( "\n" );
504                         desc.append( "    Branches with support: " + cs.getN() );
505                         desc.append( "\n" );
506                         desc.append( "    Median: " + ForesterUtil.round( cs.median(), 6 ) );
507                         desc.append( "\n" );
508                         desc.append( "    Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
509                         desc.append( "\n" );
510                         if ( cs.getN() > 2 ) {
511                             desc.append( "    SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
512                             desc.append( "\n" );
513                         }
514                         desc.append( "    Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
515                         desc.append( "\n" );
516                         desc.append( "    Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
517                         desc.append( "\n" );
518                     }
519                 }
520             }
521         }
522         return desc.toString();
523     }
524
525     public static MaskFormatter createMaskFormatter( final String s ) {
526         MaskFormatter formatter = null;
527         try {
528             formatter = new MaskFormatter( s );
529         }
530         catch ( final ParseException e ) {
531             throw new IllegalArgumentException( e );
532         }
533         return formatter;
534     }
535
536     /**
537      * Exits with -1.
538      * 
539      * 
540      * @param message
541      *            to message to be printed
542      */
543     final static void dieWithSystemError( final String message ) {
544         System.out.println();
545         System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
546         System.out.println( "Please contact the authors." );
547         System.out.println( Constants.PRG_NAME + " needs to close." );
548         System.out.println();
549         System.exit( -1 );
550     }
551
552     final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
553         if ( !node.getNodeData().isHasDate() ) {
554             node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
555         }
556     }
557
558     final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
559         if ( !node.getNodeData().isHasDistribution() ) {
560             node.getNodeData().setDistribution( new Distribution( "" ) );
561         }
562     }
563
564     public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
565         if ( !node.getNodeData().isHasSequence() ) {
566             node.getNodeData().setSequence( new Sequence() );
567         }
568     }
569
570     public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
571         if ( !node.getNodeData().isHasTaxonomy() ) {
572             node.getNodeData().setTaxonomy( new Taxonomy() );
573         }
574     }
575
576     public static String[] getAllPossibleRanks() {
577         final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
578         int i = 0;
579         for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
580             if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
581                 str_array[ i++ ] = e;
582             }
583         }
584         return str_array;
585     }
586
587     final static String[] getAllRanks( final Phylogeny tree ) {
588         final SortedSet<String> ranks = new TreeSet<String>();
589         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
590             final PhylogenyNode n = it.next();
591             if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
592                 ranks.add( n.getNodeData().getTaxonomy().getRank() );
593             }
594         }
595         return ForesterUtil.stringSetToArray( ranks );
596     }
597
598     final static String[] getAvailableFontFamiliesSorted() {
599         return AVAILABLE_FONT_FAMILIES_SORTED;
600     }
601
602     final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
603         boolean inferred = false;
604         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
605             final PhylogenyNode n = it.next();
606             if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
607                 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
608                 if ( !ForesterUtil.isEmpty( sn ) ) {
609                     n.getNodeData().setTaxonomy( new Taxonomy() );
610                     n.getNodeData().getTaxonomy().setScientificName( sn );
611                     inferred = true;
612                 }
613             }
614         }
615         if ( inferred ) {
616             tree.setRerootable( false );
617         }
618     }
619
620     final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
621         if ( !node.getNodeData().isHasEvent() ) {
622             return false;
623         }
624         if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
625             return false;
626         }
627         return true;
628     }
629
630     final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
631         final PhylogenyNodeIterator it = phy.iteratorPostorder();
632         while ( it.hasNext() ) {
633             if ( it.next().getNodeData().isHasEvent() ) {
634                 return true;
635             }
636         }
637         return false;
638     }
639
640     /**
641      * Returns true if at least one branch has a length larger than zero.
642      * 
643      * 
644      * @param phy
645      */
646     final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
647         final PhylogenyNodeIterator it = phy.iteratorPostorder();
648         while ( it.hasNext() ) {
649             if ( it.next().getDistanceToParent() > 0.0 ) {
650                 return true;
651             }
652         }
653         return false;
654     }
655
656     final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
657         final PhylogenyNodeIterator it = phy.iteratorPostorder();
658         while ( it.hasNext() ) {
659             if ( it.next().getBranchData().isHasConfidences() ) {
660                 return true;
661             }
662         }
663         return false;
664     }
665
666     final static boolean isJava15() {
667         try {
668             final String s = ForesterUtil.JAVA_VERSION;
669             return s.startsWith( "1.5" );
670         }
671         catch ( final Exception e ) {
672             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
673             return false;
674         }
675     }
676
677     final static boolean isMac() {
678         try {
679             final String s = ForesterUtil.OS_NAME.toLowerCase();
680             return s.startsWith( "mac" );
681         }
682         catch ( final Exception e ) {
683             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
684             return false;
685         }
686     }
687
688     final static boolean isUsOrCanada() {
689         try {
690             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
691                 return true;
692             }
693         }
694         catch ( final Exception e ) {
695             return false;
696         }
697         return false;
698     }
699
700     final static boolean isWindows() {
701         try {
702             final String s = ForesterUtil.OS_NAME.toLowerCase();
703             return s.indexOf( "win" ) > -1;
704         }
705         catch ( final Exception e ) {
706             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
707             return false;
708         }
709     }
710
711     final public static void launchWebBrowser( final URI uri,
712                                                final boolean is_applet,
713                                                final JApplet applet,
714                                                final String frame_name ) throws IOException {
715         if ( is_applet ) {
716             applet.getAppletContext().showDocument( uri.toURL(), frame_name );
717         }
718         else {
719             // This requires Java 1.6:
720             // =======================
721             // boolean no_desktop = false;
722             // try {
723             // if ( Desktop.isDesktopSupported() ) {
724             // System.out.println( "desktop supported" );
725             // final Desktop dt = Desktop.getDesktop();
726             // dt.browse( uri );
727             // }
728             // else {
729             // no_desktop = true;
730             // }
731             // }
732             // catch ( final Exception ex ) {
733             // ex.printStackTrace();
734             // no_desktop = true;
735             // }
736             // catch ( final Error er ) {
737             // er.printStackTrace();
738             // no_desktop = true;
739             // }
740             // if ( no_desktop ) {
741             // System.out.println( "desktop not supported" );
742             try {
743                 openUrlInWebBrowser( uri.toString() );
744             }
745             catch ( final Exception e ) {
746                 throw new IOException( e );
747             }
748             // }
749         }
750     }
751
752     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
753                                                                       final ControlPanel atv_control,
754                                                                       final Configuration configuration ) {
755         if ( ( t != null ) && !t.isEmpty() ) {
756             if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
757                 atv_control.setDrawPhylogram( false );
758                 atv_control.setDrawPhylogramEnabled( false );
759             }
760             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
761                 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
762                     if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
763                         atv_control.setDrawPhylogram( true );
764                         atv_control.setDrawPhylogramEnabled( true );
765                     }
766                     else {
767                         atv_control.setDrawPhylogram( false );
768                     }
769                 }
770             }
771             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
772                 if ( atv_control.getWriteConfidenceCb() != null ) {
773                     if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
774                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
775                     }
776                     else {
777                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
778                     }
779                 }
780             }
781             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
782                 if ( atv_control.getShowEventsCb() != null ) {
783                     if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
784                         atv_control.setCheckbox( Configuration.write_events, true );
785                     }
786                     else {
787                         atv_control.setCheckbox( Configuration.write_events, false );
788                     }
789                 }
790             }
791         }
792     }
793
794     final private static char normalizeCharForRGB( char c ) {
795         c -= 65;
796         c *= 10.2;
797         c = c > 255 ? 255 : c;
798         c = c < 0 ? 0 : c;
799         return c;
800     }
801
802     public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
803         final String n = sequence_name.trim();
804         final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
805         String group1 = "";
806         String group2 = "";
807         if ( matcher1.matches() ) {
808             group1 = matcher1.group( 1 );
809             group2 = matcher1.group( 2 );
810         }
811         else {
812             final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
813             if ( matcher2.matches() ) {
814                 group1 = matcher2.group( 1 );
815                 group2 = matcher2.group( 2 );
816             }
817         }
818         if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
819             return null;
820         }
821         return new Accession( group2, group1 );
822     }
823
824     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
825             SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
826             InvocationTargetException, InterruptedException {
827         final String os = System.getProperty( "os.name" );
828         final Runtime runtime = Runtime.getRuntime();
829         if ( os.toLowerCase().startsWith( "win" ) ) {
830             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
831         }
832         else if ( isMac() ) {
833             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
834             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
835             open_url.invoke( null, new Object[] { url } );
836         }
837         else {
838             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
839             String browser = null;
840             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
841                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
842                     browser = browsers[ i ];
843                 }
844             }
845             if ( browser == null ) {
846                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
847             }
848             else {
849                 runtime.exec( new String[] { browser, url } );
850             }
851         }
852     }
853
854     final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
855         try {
856             AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
857         }
858         catch ( final Exception e ) {
859             throw new IOException( e );
860         }
861     }
862
863     final static void printAppletMessage( final String applet_name, final String message ) {
864         System.out.println( "[" + applet_name + "] > " + message );
865     }
866
867     public final static void printWarningMessage( final String name, final String message ) {
868         System.out.println( "[" + name + "] > " + message );
869     }
870
871     final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
872             throws FileNotFoundException, IOException {
873         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
874         PhylogenyParser parser = null;
875         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
876             parser = new TolParser();
877         }
878         else {
879             parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
880         }
881         return factory.create( url.openStream(), parser );
882     }
883
884     final static void removeBranchColors( final Phylogeny phy ) {
885         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
886             it.next().getBranchData().setBranchColor( null );
887         }
888     }
889
890     final public static void showErrorMessage( final Component parent, final String error_msg ) {
891         printAppletMessage( Constants.PRG_NAME, error_msg );
892         JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
893                 + "] Error", JOptionPane.ERROR_MESSAGE );
894     }
895
896     public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
897                                                                     final PhylogenyNode node,
898                                                                     final List<String> data ) {
899         final StringBuilder sb = new StringBuilder();
900         if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
901             showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
902         }
903         if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
904                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
905             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
906         }
907         if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
908                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
909             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
910         }
911         if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
912                 && ( node.getNodeData().getSequence().getAccession() != null )
913                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
914             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
915         }
916         if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
917                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
918             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
919         }
920         if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
921                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
922             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
923         }
924         if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
925                 && node.getNodeData().isHasSequence()
926                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
927             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
928         }
929         final String s = sb.toString().trim();
930         if ( !ForesterUtil.isEmpty( s ) ) {
931             data.add( s );
932         }
933     }
934
935     public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
936         if ( sb.length() > 0 ) {
937             sb.append( "\t" );
938         }
939         sb.append( s );
940     }
941
942     final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
943         JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
944     }
945
946     final static void unexpectedError( final Error err ) {
947         err.printStackTrace();
948         final StringBuffer sb = new StringBuffer();
949         for( final StackTraceElement s : err.getStackTrace() ) {
950             sb.append( s + "\n" );
951         }
952         JOptionPane
953                 .showMessageDialog( null,
954                                     "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
955                                             + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
956                                     "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
957                                     JOptionPane.ERROR_MESSAGE );
958         System.exit( -1 );
959     }
960
961     final static void unexpectedException( final Exception ex ) {
962         ex.printStackTrace();
963         final StringBuffer sb = new StringBuffer();
964         for( final StackTraceElement s : ex.getStackTrace() ) {
965             sb.append( s + "\n" );
966         }
967         JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
968                 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
969                 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
970     }
971
972     final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
973                                                                        int width,
974                                                                        int height,
975                                                                        final TreePanel tree_panel,
976                                                                        final ControlPanel ac,
977                                                                        final GraphicsExportType type,
978                                                                        final Options options ) throws IOException {
979         if ( !options.isGraphicsExportUsingActualSize() ) {
980             if ( options.isGraphicsExportVisibleOnly() ) {
981                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
982             }
983             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
984             tree_panel.resetPreferredSize();
985             tree_panel.repaint();
986         }
987         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
988                                                                    RenderingHints.VALUE_RENDER_QUALITY );
989         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
990         if ( options.isAntialiasPrint() ) {
991             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
992             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
993         }
994         else {
995             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
996             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
997         }
998         final Phylogeny phylogeny = tree_panel.getPhylogeny();
999         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1000             return "";
1001         }
1002         Rectangle visible = null;
1003         if ( !options.isGraphicsExportUsingActualSize() ) {
1004             width = options.getPrintSizeX();
1005             height = options.getPrintSizeY();
1006         }
1007         else if ( options.isGraphicsExportVisibleOnly() ) {
1008             visible = tree_panel.getVisibleRect();
1009             width = visible.width;
1010             height = visible.height;
1011         }
1012         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1013         Graphics2D g2d = buffered_img.createGraphics();
1014         g2d.setRenderingHints( rendering_hints );
1015         int x = 0;
1016         int y = 0;
1017         if ( options.isGraphicsExportVisibleOnly() ) {
1018             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1019             g2d.setClip( null );
1020             x = visible.x;
1021             y = visible.y;
1022         }
1023         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1024         ImageIO.write( buffered_img, type.toString(), baos );
1025         g2d.dispose();
1026         System.gc();
1027         if ( !options.isGraphicsExportUsingActualSize() ) {
1028             tree_panel.getMainPanel().getControlPanel().showWhole();
1029         }
1030         String msg = baos.toString();
1031         if ( ( width > 0 ) && ( height > 0 ) ) {
1032             msg += " [size: " + width + ", " + height + "]";
1033         }
1034         return msg;
1035     }
1036
1037     public static void writePhylogenyToGraphicsFile( final File intree,
1038                                                      final File outfile,
1039                                                      final int width,
1040                                                      final int height,
1041                                                      final GraphicsExportType type,
1042                                                      final Configuration config ) throws IOException {
1043         final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
1044         Phylogeny[] phys = null;
1045         phys = PhylogenyMethods.readPhylogenies( parser, intree );
1046         writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
1047     }
1048
1049     public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
1050                                                      final File outfile,
1051                                                      final int width,
1052                                                      final int height,
1053                                                      final GraphicsExportType type,
1054                                                      final Configuration config ) throws IOException {
1055         final Phylogeny[] phys = new Phylogeny[ 1 ];
1056         phys[ 0 ] = phy;
1057         final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
1058         AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
1059                 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
1060         mf.end();
1061     }
1062
1063     final static String writePhylogenyToGraphicsFile( final String file_name,
1064                                                       int width,
1065                                                       int height,
1066                                                       final TreePanel tree_panel,
1067                                                       final ControlPanel ac,
1068                                                       final GraphicsExportType type,
1069                                                       final Options options ) throws IOException {
1070         if ( !options.isGraphicsExportUsingActualSize() ) {
1071             if ( options.isGraphicsExportVisibleOnly() ) {
1072                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1073             }
1074             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1075             tree_panel.resetPreferredSize();
1076             tree_panel.repaint();
1077         }
1078         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1079                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1080         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1081         if ( options.isAntialiasPrint() ) {
1082             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1083             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1084         }
1085         else {
1086             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1087             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1088         }
1089         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1090         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1091             return "";
1092         }
1093         final File file = new File( file_name );
1094         if ( file.isDirectory() ) {
1095             throw new IOException( "\"" + file_name + "\" is a directory" );
1096         }
1097         Rectangle visible = null;
1098         if ( !options.isGraphicsExportUsingActualSize() ) {
1099             width = options.getPrintSizeX();
1100             height = options.getPrintSizeY();
1101         }
1102         else if ( options.isGraphicsExportVisibleOnly() ) {
1103             visible = tree_panel.getVisibleRect();
1104             width = visible.width;
1105             height = visible.height;
1106         }
1107         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1108         Graphics2D g2d = buffered_img.createGraphics();
1109         g2d.setRenderingHints( rendering_hints );
1110         int x = 0;
1111         int y = 0;
1112         if ( options.isGraphicsExportVisibleOnly() ) {
1113             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1114             g2d.setClip( null );
1115             x = visible.x;
1116             y = visible.y;
1117         }
1118         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1119         if ( type == GraphicsExportType.TIFF ) {
1120             writeToTiff( file, buffered_img );
1121         }
1122         else {
1123             ImageIO.write( buffered_img, type.toString(), file );
1124         }
1125         g2d.dispose();
1126         System.gc();
1127         if ( !options.isGraphicsExportUsingActualSize() ) {
1128             tree_panel.getMainPanel().getControlPanel().showWhole();
1129         }
1130         String msg = file.toString();
1131         if ( ( width > 0 ) && ( height > 0 ) ) {
1132             msg += " [size: " + width + ", " + height + "]";
1133         }
1134         return msg;
1135     }
1136
1137     public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
1138                                                                          final int width,
1139                                                                          final int height,
1140                                                                          final TreePanel tree_panel,
1141                                                                          final ControlPanel ac,
1142                                                                          final GraphicsExportType type,
1143                                                                          final Options options ) throws IOException {
1144         tree_panel.setParametersForPainting( width, height, true );
1145         tree_panel.resetPreferredSize();
1146         tree_panel.repaint();
1147         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1148                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1149         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1150         if ( options.isAntialiasPrint() ) {
1151             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1152             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1153         }
1154         else {
1155             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1156             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1157         }
1158         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1159         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1160             return;
1161         }
1162         if ( outfile.isDirectory() ) {
1163             throw new IOException( "\"" + outfile + "\" is a directory" );
1164         }
1165         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1166         final Graphics2D g2d = buffered_img.createGraphics();
1167         g2d.setRenderingHints( rendering_hints );
1168         tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
1169         if ( type == GraphicsExportType.TIFF ) {
1170             writeToTiff( outfile, buffered_img );
1171         }
1172         else {
1173             ImageIO.write( buffered_img, type.toString(), outfile );
1174         }
1175         g2d.dispose();
1176     }
1177
1178     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1179         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1180         ImageWriter writer = null;
1181         ImageOutputStream ios = null;
1182         // Find an appropriate writer:
1183         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1184         if ( it.hasNext() ) {
1185             writer = it.next();
1186         }
1187         else {
1188             throw new IOException( "failed to get TIFF image writer" );
1189         }
1190         // Setup writer:
1191         ios = ImageIO.createImageOutputStream( file );
1192         writer.setOutput( ios );
1193         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1194         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1195         // see writeParam.getCompressionTypes() for available compression type
1196         // strings.
1197         image_write_param.setCompressionType( "PackBits" );
1198         final String t[] = image_write_param.getCompressionTypes();
1199         for( final String string : t ) {
1200             System.out.println( string );
1201         }
1202         // Convert to an IIOImage:
1203         final IIOImage iio_image = new IIOImage( image, null, null );
1204         writer.write( null, iio_image, image_write_param );
1205     }
1206
1207     // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1208     // static void openDDBJRest() throws IOException {
1209     // //set URL
1210     // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1211     // //set parameter
1212     // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1213     // //make connection
1214     // URLConnection urlc = url.openConnection();
1215     // //use post mode
1216     // urlc.setDoOutput( true );
1217     // urlc.setAllowUserInteraction( false );
1218     // //send query
1219     // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1220     // ps.print( query );
1221     // ps.close();
1222     // //get result
1223     // BufferedReader br = new BufferedReader( new InputStreamReader(
1224     // urlc.getInputStream() ) );
1225     // String l = null;
1226     // while ( ( l = br.readLine() ) != null ) {
1227     // System.out.println( l );
1228     // }
1229     // br.close();
1230     // }
1231     public static enum GraphicsExportType {
1232         GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1233
1234         private final String _suffix;
1235
1236         private GraphicsExportType( final String suffix ) {
1237             _suffix = suffix;
1238         }
1239
1240         @Override
1241         public String toString() {
1242             return _suffix;
1243         }
1244     }
1245 }