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: https://sites.google.com/site/cmzmasek/home/software/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.io.InputStream;
40 import java.lang.reflect.InvocationTargetException;
41 import java.lang.reflect.Method;
44 import java.net.URLConnection;
45 import java.text.ParseException;
46 import java.util.Arrays;
47 import java.util.HashSet;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Locale;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
55 import javax.imageio.IIOImage;
56 import javax.imageio.ImageIO;
57 import javax.imageio.ImageWriteParam;
58 import javax.imageio.ImageWriter;
59 import javax.imageio.stream.ImageOutputStream;
60 import javax.swing.JApplet;
61 import javax.swing.JOptionPane;
62 import javax.swing.text.MaskFormatter;
64 import org.forester.io.parsers.PhylogenyParser;
65 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
66 import org.forester.io.parsers.nhx.NHXParser;
67 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
68 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
69 import org.forester.io.parsers.tol.TolParser;
70 import org.forester.io.parsers.util.ParserUtils;
71 import org.forester.phylogeny.Phylogeny;
72 import org.forester.phylogeny.PhylogenyMethods;
73 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
74 import org.forester.phylogeny.PhylogenyNode;
75 import org.forester.phylogeny.data.Confidence;
76 import org.forester.phylogeny.data.Taxonomy;
77 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
78 import org.forester.phylogeny.factories.PhylogenyFactory;
79 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
80 import org.forester.util.AsciiHistogram;
81 import org.forester.util.DescriptiveStatistics;
82 import org.forester.util.ForesterUtil;
84 public final class AptxUtil {
86 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
87 .getAvailableFontFamilyNames();
89 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
92 public static MaskFormatter createMaskFormatter( final String s ) {
93 MaskFormatter formatter = null;
95 formatter = new MaskFormatter( s );
97 catch ( final ParseException e ) {
98 throw new IllegalArgumentException( e );
103 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
104 final PhylogenyNodeIterator it = phy.iteratorPostorder();
105 while ( it.hasNext() ) {
106 if ( it.next().getNodeData().isHasEvent() ) {
114 * Returns true if at least one branch has a length larger than zero.
119 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
120 final PhylogenyNodeIterator it = phy.iteratorPostorder();
121 while ( it.hasNext() ) {
122 if ( it.next().getDistanceToParent() > 0.0 ) {
129 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
130 final PhylogenyNodeIterator it = phy.iteratorPostorder();
131 while ( it.hasNext() ) {
132 if ( it.next().getBranchData().isHasConfidences() ) {
139 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
140 final PhylogenyNodeIterator it = phy.iteratorPostorder();
141 while ( it.hasNext() ) {
142 final PhylogenyNode n = it.next();
143 if ( n.getBranchData().isHasConfidences() ) {
144 final List<Confidence> c = n.getBranchData().getConfidences();
145 for( final Confidence confidence : c ) {
146 if ( confidence.getStandardDeviation() > 0 ) {
155 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
156 final PhylogenyNodeIterator it = phy.iteratorPostorder();
157 while ( it.hasNext() ) {
158 final PhylogenyNode n = it.next();
159 if ( n.getNodeData().isHasTaxonomy()
160 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
167 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
168 final PhylogenyNodeIterator it = phy.iteratorPostorder();
169 while ( it.hasNext() ) {
170 final PhylogenyNode n = it.next();
171 if ( n.getNodeData().isHasSequence()
172 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
179 final public static void launchWebBrowser( final URI uri,
180 final boolean is_applet,
181 final JApplet applet,
182 final String frame_name ) throws IOException {
184 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
187 // This requires Java 1.6:
188 // =======================
189 // boolean no_desktop = false;
191 // if ( Desktop.isDesktopSupported() ) {
192 // System.out.println( "desktop supported" );
193 // final Desktop dt = Desktop.getDesktop();
197 // no_desktop = true;
200 // catch ( final Exception ex ) {
201 // ex.printStackTrace();
202 // no_desktop = true;
204 // catch ( final Error er ) {
205 // er.printStackTrace();
206 // no_desktop = true;
208 // if ( no_desktop ) {
209 // System.out.println( "desktop not supported" );
211 openUrlInWebBrowser( uri.toString() );
213 catch ( final Exception e ) {
214 throw new IOException( e );
220 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
221 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
222 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
223 for( final PhylogenyNode n : descs ) {
224 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
225 tax_set.add( n.getNodeData().getTaxonomy() );
231 public final static void printWarningMessage( final String name, final String message ) {
232 System.out.println( "[" + name + "] > " + message );
235 final public static void showErrorMessage( final Component parent, final String error_msg ) {
236 printAppletMessage( Constants.PRG_NAME, error_msg );
237 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
238 + "] Error", JOptionPane.ERROR_MESSAGE );
241 public static void writePhylogenyToGraphicsFile( final File intree,
245 final GraphicsExportType type,
246 final Configuration config ) throws IOException {
247 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
248 Phylogeny[] phys = null;
249 phys = PhylogenyMethods.readPhylogenies( parser, intree );
250 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
253 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
257 final GraphicsExportType type,
258 final Configuration config ) throws IOException {
259 final Phylogeny[] phys = new Phylogeny[ 1 ];
261 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
262 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
263 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
267 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
270 final TreePanel tree_panel,
271 final ControlPanel ac,
272 final GraphicsExportType type,
273 final Options options ) throws IOException {
274 tree_panel.calcParametersForPainting( width, height, true );
275 tree_panel.resetPreferredSize();
276 tree_panel.repaint();
277 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
278 RenderingHints.VALUE_RENDER_QUALITY );
279 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
280 if ( options.isAntialiasPrint() ) {
281 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
282 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
285 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
286 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
288 final Phylogeny phylogeny = tree_panel.getPhylogeny();
289 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
292 if ( outfile.isDirectory() ) {
293 throw new IOException( "\"" + outfile + "\" is a directory" );
295 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
296 final Graphics2D g2d = buffered_img.createGraphics();
297 g2d.setRenderingHints( rendering_hints );
298 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
299 if ( type == GraphicsExportType.TIFF ) {
300 writeToTiff( outfile, buffered_img );
303 ImageIO.write( buffered_img, type.toString(), outfile );
308 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
309 final String default_name,
310 final String full_path,
311 final Configuration configuration,
312 final MainPanel main_panel ) {
313 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
314 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
315 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
316 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
319 for( final Phylogeny phy : phys ) {
320 if ( !phy.isEmpty() ) {
321 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
323 String my_name_for_file = "";
324 if ( phys.length > 1 ) {
325 if ( !ForesterUtil.isEmpty( default_name ) ) {
326 my_name = new String( default_name );
328 if ( !ForesterUtil.isEmpty( full_path ) ) {
329 my_name_for_file = new String( full_path );
331 else if ( !ForesterUtil.isEmpty( default_name ) ) {
332 my_name_for_file = new String( default_name );
335 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
336 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
337 my_name_for_file.length() );
338 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
340 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
341 my_name_for_file += "_";
343 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
344 my_name_for_file += phy.getName().replaceAll( " ", "_" );
346 else if ( phy.getIdentifier() != null ) {
347 final StringBuffer sb = new StringBuffer();
348 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
349 sb.append( phy.getIdentifier().getProvider() );
352 sb.append( phy.getIdentifier().getValue() );
353 my_name_for_file += sb;
356 my_name_for_file += i;
358 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
359 && ( phy.getIdentifier() == null ) ) {
360 my_name = my_name + " [" + i + "]";
362 if ( !ForesterUtil.isEmpty( suffix ) ) {
363 my_name_for_file += suffix;
367 if ( !ForesterUtil.isEmpty( default_name ) ) {
368 my_name = new String( default_name );
370 my_name_for_file = "";
371 if ( !ForesterUtil.isEmpty( full_path ) ) {
372 my_name_for_file = new String( full_path );
374 else if ( !ForesterUtil.isEmpty( default_name ) ) {
375 my_name_for_file = new String( default_name );
377 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
378 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
379 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
381 else if ( phy.getIdentifier() != null ) {
382 final StringBuffer sb = new StringBuffer();
383 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
384 sb.append( phy.getIdentifier().getProvider() );
387 sb.append( phy.getIdentifier().getValue() );
388 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
392 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
393 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
394 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
401 final static void addPhylogenyToPanel( final Phylogeny[] phys,
402 final Configuration configuration,
403 final MainPanel main_panel ) {
404 final Phylogeny phy = phys[ 0 ];
405 main_panel.addPhylogenyInPanel( phy, configuration );
406 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
409 // Returns true if the specified format name can be written
410 final static boolean canWriteFormat( final String format_name ) {
411 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
412 return iter.hasNext();
415 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
416 final StringBuilder desc = new StringBuilder();
417 if ( ( phy != null ) && !phy.isEmpty() ) {
419 if ( treefile != null ) {
421 f = treefile.getCanonicalPath();
423 catch ( final IOException e ) {
424 //Not important, ignore.
426 if ( !ForesterUtil.isEmpty( f ) ) {
427 desc.append( "Path: " );
432 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
433 desc.append( "Name: " );
434 desc.append( phy.getName() );
437 if ( phy.getIdentifier() != null ) {
438 desc.append( "Id: " );
439 desc.append( phy.getIdentifier().toString() );
442 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
443 desc.append( "Description: " );
444 desc.append( phy.getDescription() );
447 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
448 desc.append( "Distance Unit: " );
449 desc.append( phy.getDistanceUnit() );
452 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
453 desc.append( "Type: " );
454 desc.append( phy.getType() );
457 desc.append( "Rooted: " );
458 desc.append( phy.isRooted() );
460 desc.append( "Rerootable: " );
461 desc.append( phy.isRerootable() );
463 desc.append( "Nodes: " );
464 desc.append( phy.getNodeCount() );
466 desc.append( "External nodes: " );
467 desc.append( phy.getNumberOfExternalNodes() );
469 desc.append( "Internal nodes: " );
470 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
472 desc.append( "Internal nodes with polytomies: " );
473 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
475 desc.append( "Branches: " );
476 desc.append( phy.getNumberOfBranches() );
478 desc.append( "Depth: " );
479 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
481 desc.append( "Maximum distance to root: " );
482 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
484 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
485 if ( taxs != null ) {
486 desc.append( "Distinct external taxonomies: " );
487 desc.append( taxs.size() );
489 for( final Taxonomy t : taxs ) {
490 System.out.println( t.toString() );
493 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
494 if ( bs.getN() > 3 ) {
496 desc.append( "Branch-length statistics: " );
498 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
500 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
502 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
503 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
505 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
507 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
509 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
511 final AsciiHistogram histo = new AsciiHistogram( bs );
512 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
515 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
516 if ( ds.getN() > 2 ) {
518 desc.append( "Descendants per node statistics: " );
520 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
522 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
523 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
525 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
527 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
530 List<DescriptiveStatistics> css = null;
532 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
534 catch ( final IllegalArgumentException e ) {
535 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
537 if ( ( css != null ) && ( css.size() > 0 ) ) {
539 for( int i = 0; i < css.size(); ++i ) {
540 final DescriptiveStatistics cs = css.get( i );
541 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
542 if ( css.size() > 1 ) {
543 desc.append( "Support statistics " + ( i + 1 ) + ": " );
546 desc.append( "Support statistics: " );
548 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
550 desc.append( " Type: " + cs.getDescription() );
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 ) );
558 if ( cs.getN() > 2 ) {
559 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
562 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
564 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
570 return desc.toString();
578 * to message to be printed
580 final static void dieWithSystemError( final String message ) {
581 System.out.println();
582 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
583 System.out.println( "Please contact the authors." );
584 System.out.println( Constants.PRG_NAME + " needs to close." );
585 System.out.println();
589 final static String[] getAllPossibleRanks() {
590 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
592 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
593 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
594 str_array[ i++ ] = e;
600 final static String[] getAllRanks( final Phylogeny tree ) {
601 final SortedSet<String> ranks = new TreeSet<String>();
602 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
603 final PhylogenyNode n = it.next();
604 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
605 ranks.add( n.getNodeData().getTaxonomy().getRank() );
608 return ForesterUtil.stringSetToArray( ranks );
611 final static String[] getAvailableFontFamiliesSorted() {
612 return AVAILABLE_FONT_FAMILIES_SORTED;
615 final static boolean isUsOrCanada() {
617 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
621 catch ( final Exception e ) {
627 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
628 final ControlPanel atv_control,
629 final Configuration configuration ) {
630 if ( ( t != null ) && !t.isEmpty() ) {
631 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
632 atv_control.setDrawPhylogram( false );
633 atv_control.setDrawPhylogramEnabled( false );
635 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
636 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
637 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
638 atv_control.setDrawPhylogram( true );
639 atv_control.setDrawPhylogramEnabled( true );
642 atv_control.setDrawPhylogram( false );
646 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
647 if ( atv_control.getWriteConfidenceCb() != null ) {
648 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
649 atv_control.setCheckbox( Configuration.write_confidence_values, true );
652 atv_control.setCheckbox( Configuration.write_confidence_values, false );
656 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
657 if ( atv_control.getShowEventsCb() != null ) {
658 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
659 atv_control.setCheckbox( Configuration.write_events, true );
662 atv_control.setCheckbox( Configuration.write_events, false );
669 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
671 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
673 catch ( final Exception e ) {
674 throw new IOException( e );
678 final static void outOfMemoryError( final OutOfMemoryError e ) {
679 System.err.println();
680 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
681 System.err.println();
683 System.err.println();
684 JOptionPane.showMessageDialog( null,
685 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
686 + "\n\nError: " + e.getLocalizedMessage(),
687 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
688 JOptionPane.ERROR_MESSAGE );
692 final static void printAppletMessage( final String applet_name, final String message ) {
693 System.out.println( "[" + applet_name + "] > " + message );
696 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
697 final boolean phyloxml_validate_against_xsd,
698 final boolean replace_underscores,
699 final boolean internal_numbers_are_confidences,
700 final TAXONOMY_EXTRACTION taxonomy_extraction,
701 final boolean midpoint_reroot )
702 throws FileNotFoundException, IOException {
703 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
704 final PhylogenyParser parser;
705 boolean nhx_or_nexus = false;
706 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
707 parser = new TolParser();
710 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
711 if ( parser instanceof NHXParser ) {
713 final NHXParser nhx = ( NHXParser ) parser;
714 nhx.setReplaceUnderscores( replace_underscores );
715 nhx.setIgnoreQuotes( false );
716 nhx.setTaxonomyExtraction( taxonomy_extraction );
718 else if ( parser instanceof NexusPhylogeniesParser ) {
720 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
721 nex.setReplaceUnderscores( replace_underscores );
722 nex.setIgnoreQuotes( false );
725 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
726 final URLConnection url_connection = url.openConnection();
727 url_connection.setDefaultUseCaches( false );
728 final InputStream i = url_connection.getInputStream();
729 final Phylogeny[] phys = factory.create( i, parser );
731 if ( phys != null ) {
732 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
733 for( final Phylogeny phy : phys ) {
734 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
737 if ( midpoint_reroot ) {
738 for( final Phylogeny phy : phys ) {
739 PhylogenyMethods.midpointRoot( phy );
740 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
747 final static void removeBranchColors( final Phylogeny phy ) {
748 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
749 it.next().getBranchData().setBranchColor( null );
753 final static void removeVisualStyles( final Phylogeny phy ) {
754 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
755 it.next().getNodeData().setNodeVisualData( null );
759 final static void unexpectedError( final Error e ) {
760 System.err.println();
761 e.printStackTrace( System.err );
762 System.err.println();
763 final StringBuffer sb = new StringBuffer();
764 for( final StackTraceElement s : e.getStackTrace() ) {
765 sb.append( s + "\n" );
768 .showMessageDialog( null,
769 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
770 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
772 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
773 JOptionPane.ERROR_MESSAGE );
777 final static void unexpectedException( final Exception e ) {
778 System.err.println();
779 e.printStackTrace( System.err );
780 System.err.println();
781 final StringBuffer sb = new StringBuffer();
782 for( final StackTraceElement s : e.getStackTrace() ) {
783 sb.append( s + "\n" );
785 JOptionPane.showMessageDialog( null,
786 "An unexpected exception has occured. \nPlease contact: "
787 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
789 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
790 JOptionPane.ERROR_MESSAGE );
793 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
796 final TreePanel tree_panel,
797 final ControlPanel ac,
798 final GraphicsExportType type,
799 final Options options ) throws IOException {
800 if ( !options.isGraphicsExportUsingActualSize() ) {
801 if ( options.isGraphicsExportVisibleOnly() ) {
802 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
804 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
805 tree_panel.resetPreferredSize();
806 tree_panel.repaint();
808 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
809 RenderingHints.VALUE_RENDER_QUALITY );
810 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
811 if ( options.isAntialiasPrint() ) {
812 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
813 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
816 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
817 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
819 final Phylogeny phylogeny = tree_panel.getPhylogeny();
820 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
823 Rectangle visible = null;
824 if ( !options.isGraphicsExportUsingActualSize() ) {
825 width = options.getPrintSizeX();
826 height = options.getPrintSizeY();
828 else if ( options.isGraphicsExportVisibleOnly() ) {
829 visible = tree_panel.getVisibleRect();
830 width = visible.width;
831 height = visible.height;
833 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
834 Graphics2D g2d = buffered_img.createGraphics();
835 g2d.setRenderingHints( rendering_hints );
838 if ( options.isGraphicsExportVisibleOnly() ) {
839 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
844 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
845 ImageIO.write( buffered_img, type.toString(), baos );
848 if ( !options.isGraphicsExportUsingActualSize() ) {
849 tree_panel.getMainPanel().getControlPanel().showWhole();
851 String msg = baos.toString();
852 if ( ( width > 0 ) && ( height > 0 ) ) {
853 msg += " [size: " + width + ", " + height + "]";
858 final static String writePhylogenyToGraphicsFile( final String file_name,
861 final TreePanel tree_panel,
862 final ControlPanel ac,
863 final GraphicsExportType type,
864 final Options options ) throws IOException {
865 if ( !options.isGraphicsExportUsingActualSize() ) {
866 if ( options.isGraphicsExportVisibleOnly() ) {
867 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
869 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
870 tree_panel.resetPreferredSize();
871 tree_panel.repaint();
873 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
874 RenderingHints.VALUE_RENDER_QUALITY );
875 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
876 if ( options.isAntialiasPrint() ) {
877 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
878 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
881 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
882 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
884 final Phylogeny phylogeny = tree_panel.getPhylogeny();
885 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
888 final File file = new File( file_name );
889 if ( file.isDirectory() ) {
890 throw new IOException( "\"" + file_name + "\" is a directory" );
892 Rectangle visible = null;
893 if ( !options.isGraphicsExportUsingActualSize() ) {
894 width = options.getPrintSizeX();
895 height = options.getPrintSizeY();
897 else if ( options.isGraphicsExportVisibleOnly() ) {
898 visible = tree_panel.getVisibleRect();
899 width = visible.width;
900 height = visible.height;
902 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
903 Graphics2D g2d = buffered_img.createGraphics();
904 g2d.setRenderingHints( rendering_hints );
907 if ( options.isGraphicsExportVisibleOnly() ) {
908 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
913 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
914 if ( type == GraphicsExportType.TIFF ) {
915 writeToTiff( file, buffered_img );
918 ImageIO.write( buffered_img, type.toString(), file );
922 if ( !options.isGraphicsExportUsingActualSize() ) {
923 tree_panel.getMainPanel().getControlPanel().showWhole();
925 String msg = file.toString();
926 if ( ( width > 0 ) && ( height > 0 ) ) {
927 msg += " [size: " + width + ", " + height + "]";
932 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
933 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
934 ImageWriter writer = null;
935 ImageOutputStream ios = null;
936 // Find an appropriate writer:
937 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
938 if ( it.hasNext() ) {
942 throw new IOException( "failed to get TIFF image writer" );
945 ios = ImageIO.createImageOutputStream( file );
946 writer.setOutput( ios );
947 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
948 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
949 // see writeParam.getCompressionTypes() for available compression type
951 image_write_param.setCompressionType( "PackBits" );
952 final String t[] = image_write_param.getCompressionTypes();
953 for( final String string : t ) {
954 System.out.println( string );
956 // Convert to an IIOImage:
957 final IIOImage iio_image = new IIOImage( image, null, null );
958 writer.write( null, iio_image, image_write_param );
961 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
962 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
963 InvocationTargetException, InterruptedException {
964 final String os = System.getProperty( "os.name" );
965 final Runtime runtime = Runtime.getRuntime();
966 if ( os.toLowerCase().startsWith( "win" ) ) {
967 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
969 else if ( ForesterUtil.isMac() ) {
970 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
971 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
972 open_url.invoke( null, new Object[] { url } );
975 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
976 String browser = null;
977 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
978 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
979 browser = browsers[ i ];
982 if ( browser == null ) {
983 throw new IOException( "could not find a web browser to open [" + url + "] in" );
986 runtime.exec( new String[] { browser, url } );
991 public static enum GraphicsExportType {
992 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
994 private final String _suffix;
996 private GraphicsExportType( final String suffix ) {
1001 public String toString() {
1006 final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
1007 final String my_str = str.toUpperCase();
1008 char first = my_str.charAt( 0 );
1011 if ( my_str.length() > 1 ) {
1012 if ( is_taxonomy ) {
1013 second = my_str.charAt( 1 );
1016 second = my_str.charAt( my_str.length() - 1 );
1018 if ( is_taxonomy ) {
1019 if ( my_str.length() > 2 ) {
1020 if ( my_str.indexOf( " " ) > 0 ) {
1021 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
1024 third = my_str.charAt( 2 );
1028 else if ( my_str.length() > 2 ) {
1029 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
1032 first = normalizeCharForRGB( first );
1033 second = normalizeCharForRGB( second );
1034 third = normalizeCharForRGB( third );
1035 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
1038 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
1041 return new Color( first, second, third );
1044 final private static char normalizeCharForRGB( char c ) {
1047 c = c > 255 ? 255 : c;