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