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