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.lang.reflect.InvocationTargetException;
40 import java.lang.reflect.Method;
43 import java.security.KeyManagementException;
44 import java.security.NoSuchAlgorithmException;
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.BranchWidth;
76 import org.forester.phylogeny.data.Confidence;
77 import org.forester.phylogeny.data.Taxonomy;
78 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
79 import org.forester.util.AsciiHistogram;
80 import org.forester.util.DescriptiveStatistics;
81 import org.forester.util.ForesterUtil;
83 public final class AptxUtil {
85 public static enum GraphicsExportType {
86 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
88 private final String _suffix;
90 private GraphicsExportType( final String suffix ) {
95 public String toString() {
99 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
100 .getAvailableFontFamilyNames();
102 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
105 final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
106 final String my_str = str.toUpperCase();
107 char first = my_str.charAt( 0 );
110 if ( my_str.length() > 1 ) {
112 second = my_str.charAt( 1 );
115 second = my_str.charAt( my_str.length() - 1 );
118 if ( my_str.length() > 2 ) {
119 if ( my_str.indexOf( " " ) > 0 ) {
120 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
123 third = my_str.charAt( 2 );
127 else if ( my_str.length() > 2 ) {
128 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
131 first = normalizeCharForRGB( first );
132 second = normalizeCharForRGB( second );
133 third = normalizeCharForRGB( third );
134 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
137 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
140 return new Color( first, second, third );
143 public static MaskFormatter createMaskFormatter( final String s ) {
144 MaskFormatter formatter = null;
146 formatter = new MaskFormatter( s );
148 catch ( final ParseException e ) {
149 throw new IllegalArgumentException( e );
154 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
155 final PhylogenyNodeIterator it = phy.iteratorPostorder();
156 while ( it.hasNext() ) {
157 if ( it.next().getNodeData().isHasEvent() ) {
165 * Returns true if at least one branch has a length larger than zero.
170 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
171 final PhylogenyNodeIterator it = phy.iteratorPostorder();
172 while ( it.hasNext() ) {
173 if ( it.next().getDistanceToParent() > 0.0 ) {
180 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
181 final PhylogenyNodeIterator it = phy.iteratorPostorder();
182 while ( it.hasNext() ) {
183 final PhylogenyNode n = it.next();
184 if ( n.getBranchData().isHasConfidences() ) {
185 final List<Confidence> c = n.getBranchData().getConfidences();
186 for( final Confidence confidence : c ) {
187 if ( confidence.getStandardDeviation() > 0 ) {
196 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
197 final PhylogenyNodeIterator it = phy.iteratorPostorder();
198 while ( it.hasNext() ) {
199 if ( it.next().getBranchData().isHasConfidences() ) {
206 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
207 final PhylogenyNodeIterator it = phy.iteratorPostorder();
208 while ( it.hasNext() ) {
209 final PhylogenyNode n = it.next();
210 if ( n.getNodeData().isHasTaxonomy()
211 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
218 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
219 final PhylogenyNodeIterator it = phy.iteratorPostorder();
220 while ( it.hasNext() ) {
221 final PhylogenyNode n = it.next();
222 if ( n.getNodeData().isHasSequence()
223 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
230 final public static void launchWebBrowser( final URI uri,
231 final boolean is_applet,
232 final JApplet applet,
233 final String frame_name ) throws IOException {
235 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
238 // This requires Java 1.6:
239 // =======================
240 // boolean no_desktop = false;
242 // if ( Desktop.isDesktopSupported() ) {
243 // System.out.println( "desktop supported" );
244 // final Desktop dt = Desktop.getDesktop();
248 // no_desktop = true;
251 // catch ( final Exception ex ) {
252 // ex.printStackTrace();
253 // no_desktop = true;
255 // catch ( final Error er ) {
256 // er.printStackTrace();
257 // no_desktop = true;
259 // if ( no_desktop ) {
260 // System.out.println( "desktop not supported" );
262 openUrlInWebBrowser( uri.toString() );
264 catch ( final Exception e ) {
265 throw new IOException( e );
271 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
272 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
273 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
274 for( final PhylogenyNode n : descs ) {
275 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
276 tax_set.add( n.getNodeData().getTaxonomy() );
282 public final static void printWarningMessage( final String name, final String message ) {
283 System.out.println( "[" + name + "] > " + message );
286 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
287 final boolean phyloxml_validate_against_xsd,
288 final boolean replace_underscores,
289 final boolean internal_numbers_are_confidences,
290 final TAXONOMY_EXTRACTION taxonomy_extraction,
291 final boolean midpoint_reroot )
292 throws FileNotFoundException, IOException {
293 final PhylogenyParser parser;
294 boolean nhx_or_nexus = false;
295 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
296 parser = new TolParser();
299 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
300 if ( parser instanceof NHXParser ) {
302 final NHXParser nhx = ( NHXParser ) parser;
303 nhx.setReplaceUnderscores( replace_underscores );
304 nhx.setIgnoreQuotes( false );
305 nhx.setTaxonomyExtraction( taxonomy_extraction );
307 else if ( parser instanceof NexusPhylogeniesParser ) {
309 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
310 nex.setReplaceUnderscores( replace_underscores );
311 nex.setIgnoreQuotes( false );
314 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
315 Phylogeny[] phys = null;
317 phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
319 catch ( final KeyManagementException e ) {
320 throw new IOException( e.getMessage() );
322 catch ( final NoSuchAlgorithmException e ) {
323 throw new IOException( e.getMessage() );
325 if ( phys != null ) {
326 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
327 for( final Phylogeny phy : phys ) {
328 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
331 if ( midpoint_reroot ) {
332 for( final Phylogeny phy : phys ) {
333 PhylogenyMethods.midpointRoot( phy );
334 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
341 final public static void showErrorMessage( final Component parent, final String error_msg ) {
342 printAppletMessage( AptxConstants.PRG_NAME, error_msg );
343 JOptionPane.showMessageDialog( parent, error_msg, "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
344 + "] Error", JOptionPane.ERROR_MESSAGE );
347 public static void writePhylogenyToGraphicsFile( final File intree,
351 final GraphicsExportType type,
352 final Configuration config ) throws IOException {
353 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
354 Phylogeny[] phys = null;
355 phys = PhylogenyMethods.readPhylogenies( parser, intree );
356 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
359 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
363 final GraphicsExportType type,
364 final Configuration config ) throws IOException {
365 final Phylogeny[] phys = new Phylogeny[ 1 ];
367 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
368 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
369 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
373 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
376 final TreePanel tree_panel,
377 final ControlPanel ac,
378 final GraphicsExportType type,
379 final Options options ) throws IOException {
380 tree_panel.calcParametersForPainting( width, height );
381 tree_panel.resetPreferredSize();
382 tree_panel.repaint();
383 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
384 RenderingHints.VALUE_RENDER_QUALITY );
385 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
386 if ( options.isAntialiasPrint() ) {
387 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
388 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
391 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
392 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
394 final Phylogeny phylogeny = tree_panel.getPhylogeny();
395 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
398 if ( outfile.isDirectory() ) {
399 throw new IOException( "\"" + outfile + "\" is a directory" );
401 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
402 final Graphics2D g2d = buffered_img.createGraphics();
403 g2d.setRenderingHints( rendering_hints );
404 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
405 if ( type == GraphicsExportType.TIFF ) {
406 writeToTiff( outfile, buffered_img );
409 ImageIO.write( buffered_img, type.toString(), outfile );
414 final private static char normalizeCharForRGB( char c ) {
417 c = c > 255 ? 255 : c;
422 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
423 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
424 InvocationTargetException, InterruptedException {
425 final String os = System.getProperty( "os.name" );
426 final Runtime runtime = Runtime.getRuntime();
427 if ( os.toLowerCase().startsWith( "win" ) ) {
428 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
430 else if ( ForesterUtil.isMac() ) {
431 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
432 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
433 open_url.invoke( null, new Object[] { url } );
436 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
437 String browser = null;
438 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
439 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
440 browser = browsers[ i ];
443 if ( browser == null ) {
444 throw new IOException( "could not find a web browser to open [" + url + "] in" );
447 runtime.exec( new String[] { browser, url } );
452 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
453 final String default_name,
454 final String full_path,
455 final Configuration configuration,
456 final MainPanel main_panel ) {
457 if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
458 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
459 + " phylogenies,\ngoing to load only the first " + AptxConstants.MAX_TREES_TO_LOAD, AptxConstants.PRG_NAME
460 + " more than " + AptxConstants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
463 for( final Phylogeny phy : phys ) {
464 if ( !phy.isEmpty() ) {
465 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
467 String my_name_for_file = "";
468 if ( phys.length > 1 ) {
469 if ( !ForesterUtil.isEmpty( default_name ) ) {
470 my_name = new String( default_name );
472 if ( !ForesterUtil.isEmpty( full_path ) ) {
473 my_name_for_file = new String( full_path );
475 else if ( !ForesterUtil.isEmpty( default_name ) ) {
476 my_name_for_file = new String( default_name );
479 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
480 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
481 my_name_for_file.length() );
482 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
484 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
485 my_name_for_file += "_";
487 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
488 my_name_for_file += phy.getName().replaceAll( " ", "_" );
490 else if ( phy.getIdentifier() != null ) {
491 final StringBuffer sb = new StringBuffer();
492 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
493 sb.append( phy.getIdentifier().getProvider() );
496 sb.append( phy.getIdentifier().getValue() );
497 my_name_for_file += sb;
500 my_name_for_file += i;
502 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
503 && ( phy.getIdentifier() == null ) ) {
504 my_name = my_name + " [" + i + "]";
506 if ( !ForesterUtil.isEmpty( suffix ) ) {
507 my_name_for_file += suffix;
511 if ( !ForesterUtil.isEmpty( default_name ) ) {
512 my_name = new String( default_name );
514 my_name_for_file = "";
515 if ( !ForesterUtil.isEmpty( full_path ) ) {
516 my_name_for_file = new String( full_path );
518 else if ( !ForesterUtil.isEmpty( default_name ) ) {
519 my_name_for_file = new String( default_name );
521 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
522 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
523 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
525 else if ( phy.getIdentifier() != null ) {
526 final StringBuffer sb = new StringBuffer();
527 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
528 sb.append( phy.getIdentifier().getProvider() );
531 sb.append( phy.getIdentifier().getValue() );
532 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
536 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
537 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
538 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
545 final static void addPhylogenyToPanel( final Phylogeny[] phys,
546 final Configuration configuration,
547 final MainPanel main_panel ) {
548 final Phylogeny phy = phys[ 0 ];
549 main_panel.addPhylogenyInPanel( phy, configuration );
550 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
553 // Returns true if the specified format name can be written
554 final static boolean canWriteFormat( final String format_name ) {
555 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
556 return iter.hasNext();
559 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
560 final StringBuilder desc = new StringBuilder();
561 if ( ( phy != null ) && !phy.isEmpty() ) {
563 if ( treefile != null ) {
565 f = treefile.getCanonicalPath();
567 catch ( final IOException e ) {
568 //Not important, ignore.
570 if ( !ForesterUtil.isEmpty( f ) ) {
571 desc.append( "Path: " );
576 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
577 desc.append( "Name: " );
578 desc.append( phy.getName() );
581 if ( phy.getIdentifier() != null ) {
582 desc.append( "Id: " );
583 desc.append( phy.getIdentifier().toString() );
586 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
587 desc.append( "Description: " );
588 desc.append( phy.getDescription() );
591 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
592 desc.append( "Distance Unit: " );
593 desc.append( phy.getDistanceUnit() );
596 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
597 desc.append( "Type: " );
598 desc.append( phy.getType() );
601 desc.append( "Rooted: " );
602 desc.append( phy.isRooted() );
604 desc.append( "Rerootable: " );
605 desc.append( phy.isRerootable() );
607 desc.append( "Nodes: " );
608 desc.append( phy.getNodeCount() );
610 desc.append( "External nodes: " );
611 desc.append( phy.getNumberOfExternalNodes() );
613 desc.append( "Internal nodes: " );
614 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
616 desc.append( "Internal nodes with polytomies: " );
617 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
619 desc.append( "Branches: " );
620 desc.append( phy.getNumberOfBranches() );
622 desc.append( "Depth: " );
623 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
625 desc.append( "Maximum distance to root: " );
626 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
628 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
629 if ( taxs != null ) {
630 desc.append( "Distinct external taxonomies: " );
631 desc.append( taxs.size() );
633 for( final Taxonomy t : taxs ) {
634 System.out.println( t.toString() );
637 final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
638 if ( bs.getN() > 3 ) {
640 desc.append( "Branch-length statistics: " );
642 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
644 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
646 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
647 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
649 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
651 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
653 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
655 final AsciiHistogram histo = new AsciiHistogram( bs );
656 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
659 final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
660 if ( ds.getN() > 2 ) {
662 desc.append( "Descendants per node statistics: " );
664 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
666 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
667 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
669 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
671 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
674 List<DescriptiveStatistics> css = null;
676 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
678 catch ( final IllegalArgumentException e ) {
679 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
681 if ( ( css != null ) && ( css.size() > 0 ) ) {
683 for( int i = 0; i < css.size(); ++i ) {
684 final DescriptiveStatistics cs = css.get( i );
685 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
686 if ( css.size() > 1 ) {
687 desc.append( "Support statistics " + ( i + 1 ) + ": " );
690 desc.append( "Support statistics: " );
692 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
694 desc.append( " Type: " + cs.getDescription() );
697 desc.append( " Branches with support: " + cs.getN() );
699 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
701 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
702 if ( cs.getN() > 2 ) {
703 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
706 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
708 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
714 return desc.toString();
722 * to message to be printed
724 final static void dieWithSystemError( final String message ) {
725 System.out.println();
726 System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
727 System.out.println( "Please contact the authors." );
728 System.out.println( AptxConstants.PRG_NAME + " needs to close." );
729 System.out.println();
733 final static String[] getAllPossibleRanks() {
734 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
736 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
737 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
738 str_array[ i++ ] = e;
744 final static String[] getAllRanks( final Phylogeny tree ) {
745 final SortedSet<String> ranks = new TreeSet<String>();
746 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
747 final PhylogenyNode n = it.next();
748 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
749 ranks.add( n.getNodeData().getTaxonomy().getRank() );
752 return ForesterUtil.stringSetToArray( ranks );
755 final static String[] getAvailableFontFamiliesSorted() {
756 return AVAILABLE_FONT_FAMILIES_SORTED;
759 final static boolean isUsOrCanada() {
761 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
765 catch ( final Exception e ) {
770 final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t,
771 final ControlPanel cp ) {
772 if ( ( t != null ) && !t.isEmpty() ) {
773 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
775 cp.setDrawPhylogram( false );
776 cp.setDrawPhylogramEnabled( false );
778 else if ( cp.getDisplayAsPhylogramCb() != null ) {
779 cp.setDrawPhylogramEnabled( true );
783 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
784 final ControlPanel atv_control,
785 final Configuration configuration ) {
786 if ( ( t != null ) && !t.isEmpty() ) {
787 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
789 atv_control.setDrawPhylogram( false );
790 atv_control.setDrawPhylogramEnabled( false );
793 if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
794 && atv_control.getUseVisualStylesCb() != null ) {
795 atv_control.getUseVisualStylesCb().setSelected( true );
797 if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
798 && t.getFirstExternalNode().getBranchData().getBranchWidth().getValue()
799 != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
800 && atv_control.getUseBranchWidthsCb() != null ) {
801 atv_control.getUseBranchWidthsCb().setSelected( true );
805 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
806 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
808 atv_control.setDrawPhylogram( true );
809 atv_control.setDrawPhylogramEnabled( true );
812 atv_control.setDrawPhylogram( false );
816 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
817 if ( atv_control.getWriteConfidenceCb() != null ) {
818 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
819 atv_control.setCheckbox( Configuration.write_confidence_values, true );
822 atv_control.setCheckbox( Configuration.write_confidence_values, false );
826 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
827 if ( atv_control.getShowEventsCb() != null ) {
828 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
829 atv_control.setCheckbox( Configuration.write_events, true );
832 atv_control.setCheckbox( Configuration.write_events, false );
839 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
841 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, AptxConstants.PRG_NAME );
843 catch ( final Exception e ) {
844 throw new IOException( e );
848 final static void outOfMemoryError( final OutOfMemoryError e ) {
849 System.err.println();
850 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
851 System.err.println();
853 System.err.println();
854 JOptionPane.showMessageDialog( null,
855 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
856 + "\n\nError: " + e.getLocalizedMessage(),
857 "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
858 JOptionPane.ERROR_MESSAGE );
862 final static void printAppletMessage( final String applet_name, final String message ) {
863 System.out.println( "[" + applet_name + "] > " + message );
866 final static void removeBranchColors( final Phylogeny phy ) {
867 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
868 it.next().getBranchData().setBranchColor( null );
872 final static void removeVisualStyles( final Phylogeny phy ) {
873 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
874 it.next().getNodeData().setNodeVisualData( null );
878 final static void unexpectedError( final Error e ) {
879 System.err.println();
880 e.printStackTrace( System.err );
881 System.err.println();
882 final StringBuffer sb = new StringBuffer();
883 for( final StackTraceElement s : e.getStackTrace() ) {
884 sb.append( s + "\n" );
887 .showMessageDialog( null,
888 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
889 + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
891 "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
892 JOptionPane.ERROR_MESSAGE );
896 final static void unexpectedException( final Exception e ) {
897 System.err.println();
898 e.printStackTrace( System.err );
899 System.err.println();
900 final StringBuffer sb = new StringBuffer();
901 for( final StackTraceElement s : e.getStackTrace() ) {
902 sb.append( s + "\n" );
904 JOptionPane.showMessageDialog( null,
905 "An unexpected exception has occured. \nPlease contact: "
906 + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
908 "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
909 JOptionPane.ERROR_MESSAGE );
912 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
915 final TreePanel tree_panel,
916 final ControlPanel ac,
917 final GraphicsExportType type,
918 final Options options ) throws IOException {
920 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
921 RenderingHints.VALUE_RENDER_QUALITY );
922 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
923 if ( options.isAntialiasPrint() ) {
924 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
925 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
928 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
929 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
931 final Phylogeny phylogeny = tree_panel.getPhylogeny();
932 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
935 Rectangle visible = null;
936 // if ( !options.isGraphicsExportUsingActualSize() ) {
937 // width = options.getPrintSizeX();
938 // height = options.getPrintSizeY();
940 /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
941 visible = tree_panel.getVisibleRect();
942 width = visible.width;
943 height = visible.height;
945 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
946 Graphics2D g2d = buffered_img.createGraphics();
947 g2d.setRenderingHints( rendering_hints );
950 if ( options.isGraphicsExportVisibleOnly() ) {
951 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
956 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
957 ImageIO.write( buffered_img, type.toString(), baos );
960 if ( !options.isGraphicsExportUsingActualSize() ) {
961 tree_panel.getMainPanel().getControlPanel().showWhole();
963 String msg = baos.toString();
964 if ( ( width > 0 ) && ( height > 0 ) ) {
965 msg += " [size: " + width + ", " + height + "]";
970 final static String writePhylogenyToGraphicsFile( final String file_name,
973 final TreePanel tree_panel,
974 final ControlPanel ac,
975 final GraphicsExportType type,
976 final Options options ) throws IOException {
978 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
979 RenderingHints.VALUE_RENDER_QUALITY );
980 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
981 if ( options.isAntialiasPrint() ) {
982 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
983 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
986 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
987 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
989 final Phylogeny phylogeny = tree_panel.getPhylogeny();
990 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
993 final File file = new File( file_name );
994 if ( file.isDirectory() ) {
995 throw new IOException( "\"" + file_name + "\" is a directory" );
997 Rectangle visible = null;
998 // if ( !options.isGraphicsExportUsingActualSize() ) {
999 // width = options.getPrintSizeX();
1000 // height = options.getPrintSizeY();
1002 /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1003 visible = tree_panel.getVisibleRect();
1004 width = visible.width;
1005 height = visible.height;
1007 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1008 Graphics2D g2d = buffered_img.createGraphics();
1009 g2d.setRenderingHints( rendering_hints );
1012 if ( options.isGraphicsExportVisibleOnly() ) {
1013 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1014 g2d.setClip( null );
1018 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1019 if ( type == GraphicsExportType.TIFF ) {
1020 writeToTiff( file, buffered_img );
1023 ImageIO.write( buffered_img, type.toString(), file );
1027 if ( !options.isGraphicsExportUsingActualSize() ) {
1028 tree_panel.getMainPanel().getControlPanel().showWhole();
1030 String msg = file.toString();
1031 if ( ( width > 0 ) && ( height > 0 ) ) {
1032 msg += " [size: " + width + ", " + height + "]";
1037 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1038 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1039 ImageWriter writer = null;
1040 ImageOutputStream ios = null;
1041 // Find an appropriate writer:
1042 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1043 if ( it.hasNext() ) {
1047 throw new IOException( "failed to get TIFF image writer" );
1050 ios = ImageIO.createImageOutputStream( file );
1051 writer.setOutput( ios );
1052 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1053 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1054 // see writeParam.getCompressionTypes() for available compression type
1056 image_write_param.setCompressionType( "PackBits" );
1057 final String t[] = image_write_param.getCompressionTypes();
1058 for( final String string : t ) {
1059 System.out.println( string );
1061 // Convert to an IIOImage:
1062 final IIOImage iio_image = new IIOImage( image, null, null );
1063 writer.write( null, iio_image, image_write_param );