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.AncestralTaxonomyInference;
66 import org.forester.analysis.TaxonomyDataManager;
67 import org.forester.io.parsers.PhylogenyParser;
68 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
69 import org.forester.io.parsers.tol.TolParser;
70 import org.forester.io.parsers.util.ParserUtils;
71 import org.forester.phylogeny.Phylogeny;
72 import org.forester.phylogeny.PhylogenyMethods;
73 import org.forester.phylogeny.PhylogenyNode;
74 import org.forester.phylogeny.data.Accession;
75 import org.forester.phylogeny.data.BranchColor;
76 import org.forester.phylogeny.data.Distribution;
77 import org.forester.phylogeny.data.Sequence;
78 import org.forester.phylogeny.data.Taxonomy;
79 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
80 import org.forester.phylogeny.factories.PhylogenyFactory;
81 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
82 import org.forester.phylogeny.iterators.PreorderTreeIterator;
83 import org.forester.util.AsciiHistogram;
84 import org.forester.util.DescriptiveStatistics;
85 import org.forester.util.ForesterUtil;
86 import org.forester.ws.seqdb.UniProtTaxonomy;
88 public final class AptxUtil {
90 private final static Pattern seq_identifier_pattern_1 = Pattern
91 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
92 private final static Pattern seq_identifier_pattern_2 = Pattern
93 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
94 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
95 .getAvailableFontFamilyNames();
97 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
100 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
101 final String n = sequence_name.trim();
102 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
105 if ( matcher1.matches() ) {
106 group1 = matcher1.group( 1 );
107 group2 = matcher1.group( 2 );
110 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
111 if ( matcher2.matches() ) {
112 group1 = matcher2.group( 1 );
113 group2 = matcher2.group( 2 );
116 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
119 return new Accession( group2, group1 );
122 public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
123 if ( !node.getNodeData().isHasTaxonomy() ) {
124 node.getNodeData().setTaxonomy( new Taxonomy() );
128 public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
129 if ( !node.getNodeData().isHasSequence() ) {
130 node.getNodeData().setSequence( new Sequence() );
134 final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
135 if ( !node.getNodeData().isHasDistribution() ) {
136 node.getNodeData().setDistribution( new Distribution( "" ) );
140 final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
141 if ( !node.getNodeData().isHasDate() ) {
142 node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
146 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
147 final PhylogenyNodeIterator it = phy.iteratorPostorder();
148 while ( it.hasNext() ) {
149 if ( it.next().getBranchData().isHasConfidences() ) {
156 public static void writePhylogenyToGraphicsFile( final File intree,
160 final GraphicsExportType type,
161 final Configuration config ) throws IOException {
162 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
163 Phylogeny[] phys = null;
164 phys = PhylogenyMethods.readPhylogenies( parser, intree );
165 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
168 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
172 final GraphicsExportType type,
173 final Configuration config ) throws IOException {
174 final Phylogeny[] phys = new Phylogeny[ 1 ];
176 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
177 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
178 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
183 * Returns true if at least one branch has a length larger than zero.
188 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
189 final PhylogenyNodeIterator it = phy.iteratorPostorder();
190 while ( it.hasNext() ) {
191 if ( it.next().getDistanceToParent() > 0.0 ) {
198 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
199 final PhylogenyNodeIterator it = phy.iteratorPostorder();
200 while ( it.hasNext() ) {
201 if ( it.next().getNodeData().isHasEvent() ) {
208 public static MaskFormatter createMaskFormatter( final String s ) {
209 MaskFormatter formatter = null;
211 formatter = new MaskFormatter( s );
213 catch ( final ParseException e ) {
214 throw new IllegalArgumentException( e );
219 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
220 final String default_name,
221 final String full_path,
222 final Configuration configuration,
223 final MainPanel main_panel ) {
224 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
225 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
226 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
227 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
230 for( final Phylogeny phy : phys ) {
231 if ( !phy.isEmpty() ) {
232 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
234 String my_name_for_file = "";
235 if ( phys.length > 1 ) {
236 if ( !ForesterUtil.isEmpty( default_name ) ) {
237 my_name = new String( default_name );
239 if ( !ForesterUtil.isEmpty( full_path ) ) {
240 my_name_for_file = new String( full_path );
242 else if ( !ForesterUtil.isEmpty( default_name ) ) {
243 my_name_for_file = new String( default_name );
246 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
247 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
248 my_name_for_file.length() );
249 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
251 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
252 my_name_for_file += "_";
254 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
255 my_name_for_file += phy.getName().replaceAll( " ", "_" );
257 else if ( phy.getIdentifier() != null ) {
258 final StringBuffer sb = new StringBuffer();
259 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
260 sb.append( phy.getIdentifier().getProvider() );
263 sb.append( phy.getIdentifier().getValue() );
264 my_name_for_file += sb;
267 my_name_for_file += i;
269 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
270 && ( phy.getIdentifier() == null ) ) {
271 my_name = my_name + " [" + i + "]";
273 if ( !ForesterUtil.isEmpty( suffix ) ) {
274 my_name_for_file += suffix;
278 if ( !ForesterUtil.isEmpty( default_name ) ) {
279 my_name = new String( default_name );
281 my_name_for_file = "";
282 if ( !ForesterUtil.isEmpty( full_path ) ) {
283 my_name_for_file = new String( full_path );
285 else if ( !ForesterUtil.isEmpty( default_name ) ) {
286 my_name_for_file = new String( default_name );
288 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
289 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
290 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
292 else if ( phy.getIdentifier() != null ) {
293 final StringBuffer sb = new StringBuffer();
294 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
295 sb.append( phy.getIdentifier().getProvider() );
298 sb.append( phy.getIdentifier().getValue() );
299 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
303 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
304 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
305 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
312 final static void addPhylogenyToPanel( final Phylogeny[] phys,
313 final Configuration configuration,
314 final MainPanel main_panel ) {
315 final Phylogeny phy = phys[ 0 ];
316 main_panel.addPhylogenyInPanel( phy, configuration );
317 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
320 final static Color calculateColorFromString( final String str ) {
321 final String species_uc = str.toUpperCase();
322 char first = species_uc.charAt( 0 );
325 if ( species_uc.length() > 1 ) {
326 second = species_uc.charAt( 1 );
327 if ( species_uc.length() > 2 ) {
328 if ( species_uc.indexOf( " " ) > 0 ) {
329 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
332 third = species_uc.charAt( 2 );
336 first = AptxUtil.normalizeCharForRGB( first );
337 second = AptxUtil.normalizeCharForRGB( second );
338 third = AptxUtil.normalizeCharForRGB( third );
339 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
342 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
345 return new Color( first, second, third );
348 // Returns true if the specified format name can be written
349 final static boolean canWriteFormat( final String format_name ) {
350 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
351 return iter.hasNext();
354 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
355 boolean inferred = false;
356 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
357 final PhylogenyNode n = it.next();
358 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
359 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
360 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
361 AptxUtil.collapseSubtree( n, true );
362 if ( !n.getNodeData().isHasTaxonomy() ) {
363 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
364 .getTaxonomy().copy() );
369 n.setCollapse( false );
374 phy.setRerootable( false );
378 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
379 node.setCollapse( collapse );
380 if ( node.isExternal() ) {
383 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
384 while ( it.hasNext() ) {
385 it.next().setCollapse( collapse );
389 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
390 double max_conf = 0.0;
391 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
392 final PhylogenyNode n = it.next();
393 n.getBranchData().setBranchColor( null );
394 if ( n.getBranchData().isHasConfidences() ) {
395 final double conf = PhylogenyMethods.getConfidenceValue( n );
396 if ( conf > max_conf ) {
401 if ( max_conf > 0.0 ) {
402 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
403 final Color br = tree_panel.getTreeColorSet().getBranchColor();
404 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
405 final PhylogenyNode n = it.next();
406 if ( n.getBranchData().isHasConfidences() ) {
407 final double conf = PhylogenyMethods.getConfidenceValue( n );
408 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
409 colorizeSubtree( n, c );
415 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
416 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
417 int colorizations = 0;
418 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
419 final PhylogenyNode n = it.next();
420 if ( n.getNodeData().isHasTaxonomy()
421 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
422 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
423 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
424 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
425 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
426 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
428 colorizeSubtree( n, c );
430 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
431 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
436 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
437 final PhylogenyNode node = it.next();
438 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
439 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
440 boolean success = false;
441 if ( !true_lineage_to_color_map.isEmpty() ) {
442 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
443 if ( true_lineage_to_color_map.containsKey( lin ) ) {
444 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
452 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
453 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
454 final Taxonomy temp_tax = new Taxonomy();
455 temp_tax.setScientificName( lin );
456 if ( lineage_to_rank_map.containsKey( lin )
457 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
458 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
459 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
460 colorizeSubtree( node, c );
462 true_lineage_to_color_map.put( lin, c.getValue() );
466 UniProtTaxonomy up = null;
468 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
470 catch ( final Exception e ) {
473 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
474 lineage_to_rank_map.put( lin, up.getRank() );
475 if ( up.getRank().equalsIgnoreCase( rank ) ) {
476 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
477 colorizeSubtree( node, c );
479 true_lineage_to_color_map.put( lin, c.getValue() );
488 return colorizations;
491 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
492 node.getBranchData().setBranchColor( c );
493 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
494 for( final PhylogenyNode desc : descs ) {
495 desc.getBranchData().setBranchColor( c );
499 final static String[] getAllRanks( final Phylogeny tree ) {
500 final SortedSet<String> ranks = new TreeSet<String>();
501 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
502 final PhylogenyNode n = it.next();
503 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
504 ranks.add( n.getNodeData().getTaxonomy().getRank() );
507 return ForesterUtil.stringSetToArray( ranks );
510 public static String[] getAllPossibleRanks() {
511 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
513 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
514 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
515 str_array[ i++ ] = e;
521 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
522 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
523 it.next().getBranchData().setBranchColor( null );
525 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
526 final PhylogenyNode n = it.next();
527 if ( !n.getBranchData().isHasBranchColor() ) {
528 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
530 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
531 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
532 for( final PhylogenyNode desc : descs ) {
534 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
541 final static String createBasicInformation( final Phylogeny phy ) {
542 final StringBuilder desc = new StringBuilder();
543 if ( ( phy != null ) && !phy.isEmpty() ) {
544 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
545 desc.append( "Name: " );
546 desc.append( phy.getName() );
549 if ( phy.getIdentifier() != null ) {
550 desc.append( "Id: " );
551 desc.append( phy.getIdentifier() );
554 desc.append( "Rooted: " );
555 desc.append( phy.isRooted() );
557 desc.append( "Rerootable: " );
558 desc.append( phy.isRerootable() );
560 desc.append( "Node sum: " );
561 desc.append( phy.getNodeCount() );
563 desc.append( "External node sum: " );
564 desc.append( phy.getNumberOfExternalNodes() );
566 desc.append( "Internal node sum: " );
567 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
569 desc.append( "Branche sum: " );
570 desc.append( phy.getNumberOfBranches() );
572 desc.append( "Depth: " );
573 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
575 desc.append( "Maximum distance to root: " );
576 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
578 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
579 if ( taxs != null ) {
580 desc.append( "Distinct external taxonomies: " );
581 desc.append( taxs.size() );
584 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
585 if ( bs.getN() > 2 ) {
587 desc.append( "Branch-length statistics: " );
589 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
591 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
593 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
595 desc.append( " SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
597 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
599 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
602 final AsciiHistogram histo = new AsciiHistogram( bs );
603 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
605 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
606 if ( ds.getN() > 2 ) {
608 desc.append( "Descendants per node statistics: " );
610 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
612 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
614 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
616 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
618 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
621 List<DescriptiveStatistics> css = null;
623 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
625 catch ( final IllegalArgumentException e ) {
626 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
628 if ( ( css != null ) && ( css.size() > 0 ) ) {
630 for( int i = 0; i < css.size(); ++i ) {
631 final DescriptiveStatistics cs = css.get( i );
632 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
633 if ( css.size() > 1 ) {
634 desc.append( "Support statistics " + ( i + 1 ) + ": " );
637 desc.append( "Support statistics: " );
639 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
641 desc.append( " Type: " + cs.getDescription() );
644 desc.append( " Branches with support: " + cs.getN() );
646 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
648 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
650 if ( cs.getN() > 2 ) {
651 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
654 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
656 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
662 return desc.toString();
670 * to message to be printed
672 final static void dieWithSystemError( final String message ) {
673 System.out.println();
674 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
675 System.out.println( "Please contact the authors." );
676 System.out.println( Constants.PRG_NAME + " needs to close." );
677 System.out.println();
681 final static String[] getAvailableFontFamiliesSorted() {
682 return AVAILABLE_FONT_FAMILIES_SORTED;
685 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
686 boolean inferred = false;
687 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
688 final PhylogenyNode n = it.next();
689 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
690 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
691 if ( !ForesterUtil.isEmpty( sn ) ) {
692 n.getNodeData().setTaxonomy( new Taxonomy() );
693 n.getNodeData().getTaxonomy().setScientificName( sn );
699 tree.setRerootable( false );
703 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
704 if ( !node.getNodeData().isHasEvent() ) {
707 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
713 final static boolean isJava15() {
715 final String s = ForesterUtil.JAVA_VERSION;
716 return s.startsWith( "1.5" );
718 catch ( final Exception e ) {
719 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
724 final static boolean isMac() {
726 final String s = ForesterUtil.OS_NAME.toLowerCase();
727 return s.startsWith( "mac" );
729 catch ( final Exception e ) {
730 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
735 final static boolean isUsOrCanada() {
737 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
741 catch ( final Exception e ) {
747 final static boolean isWindows() {
749 final String s = ForesterUtil.OS_NAME.toLowerCase();
750 return s.indexOf( "win" ) > -1;
752 catch ( final Exception e ) {
753 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
758 final public static void launchWebBrowser( final URI uri,
759 final boolean is_applet,
760 final JApplet applet,
761 final String frame_name ) throws IOException {
763 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
766 // This requires Java 1.6:
767 // =======================
768 // boolean no_desktop = false;
770 // if ( Desktop.isDesktopSupported() ) {
771 // System.out.println( "desktop supported" );
772 // final Desktop dt = Desktop.getDesktop();
776 // no_desktop = true;
779 // catch ( final Exception ex ) {
780 // ex.printStackTrace();
781 // no_desktop = true;
783 // catch ( final Error er ) {
784 // er.printStackTrace();
785 // no_desktop = true;
787 // if ( no_desktop ) {
788 // System.out.println( "desktop not supported" );
790 openUrlInWebBrowser( uri.toString() );
792 catch ( final Exception e ) {
793 throw new IOException( e );
799 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
800 final ControlPanel atv_control,
801 final Configuration configuration ) {
802 if ( ( t != null ) && !t.isEmpty() ) {
803 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
804 atv_control.setDrawPhylogram( false );
805 atv_control.setDrawPhylogramEnabled( false );
807 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
808 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
809 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
810 atv_control.setDrawPhylogram( true );
811 atv_control.setDrawPhylogramEnabled( true );
814 atv_control.setDrawPhylogram( false );
818 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
819 if ( atv_control.getWriteConfidenceCb() != null ) {
820 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
821 atv_control.setCheckbox( Configuration.write_confidence_values, true );
824 atv_control.setCheckbox( Configuration.write_confidence_values, false );
828 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
829 if ( atv_control.getShowEventsCb() != null ) {
830 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
831 atv_control.setCheckbox( Configuration.write_events, true );
834 atv_control.setCheckbox( Configuration.write_events, false );
841 final private static char normalizeCharForRGB( char c ) {
844 c = c > 255 ? 255 : c;
849 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
850 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
851 InvocationTargetException, InterruptedException {
852 final String os = System.getProperty( "os.name" );
853 final Runtime runtime = Runtime.getRuntime();
854 if ( os.toLowerCase().startsWith( "win" ) ) {
855 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
857 else if ( isMac() ) {
858 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
859 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
860 open_url.invoke( null, new Object[] { url } );
863 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
864 String browser = null;
865 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
866 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
867 browser = browsers[ i ];
870 if ( browser == null ) {
871 throw new IOException( "could not find a web browser to open [" + url + "] in" );
874 runtime.exec( new String[] { browser, url } );
879 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
881 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
883 catch ( final Exception e ) {
884 throw new IOException( e );
888 final static void printAppletMessage( final String applet_name, final String message ) {
889 System.out.println( "[" + applet_name + "] > " + message );
892 public final static void printWarningMessage( final String name, final String message ) {
893 System.out.println( "[" + name + "] > " + message );
896 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
897 throws FileNotFoundException, IOException {
898 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
899 PhylogenyParser parser = null;
900 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
901 parser = new TolParser();
904 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
906 return factory.create( url.openStream(), parser );
909 final static void removeBranchColors( final Phylogeny phy ) {
910 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
911 it.next().getBranchData().setBranchColor( null );
915 final public static void showErrorMessage( final Component parent, final String error_msg ) {
916 printAppletMessage( Constants.PRG_NAME, error_msg );
917 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
918 + "] Error", JOptionPane.ERROR_MESSAGE );
921 final static void unexpectedError( final Error err ) {
922 err.printStackTrace();
923 final StringBuffer sb = new StringBuffer();
924 for( final StackTraceElement s : err.getStackTrace() ) {
925 sb.append( s + "\n" );
928 .showMessageDialog( null,
929 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
930 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
931 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
932 JOptionPane.ERROR_MESSAGE );
936 final static void unexpectedException( final Exception ex ) {
937 ex.printStackTrace();
938 final StringBuffer sb = new StringBuffer();
939 for( final StackTraceElement s : ex.getStackTrace() ) {
940 sb.append( s + "\n" );
942 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
943 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
944 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
947 final static String writePhylogenyToGraphicsFile( final String file_name,
950 final TreePanel tree_panel,
951 final ControlPanel ac,
952 final GraphicsExportType type,
953 final Options options ) throws IOException {
954 if ( !options.isGraphicsExportUsingActualSize() ) {
955 if ( options.isGraphicsExportVisibleOnly() ) {
956 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
958 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
959 tree_panel.resetPreferredSize();
960 tree_panel.repaint();
962 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
963 RenderingHints.VALUE_RENDER_QUALITY );
964 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
965 if ( options.isAntialiasPrint() ) {
966 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
967 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
970 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
971 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
973 final Phylogeny phylogeny = tree_panel.getPhylogeny();
974 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
977 final File file = new File( file_name );
978 if ( file.isDirectory() ) {
979 throw new IOException( "\"" + file_name + "\" is a directory" );
981 Rectangle visible = null;
982 if ( !options.isGraphicsExportUsingActualSize() ) {
983 width = options.getPrintSizeX();
984 height = options.getPrintSizeY();
986 else if ( options.isGraphicsExportVisibleOnly() ) {
987 visible = tree_panel.getVisibleRect();
988 width = visible.width;
989 height = visible.height;
991 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
992 Graphics2D g2d = buffered_img.createGraphics();
993 g2d.setRenderingHints( rendering_hints );
996 if ( options.isGraphicsExportVisibleOnly() ) {
997 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1002 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1003 if ( type == GraphicsExportType.TIFF ) {
1004 writeToTiff( file, buffered_img );
1007 ImageIO.write( buffered_img, type.toString(), file );
1011 if ( !options.isGraphicsExportUsingActualSize() ) {
1012 tree_panel.getMainPanel().getControlPanel().showWhole();
1014 String msg = file.toString();
1015 if ( ( width > 0 ) && ( height > 0 ) ) {
1016 msg += " [size: " + width + ", " + height + "]";
1021 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
1024 final TreePanel tree_panel,
1025 final ControlPanel ac,
1026 final GraphicsExportType type,
1027 final Options options ) throws IOException {
1028 tree_panel.setParametersForPainting( width, height, true );
1029 tree_panel.resetPreferredSize();
1030 tree_panel.repaint();
1031 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1032 RenderingHints.VALUE_RENDER_QUALITY );
1033 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1034 if ( options.isAntialiasPrint() ) {
1035 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1036 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1039 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1040 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1042 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1043 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1046 if ( outfile.isDirectory() ) {
1047 throw new IOException( "\"" + outfile + "\" is a directory" );
1049 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1050 final Graphics2D g2d = buffered_img.createGraphics();
1051 g2d.setRenderingHints( rendering_hints );
1052 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
1053 if ( type == GraphicsExportType.TIFF ) {
1054 writeToTiff( outfile, buffered_img );
1057 ImageIO.write( buffered_img, type.toString(), outfile );
1062 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1065 final TreePanel tree_panel,
1066 final ControlPanel ac,
1067 final GraphicsExportType type,
1068 final Options options ) throws IOException {
1069 if ( !options.isGraphicsExportUsingActualSize() ) {
1070 if ( options.isGraphicsExportVisibleOnly() ) {
1071 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1073 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1074 tree_panel.resetPreferredSize();
1075 tree_panel.repaint();
1077 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1078 RenderingHints.VALUE_RENDER_QUALITY );
1079 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1080 if ( options.isAntialiasPrint() ) {
1081 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1082 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1085 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1086 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1088 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1089 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1092 Rectangle visible = null;
1093 if ( !options.isGraphicsExportUsingActualSize() ) {
1094 width = options.getPrintSizeX();
1095 height = options.getPrintSizeY();
1097 else if ( options.isGraphicsExportVisibleOnly() ) {
1098 visible = tree_panel.getVisibleRect();
1099 width = visible.width;
1100 height = visible.height;
1102 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1103 Graphics2D g2d = buffered_img.createGraphics();
1104 g2d.setRenderingHints( rendering_hints );
1107 if ( options.isGraphicsExportVisibleOnly() ) {
1108 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1109 g2d.setClip( null );
1113 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1114 ImageIO.write( buffered_img, type.toString(), baos );
1117 if ( !options.isGraphicsExportUsingActualSize() ) {
1118 tree_panel.getMainPanel().getControlPanel().showWhole();
1120 String msg = baos.toString();
1121 if ( ( width > 0 ) && ( height > 0 ) ) {
1122 msg += " [size: " + width + ", " + height + "]";
1127 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1128 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1129 ImageWriter writer = null;
1130 ImageOutputStream ios = null;
1131 // Find an appropriate writer:
1132 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1133 if ( it.hasNext() ) {
1137 throw new IOException( "failed to get TIFF image writer" );
1140 ios = ImageIO.createImageOutputStream( file );
1141 writer.setOutput( ios );
1142 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1143 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1144 // see writeParam.getCompressionTypes() for available compression type
1146 image_write_param.setCompressionType( "PackBits" );
1147 final String t[] = image_write_param.getCompressionTypes();
1148 for( final String string : t ) {
1149 System.out.println( string );
1151 // Convert to an IIOImage:
1152 final IIOImage iio_image = new IIOImage( image, null, null );
1153 writer.write( null, iio_image, image_write_param );
1156 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1157 // static void openDDBJRest() throws IOException {
1159 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1161 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1162 // //make connection
1163 // URLConnection urlc = url.openConnection();
1165 // urlc.setDoOutput( true );
1166 // urlc.setAllowUserInteraction( false );
1168 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1169 // ps.print( query );
1172 // BufferedReader br = new BufferedReader( new InputStreamReader(
1173 // urlc.getInputStream() ) );
1175 // while ( ( l = br.readLine() ) != null ) {
1176 // System.out.println( l );
1180 public static enum GraphicsExportType {
1181 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1183 private final String _suffix;
1185 private GraphicsExportType( final String suffix ) {
1190 public String toString() {