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