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