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.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.DescriptiveStatistics;
83 import org.forester.util.ForesterUtil;
84 import org.forester.ws.uniprot.UniProtTaxonomy;
86 public final class AptxUtil {
88 private final static Pattern seq_identifier_pattern_1 = Pattern
89 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
90 private final static Pattern seq_identifier_pattern_2 = Pattern
91 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
92 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
93 .getAvailableFontFamilyNames();
95 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
98 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
99 final String n = sequence_name.trim();
100 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
103 if ( matcher1.matches() ) {
104 group1 = matcher1.group( 1 );
105 group2 = matcher1.group( 2 );
108 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
109 if ( matcher2.matches() ) {
110 group1 = matcher2.group( 1 );
111 group2 = matcher2.group( 2 );
114 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
117 return new Accession( group2, group1 );
120 public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
121 if ( !node.getNodeData().isHasTaxonomy() ) {
122 node.getNodeData().setTaxonomy( new Taxonomy() );
126 public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
127 if ( !node.getNodeData().isHasSequence() ) {
128 node.getNodeData().setSequence( new Sequence() );
132 final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
133 if ( !node.getNodeData().isHasDistribution() ) {
134 node.getNodeData().setDistribution( new Distribution( "" ) );
138 final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
139 if ( !node.getNodeData().isHasDate() ) {
140 node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
144 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
145 final PhylogenyNodeIterator it = phy.iteratorPostorder();
146 while ( it.hasNext() ) {
147 if ( it.next().getBranchData().isHasConfidences() ) {
154 public static void writePhylogenyToGraphicsFile( final File intree,
158 final GraphicsExportType type,
159 final Configuration config ) throws IOException {
160 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
161 Phylogeny[] phys = null;
162 phys = PhylogenyMethods.readPhylogenies( parser, intree );
163 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
166 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
170 final GraphicsExportType type,
171 final Configuration config ) throws IOException {
172 final Phylogeny[] phys = new Phylogeny[ 1 ];
174 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
175 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
176 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
181 * Returns true if at least one branch has a length larger than zero.
186 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
187 final PhylogenyNodeIterator it = phy.iteratorPostorder();
188 while ( it.hasNext() ) {
189 if ( it.next().getDistanceToParent() > 0.0 ) {
196 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
197 final PhylogenyNodeIterator it = phy.iteratorPostorder();
198 while ( it.hasNext() ) {
199 if ( it.next().getNodeData().isHasEvent() ) {
206 public static MaskFormatter createMaskFormatter( final String s ) {
207 MaskFormatter formatter = null;
209 formatter = new MaskFormatter( s );
211 catch ( final ParseException e ) {
212 throw new IllegalArgumentException( e );
217 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
218 final String default_name,
219 final String full_path,
220 final Configuration configuration,
221 final MainPanel main_panel ) {
222 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
223 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
224 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
225 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
228 for( final Phylogeny phy : phys ) {
229 if ( !phy.isEmpty() ) {
230 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
232 String my_name_for_file = "";
233 if ( phys.length > 1 ) {
234 if ( !ForesterUtil.isEmpty( default_name ) ) {
235 my_name = new String( default_name );
237 if ( !ForesterUtil.isEmpty( full_path ) ) {
238 my_name_for_file = new String( full_path );
240 else if ( !ForesterUtil.isEmpty( default_name ) ) {
241 my_name_for_file = new String( default_name );
244 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
245 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
246 my_name_for_file.length() );
247 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
249 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
250 my_name_for_file += "_";
252 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
253 my_name_for_file += phy.getName().replaceAll( " ", "_" );
255 else if ( phy.getIdentifier() != null ) {
256 final StringBuffer sb = new StringBuffer();
257 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
258 sb.append( phy.getIdentifier().getProvider() );
261 sb.append( phy.getIdentifier().getValue() );
262 my_name_for_file += sb;
265 my_name_for_file += i;
267 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
268 && ( phy.getIdentifier() == null ) ) {
269 my_name = my_name + " [" + i + "]";
271 if ( !ForesterUtil.isEmpty( suffix ) ) {
272 my_name_for_file += suffix;
276 if ( !ForesterUtil.isEmpty( default_name ) ) {
277 my_name = new String( default_name );
279 my_name_for_file = "";
280 if ( !ForesterUtil.isEmpty( full_path ) ) {
281 my_name_for_file = new String( full_path );
283 else if ( !ForesterUtil.isEmpty( default_name ) ) {
284 my_name_for_file = new String( default_name );
286 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
287 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
288 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
290 else if ( phy.getIdentifier() != null ) {
291 final StringBuffer sb = new StringBuffer();
292 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
293 sb.append( phy.getIdentifier().getProvider() );
296 sb.append( phy.getIdentifier().getValue() );
297 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
301 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
302 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
303 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
310 final static void addPhylogenyToPanel( final Phylogeny[] phys,
311 final Configuration configuration,
312 final MainPanel main_panel ) {
313 final Phylogeny phy = phys[ 0 ];
314 main_panel.addPhylogenyInPanel( phy, configuration );
315 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
318 final static Color calculateColorFromString( final String str ) {
319 final String species_uc = str.toUpperCase();
320 char first = species_uc.charAt( 0 );
323 if ( species_uc.length() > 1 ) {
324 second = species_uc.charAt( 1 );
325 if ( species_uc.length() > 2 ) {
326 if ( species_uc.indexOf( " " ) > 0 ) {
327 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
330 third = species_uc.charAt( 2 );
334 first = AptxUtil.normalizeCharForRGB( first );
335 second = AptxUtil.normalizeCharForRGB( second );
336 third = AptxUtil.normalizeCharForRGB( third );
337 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
340 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
343 return new Color( first, second, third );
346 // Returns true if the specified format name can be written
347 final static boolean canWriteFormat( final String format_name ) {
348 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
349 return iter.hasNext();
352 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
353 boolean inferred = false;
354 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
355 final PhylogenyNode n = it.next();
356 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
357 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
358 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
359 AptxUtil.collapseSubtree( n, true );
360 if ( !n.getNodeData().isHasTaxonomy() ) {
361 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
362 .getTaxonomy().copy() );
367 n.setCollapse( false );
372 phy.setRerootable( false );
376 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
377 node.setCollapse( collapse );
378 if ( node.isExternal() ) {
381 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
382 while ( it.hasNext() ) {
383 it.next().setCollapse( collapse );
387 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
388 double max_conf = 0.0;
389 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
390 final PhylogenyNode n = it.next();
391 n.getBranchData().setBranchColor( null );
392 if ( n.getBranchData().isHasConfidences() ) {
393 final double conf = PhylogenyMethods.getConfidenceValue( n );
394 if ( conf > max_conf ) {
399 if ( max_conf > 0.0 ) {
400 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
401 final Color br = tree_panel.getTreeColorSet().getBranchColor();
402 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
403 final PhylogenyNode n = it.next();
404 if ( n.getBranchData().isHasConfidences() ) {
405 final double conf = PhylogenyMethods.getConfidenceValue( n );
406 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
407 colorizeSubtree( n, c );
413 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
414 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
415 int colorizations = 0;
416 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
417 final PhylogenyNode n = it.next();
418 if ( n.getNodeData().isHasTaxonomy()
419 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
420 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
421 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
422 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
423 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
424 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
426 colorizeSubtree( n, c );
428 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
429 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
434 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
435 final PhylogenyNode node = it.next();
436 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
437 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
438 boolean success = false;
439 if ( !true_lineage_to_color_map.isEmpty() ) {
440 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
441 if ( true_lineage_to_color_map.containsKey( lin ) ) {
442 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
450 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
451 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
452 final Taxonomy temp_tax = new Taxonomy();
453 temp_tax.setScientificName( lin );
454 if ( lineage_to_rank_map.containsKey( lin )
455 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
456 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
457 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
458 colorizeSubtree( node, c );
460 true_lineage_to_color_map.put( lin, c.getValue() );
464 UniProtTaxonomy up = null;
466 up = AncestralTaxonomyInference.obtainUniProtTaxonomy( temp_tax, null, null );
468 catch ( final Exception e ) {
471 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
472 lineage_to_rank_map.put( lin, up.getRank() );
473 if ( up.getRank().equalsIgnoreCase( rank ) ) {
474 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
475 colorizeSubtree( node, c );
477 true_lineage_to_color_map.put( lin, c.getValue() );
486 return colorizations;
489 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
490 node.getBranchData().setBranchColor( c );
491 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
492 for( final PhylogenyNode desc : descs ) {
493 desc.getBranchData().setBranchColor( c );
497 final static String[] getAllRanks( final Phylogeny tree ) {
498 final SortedSet<String> ranks = new TreeSet<String>();
499 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
500 final PhylogenyNode n = it.next();
501 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
502 ranks.add( n.getNodeData().getTaxonomy().getRank() );
505 return ForesterUtil.stringSetToArray( ranks );
508 public static String[] getAllPossibleRanks() {
509 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
511 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
512 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
513 str_array[ i++ ] = e;
519 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
520 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
521 it.next().getBranchData().setBranchColor( null );
523 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
524 final PhylogenyNode n = it.next();
525 if ( !n.getBranchData().isHasBranchColor() ) {
526 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
528 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
529 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
530 for( final PhylogenyNode desc : descs ) {
532 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
539 final static String crateBasicInformation( final Phylogeny phy ) {
540 final StringBuilder desc = new StringBuilder();
541 if ( ( phy != null ) && !phy.isEmpty() ) {
542 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
543 desc.append( "Name: " );
544 desc.append( phy.getName() );
547 if ( phy.getIdentifier() != null ) {
548 desc.append( "Id: " );
549 desc.append( phy.getIdentifier() );
552 desc.append( "Rooted: " );
553 desc.append( phy.isRooted() );
555 desc.append( "Rerootable: " );
556 desc.append( phy.isRerootable() );
558 desc.append( "Node sum: " );
559 desc.append( phy.getNodeCount() );
561 desc.append( "External node sum: " );
562 desc.append( phy.getNumberOfExternalNodes() );
564 desc.append( "Internal node sum: " );
565 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
567 desc.append( "Branche sum: " );
568 desc.append( phy.getNumberOfBranches() );
570 desc.append( "Depth: " );
571 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
573 desc.append( "Maximum distance to root: " );
574 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
576 desc.append( "Descendants per node statistics: " );
577 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
579 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
581 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
583 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
585 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
587 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
589 final DescriptiveStatistics cs = PhylogenyMethods.calculatConfidenceStatistics( phy );
590 if ( cs.getN() > 1 ) {
591 desc.append( "Support statistics: " );
593 desc.append( " Branches with support: " + cs.getN() );
595 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
597 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
599 if ( cs.getN() > 2 ) {
600 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
603 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
605 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
608 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
609 if ( taxs != null ) {
610 desc.append( "Distinct external taxonomies: " );
611 desc.append( taxs.size() );
614 return desc.toString();
622 * to message to be printed
624 final static void dieWithSystemError( final String message ) {
625 System.out.println();
626 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
627 System.out.println( "Please contact the authors." );
628 System.out.println( Constants.PRG_NAME + " needs to close." );
629 System.out.println();
633 final static String[] getAvailableFontFamiliesSorted() {
634 return AVAILABLE_FONT_FAMILIES_SORTED;
637 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
638 boolean inferred = false;
639 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
640 final PhylogenyNode n = it.next();
641 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
642 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
643 if ( !ForesterUtil.isEmpty( sn ) ) {
644 n.getNodeData().setTaxonomy( new Taxonomy() );
645 n.getNodeData().getTaxonomy().setScientificName( sn );
651 tree.setRerootable( false );
655 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
656 if ( !node.getNodeData().isHasEvent() ) {
659 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
665 final static boolean isJava15() {
667 final String s = ForesterUtil.JAVA_VERSION;
668 return s.startsWith( "1.5" );
670 catch ( final Exception e ) {
671 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
676 final static boolean isMac() {
678 final String s = ForesterUtil.OS_NAME.toLowerCase();
679 return s.startsWith( "mac" );
681 catch ( final Exception e ) {
682 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
687 final static boolean isUsOrCanada() {
689 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
693 catch ( final Exception e ) {
699 final static boolean isWindows() {
701 final String s = ForesterUtil.OS_NAME.toLowerCase();
702 return s.indexOf( "win" ) > -1;
704 catch ( final Exception e ) {
705 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
710 final public static void launchWebBrowser( final URI uri,
711 final boolean is_applet,
712 final JApplet applet,
713 final String frame_name ) throws IOException {
715 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
718 // This requires Java 1.6:
719 // =======================
720 // boolean no_desktop = false;
722 // if ( Desktop.isDesktopSupported() ) {
723 // System.out.println( "desktop supported" );
724 // final Desktop dt = Desktop.getDesktop();
728 // no_desktop = true;
731 // catch ( final Exception ex ) {
732 // ex.printStackTrace();
733 // no_desktop = true;
735 // catch ( final Error er ) {
736 // er.printStackTrace();
737 // no_desktop = true;
739 // if ( no_desktop ) {
740 // System.out.println( "desktop not supported" );
742 openUrlInWebBrowser( uri.toString() );
744 catch ( final Exception e ) {
745 throw new IOException( e );
751 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
752 final ControlPanel atv_control,
753 final Configuration configuration ) {
754 if ( ( t != null ) && !t.isEmpty() ) {
755 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
756 atv_control.setDrawPhylogram( false );
757 atv_control.setDrawPhylogramEnabled( false );
759 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
760 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
761 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
762 atv_control.setDrawPhylogram( true );
763 atv_control.setDrawPhylogramEnabled( true );
766 atv_control.setDrawPhylogram( false );
770 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
771 if ( atv_control.getWriteConfidenceCb() != null ) {
772 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
773 atv_control.setCheckbox( Configuration.write_confidence_values, true );
776 atv_control.setCheckbox( Configuration.write_confidence_values, false );
780 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
781 if ( atv_control.getShowEventsCb() != null ) {
782 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
783 atv_control.setCheckbox( Configuration.write_events, true );
786 atv_control.setCheckbox( Configuration.write_events, false );
793 final private static char normalizeCharForRGB( char c ) {
796 c = c > 255 ? 255 : c;
801 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
802 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
803 InvocationTargetException, InterruptedException {
804 final String os = System.getProperty( "os.name" );
805 final Runtime runtime = Runtime.getRuntime();
806 if ( os.toLowerCase().startsWith( "win" ) ) {
807 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
809 else if ( isMac() ) {
810 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
811 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
812 open_url.invoke( null, new Object[] { url } );
815 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
816 String browser = null;
817 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
818 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
819 browser = browsers[ i ];
822 if ( browser == null ) {
823 throw new IOException( "could not find a web browser to open [" + url + "] in" );
826 runtime.exec( new String[] { browser, url } );
831 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
833 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
835 catch ( final Exception e ) {
836 throw new IOException( e );
840 final static void printAppletMessage( final String applet_name, final String message ) {
841 System.out.println( "[" + applet_name + "] > " + message );
844 public final static void printWarningMessage( final String name, final String message ) {
845 System.out.println( "[" + name + "] > " + message );
848 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
849 throws FileNotFoundException, IOException {
850 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
851 PhylogenyParser parser = null;
852 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
853 parser = new TolParser();
856 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
858 return factory.create( url.openStream(), parser );
861 final static void removeBranchColors( final Phylogeny phy ) {
862 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
863 it.next().getBranchData().setBranchColor( null );
867 final public static void showErrorMessage( final Component parent, final String error_msg ) {
868 printAppletMessage( Constants.PRG_NAME, error_msg );
869 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
870 + "] Error", JOptionPane.ERROR_MESSAGE );
873 final static void unexpectedError( final Error err ) {
874 err.printStackTrace();
875 final StringBuffer sb = new StringBuffer();
876 for( final StackTraceElement s : err.getStackTrace() ) {
877 sb.append( s + "\n" );
880 .showMessageDialog( null,
881 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
882 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
883 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
884 JOptionPane.ERROR_MESSAGE );
888 final static void unexpectedException( final Exception ex ) {
889 ex.printStackTrace();
890 final StringBuffer sb = new StringBuffer();
891 for( final StackTraceElement s : ex.getStackTrace() ) {
892 sb.append( s + "\n" );
894 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
895 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
896 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
899 final static String writePhylogenyToGraphicsFile( final String file_name,
902 final TreePanel tree_panel,
903 final ControlPanel ac,
904 final GraphicsExportType type,
905 final Options options ) throws IOException {
906 if ( !options.isGraphicsExportUsingActualSize() ) {
907 if ( options.isGraphicsExportVisibleOnly() ) {
908 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
910 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
911 tree_panel.resetPreferredSize();
912 tree_panel.repaint();
914 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
915 RenderingHints.VALUE_RENDER_QUALITY );
916 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
917 if ( options.isAntialiasPrint() ) {
918 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
919 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
922 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
923 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
925 final Phylogeny phylogeny = tree_panel.getPhylogeny();
926 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
929 final File file = new File( file_name );
930 if ( file.isDirectory() ) {
931 throw new IOException( "\"" + file_name + "\" is a directory" );
933 Rectangle visible = null;
934 if ( !options.isGraphicsExportUsingActualSize() ) {
935 width = options.getPrintSizeX();
936 height = options.getPrintSizeY();
938 else if ( options.isGraphicsExportVisibleOnly() ) {
939 visible = tree_panel.getVisibleRect();
940 width = visible.width;
941 height = visible.height;
943 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
944 Graphics2D g2d = buffered_img.createGraphics();
945 g2d.setRenderingHints( rendering_hints );
948 if ( options.isGraphicsExportVisibleOnly() ) {
949 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
954 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
955 if ( type == GraphicsExportType.TIFF ) {
956 writeToTiff( file, buffered_img );
959 ImageIO.write( buffered_img, type.toString(), file );
963 if ( !options.isGraphicsExportUsingActualSize() ) {
964 tree_panel.getMainPanel().getControlPanel().showWhole();
966 String msg = file.toString();
967 if ( ( width > 0 ) && ( height > 0 ) ) {
968 msg += " [size: " + width + ", " + height + "]";
973 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
976 final TreePanel tree_panel,
977 final ControlPanel ac,
978 final GraphicsExportType type,
979 final Options options ) throws IOException {
980 tree_panel.setParametersForPainting( width, height, true );
981 tree_panel.resetPreferredSize();
982 tree_panel.repaint();
983 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
984 RenderingHints.VALUE_RENDER_QUALITY );
985 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
986 if ( options.isAntialiasPrint() ) {
987 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
988 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
991 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
992 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
994 final Phylogeny phylogeny = tree_panel.getPhylogeny();
995 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
998 if ( outfile.isDirectory() ) {
999 throw new IOException( "\"" + outfile + "\" is a directory" );
1001 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1002 final Graphics2D g2d = buffered_img.createGraphics();
1003 g2d.setRenderingHints( rendering_hints );
1004 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
1005 if ( type == GraphicsExportType.TIFF ) {
1006 writeToTiff( outfile, buffered_img );
1009 ImageIO.write( buffered_img, type.toString(), outfile );
1014 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1017 final TreePanel tree_panel,
1018 final ControlPanel ac,
1019 final GraphicsExportType type,
1020 final Options options ) throws IOException {
1021 if ( !options.isGraphicsExportUsingActualSize() ) {
1022 if ( options.isGraphicsExportVisibleOnly() ) {
1023 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1025 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1026 tree_panel.resetPreferredSize();
1027 tree_panel.repaint();
1029 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1030 RenderingHints.VALUE_RENDER_QUALITY );
1031 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1032 if ( options.isAntialiasPrint() ) {
1033 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1034 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1037 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1038 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1040 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1041 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1044 Rectangle visible = null;
1045 if ( !options.isGraphicsExportUsingActualSize() ) {
1046 width = options.getPrintSizeX();
1047 height = options.getPrintSizeY();
1049 else if ( options.isGraphicsExportVisibleOnly() ) {
1050 visible = tree_panel.getVisibleRect();
1051 width = visible.width;
1052 height = visible.height;
1054 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1055 Graphics2D g2d = buffered_img.createGraphics();
1056 g2d.setRenderingHints( rendering_hints );
1059 if ( options.isGraphicsExportVisibleOnly() ) {
1060 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1061 g2d.setClip( null );
1065 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1066 ImageIO.write( buffered_img, type.toString(), baos );
1069 if ( !options.isGraphicsExportUsingActualSize() ) {
1070 tree_panel.getMainPanel().getControlPanel().showWhole();
1072 String msg = baos.toString();
1073 if ( ( width > 0 ) && ( height > 0 ) ) {
1074 msg += " [size: " + width + ", " + height + "]";
1079 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1080 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1081 ImageWriter writer = null;
1082 ImageOutputStream ios = null;
1083 // Find an appropriate writer:
1084 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1085 if ( it.hasNext() ) {
1089 throw new IOException( "failed to get TIFF image writer" );
1092 ios = ImageIO.createImageOutputStream( file );
1093 writer.setOutput( ios );
1094 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1095 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1096 // see writeParam.getCompressionTypes() for available compression type
1098 image_write_param.setCompressionType( "PackBits" );
1099 final String t[] = image_write_param.getCompressionTypes();
1100 for( final String string : t ) {
1101 System.out.println( string );
1103 // Convert to an IIOImage:
1104 final IIOImage iio_image = new IIOImage( image, null, null );
1105 writer.write( null, iio_image, image_write_param );
1108 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1109 // static void openDDBJRest() throws IOException {
1111 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1113 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1114 // //make connection
1115 // URLConnection urlc = url.openConnection();
1117 // urlc.setDoOutput( true );
1118 // urlc.setAllowUserInteraction( false );
1120 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1121 // ps.print( query );
1124 // BufferedReader br = new BufferedReader( new InputStreamReader(
1125 // urlc.getInputStream() ) );
1127 // while ( ( l = br.readLine() ) != null ) {
1128 // System.out.println( l );
1132 public static enum GraphicsExportType {
1133 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1135 private final String _suffix;
1137 private GraphicsExportType( final String suffix ) {
1142 public String toString() {