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