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() > 2 ) {
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 ) );
601 final AsciiHistogram histo = new AsciiHistogram( bs );
602 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
604 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
605 if ( ds.getN() > 2 ) {
607 desc.append( "Descendants per node statistics: " );
609 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
611 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
613 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
615 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
617 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
620 List<DescriptiveStatistics> css = null;
622 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
624 catch ( final IllegalArgumentException e ) {
625 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
627 if ( ( css != null ) && ( css.size() > 0 ) ) {
629 for( int i = 0; i < css.size(); ++i ) {
630 final DescriptiveStatistics cs = css.get( i );
631 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
632 if ( css.size() > 1 ) {
633 desc.append( "Support statistics " + ( i + 1 ) + ": " );
636 desc.append( "Support statistics: " );
638 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
640 desc.append( " Type: " + cs.getDescription() );
643 desc.append( " Branches with support: " + cs.getN() );
645 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
647 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
649 if ( cs.getN() > 2 ) {
650 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
653 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
655 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
661 return desc.toString();
669 * to message to be printed
671 final static void dieWithSystemError( final String message ) {
672 System.out.println();
673 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
674 System.out.println( "Please contact the authors." );
675 System.out.println( Constants.PRG_NAME + " needs to close." );
676 System.out.println();
680 final static String[] getAvailableFontFamiliesSorted() {
681 return AVAILABLE_FONT_FAMILIES_SORTED;
684 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
685 boolean inferred = false;
686 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
687 final PhylogenyNode n = it.next();
688 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
689 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
690 if ( !ForesterUtil.isEmpty( sn ) ) {
691 n.getNodeData().setTaxonomy( new Taxonomy() );
692 n.getNodeData().getTaxonomy().setScientificName( sn );
698 tree.setRerootable( false );
702 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
703 if ( !node.getNodeData().isHasEvent() ) {
706 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
712 final static boolean isJava15() {
714 final String s = ForesterUtil.JAVA_VERSION;
715 return s.startsWith( "1.5" );
717 catch ( final Exception e ) {
718 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
723 final static boolean isMac() {
725 final String s = ForesterUtil.OS_NAME.toLowerCase();
726 return s.startsWith( "mac" );
728 catch ( final Exception e ) {
729 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
734 final static boolean isUsOrCanada() {
736 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
740 catch ( final Exception e ) {
746 final static boolean isWindows() {
748 final String s = ForesterUtil.OS_NAME.toLowerCase();
749 return s.indexOf( "win" ) > -1;
751 catch ( final Exception e ) {
752 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
757 final public static void launchWebBrowser( final URI uri,
758 final boolean is_applet,
759 final JApplet applet,
760 final String frame_name ) throws IOException {
762 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
765 // This requires Java 1.6:
766 // =======================
767 // boolean no_desktop = false;
769 // if ( Desktop.isDesktopSupported() ) {
770 // System.out.println( "desktop supported" );
771 // final Desktop dt = Desktop.getDesktop();
775 // no_desktop = true;
778 // catch ( final Exception ex ) {
779 // ex.printStackTrace();
780 // no_desktop = true;
782 // catch ( final Error er ) {
783 // er.printStackTrace();
784 // no_desktop = true;
786 // if ( no_desktop ) {
787 // System.out.println( "desktop not supported" );
789 openUrlInWebBrowser( uri.toString() );
791 catch ( final Exception e ) {
792 throw new IOException( e );
798 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
799 final ControlPanel atv_control,
800 final Configuration configuration ) {
801 if ( ( t != null ) && !t.isEmpty() ) {
802 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
803 atv_control.setDrawPhylogram( false );
804 atv_control.setDrawPhylogramEnabled( false );
806 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
807 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
808 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
809 atv_control.setDrawPhylogram( true );
810 atv_control.setDrawPhylogramEnabled( true );
813 atv_control.setDrawPhylogram( false );
817 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
818 if ( atv_control.getWriteConfidenceCb() != null ) {
819 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
820 atv_control.setCheckbox( Configuration.write_confidence_values, true );
823 atv_control.setCheckbox( Configuration.write_confidence_values, false );
827 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
828 if ( atv_control.getShowEventsCb() != null ) {
829 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
830 atv_control.setCheckbox( Configuration.write_events, true );
833 atv_control.setCheckbox( Configuration.write_events, false );
840 final private static char normalizeCharForRGB( char c ) {
843 c = c > 255 ? 255 : c;
848 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
849 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
850 InvocationTargetException, InterruptedException {
851 final String os = System.getProperty( "os.name" );
852 final Runtime runtime = Runtime.getRuntime();
853 if ( os.toLowerCase().startsWith( "win" ) ) {
854 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
856 else if ( isMac() ) {
857 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
858 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
859 open_url.invoke( null, new Object[] { url } );
862 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
863 String browser = null;
864 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
865 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
866 browser = browsers[ i ];
869 if ( browser == null ) {
870 throw new IOException( "could not find a web browser to open [" + url + "] in" );
873 runtime.exec( new String[] { browser, url } );
878 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
880 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
882 catch ( final Exception e ) {
883 throw new IOException( e );
887 final static void printAppletMessage( final String applet_name, final String message ) {
888 System.out.println( "[" + applet_name + "] > " + message );
891 public final static void printWarningMessage( final String name, final String message ) {
892 System.out.println( "[" + name + "] > " + message );
895 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
896 throws FileNotFoundException, IOException {
897 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
898 PhylogenyParser parser = null;
899 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
900 parser = new TolParser();
903 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
905 return factory.create( url.openStream(), parser );
908 final static void removeBranchColors( final Phylogeny phy ) {
909 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
910 it.next().getBranchData().setBranchColor( null );
914 final public static void showErrorMessage( final Component parent, final String error_msg ) {
915 printAppletMessage( Constants.PRG_NAME, error_msg );
916 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
917 + "] Error", JOptionPane.ERROR_MESSAGE );
920 final static void unexpectedError( final Error err ) {
921 err.printStackTrace();
922 final StringBuffer sb = new StringBuffer();
923 for( final StackTraceElement s : err.getStackTrace() ) {
924 sb.append( s + "\n" );
927 .showMessageDialog( null,
928 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
929 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
930 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
931 JOptionPane.ERROR_MESSAGE );
935 final static void unexpectedException( final Exception ex ) {
936 ex.printStackTrace();
937 final StringBuffer sb = new StringBuffer();
938 for( final StackTraceElement s : ex.getStackTrace() ) {
939 sb.append( s + "\n" );
941 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
942 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
943 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
946 final static String writePhylogenyToGraphicsFile( final String file_name,
949 final TreePanel tree_panel,
950 final ControlPanel ac,
951 final GraphicsExportType type,
952 final Options options ) throws IOException {
953 if ( !options.isGraphicsExportUsingActualSize() ) {
954 if ( options.isGraphicsExportVisibleOnly() ) {
955 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
957 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
958 tree_panel.resetPreferredSize();
959 tree_panel.repaint();
961 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
962 RenderingHints.VALUE_RENDER_QUALITY );
963 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
964 if ( options.isAntialiasPrint() ) {
965 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
966 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
969 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
970 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
972 final Phylogeny phylogeny = tree_panel.getPhylogeny();
973 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
976 final File file = new File( file_name );
977 if ( file.isDirectory() ) {
978 throw new IOException( "\"" + file_name + "\" is a directory" );
980 Rectangle visible = null;
981 if ( !options.isGraphicsExportUsingActualSize() ) {
982 width = options.getPrintSizeX();
983 height = options.getPrintSizeY();
985 else if ( options.isGraphicsExportVisibleOnly() ) {
986 visible = tree_panel.getVisibleRect();
987 width = visible.width;
988 height = visible.height;
990 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
991 Graphics2D g2d = buffered_img.createGraphics();
992 g2d.setRenderingHints( rendering_hints );
995 if ( options.isGraphicsExportVisibleOnly() ) {
996 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1001 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1002 if ( type == GraphicsExportType.TIFF ) {
1003 writeToTiff( file, buffered_img );
1006 ImageIO.write( buffered_img, type.toString(), file );
1010 if ( !options.isGraphicsExportUsingActualSize() ) {
1011 tree_panel.getMainPanel().getControlPanel().showWhole();
1013 String msg = file.toString();
1014 if ( ( width > 0 ) && ( height > 0 ) ) {
1015 msg += " [size: " + width + ", " + height + "]";
1020 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
1023 final TreePanel tree_panel,
1024 final ControlPanel ac,
1025 final GraphicsExportType type,
1026 final Options options ) throws IOException {
1027 tree_panel.setParametersForPainting( width, height, true );
1028 tree_panel.resetPreferredSize();
1029 tree_panel.repaint();
1030 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1031 RenderingHints.VALUE_RENDER_QUALITY );
1032 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1033 if ( options.isAntialiasPrint() ) {
1034 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1035 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1038 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1039 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1041 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1042 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1045 if ( outfile.isDirectory() ) {
1046 throw new IOException( "\"" + outfile + "\" is a directory" );
1048 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1049 final Graphics2D g2d = buffered_img.createGraphics();
1050 g2d.setRenderingHints( rendering_hints );
1051 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
1052 if ( type == GraphicsExportType.TIFF ) {
1053 writeToTiff( outfile, buffered_img );
1056 ImageIO.write( buffered_img, type.toString(), outfile );
1061 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1064 final TreePanel tree_panel,
1065 final ControlPanel ac,
1066 final GraphicsExportType type,
1067 final Options options ) throws IOException {
1068 if ( !options.isGraphicsExportUsingActualSize() ) {
1069 if ( options.isGraphicsExportVisibleOnly() ) {
1070 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1072 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1073 tree_panel.resetPreferredSize();
1074 tree_panel.repaint();
1076 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1077 RenderingHints.VALUE_RENDER_QUALITY );
1078 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1079 if ( options.isAntialiasPrint() ) {
1080 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1081 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1084 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1085 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1087 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1088 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1091 Rectangle visible = null;
1092 if ( !options.isGraphicsExportUsingActualSize() ) {
1093 width = options.getPrintSizeX();
1094 height = options.getPrintSizeY();
1096 else if ( options.isGraphicsExportVisibleOnly() ) {
1097 visible = tree_panel.getVisibleRect();
1098 width = visible.width;
1099 height = visible.height;
1101 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1102 Graphics2D g2d = buffered_img.createGraphics();
1103 g2d.setRenderingHints( rendering_hints );
1106 if ( options.isGraphicsExportVisibleOnly() ) {
1107 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1108 g2d.setClip( null );
1112 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1113 ImageIO.write( buffered_img, type.toString(), baos );
1116 if ( !options.isGraphicsExportUsingActualSize() ) {
1117 tree_panel.getMainPanel().getControlPanel().showWhole();
1119 String msg = baos.toString();
1120 if ( ( width > 0 ) && ( height > 0 ) ) {
1121 msg += " [size: " + width + ", " + height + "]";
1126 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1127 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1128 ImageWriter writer = null;
1129 ImageOutputStream ios = null;
1130 // Find an appropriate writer:
1131 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1132 if ( it.hasNext() ) {
1136 throw new IOException( "failed to get TIFF image writer" );
1139 ios = ImageIO.createImageOutputStream( file );
1140 writer.setOutput( ios );
1141 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1142 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1143 // see writeParam.getCompressionTypes() for available compression type
1145 image_write_param.setCompressionType( "PackBits" );
1146 final String t[] = image_write_param.getCompressionTypes();
1147 for( final String string : t ) {
1148 System.out.println( string );
1150 // Convert to an IIOImage:
1151 final IIOImage iio_image = new IIOImage( image, null, null );
1152 writer.write( null, iio_image, image_write_param );
1155 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1156 // static void openDDBJRest() throws IOException {
1158 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1160 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1161 // //make connection
1162 // URLConnection urlc = url.openConnection();
1164 // urlc.setDoOutput( true );
1165 // urlc.setAllowUserInteraction( false );
1167 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1168 // ps.print( query );
1171 // BufferedReader br = new BufferedReader( new InputStreamReader(
1172 // urlc.getInputStream() ) );
1174 // while ( ( l = br.readLine() ) != null ) {
1175 // System.out.println( l );
1179 public static enum GraphicsExportType {
1180 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1182 private final String _suffix;
1184 private GraphicsExportType( final String suffix ) {
1189 public String toString() {