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;
54 import javax.imageio.IIOImage;
55 import javax.imageio.ImageIO;
56 import javax.imageio.ImageWriteParam;
57 import javax.imageio.ImageWriter;
58 import javax.imageio.stream.ImageOutputStream;
59 import javax.swing.JApplet;
60 import javax.swing.JOptionPane;
61 import javax.swing.text.MaskFormatter;
63 import org.forester.analysis.AncestralTaxonomyInference;
64 import org.forester.io.parsers.PhylogenyParser;
65 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
66 import org.forester.io.parsers.tol.TolParser;
67 import org.forester.io.parsers.util.ParserUtils;
68 import org.forester.phylogeny.Phylogeny;
69 import org.forester.phylogeny.PhylogenyMethods;
70 import org.forester.phylogeny.PhylogenyNode;
71 import org.forester.phylogeny.data.BranchColor;
72 import org.forester.phylogeny.data.Distribution;
73 import org.forester.phylogeny.data.Sequence;
74 import org.forester.phylogeny.data.Taxonomy;
75 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
76 import org.forester.phylogeny.factories.PhylogenyFactory;
77 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
78 import org.forester.phylogeny.iterators.PreorderTreeIterator;
79 import org.forester.util.DescriptiveStatistics;
80 import org.forester.util.ForesterUtil;
81 import org.forester.ws.uniprot.UniProtTaxonomy;
83 public final class AptxUtil {
85 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
86 .getAvailableFontFamilyNames();
88 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
91 public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
92 if ( !node.getNodeData().isHasTaxonomy() ) {
93 node.getNodeData().setTaxonomy( new Taxonomy() );
97 public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
98 if ( !node.getNodeData().isHasSequence() ) {
99 node.getNodeData().setSequence( new Sequence() );
103 final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
104 if ( !node.getNodeData().isHasDistribution() ) {
105 node.getNodeData().setDistribution( new Distribution( "" ) );
109 final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
110 if ( !node.getNodeData().isHasDate() ) {
111 node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
115 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
116 final PhylogenyNodeIterator it = phy.iteratorPostorder();
117 while ( it.hasNext() ) {
118 if ( it.next().getBranchData().isHasConfidences() ) {
125 public static void writePhylogenyToGraphicsFile( final File intree,
129 final GraphicsExportType type,
130 final Configuration config ) throws IOException {
131 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
132 Phylogeny[] phys = null;
133 phys = PhylogenyMethods.readPhylogenies( parser, intree );
134 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
137 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
141 final GraphicsExportType type,
142 final Configuration config ) throws IOException {
143 final Phylogeny[] phys = new Phylogeny[ 1 ];
145 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
146 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
147 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
152 * Returns true if at least one branch has a length larger than zero.
157 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
158 final PhylogenyNodeIterator it = phy.iteratorPostorder();
159 while ( it.hasNext() ) {
160 if ( it.next().getDistanceToParent() > 0.0 ) {
167 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
168 final PhylogenyNodeIterator it = phy.iteratorPostorder();
169 while ( it.hasNext() ) {
170 if ( it.next().getNodeData().isHasEvent() ) {
177 public static MaskFormatter createMaskFormatter( final String s ) {
178 MaskFormatter formatter = null;
180 formatter = new MaskFormatter( s );
182 catch ( final ParseException e ) {
183 throw new IllegalArgumentException( e );
188 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
189 final String default_name,
190 final String full_path,
191 final Configuration configuration,
192 final MainPanel main_panel ) {
193 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
194 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
195 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
196 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
199 for( final Phylogeny phy : phys ) {
200 if ( !phy.isEmpty() ) {
201 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
203 String my_name_for_file = "";
204 if ( phys.length > 1 ) {
205 if ( !ForesterUtil.isEmpty( default_name ) ) {
206 my_name = new String( default_name );
208 if ( !ForesterUtil.isEmpty( full_path ) ) {
209 my_name_for_file = new String( full_path );
211 else if ( !ForesterUtil.isEmpty( default_name ) ) {
212 my_name_for_file = new String( default_name );
215 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
216 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
217 my_name_for_file.length() );
218 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
220 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
221 my_name_for_file += "_";
223 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
224 my_name_for_file += phy.getName().replaceAll( " ", "_" );
226 else if ( phy.getIdentifier() != null ) {
227 final StringBuffer sb = new StringBuffer();
228 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
229 sb.append( phy.getIdentifier().getProvider() );
232 sb.append( phy.getIdentifier().getValue() );
233 my_name_for_file += sb;
236 my_name_for_file += i;
238 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
239 && ( phy.getIdentifier() == null ) ) {
240 my_name = my_name + " [" + i + "]";
242 if ( !ForesterUtil.isEmpty( suffix ) ) {
243 my_name_for_file += suffix;
247 if ( !ForesterUtil.isEmpty( default_name ) ) {
248 my_name = new String( default_name );
250 my_name_for_file = "";
251 if ( !ForesterUtil.isEmpty( full_path ) ) {
252 my_name_for_file = new String( full_path );
254 else if ( !ForesterUtil.isEmpty( default_name ) ) {
255 my_name_for_file = new String( default_name );
257 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
258 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
259 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
261 else if ( phy.getIdentifier() != null ) {
262 final StringBuffer sb = new StringBuffer();
263 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
264 sb.append( phy.getIdentifier().getProvider() );
267 sb.append( phy.getIdentifier().getValue() );
268 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
272 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
273 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
274 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
281 final static void addPhylogenyToPanel( final Phylogeny[] phys,
282 final Configuration configuration,
283 final MainPanel main_panel ) {
284 final Phylogeny phy = phys[ 0 ];
285 main_panel.addPhylogenyInPanel( phy, configuration );
286 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
289 final static Color calculateColorFromString( final String str ) {
290 final String species_uc = str.toUpperCase();
291 char first = species_uc.charAt( 0 );
294 if ( species_uc.length() > 1 ) {
295 second = species_uc.charAt( 1 );
296 if ( species_uc.length() > 2 ) {
297 if ( species_uc.indexOf( " " ) > 0 ) {
298 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
301 third = species_uc.charAt( 2 );
305 first = AptxUtil.normalizeCharForRGB( first );
306 second = AptxUtil.normalizeCharForRGB( second );
307 third = AptxUtil.normalizeCharForRGB( third );
308 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
311 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
314 return new Color( first, second, third );
317 // Returns true if the specified format name can be written
318 final static boolean canWriteFormat( final String format_name ) {
319 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
320 return iter.hasNext();
323 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
324 boolean inferred = false;
325 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
326 final PhylogenyNode n = it.next();
327 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
328 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
329 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
330 AptxUtil.collapseSubtree( n, true );
331 if ( !n.getNodeData().isHasTaxonomy() ) {
332 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
333 .getTaxonomy().copy() );
338 n.setCollapse( false );
343 phy.setRerootable( false );
347 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
348 node.setCollapse( collapse );
349 if ( node.isExternal() ) {
352 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
353 while ( it.hasNext() ) {
354 it.next().setCollapse( collapse );
358 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
359 double max_conf = 0.0;
360 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
361 final PhylogenyNode n = it.next();
362 n.getBranchData().setBranchColor( null );
363 if ( n.getBranchData().isHasConfidences() ) {
364 final double conf = PhylogenyMethods.getConfidenceValue( n );
365 if ( conf > max_conf ) {
370 if ( max_conf > 0.0 ) {
371 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
372 final Color br = tree_panel.getTreeColorSet().getBranchColor();
373 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
374 final PhylogenyNode n = it.next();
375 if ( n.getBranchData().isHasConfidences() ) {
376 final double conf = PhylogenyMethods.getConfidenceValue( n );
377 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
378 colorizeSubtree( n, c );
384 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
385 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
386 int colorizations = 0;
387 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
388 final PhylogenyNode n = it.next();
389 if ( n.getNodeData().isHasTaxonomy()
390 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
391 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
392 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
393 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
394 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
395 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
397 colorizeSubtree( n, c );
399 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
400 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
405 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
406 final PhylogenyNode node = it.next();
407 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
408 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
409 boolean success = false;
410 if ( !true_lineage_to_color_map.isEmpty() ) {
411 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
412 if ( true_lineage_to_color_map.containsKey( lin ) ) {
413 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
421 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
422 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
423 final Taxonomy temp_tax = new Taxonomy();
424 temp_tax.setScientificName( lin );
425 if ( lineage_to_rank_map.containsKey( lin )
426 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
427 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
428 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
429 colorizeSubtree( node, c );
431 true_lineage_to_color_map.put( lin, c.getValue() );
435 UniProtTaxonomy up = null;
437 up = AncestralTaxonomyInference.obtainUniProtTaxonomy( temp_tax, null, null );
439 catch ( final Exception e ) {
442 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
443 lineage_to_rank_map.put( lin, up.getRank() );
444 if ( up.getRank().equalsIgnoreCase( rank ) ) {
445 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
446 colorizeSubtree( node, c );
448 true_lineage_to_color_map.put( lin, c.getValue() );
457 return colorizations;
460 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
461 node.getBranchData().setBranchColor( c );
462 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
463 for( final PhylogenyNode desc : descs ) {
464 desc.getBranchData().setBranchColor( c );
468 final static String[] getAllRanks( final Phylogeny tree ) {
469 final SortedSet<String> ranks = new TreeSet<String>();
470 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
471 final PhylogenyNode n = it.next();
472 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
473 ranks.add( n.getNodeData().getTaxonomy().getRank() );
476 return ForesterUtil.stringSetToArray( ranks );
479 public static String[] getAllPossibleRanks() {
480 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
482 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
483 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
484 str_array[ i++ ] = e;
490 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
491 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
492 it.next().getBranchData().setBranchColor( null );
494 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
495 final PhylogenyNode n = it.next();
496 if ( !n.getBranchData().isHasBranchColor() ) {
497 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
499 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
500 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
501 for( final PhylogenyNode desc : descs ) {
503 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
510 final static String crateBasicInformation( final Phylogeny phy ) {
511 final StringBuilder desc = new StringBuilder();
512 if ( ( phy != null ) && !phy.isEmpty() ) {
513 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
514 desc.append( "Name: " );
515 desc.append( phy.getName() );
518 if ( phy.getIdentifier() != null ) {
519 desc.append( "Id: " );
520 desc.append( phy.getIdentifier() );
523 desc.append( "Rooted: " );
524 desc.append( phy.isRooted() );
526 desc.append( "Rerootable: " );
527 desc.append( phy.isRerootable() );
529 desc.append( "Node sum: " );
530 desc.append( phy.getNodeCount() );
532 desc.append( "External node sum: " );
533 desc.append( phy.getNumberOfExternalNodes() );
535 desc.append( "Internal node sum: " );
536 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
538 desc.append( "Branche sum: " );
539 desc.append( phy.getNumberOfBranches() );
541 desc.append( "Depth: " );
542 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
544 desc.append( "Maximum distance to root: " );
545 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
547 desc.append( "Descendants per node statistics: " );
548 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
550 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
552 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
554 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
556 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
558 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
560 final DescriptiveStatistics cs = PhylogenyMethods.calculatConfidenceStatistics( phy );
561 if ( cs.getN() > 1 ) {
562 desc.append( "Support statistics: " );
564 desc.append( " Branches with support: " + cs.getN() );
566 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
568 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
570 if ( cs.getN() > 2 ) {
571 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
574 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
576 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
579 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
580 if ( taxs != null ) {
581 desc.append( "Distinct external taxonomies: " );
582 desc.append( taxs.size() );
585 return desc.toString();
593 * to message to be printed
595 final static void dieWithSystemError( final String message ) {
596 System.out.println();
597 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
598 System.out.println( "Please contact the authors." );
599 System.out.println( Constants.PRG_NAME + " needs to close." );
600 System.out.println();
604 final static String[] getAvailableFontFamiliesSorted() {
605 return AVAILABLE_FONT_FAMILIES_SORTED;
608 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
609 boolean inferred = false;
610 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
611 final PhylogenyNode n = it.next();
612 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
613 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
614 if ( !ForesterUtil.isEmpty( sn ) ) {
615 n.getNodeData().setTaxonomy( new Taxonomy() );
616 n.getNodeData().getTaxonomy().setScientificName( sn );
622 tree.setRerootable( false );
626 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
627 if ( !node.getNodeData().isHasEvent() ) {
630 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
636 final static boolean isJava15() {
638 final String s = ForesterUtil.JAVA_VERSION;
639 return s.startsWith( "1.5" );
641 catch ( final Exception e ) {
642 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
647 final static boolean isMac() {
649 final String s = ForesterUtil.OS_NAME.toLowerCase();
650 return s.startsWith( "mac" );
652 catch ( final Exception e ) {
653 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
658 final static boolean isUsOrCanada() {
660 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
664 catch ( final Exception e ) {
670 final static boolean isWindows() {
672 final String s = ForesterUtil.OS_NAME.toLowerCase();
673 return s.indexOf( "win" ) > -1;
675 catch ( final Exception e ) {
676 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
681 final static void launchWebBrowser( final URI uri,
682 final boolean is_applet,
683 final JApplet applet,
684 final String frame_name ) throws IOException {
686 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
689 // This requires Java 1.6:
690 // =======================
691 // boolean no_desktop = false;
693 // if ( Desktop.isDesktopSupported() ) {
694 // System.out.println( "desktop supported" );
695 // final Desktop dt = Desktop.getDesktop();
699 // no_desktop = true;
702 // catch ( final Exception ex ) {
703 // ex.printStackTrace();
704 // no_desktop = true;
706 // catch ( final Error er ) {
707 // er.printStackTrace();
708 // no_desktop = true;
710 // if ( no_desktop ) {
711 // System.out.println( "desktop not supported" );
713 openUrlInWebBrowser( uri.toString() );
715 catch ( final Exception e ) {
716 throw new IOException( e );
722 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
723 final ControlPanel atv_control,
724 final Configuration configuration ) {
725 if ( ( t != null ) && !t.isEmpty() ) {
726 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
727 atv_control.setDrawPhylogram( false );
728 atv_control.setDrawPhylogramEnabled( false );
730 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
731 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
732 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
733 atv_control.setDrawPhylogram( true );
734 atv_control.setDrawPhylogramEnabled( true );
737 atv_control.setDrawPhylogram( false );
741 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
742 if ( atv_control.getWriteConfidenceCb() != null ) {
743 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
744 atv_control.setCheckbox( Configuration.write_confidence_values, true );
747 atv_control.setCheckbox( Configuration.write_confidence_values, false );
751 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
752 if ( atv_control.getShowEventsCb() != null ) {
753 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
754 atv_control.setCheckbox( Configuration.write_events, true );
757 atv_control.setCheckbox( Configuration.write_events, false );
764 final private static char normalizeCharForRGB( char c ) {
767 c = c > 255 ? 255 : c;
772 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
773 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
774 InvocationTargetException, InterruptedException {
775 final String os = System.getProperty( "os.name" );
776 final Runtime runtime = Runtime.getRuntime();
777 if ( os.toLowerCase().startsWith( "win" ) ) {
778 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
780 else if ( isMac() ) {
781 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
782 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
783 open_url.invoke( null, new Object[] { url } );
786 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
787 String browser = null;
788 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
789 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
790 browser = browsers[ i ];
793 if ( browser == null ) {
794 throw new IOException( "could not find a web browser to open [" + url + "] in" );
797 runtime.exec( new String[] { browser, url } );
802 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
804 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
806 catch ( final Exception e ) {
807 throw new IOException( e );
811 final static void printAppletMessage( final String applet_name, final String message ) {
812 System.out.println( "[" + applet_name + "] > " + message );
815 public final static void printWarningMessage( final String name, final String message ) {
816 System.out.println( "[" + name + "] > " + message );
819 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
820 throws FileNotFoundException, IOException {
821 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
822 PhylogenyParser parser = null;
823 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
824 parser = new TolParser();
827 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
829 return factory.create( url.openStream(), parser );
832 final static void removeBranchColors( final Phylogeny phy ) {
833 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
834 it.next().getBranchData().setBranchColor( null );
838 final static void showErrorMessage( final Component parent, final String error_msg ) {
839 printAppletMessage( Constants.PRG_NAME, error_msg );
840 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
841 + "] Error", JOptionPane.ERROR_MESSAGE );
844 final static void unexpectedError( final Error err ) {
845 err.printStackTrace();
846 final StringBuffer sb = new StringBuffer();
847 for( final StackTraceElement s : err.getStackTrace() ) {
848 sb.append( s + "\n" );
851 .showMessageDialog( null,
852 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
853 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
854 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
855 JOptionPane.ERROR_MESSAGE );
859 final static void unexpectedException( final Exception ex ) {
860 ex.printStackTrace();
861 final StringBuffer sb = new StringBuffer();
862 for( final StackTraceElement s : ex.getStackTrace() ) {
863 sb.append( s + "\n" );
865 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
866 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
867 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
870 final static String writePhylogenyToGraphicsFile( final String file_name,
873 final TreePanel tree_panel,
874 final ControlPanel ac,
875 final GraphicsExportType type,
876 final Options options ) throws IOException {
877 if ( !options.isGraphicsExportUsingActualSize() ) {
878 if ( options.isGraphicsExportVisibleOnly() ) {
879 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
881 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
882 tree_panel.resetPreferredSize();
883 tree_panel.repaint();
885 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
886 RenderingHints.VALUE_RENDER_QUALITY );
887 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
888 if ( options.isAntialiasPrint() ) {
889 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
890 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
893 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
894 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
896 final Phylogeny phylogeny = tree_panel.getPhylogeny();
897 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
900 final File file = new File( file_name );
901 if ( file.isDirectory() ) {
902 throw new IOException( "\"" + file_name + "\" is a directory" );
904 Rectangle visible = null;
905 if ( !options.isGraphicsExportUsingActualSize() ) {
906 width = options.getPrintSizeX();
907 height = options.getPrintSizeY();
909 else if ( options.isGraphicsExportVisibleOnly() ) {
910 visible = tree_panel.getVisibleRect();
911 width = visible.width;
912 height = visible.height;
914 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
915 Graphics2D g2d = buffered_img.createGraphics();
916 g2d.setRenderingHints( rendering_hints );
919 if ( options.isGraphicsExportVisibleOnly() ) {
920 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
925 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
926 if ( type == GraphicsExportType.TIFF ) {
927 writeToTiff( file, buffered_img );
930 ImageIO.write( buffered_img, type.toString(), file );
934 if ( !options.isGraphicsExportUsingActualSize() ) {
935 tree_panel.getMainPanel().getControlPanel().showWhole();
937 String msg = file.toString();
938 if ( ( width > 0 ) && ( height > 0 ) ) {
939 msg += " [size: " + width + ", " + height + "]";
944 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
947 final TreePanel tree_panel,
948 final ControlPanel ac,
949 final GraphicsExportType type,
950 final Options options ) throws IOException {
951 tree_panel.setParametersForPainting( width, height, true );
952 tree_panel.resetPreferredSize();
953 tree_panel.repaint();
954 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
955 RenderingHints.VALUE_RENDER_QUALITY );
956 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
957 if ( options.isAntialiasPrint() ) {
958 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
959 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
962 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
963 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
965 final Phylogeny phylogeny = tree_panel.getPhylogeny();
966 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
969 if ( outfile.isDirectory() ) {
970 throw new IOException( "\"" + outfile + "\" is a directory" );
972 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
973 final Graphics2D g2d = buffered_img.createGraphics();
974 g2d.setRenderingHints( rendering_hints );
975 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
976 if ( type == GraphicsExportType.TIFF ) {
977 writeToTiff( outfile, buffered_img );
980 ImageIO.write( buffered_img, type.toString(), outfile );
985 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
988 final TreePanel tree_panel,
989 final ControlPanel ac,
990 final GraphicsExportType type,
991 final Options options ) throws IOException {
992 if ( !options.isGraphicsExportUsingActualSize() ) {
993 if ( options.isGraphicsExportVisibleOnly() ) {
994 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
996 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
997 tree_panel.resetPreferredSize();
998 tree_panel.repaint();
1000 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1001 RenderingHints.VALUE_RENDER_QUALITY );
1002 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1003 if ( options.isAntialiasPrint() ) {
1004 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1005 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1008 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1009 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1011 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1012 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1015 Rectangle visible = null;
1016 if ( !options.isGraphicsExportUsingActualSize() ) {
1017 width = options.getPrintSizeX();
1018 height = options.getPrintSizeY();
1020 else if ( options.isGraphicsExportVisibleOnly() ) {
1021 visible = tree_panel.getVisibleRect();
1022 width = visible.width;
1023 height = visible.height;
1025 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1026 Graphics2D g2d = buffered_img.createGraphics();
1027 g2d.setRenderingHints( rendering_hints );
1030 if ( options.isGraphicsExportVisibleOnly() ) {
1031 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1032 g2d.setClip( null );
1036 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1037 ImageIO.write( buffered_img, type.toString(), baos );
1040 if ( !options.isGraphicsExportUsingActualSize() ) {
1041 tree_panel.getMainPanel().getControlPanel().showWhole();
1043 String msg = baos.toString();
1044 if ( ( width > 0 ) && ( height > 0 ) ) {
1045 msg += " [size: " + width + ", " + height + "]";
1050 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1051 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1052 ImageWriter writer = null;
1053 ImageOutputStream ios = null;
1054 // Find an appropriate writer:
1055 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1056 if ( it.hasNext() ) {
1060 throw new IOException( "failed to get TIFF image writer" );
1063 ios = ImageIO.createImageOutputStream( file );
1064 writer.setOutput( ios );
1065 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1066 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1067 // see writeParam.getCompressionTypes() for available compression type
1069 image_write_param.setCompressionType( "PackBits" );
1070 final String t[] = image_write_param.getCompressionTypes();
1071 for( final String string : t ) {
1072 System.out.println( string );
1074 // Convert to an IIOImage:
1075 final IIOImage iio_image = new IIOImage( image, null, null );
1076 writer.write( null, iio_image, image_write_param );
1079 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1080 // static void openDDBJRest() throws IOException {
1082 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1084 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1085 // //make connection
1086 // URLConnection urlc = url.openConnection();
1088 // urlc.setDoOutput( true );
1089 // urlc.setAllowUserInteraction( false );
1091 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1092 // ps.print( query );
1095 // BufferedReader br = new BufferedReader( new InputStreamReader(
1096 // urlc.getInputStream() ) );
1098 // while ( ( l = br.readLine() ) != null ) {
1099 // System.out.println( l );
1103 public static enum GraphicsExportType {
1104 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1106 private final String _suffix;
1108 private GraphicsExportType( final String suffix ) {
1113 public String toString() {