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 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
135 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
136 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
141 * Returns true if at least one branch has a length larger than zero.
146 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
147 final PhylogenyNodeIterator it = phy.iteratorPostorder();
148 while ( it.hasNext() ) {
149 if ( it.next().getDistanceToParent() > 0.0 ) {
156 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
157 final PhylogenyNodeIterator it = phy.iteratorPostorder();
158 while ( it.hasNext() ) {
159 if ( it.next().getNodeData().isHasEvent() ) {
166 public static MaskFormatter createMaskFormatter( final String s ) {
167 MaskFormatter formatter = null;
169 formatter = new MaskFormatter( s );
171 catch ( final ParseException e ) {
172 throw new IllegalArgumentException( e );
177 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
178 final String default_name,
179 final String full_path,
180 final Configuration configuration,
181 final MainPanel main_panel ) {
182 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
183 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
184 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
185 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
188 for( final Phylogeny phy : phys ) {
189 if ( !phy.isEmpty() ) {
190 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
192 String my_name_for_file = "";
193 if ( phys.length > 1 ) {
194 if ( !ForesterUtil.isEmpty( default_name ) ) {
195 my_name = new String( default_name );
197 if ( !ForesterUtil.isEmpty( full_path ) ) {
198 my_name_for_file = new String( full_path );
200 else if ( !ForesterUtil.isEmpty( default_name ) ) {
201 my_name_for_file = new String( default_name );
204 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
205 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
206 my_name_for_file.length() );
207 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
209 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
210 my_name_for_file += "_";
212 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
213 my_name_for_file += phy.getName().replaceAll( " ", "_" );
215 else if ( phy.getIdentifier() != null ) {
216 final StringBuffer sb = new StringBuffer();
217 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
218 sb.append( phy.getIdentifier().getProvider() );
221 sb.append( phy.getIdentifier().getValue() );
222 my_name_for_file += sb;
225 my_name_for_file += i;
227 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
228 && ( phy.getIdentifier() == null ) ) {
229 my_name = my_name + " [" + i + "]";
231 if ( !ForesterUtil.isEmpty( suffix ) ) {
232 my_name_for_file += suffix;
236 if ( !ForesterUtil.isEmpty( default_name ) ) {
237 my_name = new String( default_name );
239 my_name_for_file = "";
240 if ( !ForesterUtil.isEmpty( full_path ) ) {
241 my_name_for_file = new String( full_path );
243 else if ( !ForesterUtil.isEmpty( default_name ) ) {
244 my_name_for_file = new String( default_name );
246 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
247 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
248 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
250 else if ( phy.getIdentifier() != null ) {
251 final StringBuffer sb = new StringBuffer();
252 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
253 sb.append( phy.getIdentifier().getProvider() );
256 sb.append( phy.getIdentifier().getValue() );
257 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
261 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
262 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
263 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
270 final static void addPhylogenyToPanel( final Phylogeny[] phys,
271 final Configuration configuration,
272 final MainPanel main_panel ) {
273 final Phylogeny phy = phys[ 0 ];
274 main_panel.addPhylogenyInPanel( phy, configuration );
275 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
278 final static Color calculateColorFromString( final String str ) {
279 final String species_uc = str.toUpperCase();
280 char first = species_uc.charAt( 0 );
283 if ( species_uc.length() > 1 ) {
284 second = species_uc.charAt( 1 );
285 if ( species_uc.length() > 2 ) {
286 if ( species_uc.indexOf( " " ) > 0 ) {
287 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
290 third = species_uc.charAt( 2 );
294 first = AptxUtil.normalizeCharForRGB( first );
295 second = AptxUtil.normalizeCharForRGB( second );
296 third = AptxUtil.normalizeCharForRGB( third );
297 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
300 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
303 return new Color( first, second, third );
306 // Returns true if the specified format name can be written
307 final static boolean canWriteFormat( final String format_name ) {
308 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
309 return iter.hasNext();
312 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
313 boolean inferred = false;
314 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
315 final PhylogenyNode n = it.next();
316 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
317 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
318 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
319 AptxUtil.collapseSubtree( n, true );
320 if ( !n.getNodeData().isHasTaxonomy() ) {
321 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
322 .getTaxonomy().copy() );
327 n.setCollapse( false );
332 phy.setRerootable( false );
336 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
337 node.setCollapse( collapse );
338 if ( node.isExternal() ) {
341 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
342 while ( it.hasNext() ) {
343 it.next().setCollapse( collapse );
347 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
348 double max_conf = 0.0;
349 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
350 final PhylogenyNode n = it.next();
351 n.getBranchData().setBranchColor( null );
352 if ( n.getBranchData().isHasConfidences() ) {
353 final double conf = PhylogenyMethods.getConfidenceValue( n );
354 if ( conf > max_conf ) {
359 if ( max_conf > 0.0 ) {
360 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
361 final Color br = tree_panel.getTreeColorSet().getBranchColor();
362 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
363 final PhylogenyNode n = it.next();
364 if ( n.getBranchData().isHasConfidences() ) {
365 final double conf = PhylogenyMethods.getConfidenceValue( n );
366 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
367 colorizeSubtree( n, c );
373 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
374 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
375 int colorizations = 0;
376 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
377 final PhylogenyNode n = it.next();
378 if ( n.getNodeData().isHasTaxonomy()
379 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
380 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
381 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
382 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
383 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
384 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
386 colorizeSubtree( n, c );
388 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
389 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
394 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
395 final PhylogenyNode node = it.next();
396 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
397 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
398 boolean success = false;
399 if ( !true_lineage_to_color_map.isEmpty() ) {
400 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
401 if ( true_lineage_to_color_map.containsKey( lin ) ) {
402 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
410 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
411 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
412 final Taxonomy temp_tax = new Taxonomy();
413 temp_tax.setScientificName( lin );
414 if ( lineage_to_rank_map.containsKey( lin )
415 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
416 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
417 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
418 colorizeSubtree( node, c );
420 true_lineage_to_color_map.put( lin, c.getValue() );
424 UniProtTaxonomy up = null;
426 up = AncestralTaxonomyInference.obtainUniProtTaxonomy( temp_tax, null, null );
428 catch ( final Exception e ) {
431 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
432 lineage_to_rank_map.put( lin, up.getRank() );
433 if ( up.getRank().equalsIgnoreCase( rank ) ) {
434 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
435 colorizeSubtree( node, c );
437 true_lineage_to_color_map.put( lin, c.getValue() );
446 return colorizations;
449 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
450 node.getBranchData().setBranchColor( c );
451 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
452 for( final PhylogenyNode desc : descs ) {
453 desc.getBranchData().setBranchColor( c );
457 final static String[] getAllRanks( final Phylogeny tree ) {
458 final SortedSet<String> ranks = new TreeSet<String>();
459 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
460 final PhylogenyNode n = it.next();
461 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
462 ranks.add( n.getNodeData().getTaxonomy().getRank() );
465 return ForesterUtil.stringSetToArray( ranks );
468 public static String[] getAllPossibleRanks() {
469 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
471 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
472 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
473 str_array[ i++ ] = e;
479 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
480 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
481 it.next().getBranchData().setBranchColor( null );
483 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
484 final PhylogenyNode n = it.next();
485 if ( !n.getBranchData().isHasBranchColor() ) {
486 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
488 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
489 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
490 for( final PhylogenyNode desc : descs ) {
492 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
499 final static String crateBasicInformation( final Phylogeny phy ) {
500 final StringBuilder desc = new StringBuilder();
501 if ( ( phy != null ) && !phy.isEmpty() ) {
502 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
503 desc.append( "Name: " );
504 desc.append( phy.getName() );
507 if ( phy.getIdentifier() != null ) {
508 desc.append( "Id: " );
509 desc.append( phy.getIdentifier() );
512 desc.append( "Rooted: " );
513 desc.append( phy.isRooted() );
515 desc.append( "Rerootable: " );
516 desc.append( phy.isRerootable() );
518 desc.append( "Node sum: " );
519 desc.append( phy.getNodeCount() );
521 desc.append( "External node sum: " );
522 desc.append( phy.getNumberOfExternalNodes() );
524 desc.append( "Internal node sum: " );
525 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
527 desc.append( "Branche sum: " );
528 desc.append( phy.getNumberOfBranches() );
530 desc.append( "Depth: " );
531 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
533 desc.append( "Maximum distance to root: " );
534 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
536 desc.append( "Descendants per node statistics: " );
537 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
539 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
541 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
543 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
545 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
547 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
549 final DescriptiveStatistics cs = PhylogenyMethods.calculatConfidenceStatistics( phy );
550 if ( cs.getN() > 1 ) {
551 desc.append( "Support statistics: " );
553 desc.append( " Branches with support: " + cs.getN() );
555 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
557 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
559 if ( cs.getN() > 2 ) {
560 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
563 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
565 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
568 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
569 if ( taxs != null ) {
570 desc.append( "Distinct external taxonomies: " );
571 desc.append( taxs.size() );
574 return desc.toString();
582 * to message to be printed
584 final static void dieWithSystemError( final String message ) {
585 System.out.println();
586 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
587 System.out.println( "Please contact the authors." );
588 System.out.println( Constants.PRG_NAME + " needs to close." );
589 System.out.println();
593 final static String[] getAvailableFontFamiliesSorted() {
594 return AVAILABLE_FONT_FAMILIES_SORTED;
597 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
598 boolean inferred = false;
599 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
600 final PhylogenyNode n = it.next();
601 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
602 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
603 if ( !ForesterUtil.isEmpty( sn ) ) {
604 n.getNodeData().setTaxonomy( new Taxonomy() );
605 n.getNodeData().getTaxonomy().setScientificName( sn );
611 tree.setRerootable( false );
615 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
616 if ( !node.getNodeData().isHasEvent() ) {
619 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
625 final static boolean isJava15() {
627 final String s = ForesterUtil.JAVA_VERSION;
628 return s.startsWith( "1.5" );
630 catch ( final Exception e ) {
631 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
636 final static boolean isMac() {
638 final String s = ForesterUtil.OS_NAME.toLowerCase();
639 return s.startsWith( "mac" );
641 catch ( final Exception e ) {
642 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
647 final static boolean isUsOrCanada() {
649 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
653 catch ( final Exception e ) {
659 final static boolean isWindows() {
661 final String s = ForesterUtil.OS_NAME.toLowerCase();
662 return s.indexOf( "win" ) > -1;
664 catch ( final Exception e ) {
665 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
670 final static void launchWebBrowser( final URI uri,
671 final boolean is_applet,
672 final JApplet applet,
673 final String frame_name ) throws IOException {
675 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
678 // This requires Java 1.6:
679 // =======================
680 // boolean no_desktop = false;
682 // if ( Desktop.isDesktopSupported() ) {
683 // System.out.println( "desktop supported" );
684 // final Desktop dt = Desktop.getDesktop();
688 // no_desktop = true;
691 // catch ( final Exception ex ) {
692 // ex.printStackTrace();
693 // no_desktop = true;
695 // catch ( final Error er ) {
696 // er.printStackTrace();
697 // no_desktop = true;
699 // if ( no_desktop ) {
700 // System.out.println( "desktop not supported" );
702 openUrlInWebBrowser( uri.toString() );
704 catch ( final Exception e ) {
705 throw new IOException( e );
711 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
712 final ControlPanel atv_control,
713 final Configuration configuration ) {
714 if ( ( t != null ) && !t.isEmpty() ) {
715 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
716 atv_control.setDrawPhylogram( false );
717 atv_control.setDrawPhylogramEnabled( false );
719 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
720 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
721 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
722 atv_control.setDrawPhylogram( true );
723 atv_control.setDrawPhylogramEnabled( true );
726 atv_control.setDrawPhylogram( false );
730 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
731 if ( atv_control.getWriteConfidenceCb() != null ) {
732 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
733 atv_control.setCheckbox( Configuration.write_confidence_values, true );
736 atv_control.setCheckbox( Configuration.write_confidence_values, false );
740 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
741 if ( atv_control.getShowEventsCb() != null ) {
742 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
743 atv_control.setCheckbox( Configuration.write_events, true );
746 atv_control.setCheckbox( Configuration.write_events, false );
753 final private static char normalizeCharForRGB( char c ) {
756 c = c > 255 ? 255 : c;
761 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
762 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
763 InvocationTargetException, InterruptedException {
764 final String os = System.getProperty( "os.name" );
765 final Runtime runtime = Runtime.getRuntime();
766 if ( os.toLowerCase().startsWith( "win" ) ) {
767 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
769 else if ( isMac() ) {
770 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
771 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
772 open_url.invoke( null, new Object[] { url } );
775 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
776 String browser = null;
777 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
778 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
779 browser = browsers[ i ];
782 if ( browser == null ) {
783 throw new IOException( "could not find a web browser to open [" + url + "] in" );
786 runtime.exec( new String[] { browser, url } );
791 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
793 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
795 catch ( final Exception e ) {
796 throw new IOException( e );
800 final static void printAppletMessage( final String applet_name, final String message ) {
801 System.out.println( "[" + applet_name + "] > " + message );
804 public final static void printWarningMessage( final String name, final String message ) {
805 System.out.println( "[" + name + "] > " + message );
808 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
809 throws FileNotFoundException, IOException {
810 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
811 PhylogenyParser parser = null;
812 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
813 parser = new TolParser();
816 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
818 return factory.create( url.openStream(), parser );
821 final static void removeBranchColors( final Phylogeny phy ) {
822 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
823 it.next().getBranchData().setBranchColor( null );
827 final static void showErrorMessage( final Component parent, final String error_msg ) {
828 printAppletMessage( Constants.PRG_NAME, error_msg );
829 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
830 + "] Error", JOptionPane.ERROR_MESSAGE );
833 final static void unexpectedError( final Error err ) {
834 err.printStackTrace();
835 final StringBuffer sb = new StringBuffer();
836 for( final StackTraceElement s : err.getStackTrace() ) {
837 sb.append( s + "\n" );
840 .showMessageDialog( null,
841 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
842 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
843 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
844 JOptionPane.ERROR_MESSAGE );
848 final static void unexpectedException( final Exception ex ) {
849 ex.printStackTrace();
850 final StringBuffer sb = new StringBuffer();
851 for( final StackTraceElement s : ex.getStackTrace() ) {
852 sb.append( s + "\n" );
854 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
855 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
856 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
859 final static String writePhylogenyToGraphicsFile( final String file_name,
862 final TreePanel tree_panel,
863 final ControlPanel ac,
864 final GraphicsExportType type,
865 final Options options ) throws IOException {
866 if ( !options.isGraphicsExportUsingActualSize() ) {
867 if ( options.isGraphicsExportVisibleOnly() ) {
868 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
870 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
871 tree_panel.resetPreferredSize();
872 tree_panel.repaint();
874 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
875 RenderingHints.VALUE_RENDER_QUALITY );
876 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
877 if ( options.isAntialiasPrint() ) {
878 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
879 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
882 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
883 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
885 final Phylogeny phylogeny = tree_panel.getPhylogeny();
886 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
889 final File file = new File( file_name );
890 if ( file.isDirectory() ) {
891 throw new IOException( "\"" + file_name + "\" is a directory" );
893 Rectangle visible = null;
894 if ( !options.isGraphicsExportUsingActualSize() ) {
895 width = options.getPrintSizeX();
896 height = options.getPrintSizeY();
898 else if ( options.isGraphicsExportVisibleOnly() ) {
899 visible = tree_panel.getVisibleRect();
900 width = visible.width;
901 height = visible.height;
903 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
904 Graphics2D g2d = buffered_img.createGraphics();
905 g2d.setRenderingHints( rendering_hints );
908 if ( options.isGraphicsExportVisibleOnly() ) {
909 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
914 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
915 if ( type == GraphicsExportType.TIFF ) {
916 writeToTiff( file, buffered_img );
919 ImageIO.write( buffered_img, type.toString(), file );
923 if ( !options.isGraphicsExportUsingActualSize() ) {
924 tree_panel.getMainPanel().getControlPanel().showWhole();
926 String msg = file.toString();
927 if ( ( width > 0 ) && ( height > 0 ) ) {
928 msg += " [size: " + width + ", " + height + "]";
933 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
936 final TreePanel tree_panel,
937 final ControlPanel ac,
938 final GraphicsExportType type,
939 final Options options ) throws IOException {
940 tree_panel.setParametersForPainting( width, height, true );
941 tree_panel.resetPreferredSize();
942 tree_panel.repaint();
943 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
944 RenderingHints.VALUE_RENDER_QUALITY );
945 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
946 if ( options.isAntialiasPrint() ) {
947 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
948 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
951 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
952 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
954 final Phylogeny phylogeny = tree_panel.getPhylogeny();
955 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
958 if ( outfile.isDirectory() ) {
959 throw new IOException( "\"" + outfile + "\" is a directory" );
961 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
962 final Graphics2D g2d = buffered_img.createGraphics();
963 g2d.setRenderingHints( rendering_hints );
964 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
965 if ( type == GraphicsExportType.TIFF ) {
966 writeToTiff( outfile, buffered_img );
969 ImageIO.write( buffered_img, type.toString(), outfile );
974 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
977 final TreePanel tree_panel,
978 final ControlPanel ac,
979 final GraphicsExportType type,
980 final Options options ) throws IOException {
981 if ( !options.isGraphicsExportUsingActualSize() ) {
982 if ( options.isGraphicsExportVisibleOnly() ) {
983 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
985 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
986 tree_panel.resetPreferredSize();
987 tree_panel.repaint();
989 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
990 RenderingHints.VALUE_RENDER_QUALITY );
991 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
992 if ( options.isAntialiasPrint() ) {
993 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
994 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
997 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
998 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1000 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1001 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1004 Rectangle visible = null;
1005 if ( !options.isGraphicsExportUsingActualSize() ) {
1006 width = options.getPrintSizeX();
1007 height = options.getPrintSizeY();
1009 else if ( options.isGraphicsExportVisibleOnly() ) {
1010 visible = tree_panel.getVisibleRect();
1011 width = visible.width;
1012 height = visible.height;
1014 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1015 Graphics2D g2d = buffered_img.createGraphics();
1016 g2d.setRenderingHints( rendering_hints );
1019 if ( options.isGraphicsExportVisibleOnly() ) {
1020 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1021 g2d.setClip( null );
1025 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1026 ImageIO.write( buffered_img, type.toString(), baos );
1029 if ( !options.isGraphicsExportUsingActualSize() ) {
1030 tree_panel.getMainPanel().getControlPanel().showWhole();
1032 String msg = baos.toString();
1033 if ( ( width > 0 ) && ( height > 0 ) ) {
1034 msg += " [size: " + width + ", " + height + "]";
1039 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1040 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1041 ImageWriter writer = null;
1042 ImageOutputStream ios = null;
1043 // Find an appropriate writer:
1044 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1045 if ( it.hasNext() ) {
1049 throw new IOException( "failed to get TIFF image writer" );
1052 ios = ImageIO.createImageOutputStream( file );
1053 writer.setOutput( ios );
1054 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1055 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1056 // see writeParam.getCompressionTypes() for available compression type
1058 image_write_param.setCompressionType( "PackBits" );
1059 final String t[] = image_write_param.getCompressionTypes();
1060 for( final String string : t ) {
1061 System.out.println( string );
1063 // Convert to an IIOImage:
1064 final IIOImage iio_image = new IIOImage( image, null, null );
1065 writer.write( null, iio_image, image_write_param );
1068 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1069 // static void openDDBJRest() throws IOException {
1071 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1073 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1074 // //make connection
1075 // URLConnection urlc = url.openConnection();
1077 // urlc.setDoOutput( true );
1078 // urlc.setAllowUserInteraction( false );
1080 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1081 // ps.print( query );
1084 // BufferedReader br = new BufferedReader( new InputStreamReader(
1085 // urlc.getInputStream() ) );
1087 // while ( ( l = br.readLine() ) != null ) {
1088 // System.out.println( l );
1092 public static enum GraphicsExportType {
1093 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1095 private final String _suffix;
1097 private GraphicsExportType( final String suffix ) {
1102 public String toString() {