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 = ( char ) ( Math.abs( str.hashCode() / 16909320 ) );
570                 System.out.println( str.hashCode() );
571             }
572         }
573         first = AptxUtil.normalizeCharForRGB( first );
574         second = AptxUtil.normalizeCharForRGB( second );
575         if ( is_taxonomy ) {
576             third = AptxUtil.normalizeCharForRGB( third );
577         }
578         else {
579             third = third > 255 ? 255 : third;
580         }
581         if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
582             first = 0;
583         }
584         else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
585             second = 255;
586         }
587         return new Color( first, second, third );
588     }
589
590     // Returns true if the specified format name can be written
591     final static boolean canWriteFormat( final String format_name ) {
592         final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
593         return iter.hasNext();
594     }
595
596     final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
597         boolean inferred = false;
598         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
599             final PhylogenyNode n = it.next();
600             if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
601                 final Set<Taxonomy> taxs = obtainDistinctTaxonomies( n );
602                 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
603                     AptxUtil.collapseSubtree( n, true );
604                     if ( !n.getNodeData().isHasTaxonomy() ) {
605                         n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
606                                 .getTaxonomy().copy() );
607                     }
608                     inferred = true;
609                 }
610                 else {
611                     n.setCollapse( false );
612                 }
613             }
614         }
615         if ( inferred ) {
616             phy.setRerootable( false );
617         }
618     }
619
620     final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
621         node.setCollapse( collapse );
622         if ( node.isExternal() ) {
623             return;
624         }
625         final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
626         while ( it.hasNext() ) {
627             it.next().setCollapse( collapse );
628         }
629     }
630
631     final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
632         double max_conf = 0.0;
633         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
634             final PhylogenyNode n = it.next();
635             n.getBranchData().setBranchColor( null );
636             if ( n.getBranchData().isHasConfidences() ) {
637                 final double conf = PhylogenyMethods.getConfidenceValue( n );
638                 if ( conf > max_conf ) {
639                     max_conf = conf;
640                 }
641             }
642         }
643         if ( max_conf > 0.0 ) {
644             final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
645             final Color br = tree_panel.getTreeColorSet().getBranchColor();
646             for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
647                 final PhylogenyNode n = it.next();
648                 if ( n.getBranchData().isHasConfidences() ) {
649                     final double conf = PhylogenyMethods.getConfidenceValue( n );
650                     final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
651                     colorizeSubtree( n, c );
652                 }
653             }
654         }
655     }
656
657     final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
658         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
659             it.next().getBranchData().setBranchColor( null );
660         }
661         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
662             final PhylogenyNode n = it.next();
663             if ( !n.getBranchData().isHasBranchColor() ) {
664                 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
665                 if ( tax != null ) {
666                     n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
667                     final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
668                     for( final PhylogenyNode desc : descs ) {
669                         desc.getBranchData()
670                                 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
671                     }
672                 }
673             }
674         }
675     }
676
677     final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
678         final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
679         int colorizations = 0;
680         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
681             final PhylogenyNode n = it.next();
682             if ( n.getNodeData().isHasTaxonomy()
683                     && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
684                             || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
685                             .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
686                 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
687                         && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
688                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
689                             .getTaxonomy() ) );
690                     colorizeSubtree( n, c );
691                     ++colorizations;
692                     if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
693                         true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
694                     }
695                 }
696             }
697         }
698         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
699             final PhylogenyNode node = it.next();
700             if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
701                     && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
702                 boolean success = false;
703                 if ( !true_lineage_to_color_map.isEmpty() ) {
704                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
705                         if ( true_lineage_to_color_map.containsKey( lin ) ) {
706                             colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
707                             ++colorizations;
708                             success = true;
709                             break;
710                         }
711                     }
712                 }
713                 if ( !success ) {
714                     final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
715                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
716                         final Taxonomy temp_tax = new Taxonomy();
717                         temp_tax.setScientificName( lin );
718                         if ( lineage_to_rank_map.containsKey( lin )
719                                 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
720                                 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
721                             final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
722                             colorizeSubtree( node, c );
723                             ++colorizations;
724                             true_lineage_to_color_map.put( lin, c.getValue() );
725                             break;
726                         }
727                         else {
728                             UniProtTaxonomy up = null;
729                             try {
730                                 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
731                             }
732                             catch ( final Exception e ) {
733                                 e.printStackTrace();
734                             }
735                             if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
736                                 lineage_to_rank_map.put( lin, up.getRank() );
737                                 if ( up.getRank().equalsIgnoreCase( rank ) ) {
738                                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
739                                     colorizeSubtree( node, c );
740                                     ++colorizations;
741                                     true_lineage_to_color_map.put( lin, c.getValue() );
742                                     break;
743                                 }
744                             }
745                         }
746                     }
747                 }
748             }
749         }
750         return colorizations;
751     }
752
753     final static String createAnnotationString( final SortedSet<Annotation> annotations ) {
754         final SortedMap<String, List<Annotation>> m = new TreeMap<String, List<Annotation>>();
755         for( final Annotation an : annotations ) {
756             final String ref_source = ForesterUtil.isEmpty( an.getRefSource() ) ? "?" : an.getRefSource();
757             if ( !m.containsKey( ref_source ) ) {
758                 m.put( ref_source, new ArrayList<Annotation>() );
759             }
760             m.get( ref_source ).add( an );
761         }
762         final StringBuilder sb = new StringBuilder();
763         for( final Entry<String, List<Annotation>> e : m.entrySet() ) {
764             final String ref_source = e.getKey();
765             final List<Annotation> ans = e.getValue();
766             if ( m.size() > 1 ) {
767                 sb.append( "[" );
768             }
769             if ( !ref_source.equals( "?" ) ) {
770                 sb.append( ref_source );
771                 sb.append( ": " );
772             }
773             for( int i = 0; i < ans.size(); ++i ) {
774                 final Annotation an = ans.get( i );
775                 if ( !ForesterUtil.isEmpty( an.getRefValue() ) ) {
776                     sb.append( an.getRefValue() );
777                     sb.append( " " );
778                 }
779                 if ( !ForesterUtil.isEmpty( an.getDesc() ) ) {
780                     sb.append( an.getDesc() );
781                 }
782                 if ( sb.charAt( sb.length() - 1 ) == ' ' ) {
783                     sb.deleteCharAt( sb.length() - 1 );
784                 }
785                 if ( i < ans.size() - 1 ) {
786                     sb.append( ", " );
787                 }
788             }
789             if ( m.size() > 1 ) {
790                 sb.append( "] " );
791             }
792         }
793         return sb.toString();
794     }
795
796     final static String createBasicInformation( final Phylogeny phy ) {
797         final StringBuilder desc = new StringBuilder();
798         if ( ( phy != null ) && !phy.isEmpty() ) {
799             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
800                 desc.append( "Name: " );
801                 desc.append( phy.getName() );
802                 desc.append( "\n" );
803             }
804             if ( phy.getIdentifier() != null ) {
805                 desc.append( "Id: " );
806                 desc.append( phy.getIdentifier().toString() );
807                 desc.append( "\n" );
808             }
809             if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
810                 desc.append( "Description: " );
811                 desc.append( phy.getDescription() );
812                 desc.append( "\n" );
813             }
814             if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
815                 desc.append( "Distance Unit: " );
816                 desc.append( phy.getDistanceUnit() );
817                 desc.append( "\n" );
818             }
819             if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
820                 desc.append( "Type: " );
821                 desc.append( phy.getType() );
822                 desc.append( "\n" );
823             }
824             desc.append( "Rooted: " );
825             desc.append( phy.isRooted() );
826             desc.append( "\n" );
827             desc.append( "Rerootable: " );
828             desc.append( phy.isRerootable() );
829             desc.append( "\n" );
830             desc.append( "Nodes: " );
831             desc.append( phy.getNodeCount() );
832             desc.append( "\n" );
833             desc.append( "External nodes: " );
834             desc.append( phy.getNumberOfExternalNodes() );
835             desc.append( "\n" );
836             desc.append( "Internal nodes: " );
837             desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
838             desc.append( "\n" );
839             desc.append( "Internal nodes with polytomies: " );
840             desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
841             desc.append( "\n" );
842             desc.append( "Branches: " );
843             desc.append( phy.getNumberOfBranches() );
844             desc.append( "\n" );
845             desc.append( "Depth: " );
846             desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
847             desc.append( "\n" );
848             desc.append( "Maximum distance to root: " );
849             desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
850             desc.append( "\n" );
851             final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
852             if ( taxs != null ) {
853                 desc.append( "Distinct external taxonomies: " );
854                 desc.append( taxs.size() );
855             }
856             for( final Taxonomy t : taxs ) {
857                 System.out.println( t.toString() );
858             }
859             desc.append( "\n" );
860             final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
861             if ( bs.getN() > 3 ) {
862                 desc.append( "\n" );
863                 desc.append( "Branch-length statistics: " );
864                 desc.append( "\n" );
865                 desc.append( "    Number of branches with non-negative branch-lengths: " + bs.getN() );
866                 desc.append( "\n" );
867                 desc.append( "    Median: " + ForesterUtil.round( bs.median(), 6 ) );
868                 desc.append( "\n" );
869                 desc.append( "    Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
870                         + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
871                 desc.append( "\n" );
872                 desc.append( "    Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
873                 desc.append( "\n" );
874                 desc.append( "    Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
875                 desc.append( "\n" );
876                 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
877                     desc.append( "\n" );
878                     final AsciiHistogram histo = new AsciiHistogram( bs );
879                     desc.append( histo.toStringBuffer( 12, '#', 40, 7, "    " ) );
880                 }
881             }
882             final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
883             if ( ds.getN() > 2 ) {
884                 desc.append( "\n" );
885                 desc.append( "Descendants per node statistics: " );
886                 desc.append( "\n" );
887                 desc.append( "    Median: " + ForesterUtil.round( ds.median(), 2 ) );
888                 desc.append( "\n" );
889                 desc.append( "    Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) + " (stdev: "
890                         + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) + ")" );
891                 desc.append( "\n" );
892                 desc.append( "    Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
893                 desc.append( "\n" );
894                 desc.append( "    Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
895                 desc.append( "\n" );
896             }
897             List<DescriptiveStatistics> css = null;
898             try {
899                 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
900             }
901             catch ( final IllegalArgumentException e ) {
902                 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
903             }
904             if ( ( css != null ) && ( css.size() > 0 ) ) {
905                 desc.append( "\n" );
906                 for( int i = 0; i < css.size(); ++i ) {
907                     final DescriptiveStatistics cs = css.get( i );
908                     if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
909                         if ( css.size() > 1 ) {
910                             desc.append( "Support statistics " + ( i + 1 ) + ": " );
911                         }
912                         else {
913                             desc.append( "Support statistics: " );
914                         }
915                         if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
916                             desc.append( "\n" );
917                             desc.append( "    Type: " + cs.getDescription() );
918                         }
919                         desc.append( "\n" );
920                         desc.append( "    Branches with support: " + cs.getN() );
921                         desc.append( "\n" );
922                         desc.append( "    Median: " + ForesterUtil.round( cs.median(), 6 ) );
923                         desc.append( "\n" );
924                         desc.append( "    Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
925                         if ( cs.getN() > 2 ) {
926                             desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
927                         }
928                         desc.append( "\n" );
929                         desc.append( "    Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
930                         desc.append( "\n" );
931                         desc.append( "    Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
932                         desc.append( "\n" );
933                     }
934                 }
935             }
936         }
937         return desc.toString();
938     }
939
940     /**
941      * Exits with -1.
942      * 
943      * 
944      * @param message
945      *            to message to be printed
946      */
947     final static void dieWithSystemError( final String message ) {
948         System.out.println();
949         System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
950         System.out.println( "Please contact the authors." );
951         System.out.println( Constants.PRG_NAME + " needs to close." );
952         System.out.println();
953         System.exit( -1 );
954     }
955
956     final static String[] getAllPossibleRanks() {
957         final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
958         int i = 0;
959         for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
960             if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
961                 str_array[ i++ ] = e;
962             }
963         }
964         return str_array;
965     }
966
967     final static String[] getAllRanks( final Phylogeny tree ) {
968         final SortedSet<String> ranks = new TreeSet<String>();
969         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
970             final PhylogenyNode n = it.next();
971             if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
972                 ranks.add( n.getNodeData().getTaxonomy().getRank() );
973             }
974         }
975         return ForesterUtil.stringSetToArray( ranks );
976     }
977
978     final static String[] getAvailableFontFamiliesSorted() {
979         return AVAILABLE_FONT_FAMILIES_SORTED;
980     }
981
982     final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
983         if ( !node.getNodeData().isHasEvent() ) {
984             return false;
985         }
986         if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
987             return false;
988         }
989         return true;
990     }
991
992     final static boolean isUsOrCanada() {
993         try {
994             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
995                 return true;
996             }
997         }
998         catch ( final Exception e ) {
999             return false;
1000         }
1001         return false;
1002     }
1003
1004     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
1005                                                                       final ControlPanel atv_control,
1006                                                                       final Configuration configuration ) {
1007         if ( ( t != null ) && !t.isEmpty() ) {
1008             if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
1009                 atv_control.setDrawPhylogram( false );
1010                 atv_control.setDrawPhylogramEnabled( false );
1011             }
1012             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
1013                 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
1014                     if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
1015                         atv_control.setDrawPhylogram( true );
1016                         atv_control.setDrawPhylogramEnabled( true );
1017                     }
1018                     else {
1019                         atv_control.setDrawPhylogram( false );
1020                     }
1021                 }
1022             }
1023             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
1024                 if ( atv_control.getWriteConfidenceCb() != null ) {
1025                     if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
1026                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
1027                     }
1028                     else {
1029                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
1030                     }
1031                 }
1032             }
1033             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
1034                 if ( atv_control.getShowEventsCb() != null ) {
1035                     if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
1036                         atv_control.setCheckbox( Configuration.write_events, true );
1037                     }
1038                     else {
1039                         atv_control.setCheckbox( Configuration.write_events, false );
1040                     }
1041                 }
1042             }
1043         }
1044     }
1045
1046     final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
1047         try {
1048             AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
1049         }
1050         catch ( final Exception e ) {
1051             throw new IOException( e );
1052         }
1053     }
1054
1055     final static void outOfMemoryError( final OutOfMemoryError e ) {
1056         System.err.println();
1057         System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
1058         System.err.println();
1059         e.printStackTrace();
1060         System.err.println();
1061         JOptionPane.showMessageDialog( null,
1062                                        "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
1063                                                + "\n\nError: " + e.getLocalizedMessage(),
1064                                        "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1065                                        JOptionPane.ERROR_MESSAGE );
1066         System.exit( -1 );
1067     }
1068
1069     final static void printAppletMessage( final String applet_name, final String message ) {
1070         System.out.println( "[" + applet_name + "] > " + message );
1071     }
1072
1073     final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
1074                                                      final boolean phyloxml_validate_against_xsd,
1075                                                      final boolean replace_underscores,
1076                                                      final boolean internal_numbers_are_confidences,
1077                                                      final TAXONOMY_EXTRACTION taxonomy_extraction,
1078                                                      final boolean midpoint_reroot ) throws FileNotFoundException,
1079             IOException {
1080         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1081         final PhylogenyParser parser;
1082         boolean nhx_or_nexus = false;
1083         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1084             parser = new TolParser();
1085         }
1086         else {
1087             parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
1088             if ( parser instanceof NHXParser ) {
1089                 nhx_or_nexus = true;
1090                 final NHXParser nhx = ( NHXParser ) parser;
1091                 nhx.setReplaceUnderscores( replace_underscores );
1092                 nhx.setIgnoreQuotes( false );
1093                 nhx.setTaxonomyExtraction( taxonomy_extraction );
1094             }
1095             else if ( parser instanceof NexusPhylogeniesParser ) {
1096                 nhx_or_nexus = true;
1097                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1098                 nex.setReplaceUnderscores( replace_underscores );
1099                 nex.setIgnoreQuotes( false );
1100             }
1101         }
1102         final Phylogeny[] phys = factory.create( url.openStream(), parser );
1103         if ( nhx_or_nexus && internal_numbers_are_confidences ) {
1104             for( final Phylogeny phy : phys ) {
1105                 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1106             }
1107         }
1108         if ( midpoint_reroot ) {
1109             for( final Phylogeny phy : phys ) {
1110                 PhylogenyMethods.midpointRoot( phy );
1111                 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
1112             }
1113         }
1114         return phys;
1115     }
1116
1117     final static void removeBranchColors( final Phylogeny phy ) {
1118         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1119             it.next().getBranchData().setBranchColor( null );
1120         }
1121     }
1122
1123     final static void unexpectedError( final Error e ) {
1124         System.err.println();
1125         e.printStackTrace( System.err );
1126         System.err.println();
1127         final StringBuffer sb = new StringBuffer();
1128         for( final StackTraceElement s : e.getStackTrace() ) {
1129             sb.append( s + "\n" );
1130         }
1131         JOptionPane
1132                 .showMessageDialog( null,
1133                                     "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
1134                                             + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
1135                                             + sb,
1136                                     "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1137                                     JOptionPane.ERROR_MESSAGE );
1138         System.exit( -1 );
1139     }
1140
1141     final static void unexpectedException( final Exception e ) {
1142         System.err.println();
1143         e.printStackTrace( System.err );
1144         System.err.println();
1145         final StringBuffer sb = new StringBuffer();
1146         for( final StackTraceElement s : e.getStackTrace() ) {
1147             sb.append( s + "\n" );
1148         }
1149         JOptionPane.showMessageDialog( null,
1150                                        "An unexpected exception has occured. \nPlease contact: "
1151                                                + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
1152                                                + "\n" + sb,
1153                                        "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
1154                                        JOptionPane.ERROR_MESSAGE );
1155     }
1156
1157     final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1158                                                                        int width,
1159                                                                        int height,
1160                                                                        final TreePanel tree_panel,
1161                                                                        final ControlPanel ac,
1162                                                                        final GraphicsExportType type,
1163                                                                        final Options options ) throws IOException {
1164         if ( !options.isGraphicsExportUsingActualSize() ) {
1165             if ( options.isGraphicsExportVisibleOnly() ) {
1166                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1167             }
1168             tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1169             tree_panel.resetPreferredSize();
1170             tree_panel.repaint();
1171         }
1172         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1173                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1174         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1175         if ( options.isAntialiasPrint() ) {
1176             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1177             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1178         }
1179         else {
1180             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1181             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1182         }
1183         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1184         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1185             return "";
1186         }
1187         Rectangle visible = null;
1188         if ( !options.isGraphicsExportUsingActualSize() ) {
1189             width = options.getPrintSizeX();
1190             height = options.getPrintSizeY();
1191         }
1192         else if ( options.isGraphicsExportVisibleOnly() ) {
1193             visible = tree_panel.getVisibleRect();
1194             width = visible.width;
1195             height = visible.height;
1196         }
1197         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1198         Graphics2D g2d = buffered_img.createGraphics();
1199         g2d.setRenderingHints( rendering_hints );
1200         int x = 0;
1201         int y = 0;
1202         if ( options.isGraphicsExportVisibleOnly() ) {
1203             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1204             g2d.setClip( null );
1205             x = visible.x;
1206             y = visible.y;
1207         }
1208         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1209         ImageIO.write( buffered_img, type.toString(), baos );
1210         g2d.dispose();
1211         System.gc();
1212         if ( !options.isGraphicsExportUsingActualSize() ) {
1213             tree_panel.getMainPanel().getControlPanel().showWhole();
1214         }
1215         String msg = baos.toString();
1216         if ( ( width > 0 ) && ( height > 0 ) ) {
1217             msg += " [size: " + width + ", " + height + "]";
1218         }
1219         return msg;
1220     }
1221
1222     final static String writePhylogenyToGraphicsFile( final String file_name,
1223                                                       int width,
1224                                                       int height,
1225                                                       final TreePanel tree_panel,
1226                                                       final ControlPanel ac,
1227                                                       final GraphicsExportType type,
1228                                                       final Options options ) throws IOException {
1229         if ( !options.isGraphicsExportUsingActualSize() ) {
1230             if ( options.isGraphicsExportVisibleOnly() ) {
1231                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1232             }
1233             tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1234             tree_panel.resetPreferredSize();
1235             tree_panel.repaint();
1236         }
1237         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1238                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1239         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1240         if ( options.isAntialiasPrint() ) {
1241             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1242             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1243         }
1244         else {
1245             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1246             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1247         }
1248         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1249         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1250             return "";
1251         }
1252         final File file = new File( file_name );
1253         if ( file.isDirectory() ) {
1254             throw new IOException( "\"" + file_name + "\" is a directory" );
1255         }
1256         Rectangle visible = null;
1257         if ( !options.isGraphicsExportUsingActualSize() ) {
1258             width = options.getPrintSizeX();
1259             height = options.getPrintSizeY();
1260         }
1261         else if ( options.isGraphicsExportVisibleOnly() ) {
1262             visible = tree_panel.getVisibleRect();
1263             width = visible.width;
1264             height = visible.height;
1265         }
1266         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1267         Graphics2D g2d = buffered_img.createGraphics();
1268         g2d.setRenderingHints( rendering_hints );
1269         int x = 0;
1270         int y = 0;
1271         if ( options.isGraphicsExportVisibleOnly() ) {
1272             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1273             g2d.setClip( null );
1274             x = visible.x;
1275             y = visible.y;
1276         }
1277         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1278         if ( type == GraphicsExportType.TIFF ) {
1279             writeToTiff( file, buffered_img );
1280         }
1281         else {
1282             ImageIO.write( buffered_img, type.toString(), file );
1283         }
1284         g2d.dispose();
1285         System.gc();
1286         if ( !options.isGraphicsExportUsingActualSize() ) {
1287             tree_panel.getMainPanel().getControlPanel().showWhole();
1288         }
1289         String msg = file.toString();
1290         if ( ( width > 0 ) && ( height > 0 ) ) {
1291             msg += " [size: " + width + ", " + height + "]";
1292         }
1293         return msg;
1294     }
1295
1296     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1297         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1298         ImageWriter writer = null;
1299         ImageOutputStream ios = null;
1300         // Find an appropriate writer:
1301         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1302         if ( it.hasNext() ) {
1303             writer = it.next();
1304         }
1305         else {
1306             throw new IOException( "failed to get TIFF image writer" );
1307         }
1308         // Setup writer:
1309         ios = ImageIO.createImageOutputStream( file );
1310         writer.setOutput( ios );
1311         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1312         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1313         // see writeParam.getCompressionTypes() for available compression type
1314         // strings.
1315         image_write_param.setCompressionType( "PackBits" );
1316         final String t[] = image_write_param.getCompressionTypes();
1317         for( final String string : t ) {
1318             System.out.println( string );
1319         }
1320         // Convert to an IIOImage:
1321         final IIOImage iio_image = new IIOImage( image, null, null );
1322         writer.write( null, iio_image, image_write_param );
1323     }
1324
1325     private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1326         node.getBranchData().setBranchColor( c );
1327         final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1328         for( final PhylogenyNode desc : descs ) {
1329             desc.getBranchData().setBranchColor( c );
1330         }
1331     }
1332
1333     final private static char normalizeCharForRGB( char c ) {
1334         c -= 65;
1335         c *= 10.2;
1336         c = c > 255 ? 255 : c;
1337         c = c < 0 ? 0 : c;
1338         return c;
1339     }
1340
1341     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1342             SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1343             InvocationTargetException, InterruptedException {
1344         final String os = System.getProperty( "os.name" );
1345         final Runtime runtime = Runtime.getRuntime();
1346         if ( os.toLowerCase().startsWith( "win" ) ) {
1347             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1348         }
1349         else if ( ForesterUtil.isMac() ) {
1350             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1351             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1352             open_url.invoke( null, new Object[] { url } );
1353         }
1354         else {
1355             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1356             String browser = null;
1357             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1358                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1359                     browser = browsers[ i ];
1360                 }
1361             }
1362             if ( browser == null ) {
1363                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1364             }
1365             else {
1366                 runtime.exec( new String[] { browser, url } );
1367             }
1368         }
1369     }
1370
1371     // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1372     // static void openDDBJRest() throws IOException {
1373     // //set URL
1374     // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1375     // //set parameter
1376     // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1377     // //make connection
1378     // URLConnection urlc = url.openConnection();
1379     // //use post mode
1380     // urlc.setDoOutput( true );
1381     // urlc.setAllowUserInteraction( false );
1382     // //send query
1383     // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1384     // ps.print( query );
1385     // ps.close();
1386     // //get result
1387     // BufferedReader br = new BufferedReader( new InputStreamReader(
1388     // urlc.getInputStream() ) );
1389     // String l = null;
1390     // while ( ( l = br.readLine() ) != null ) {
1391     // System.out.println( l );
1392     // }
1393     // br.close();
1394     // }
1395     public static enum GraphicsExportType {
1396         BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
1397
1398         private final String _suffix;
1399
1400         private GraphicsExportType( final String suffix ) {
1401             _suffix = suffix;
1402         }
1403
1404         @Override
1405         public String toString() {
1406             return _suffix;
1407         }
1408     }
1409 }