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