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