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 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
100 final String default_name,
101 final String full_path,
102 final Configuration configuration,
103 final MainPanel main_panel ) {
104 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
105 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
106 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
107 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
110 for( final Phylogeny phy : phys ) {
111 if ( !phy.isEmpty() ) {
112 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
114 String my_name_for_file = "";
115 if ( phys.length > 1 ) {
116 if ( !ForesterUtil.isEmpty( default_name ) ) {
117 my_name = new String( default_name );
119 if ( !ForesterUtil.isEmpty( full_path ) ) {
120 my_name_for_file = new String( full_path );
122 else if ( !ForesterUtil.isEmpty( default_name ) ) {
123 my_name_for_file = new String( default_name );
126 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
127 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
128 my_name_for_file.length() );
129 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
131 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
132 my_name_for_file += "_";
134 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
135 my_name_for_file += phy.getName().replaceAll( " ", "_" );
137 else if ( phy.getIdentifier() != null ) {
138 final StringBuffer sb = new StringBuffer();
139 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
140 sb.append( phy.getIdentifier().getProvider() );
143 sb.append( phy.getIdentifier().getValue() );
144 my_name_for_file += sb;
147 my_name_for_file += i;
149 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
150 && ( phy.getIdentifier() == null ) ) {
151 my_name = my_name + " [" + i + "]";
153 if ( !ForesterUtil.isEmpty( suffix ) ) {
154 my_name_for_file += suffix;
158 if ( !ForesterUtil.isEmpty( default_name ) ) {
159 my_name = new String( default_name );
161 my_name_for_file = "";
162 if ( !ForesterUtil.isEmpty( full_path ) ) {
163 my_name_for_file = new String( full_path );
165 else if ( !ForesterUtil.isEmpty( default_name ) ) {
166 my_name_for_file = new String( default_name );
168 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
169 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
170 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
172 else if ( phy.getIdentifier() != null ) {
173 final StringBuffer sb = new StringBuffer();
174 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
175 sb.append( phy.getIdentifier().getProvider() );
178 sb.append( phy.getIdentifier().getValue() );
179 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
183 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
184 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
185 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
192 final static void addPhylogenyToPanel( final Phylogeny[] phys,
193 final Configuration configuration,
194 final MainPanel main_panel ) {
195 final Phylogeny phy = phys[ 0 ];
196 main_panel.addPhylogenyInPanel( phy, configuration );
197 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
200 final static Color calculateColorFromString( final String str ) {
201 final String species_uc = str.toUpperCase();
202 char first = species_uc.charAt( 0 );
205 if ( species_uc.length() > 1 ) {
206 second = species_uc.charAt( 1 );
207 if ( species_uc.length() > 2 ) {
208 if ( species_uc.indexOf( " " ) > 0 ) {
209 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
212 third = species_uc.charAt( 2 );
216 first = AptxUtil.normalizeCharForRGB( first );
217 second = AptxUtil.normalizeCharForRGB( second );
218 third = AptxUtil.normalizeCharForRGB( third );
219 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
222 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
225 return new Color( first, second, third );
228 // Returns true if the specified format name can be written
229 final static boolean canWriteFormat( final String format_name ) {
230 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
231 return iter.hasNext();
234 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
235 boolean inferred = false;
236 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
237 final PhylogenyNode n = it.next();
238 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
239 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
240 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
241 AptxUtil.collapseSubtree( n, true );
242 if ( !n.getNodeData().isHasTaxonomy() ) {
243 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
244 .getTaxonomy().copy() );
249 n.setCollapse( false );
254 phy.setRerootable( false );
258 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
259 node.setCollapse( collapse );
260 if ( node.isExternal() ) {
263 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
264 while ( it.hasNext() ) {
265 it.next().setCollapse( collapse );
269 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
270 node.getBranchData().setBranchColor( c );
271 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
272 for( final PhylogenyNode desc : descs ) {
273 desc.getBranchData().setBranchColor( c );
277 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
278 double max_conf = 0.0;
279 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
280 final PhylogenyNode n = it.next();
281 n.getBranchData().setBranchColor( null );
282 if ( n.getBranchData().isHasConfidences() ) {
283 final double conf = PhylogenyMethods.getConfidenceValue( n );
284 if ( conf > max_conf ) {
289 if ( max_conf > 0.0 ) {
290 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
291 final Color br = tree_panel.getTreeColorSet().getBranchColor();
292 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
293 final PhylogenyNode n = it.next();
294 if ( n.getBranchData().isHasConfidences() ) {
295 final double conf = PhylogenyMethods.getConfidenceValue( n );
296 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
297 colorizeSubtree( n, c );
303 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
304 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
305 it.next().getBranchData().setBranchColor( null );
307 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
308 final PhylogenyNode n = it.next();
309 if ( !n.getBranchData().isHasBranchColor() ) {
310 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
312 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
313 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
314 for( final PhylogenyNode desc : descs ) {
316 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
323 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
324 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
325 int colorizations = 0;
326 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
327 final PhylogenyNode n = it.next();
328 if ( n.getNodeData().isHasTaxonomy()
329 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
330 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
331 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
332 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
333 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
334 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
336 colorizeSubtree( n, c );
338 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
339 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
344 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
345 final PhylogenyNode node = it.next();
346 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
347 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
348 boolean success = false;
349 if ( !true_lineage_to_color_map.isEmpty() ) {
350 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
351 if ( true_lineage_to_color_map.containsKey( lin ) ) {
352 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
360 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
361 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
362 final Taxonomy temp_tax = new Taxonomy();
363 temp_tax.setScientificName( lin );
364 if ( lineage_to_rank_map.containsKey( lin )
365 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
366 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
367 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
368 colorizeSubtree( node, c );
370 true_lineage_to_color_map.put( lin, c.getValue() );
374 UniProtTaxonomy up = null;
376 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
378 catch ( final Exception e ) {
381 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
382 lineage_to_rank_map.put( lin, up.getRank() );
383 if ( up.getRank().equalsIgnoreCase( rank ) ) {
384 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
385 colorizeSubtree( node, c );
387 true_lineage_to_color_map.put( lin, c.getValue() );
396 return colorizations;
399 final static String createBasicInformation( final Phylogeny phy ) {
400 final StringBuilder desc = new StringBuilder();
401 if ( ( phy != null ) && !phy.isEmpty() ) {
402 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
403 desc.append( "Name: " );
404 desc.append( phy.getName() );
407 if ( phy.getIdentifier() != null ) {
408 desc.append( "Id: " );
409 desc.append( phy.getIdentifier() );
412 desc.append( "Rooted: " );
413 desc.append( phy.isRooted() );
415 desc.append( "Rerootable: " );
416 desc.append( phy.isRerootable() );
418 desc.append( "Node sum: " );
419 desc.append( phy.getNodeCount() );
421 desc.append( "External node sum: " );
422 desc.append( phy.getNumberOfExternalNodes() );
424 desc.append( "Internal node sum: " );
425 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
427 desc.append( "Branche sum: " );
428 desc.append( phy.getNumberOfBranches() );
430 desc.append( "Depth: " );
431 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
433 desc.append( "Maximum distance to root: " );
434 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
436 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
437 if ( taxs != null ) {
438 desc.append( "Distinct external taxonomies: " );
439 desc.append( taxs.size() );
442 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
443 if ( bs.getN() > 3 ) {
445 desc.append( "Branch-length statistics: " );
447 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
449 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
451 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
453 desc.append( " SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
455 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
457 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
459 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
461 final AsciiHistogram histo = new AsciiHistogram( bs );
462 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
465 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
466 if ( ds.getN() > 2 ) {
468 desc.append( "Descendants per node statistics: " );
470 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
472 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
474 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
476 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
478 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
481 List<DescriptiveStatistics> css = null;
483 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
485 catch ( final IllegalArgumentException e ) {
486 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
488 if ( ( css != null ) && ( css.size() > 0 ) ) {
490 for( int i = 0; i < css.size(); ++i ) {
491 final DescriptiveStatistics cs = css.get( i );
492 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
493 if ( css.size() > 1 ) {
494 desc.append( "Support statistics " + ( i + 1 ) + ": " );
497 desc.append( "Support statistics: " );
499 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
501 desc.append( " Type: " + cs.getDescription() );
504 desc.append( " Branches with support: " + cs.getN() );
506 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
508 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
510 if ( cs.getN() > 2 ) {
511 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
514 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
516 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
522 return desc.toString();
525 public static MaskFormatter createMaskFormatter( final String s ) {
526 MaskFormatter formatter = null;
528 formatter = new MaskFormatter( s );
530 catch ( final ParseException e ) {
531 throw new IllegalArgumentException( e );
541 * to message to be printed
543 final static void dieWithSystemError( final String message ) {
544 System.out.println();
545 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
546 System.out.println( "Please contact the authors." );
547 System.out.println( Constants.PRG_NAME + " needs to close." );
548 System.out.println();
552 final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
553 if ( !node.getNodeData().isHasDate() ) {
554 node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
558 final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
559 if ( !node.getNodeData().isHasDistribution() ) {
560 node.getNodeData().setDistribution( new Distribution( "" ) );
564 public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
565 if ( !node.getNodeData().isHasSequence() ) {
566 node.getNodeData().setSequence( new Sequence() );
570 public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
571 if ( !node.getNodeData().isHasTaxonomy() ) {
572 node.getNodeData().setTaxonomy( new Taxonomy() );
576 public static String[] getAllPossibleRanks() {
577 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
579 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
580 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
581 str_array[ i++ ] = e;
587 final static String[] getAllRanks( final Phylogeny tree ) {
588 final SortedSet<String> ranks = new TreeSet<String>();
589 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
590 final PhylogenyNode n = it.next();
591 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
592 ranks.add( n.getNodeData().getTaxonomy().getRank() );
595 return ForesterUtil.stringSetToArray( ranks );
598 final static String[] getAvailableFontFamiliesSorted() {
599 return AVAILABLE_FONT_FAMILIES_SORTED;
602 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
603 boolean inferred = false;
604 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
605 final PhylogenyNode n = it.next();
606 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
607 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
608 if ( !ForesterUtil.isEmpty( sn ) ) {
609 n.getNodeData().setTaxonomy( new Taxonomy() );
610 n.getNodeData().getTaxonomy().setScientificName( sn );
616 tree.setRerootable( false );
620 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
621 if ( !node.getNodeData().isHasEvent() ) {
624 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
630 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
631 final PhylogenyNodeIterator it = phy.iteratorPostorder();
632 while ( it.hasNext() ) {
633 if ( it.next().getNodeData().isHasEvent() ) {
641 * Returns true if at least one branch has a length larger than zero.
646 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
647 final PhylogenyNodeIterator it = phy.iteratorPostorder();
648 while ( it.hasNext() ) {
649 if ( it.next().getDistanceToParent() > 0.0 ) {
656 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
657 final PhylogenyNodeIterator it = phy.iteratorPostorder();
658 while ( it.hasNext() ) {
659 if ( it.next().getBranchData().isHasConfidences() ) {
666 final static boolean isJava15() {
668 final String s = ForesterUtil.JAVA_VERSION;
669 return s.startsWith( "1.5" );
671 catch ( final Exception e ) {
672 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
677 final static boolean isMac() {
679 final String s = ForesterUtil.OS_NAME.toLowerCase();
680 return s.startsWith( "mac" );
682 catch ( final Exception e ) {
683 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
688 final static boolean isUsOrCanada() {
690 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
694 catch ( final Exception e ) {
700 final static boolean isWindows() {
702 final String s = ForesterUtil.OS_NAME.toLowerCase();
703 return s.indexOf( "win" ) > -1;
705 catch ( final Exception e ) {
706 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
711 final public static void launchWebBrowser( final URI uri,
712 final boolean is_applet,
713 final JApplet applet,
714 final String frame_name ) throws IOException {
716 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
719 // This requires Java 1.6:
720 // =======================
721 // boolean no_desktop = false;
723 // if ( Desktop.isDesktopSupported() ) {
724 // System.out.println( "desktop supported" );
725 // final Desktop dt = Desktop.getDesktop();
729 // no_desktop = true;
732 // catch ( final Exception ex ) {
733 // ex.printStackTrace();
734 // no_desktop = true;
736 // catch ( final Error er ) {
737 // er.printStackTrace();
738 // no_desktop = true;
740 // if ( no_desktop ) {
741 // System.out.println( "desktop not supported" );
743 openUrlInWebBrowser( uri.toString() );
745 catch ( final Exception e ) {
746 throw new IOException( e );
752 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
753 final ControlPanel atv_control,
754 final Configuration configuration ) {
755 if ( ( t != null ) && !t.isEmpty() ) {
756 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
757 atv_control.setDrawPhylogram( false );
758 atv_control.setDrawPhylogramEnabled( false );
760 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
761 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
762 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
763 atv_control.setDrawPhylogram( true );
764 atv_control.setDrawPhylogramEnabled( true );
767 atv_control.setDrawPhylogram( false );
771 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
772 if ( atv_control.getWriteConfidenceCb() != null ) {
773 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
774 atv_control.setCheckbox( Configuration.write_confidence_values, true );
777 atv_control.setCheckbox( Configuration.write_confidence_values, false );
781 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
782 if ( atv_control.getShowEventsCb() != null ) {
783 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
784 atv_control.setCheckbox( Configuration.write_events, true );
787 atv_control.setCheckbox( Configuration.write_events, false );
794 final private static char normalizeCharForRGB( char c ) {
797 c = c > 255 ? 255 : c;
802 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
803 final String n = sequence_name.trim();
804 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
807 if ( matcher1.matches() ) {
808 group1 = matcher1.group( 1 );
809 group2 = matcher1.group( 2 );
812 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
813 if ( matcher2.matches() ) {
814 group1 = matcher2.group( 1 );
815 group2 = matcher2.group( 2 );
818 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
821 return new Accession( group2, group1 );
824 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
825 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
826 InvocationTargetException, InterruptedException {
827 final String os = System.getProperty( "os.name" );
828 final Runtime runtime = Runtime.getRuntime();
829 if ( os.toLowerCase().startsWith( "win" ) ) {
830 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
832 else if ( isMac() ) {
833 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
834 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
835 open_url.invoke( null, new Object[] { url } );
838 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
839 String browser = null;
840 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
841 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
842 browser = browsers[ i ];
845 if ( browser == null ) {
846 throw new IOException( "could not find a web browser to open [" + url + "] in" );
849 runtime.exec( new String[] { browser, url } );
854 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
856 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
858 catch ( final Exception e ) {
859 throw new IOException( e );
863 final static void printAppletMessage( final String applet_name, final String message ) {
864 System.out.println( "[" + applet_name + "] > " + message );
867 public final static void printWarningMessage( final String name, final String message ) {
868 System.out.println( "[" + name + "] > " + message );
871 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
872 throws FileNotFoundException, IOException {
873 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
874 PhylogenyParser parser = null;
875 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
876 parser = new TolParser();
879 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
881 return factory.create( url.openStream(), parser );
884 final static void removeBranchColors( final Phylogeny phy ) {
885 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
886 it.next().getBranchData().setBranchColor( null );
890 final public static void showErrorMessage( final Component parent, final String error_msg ) {
891 printAppletMessage( Constants.PRG_NAME, error_msg );
892 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
893 + "] Error", JOptionPane.ERROR_MESSAGE );
896 public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
897 final PhylogenyNode node,
898 final List<String> data ) {
899 final StringBuilder sb = new StringBuilder();
900 if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
901 showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
903 if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
904 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
905 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
907 if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
908 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
909 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
911 if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
912 && ( node.getNodeData().getSequence().getAccession() != null )
913 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
914 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
916 if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
917 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
918 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
920 if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
921 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
922 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
924 if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
925 && node.getNodeData().isHasSequence()
926 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
927 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
929 final String s = sb.toString().trim();
930 if ( !ForesterUtil.isEmpty( s ) ) {
935 public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
936 if ( sb.length() > 0 ) {
942 final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
943 JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
946 final static void unexpectedError( final Error err ) {
947 err.printStackTrace();
948 final StringBuffer sb = new StringBuffer();
949 for( final StackTraceElement s : err.getStackTrace() ) {
950 sb.append( s + "\n" );
953 .showMessageDialog( null,
954 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
955 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
956 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
957 JOptionPane.ERROR_MESSAGE );
961 final static void unexpectedException( final Exception ex ) {
962 ex.printStackTrace();
963 final StringBuffer sb = new StringBuffer();
964 for( final StackTraceElement s : ex.getStackTrace() ) {
965 sb.append( s + "\n" );
967 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
968 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
969 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
972 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
975 final TreePanel tree_panel,
976 final ControlPanel ac,
977 final GraphicsExportType type,
978 final Options options ) throws IOException {
979 if ( !options.isGraphicsExportUsingActualSize() ) {
980 if ( options.isGraphicsExportVisibleOnly() ) {
981 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
983 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
984 tree_panel.resetPreferredSize();
985 tree_panel.repaint();
987 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
988 RenderingHints.VALUE_RENDER_QUALITY );
989 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
990 if ( options.isAntialiasPrint() ) {
991 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
992 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
995 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
996 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
998 final Phylogeny phylogeny = tree_panel.getPhylogeny();
999 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1002 Rectangle visible = null;
1003 if ( !options.isGraphicsExportUsingActualSize() ) {
1004 width = options.getPrintSizeX();
1005 height = options.getPrintSizeY();
1007 else if ( options.isGraphicsExportVisibleOnly() ) {
1008 visible = tree_panel.getVisibleRect();
1009 width = visible.width;
1010 height = visible.height;
1012 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1013 Graphics2D g2d = buffered_img.createGraphics();
1014 g2d.setRenderingHints( rendering_hints );
1017 if ( options.isGraphicsExportVisibleOnly() ) {
1018 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1019 g2d.setClip( null );
1023 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1024 ImageIO.write( buffered_img, type.toString(), baos );
1027 if ( !options.isGraphicsExportUsingActualSize() ) {
1028 tree_panel.getMainPanel().getControlPanel().showWhole();
1030 String msg = baos.toString();
1031 if ( ( width > 0 ) && ( height > 0 ) ) {
1032 msg += " [size: " + width + ", " + height + "]";
1037 public static void writePhylogenyToGraphicsFile( final File intree,
1041 final GraphicsExportType type,
1042 final Configuration config ) throws IOException {
1043 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
1044 Phylogeny[] phys = null;
1045 phys = PhylogenyMethods.readPhylogenies( parser, intree );
1046 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
1049 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
1053 final GraphicsExportType type,
1054 final Configuration config ) throws IOException {
1055 final Phylogeny[] phys = new Phylogeny[ 1 ];
1057 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
1058 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
1059 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
1063 final static String writePhylogenyToGraphicsFile( final String file_name,
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 final File file = new File( file_name );
1094 if ( file.isDirectory() ) {
1095 throw new IOException( "\"" + file_name + "\" is a directory" );
1097 Rectangle visible = null;
1098 if ( !options.isGraphicsExportUsingActualSize() ) {
1099 width = options.getPrintSizeX();
1100 height = options.getPrintSizeY();
1102 else if ( options.isGraphicsExportVisibleOnly() ) {
1103 visible = tree_panel.getVisibleRect();
1104 width = visible.width;
1105 height = visible.height;
1107 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1108 Graphics2D g2d = buffered_img.createGraphics();
1109 g2d.setRenderingHints( rendering_hints );
1112 if ( options.isGraphicsExportVisibleOnly() ) {
1113 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1114 g2d.setClip( null );
1118 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1119 if ( type == GraphicsExportType.TIFF ) {
1120 writeToTiff( file, buffered_img );
1123 ImageIO.write( buffered_img, type.toString(), file );
1127 if ( !options.isGraphicsExportUsingActualSize() ) {
1128 tree_panel.getMainPanel().getControlPanel().showWhole();
1130 String msg = file.toString();
1131 if ( ( width > 0 ) && ( height > 0 ) ) {
1132 msg += " [size: " + width + ", " + height + "]";
1137 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
1140 final TreePanel tree_panel,
1141 final ControlPanel ac,
1142 final GraphicsExportType type,
1143 final Options options ) throws IOException {
1144 tree_panel.setParametersForPainting( width, height, true );
1145 tree_panel.resetPreferredSize();
1146 tree_panel.repaint();
1147 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1148 RenderingHints.VALUE_RENDER_QUALITY );
1149 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1150 if ( options.isAntialiasPrint() ) {
1151 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1152 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1155 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1156 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1158 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1159 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1162 if ( outfile.isDirectory() ) {
1163 throw new IOException( "\"" + outfile + "\" is a directory" );
1165 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1166 final Graphics2D g2d = buffered_img.createGraphics();
1167 g2d.setRenderingHints( rendering_hints );
1168 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
1169 if ( type == GraphicsExportType.TIFF ) {
1170 writeToTiff( outfile, buffered_img );
1173 ImageIO.write( buffered_img, type.toString(), outfile );
1178 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1179 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1180 ImageWriter writer = null;
1181 ImageOutputStream ios = null;
1182 // Find an appropriate writer:
1183 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1184 if ( it.hasNext() ) {
1188 throw new IOException( "failed to get TIFF image writer" );
1191 ios = ImageIO.createImageOutputStream( file );
1192 writer.setOutput( ios );
1193 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1194 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1195 // see writeParam.getCompressionTypes() for available compression type
1197 image_write_param.setCompressionType( "PackBits" );
1198 final String t[] = image_write_param.getCompressionTypes();
1199 for( final String string : t ) {
1200 System.out.println( string );
1202 // Convert to an IIOImage:
1203 final IIOImage iio_image = new IIOImage( image, null, null );
1204 writer.write( null, iio_image, image_write_param );
1207 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1208 // static void openDDBJRest() throws IOException {
1210 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1212 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1213 // //make connection
1214 // URLConnection urlc = url.openConnection();
1216 // urlc.setDoOutput( true );
1217 // urlc.setAllowUserInteraction( false );
1219 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1220 // ps.print( query );
1223 // BufferedReader br = new BufferedReader( new InputStreamReader(
1224 // urlc.getInputStream() ) );
1226 // while ( ( l = br.readLine() ) != null ) {
1227 // System.out.println( l );
1231 public static enum GraphicsExportType {
1232 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1234 private final String _suffix;
1236 private GraphicsExportType( final String suffix ) {
1241 public String toString() {