2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
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.
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.
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
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
26 package org.forester.archaeopteryx;
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;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.lang.reflect.InvocationTargetException;
40 import java.lang.reflect.Method;
43 import java.text.ParseException;
44 import java.util.Arrays;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
48 import java.util.Locale;
51 import java.util.SortedSet;
52 import java.util.TreeSet;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
56 import javax.imageio.IIOImage;
57 import javax.imageio.ImageIO;
58 import javax.imageio.ImageWriteParam;
59 import javax.imageio.ImageWriter;
60 import javax.imageio.stream.ImageOutputStream;
61 import javax.swing.JApplet;
62 import javax.swing.JOptionPane;
63 import javax.swing.text.MaskFormatter;
65 import org.forester.analysis.TaxonomyDataManager;
66 import org.forester.io.parsers.PhylogenyParser;
67 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
68 import org.forester.io.parsers.tol.TolParser;
69 import org.forester.io.parsers.util.ParserUtils;
70 import org.forester.phylogeny.Phylogeny;
71 import org.forester.phylogeny.PhylogenyMethods;
72 import org.forester.phylogeny.PhylogenyNode;
73 import org.forester.phylogeny.data.Accession;
74 import org.forester.phylogeny.data.BranchColor;
75 import org.forester.phylogeny.data.Distribution;
76 import org.forester.phylogeny.data.Sequence;
77 import org.forester.phylogeny.data.Taxonomy;
78 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
79 import org.forester.phylogeny.factories.PhylogenyFactory;
80 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
81 import org.forester.phylogeny.iterators.PreorderTreeIterator;
82 import org.forester.util.AsciiHistogram;
83 import org.forester.util.DescriptiveStatistics;
84 import org.forester.util.ForesterUtil;
85 import org.forester.ws.seqdb.UniProtTaxonomy;
87 public final class AptxUtil {
89 private final static Pattern seq_identifier_pattern_1 = Pattern
90 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
91 private final static Pattern seq_identifier_pattern_2 = Pattern
92 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
93 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
94 .getAvailableFontFamilyNames();
96 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
99 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
100 final String n = sequence_name.trim();
101 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
104 if ( matcher1.matches() ) {
105 group1 = matcher1.group( 1 );
106 group2 = matcher1.group( 2 );
109 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
110 if ( matcher2.matches() ) {
111 group1 = matcher2.group( 1 );
112 group2 = matcher2.group( 2 );
115 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
118 return new Accession( group2, group1 );
121 public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
122 if ( !node.getNodeData().isHasTaxonomy() ) {
123 node.getNodeData().setTaxonomy( new Taxonomy() );
127 public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
128 if ( !node.getNodeData().isHasSequence() ) {
129 node.getNodeData().setSequence( new Sequence() );
133 final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
134 if ( !node.getNodeData().isHasDistribution() ) {
135 node.getNodeData().setDistribution( new Distribution( "" ) );
139 final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
140 if ( !node.getNodeData().isHasDate() ) {
141 node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
145 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
146 final PhylogenyNodeIterator it = phy.iteratorPostorder();
147 while ( it.hasNext() ) {
148 if ( it.next().getBranchData().isHasConfidences() ) {
155 public static void writePhylogenyToGraphicsFile( final File intree,
159 final GraphicsExportType type,
160 final Configuration config ) throws IOException {
161 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
162 Phylogeny[] phys = null;
163 phys = PhylogenyMethods.readPhylogenies( parser, intree );
164 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
167 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
171 final GraphicsExportType type,
172 final Configuration config ) throws IOException {
173 final Phylogeny[] phys = new Phylogeny[ 1 ];
175 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
176 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
177 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
182 * Returns true if at least one branch has a length larger than zero.
187 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
188 final PhylogenyNodeIterator it = phy.iteratorPostorder();
189 while ( it.hasNext() ) {
190 if ( it.next().getDistanceToParent() > 0.0 ) {
197 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
198 final PhylogenyNodeIterator it = phy.iteratorPostorder();
199 while ( it.hasNext() ) {
200 if ( it.next().getNodeData().isHasEvent() ) {
207 public static MaskFormatter createMaskFormatter( final String s ) {
208 MaskFormatter formatter = null;
210 formatter = new MaskFormatter( s );
212 catch ( final ParseException e ) {
213 throw new IllegalArgumentException( e );
218 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
219 final String default_name,
220 final String full_path,
221 final Configuration configuration,
222 final MainPanel main_panel ) {
223 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
224 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
225 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
226 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
229 for( final Phylogeny phy : phys ) {
230 if ( !phy.isEmpty() ) {
231 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
233 String my_name_for_file = "";
234 if ( phys.length > 1 ) {
235 if ( !ForesterUtil.isEmpty( default_name ) ) {
236 my_name = new String( default_name );
238 if ( !ForesterUtil.isEmpty( full_path ) ) {
239 my_name_for_file = new String( full_path );
241 else if ( !ForesterUtil.isEmpty( default_name ) ) {
242 my_name_for_file = new String( default_name );
245 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
246 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
247 my_name_for_file.length() );
248 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
250 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
251 my_name_for_file += "_";
253 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
254 my_name_for_file += phy.getName().replaceAll( " ", "_" );
256 else if ( phy.getIdentifier() != null ) {
257 final StringBuffer sb = new StringBuffer();
258 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
259 sb.append( phy.getIdentifier().getProvider() );
262 sb.append( phy.getIdentifier().getValue() );
263 my_name_for_file += sb;
266 my_name_for_file += i;
268 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
269 && ( phy.getIdentifier() == null ) ) {
270 my_name = my_name + " [" + i + "]";
272 if ( !ForesterUtil.isEmpty( suffix ) ) {
273 my_name_for_file += suffix;
277 if ( !ForesterUtil.isEmpty( default_name ) ) {
278 my_name = new String( default_name );
280 my_name_for_file = "";
281 if ( !ForesterUtil.isEmpty( full_path ) ) {
282 my_name_for_file = new String( full_path );
284 else if ( !ForesterUtil.isEmpty( default_name ) ) {
285 my_name_for_file = new String( default_name );
287 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
288 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
289 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
291 else if ( phy.getIdentifier() != null ) {
292 final StringBuffer sb = new StringBuffer();
293 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
294 sb.append( phy.getIdentifier().getProvider() );
297 sb.append( phy.getIdentifier().getValue() );
298 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
302 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
303 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
304 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
311 final static void addPhylogenyToPanel( final Phylogeny[] phys,
312 final Configuration configuration,
313 final MainPanel main_panel ) {
314 final Phylogeny phy = phys[ 0 ];
315 main_panel.addPhylogenyInPanel( phy, configuration );
316 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
319 final static Color calculateColorFromString( final String str ) {
320 final String species_uc = str.toUpperCase();
321 char first = species_uc.charAt( 0 );
324 if ( species_uc.length() > 1 ) {
325 second = species_uc.charAt( 1 );
326 if ( species_uc.length() > 2 ) {
327 if ( species_uc.indexOf( " " ) > 0 ) {
328 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
331 third = species_uc.charAt( 2 );
335 first = AptxUtil.normalizeCharForRGB( first );
336 second = AptxUtil.normalizeCharForRGB( second );
337 third = AptxUtil.normalizeCharForRGB( third );
338 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
341 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
344 return new Color( first, second, third );
347 // Returns true if the specified format name can be written
348 final static boolean canWriteFormat( final String format_name ) {
349 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
350 return iter.hasNext();
353 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
354 boolean inferred = false;
355 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
356 final PhylogenyNode n = it.next();
357 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
358 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
359 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
360 AptxUtil.collapseSubtree( n, true );
361 if ( !n.getNodeData().isHasTaxonomy() ) {
362 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
363 .getTaxonomy().copy() );
368 n.setCollapse( false );
373 phy.setRerootable( false );
377 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
378 node.setCollapse( collapse );
379 if ( node.isExternal() ) {
382 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
383 while ( it.hasNext() ) {
384 it.next().setCollapse( collapse );
388 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
389 double max_conf = 0.0;
390 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
391 final PhylogenyNode n = it.next();
392 n.getBranchData().setBranchColor( null );
393 if ( n.getBranchData().isHasConfidences() ) {
394 final double conf = PhylogenyMethods.getConfidenceValue( n );
395 if ( conf > max_conf ) {
400 if ( max_conf > 0.0 ) {
401 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
402 final Color br = tree_panel.getTreeColorSet().getBranchColor();
403 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
404 final PhylogenyNode n = it.next();
405 if ( n.getBranchData().isHasConfidences() ) {
406 final double conf = PhylogenyMethods.getConfidenceValue( n );
407 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
408 colorizeSubtree( n, c );
414 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
415 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
416 int colorizations = 0;
417 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
418 final PhylogenyNode n = it.next();
419 if ( n.getNodeData().isHasTaxonomy()
420 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
421 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
422 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
423 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
424 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
425 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
427 colorizeSubtree( n, c );
429 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
430 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
435 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
436 final PhylogenyNode node = it.next();
437 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
438 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
439 boolean success = false;
440 if ( !true_lineage_to_color_map.isEmpty() ) {
441 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
442 if ( true_lineage_to_color_map.containsKey( lin ) ) {
443 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
451 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
452 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
453 final Taxonomy temp_tax = new Taxonomy();
454 temp_tax.setScientificName( lin );
455 if ( lineage_to_rank_map.containsKey( lin )
456 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
457 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
458 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
459 colorizeSubtree( node, c );
461 true_lineage_to_color_map.put( lin, c.getValue() );
465 UniProtTaxonomy up = null;
467 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
469 catch ( final Exception e ) {
472 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
473 lineage_to_rank_map.put( lin, up.getRank() );
474 if ( up.getRank().equalsIgnoreCase( rank ) ) {
475 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
476 colorizeSubtree( node, c );
478 true_lineage_to_color_map.put( lin, c.getValue() );
487 return colorizations;
490 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
491 node.getBranchData().setBranchColor( c );
492 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
493 for( final PhylogenyNode desc : descs ) {
494 desc.getBranchData().setBranchColor( c );
498 final static String[] getAllRanks( final Phylogeny tree ) {
499 final SortedSet<String> ranks = new TreeSet<String>();
500 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
501 final PhylogenyNode n = it.next();
502 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
503 ranks.add( n.getNodeData().getTaxonomy().getRank() );
506 return ForesterUtil.stringSetToArray( ranks );
509 public static String[] getAllPossibleRanks() {
510 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
512 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
513 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
514 str_array[ i++ ] = e;
520 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
521 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
522 it.next().getBranchData().setBranchColor( null );
524 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
525 final PhylogenyNode n = it.next();
526 if ( !n.getBranchData().isHasBranchColor() ) {
527 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
529 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
530 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
531 for( final PhylogenyNode desc : descs ) {
533 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
540 final static String createBasicInformation( final Phylogeny phy ) {
541 final StringBuilder desc = new StringBuilder();
542 if ( ( phy != null ) && !phy.isEmpty() ) {
543 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
544 desc.append( "Name: " );
545 desc.append( phy.getName() );
548 if ( phy.getIdentifier() != null ) {
549 desc.append( "Id: " );
550 desc.append( phy.getIdentifier() );
553 desc.append( "Rooted: " );
554 desc.append( phy.isRooted() );
556 desc.append( "Rerootable: " );
557 desc.append( phy.isRerootable() );
559 desc.append( "Node sum: " );
560 desc.append( phy.getNodeCount() );
562 desc.append( "External node sum: " );
563 desc.append( phy.getNumberOfExternalNodes() );
565 desc.append( "Internal node sum: " );
566 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
568 desc.append( "Branche sum: " );
569 desc.append( phy.getNumberOfBranches() );
571 desc.append( "Depth: " );
572 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
574 desc.append( "Maximum distance to root: " );
575 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
577 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
578 if ( taxs != null ) {
579 desc.append( "Distinct external taxonomies: " );
580 desc.append( taxs.size() );
583 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
584 if ( bs.getN() > 3 ) {
586 desc.append( "Branch-length statistics: " );
588 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
590 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
592 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
594 desc.append( " SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
596 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
598 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
600 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
602 final AsciiHistogram histo = new AsciiHistogram( bs );
603 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
606 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
607 if ( ds.getN() > 2 ) {
609 desc.append( "Descendants per node statistics: " );
611 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
613 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
615 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
617 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
619 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
622 List<DescriptiveStatistics> css = null;
624 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
626 catch ( final IllegalArgumentException e ) {
627 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
629 if ( ( css != null ) && ( css.size() > 0 ) ) {
631 for( int i = 0; i < css.size(); ++i ) {
632 final DescriptiveStatistics cs = css.get( i );
633 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
634 if ( css.size() > 1 ) {
635 desc.append( "Support statistics " + ( i + 1 ) + ": " );
638 desc.append( "Support statistics: " );
640 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
642 desc.append( " Type: " + cs.getDescription() );
645 desc.append( " Branches with support: " + cs.getN() );
647 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
649 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
651 if ( cs.getN() > 2 ) {
652 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
655 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
657 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
663 return desc.toString();
671 * to message to be printed
673 final static void dieWithSystemError( final String message ) {
674 System.out.println();
675 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
676 System.out.println( "Please contact the authors." );
677 System.out.println( Constants.PRG_NAME + " needs to close." );
678 System.out.println();
682 final static String[] getAvailableFontFamiliesSorted() {
683 return AVAILABLE_FONT_FAMILIES_SORTED;
686 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
687 boolean inferred = false;
688 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
689 final PhylogenyNode n = it.next();
690 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
691 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
692 if ( !ForesterUtil.isEmpty( sn ) ) {
693 n.getNodeData().setTaxonomy( new Taxonomy() );
694 n.getNodeData().getTaxonomy().setScientificName( sn );
700 tree.setRerootable( false );
704 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
705 if ( !node.getNodeData().isHasEvent() ) {
708 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
714 final static boolean isJava15() {
716 final String s = ForesterUtil.JAVA_VERSION;
717 return s.startsWith( "1.5" );
719 catch ( final Exception e ) {
720 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
725 final static boolean isMac() {
727 final String s = ForesterUtil.OS_NAME.toLowerCase();
728 return s.startsWith( "mac" );
730 catch ( final Exception e ) {
731 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
736 final static boolean isUsOrCanada() {
738 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
742 catch ( final Exception e ) {
748 final static boolean isWindows() {
750 final String s = ForesterUtil.OS_NAME.toLowerCase();
751 return s.indexOf( "win" ) > -1;
753 catch ( final Exception e ) {
754 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
759 final public static void launchWebBrowser( final URI uri,
760 final boolean is_applet,
761 final JApplet applet,
762 final String frame_name ) throws IOException {
764 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
767 // This requires Java 1.6:
768 // =======================
769 // boolean no_desktop = false;
771 // if ( Desktop.isDesktopSupported() ) {
772 // System.out.println( "desktop supported" );
773 // final Desktop dt = Desktop.getDesktop();
777 // no_desktop = true;
780 // catch ( final Exception ex ) {
781 // ex.printStackTrace();
782 // no_desktop = true;
784 // catch ( final Error er ) {
785 // er.printStackTrace();
786 // no_desktop = true;
788 // if ( no_desktop ) {
789 // System.out.println( "desktop not supported" );
791 openUrlInWebBrowser( uri.toString() );
793 catch ( final Exception e ) {
794 throw new IOException( e );
800 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
801 final ControlPanel atv_control,
802 final Configuration configuration ) {
803 if ( ( t != null ) && !t.isEmpty() ) {
804 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
805 atv_control.setDrawPhylogram( false );
806 atv_control.setDrawPhylogramEnabled( false );
808 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
809 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
810 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
811 atv_control.setDrawPhylogram( true );
812 atv_control.setDrawPhylogramEnabled( true );
815 atv_control.setDrawPhylogram( false );
819 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
820 if ( atv_control.getWriteConfidenceCb() != null ) {
821 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
822 atv_control.setCheckbox( Configuration.write_confidence_values, true );
825 atv_control.setCheckbox( Configuration.write_confidence_values, false );
829 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
830 if ( atv_control.getShowEventsCb() != null ) {
831 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
832 atv_control.setCheckbox( Configuration.write_events, true );
835 atv_control.setCheckbox( Configuration.write_events, false );
842 final private static char normalizeCharForRGB( char c ) {
845 c = c > 255 ? 255 : c;
850 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
851 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
852 InvocationTargetException, InterruptedException {
853 final String os = System.getProperty( "os.name" );
854 final Runtime runtime = Runtime.getRuntime();
855 if ( os.toLowerCase().startsWith( "win" ) ) {
856 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
858 else if ( isMac() ) {
859 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
860 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
861 open_url.invoke( null, new Object[] { url } );
864 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
865 String browser = null;
866 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
867 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
868 browser = browsers[ i ];
871 if ( browser == null ) {
872 throw new IOException( "could not find a web browser to open [" + url + "] in" );
875 runtime.exec( new String[] { browser, url } );
880 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
882 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
884 catch ( final Exception e ) {
885 throw new IOException( e );
889 final static void printAppletMessage( final String applet_name, final String message ) {
890 System.out.println( "[" + applet_name + "] > " + message );
893 public final static void printWarningMessage( final String name, final String message ) {
894 System.out.println( "[" + name + "] > " + message );
897 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
898 throws FileNotFoundException, IOException {
899 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
900 PhylogenyParser parser = null;
901 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
902 parser = new TolParser();
905 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
907 return factory.create( url.openStream(), parser );
910 final static void removeBranchColors( final Phylogeny phy ) {
911 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
912 it.next().getBranchData().setBranchColor( null );
916 final public static void showErrorMessage( final Component parent, final String error_msg ) {
917 printAppletMessage( Constants.PRG_NAME, error_msg );
918 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
919 + "] Error", JOptionPane.ERROR_MESSAGE );
922 final static void unexpectedError( final Error err ) {
923 err.printStackTrace();
924 final StringBuffer sb = new StringBuffer();
925 for( final StackTraceElement s : err.getStackTrace() ) {
926 sb.append( s + "\n" );
929 .showMessageDialog( null,
930 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
931 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
932 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
933 JOptionPane.ERROR_MESSAGE );
937 final static void unexpectedException( final Exception ex ) {
938 ex.printStackTrace();
939 final StringBuffer sb = new StringBuffer();
940 for( final StackTraceElement s : ex.getStackTrace() ) {
941 sb.append( s + "\n" );
943 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
944 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
945 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
948 final static String writePhylogenyToGraphicsFile( final String file_name,
951 final TreePanel tree_panel,
952 final ControlPanel ac,
953 final GraphicsExportType type,
954 final Options options ) throws IOException {
955 if ( !options.isGraphicsExportUsingActualSize() ) {
956 if ( options.isGraphicsExportVisibleOnly() ) {
957 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
959 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
960 tree_panel.resetPreferredSize();
961 tree_panel.repaint();
963 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
964 RenderingHints.VALUE_RENDER_QUALITY );
965 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
966 if ( options.isAntialiasPrint() ) {
967 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
968 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
971 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
972 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
974 final Phylogeny phylogeny = tree_panel.getPhylogeny();
975 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
978 final File file = new File( file_name );
979 if ( file.isDirectory() ) {
980 throw new IOException( "\"" + file_name + "\" is a directory" );
982 Rectangle visible = null;
983 if ( !options.isGraphicsExportUsingActualSize() ) {
984 width = options.getPrintSizeX();
985 height = options.getPrintSizeY();
987 else if ( options.isGraphicsExportVisibleOnly() ) {
988 visible = tree_panel.getVisibleRect();
989 width = visible.width;
990 height = visible.height;
992 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
993 Graphics2D g2d = buffered_img.createGraphics();
994 g2d.setRenderingHints( rendering_hints );
997 if ( options.isGraphicsExportVisibleOnly() ) {
998 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1003 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1004 if ( type == GraphicsExportType.TIFF ) {
1005 writeToTiff( file, buffered_img );
1008 ImageIO.write( buffered_img, type.toString(), file );
1012 if ( !options.isGraphicsExportUsingActualSize() ) {
1013 tree_panel.getMainPanel().getControlPanel().showWhole();
1015 String msg = file.toString();
1016 if ( ( width > 0 ) && ( height > 0 ) ) {
1017 msg += " [size: " + width + ", " + height + "]";
1022 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
1025 final TreePanel tree_panel,
1026 final ControlPanel ac,
1027 final GraphicsExportType type,
1028 final Options options ) throws IOException {
1029 tree_panel.setParametersForPainting( width, height, true );
1030 tree_panel.resetPreferredSize();
1031 tree_panel.repaint();
1032 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1033 RenderingHints.VALUE_RENDER_QUALITY );
1034 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1035 if ( options.isAntialiasPrint() ) {
1036 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1037 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1040 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1041 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1043 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1044 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1047 if ( outfile.isDirectory() ) {
1048 throw new IOException( "\"" + outfile + "\" is a directory" );
1050 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1051 final Graphics2D g2d = buffered_img.createGraphics();
1052 g2d.setRenderingHints( rendering_hints );
1053 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
1054 if ( type == GraphicsExportType.TIFF ) {
1055 writeToTiff( outfile, buffered_img );
1058 ImageIO.write( buffered_img, type.toString(), outfile );
1063 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1066 final TreePanel tree_panel,
1067 final ControlPanel ac,
1068 final GraphicsExportType type,
1069 final Options options ) throws IOException {
1070 if ( !options.isGraphicsExportUsingActualSize() ) {
1071 if ( options.isGraphicsExportVisibleOnly() ) {
1072 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1074 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1075 tree_panel.resetPreferredSize();
1076 tree_panel.repaint();
1078 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1079 RenderingHints.VALUE_RENDER_QUALITY );
1080 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1081 if ( options.isAntialiasPrint() ) {
1082 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1083 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1086 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1087 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1089 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1090 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1093 Rectangle visible = null;
1094 if ( !options.isGraphicsExportUsingActualSize() ) {
1095 width = options.getPrintSizeX();
1096 height = options.getPrintSizeY();
1098 else if ( options.isGraphicsExportVisibleOnly() ) {
1099 visible = tree_panel.getVisibleRect();
1100 width = visible.width;
1101 height = visible.height;
1103 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1104 Graphics2D g2d = buffered_img.createGraphics();
1105 g2d.setRenderingHints( rendering_hints );
1108 if ( options.isGraphicsExportVisibleOnly() ) {
1109 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1110 g2d.setClip( null );
1114 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1115 ImageIO.write( buffered_img, type.toString(), baos );
1118 if ( !options.isGraphicsExportUsingActualSize() ) {
1119 tree_panel.getMainPanel().getControlPanel().showWhole();
1121 String msg = baos.toString();
1122 if ( ( width > 0 ) && ( height > 0 ) ) {
1123 msg += " [size: " + width + ", " + height + "]";
1128 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1129 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1130 ImageWriter writer = null;
1131 ImageOutputStream ios = null;
1132 // Find an appropriate writer:
1133 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1134 if ( it.hasNext() ) {
1138 throw new IOException( "failed to get TIFF image writer" );
1141 ios = ImageIO.createImageOutputStream( file );
1142 writer.setOutput( ios );
1143 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1144 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1145 // see writeParam.getCompressionTypes() for available compression type
1147 image_write_param.setCompressionType( "PackBits" );
1148 final String t[] = image_write_param.getCompressionTypes();
1149 for( final String string : t ) {
1150 System.out.println( string );
1152 // Convert to an IIOImage:
1153 final IIOImage iio_image = new IIOImage( image, null, null );
1154 writer.write( null, iio_image, image_write_param );
1157 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1158 // static void openDDBJRest() throws IOException {
1160 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1162 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1163 // //make connection
1164 // URLConnection urlc = url.openConnection();
1166 // urlc.setDoOutput( true );
1167 // urlc.setAllowUserInteraction( false );
1169 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1170 // ps.print( query );
1173 // BufferedReader br = new BufferedReader( new InputStreamReader(
1174 // urlc.getInputStream() ) );
1176 // while ( ( l = br.readLine() ) != null ) {
1177 // System.out.println( l );
1181 public static enum GraphicsExportType {
1182 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1184 private final String _suffix;
1186 private GraphicsExportType( final String suffix ) {
1191 public String toString() {