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.HashMap;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Locale;
54 import java.util.SortedSet;
55 import java.util.TreeSet;
57 import javax.imageio.IIOImage;
58 import javax.imageio.ImageIO;
59 import javax.imageio.ImageWriteParam;
60 import javax.imageio.ImageWriter;
61 import javax.imageio.stream.ImageOutputStream;
62 import javax.swing.JOptionPane;
63 import javax.swing.text.MaskFormatter;
65 import org.forester.archaeopteryx.Options.PHYLOGENY_DISPLAY_TYPE;
66 import org.forester.io.parsers.PhylogenyParser;
67 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
68 import org.forester.io.parsers.nhx.NHXParser;
69 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
70 import org.forester.io.parsers.tol.TolParser;
71 import org.forester.io.parsers.util.ParserUtils;
72 import org.forester.phylogeny.Phylogeny;
73 import org.forester.phylogeny.PhylogenyMethods;
74 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
75 import org.forester.phylogeny.PhylogenyNode;
76 import org.forester.phylogeny.data.BranchWidth;
77 import org.forester.phylogeny.data.Confidence;
78 import org.forester.phylogeny.data.Taxonomy;
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;
83 import org.forester.util.TaxonomyUtil;
85 public final class AptxUtil {
87 public static enum GraphicsExportType {
88 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
90 private final String _suffix;
92 private GraphicsExportType( final String suffix ) {
97 public String toString() {
101 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
102 .getAvailableFontFamilyNames();
104 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
107 final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
108 final String my_str = str.toUpperCase();
109 char first = my_str.charAt( 0 );
112 if ( my_str.length() > 1 ) {
114 second = my_str.charAt( 1 );
117 second = my_str.charAt( my_str.length() - 1 );
120 if ( my_str.length() > 2 ) {
121 if ( my_str.indexOf( " " ) > 0 ) {
122 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
125 third = my_str.charAt( 2 );
129 else if ( my_str.length() > 2 ) {
130 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
133 first = normalizeCharForRGB( first );
134 second = normalizeCharForRGB( second );
135 third = normalizeCharForRGB( third );
136 if ( ( first > 200 ) && ( second > 200 ) && ( third > 200 ) ) {
139 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
142 else if ( Math.abs( first - second ) < 40 && Math.abs( second - third ) < 40 ) {
145 return new Color( first, second, third );
148 public static MaskFormatter createMaskFormatter( final String s ) {
149 MaskFormatter formatter = null;
151 formatter = new MaskFormatter( s );
153 catch ( final ParseException e ) {
154 throw new IllegalArgumentException( e );
159 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
160 final PhylogenyNodeIterator it = phy.iteratorPostorder();
161 while ( it.hasNext() ) {
162 if ( it.next().getNodeData().isHasEvent() ) {
170 * Returns true if at least one branch has a length larger than zero.
175 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
176 final PhylogenyNodeIterator it = phy.iteratorPostorder();
177 while ( it.hasNext() ) {
178 if ( it.next().getDistanceToParent() > 0.0 ) {
185 final static public boolean isHasNoBranchLengthSmallerThanZero( final Phylogeny phy ) {
186 final PhylogenyNodeIterator it = phy.iteratorPostorder();
187 while ( it.hasNext() ) {
188 final PhylogenyNode n = it.next();
189 if ( n.getDistanceToParent() < 0.0 && !n.isRoot() ) {
196 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
197 final PhylogenyNodeIterator it = phy.iteratorPostorder();
198 while ( it.hasNext() ) {
199 final PhylogenyNode n = it.next();
200 if ( n.getBranchData().isHasConfidences() ) {
201 final List<Confidence> c = n.getBranchData().getConfidences();
202 for( final Confidence confidence : c ) {
203 if ( confidence.getStandardDeviation() > 0 ) {
212 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
213 final PhylogenyNodeIterator it = phy.iteratorPostorder();
214 while ( it.hasNext() ) {
215 if ( it.next().getBranchData().isHasConfidences() ) {
222 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
223 final PhylogenyNodeIterator it = phy.iteratorPostorder();
224 while ( it.hasNext() ) {
225 final PhylogenyNode n = it.next();
226 if ( n.getNodeData().isHasTaxonomy()
227 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
234 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
235 final PhylogenyNodeIterator it = phy.iteratorPostorder();
236 while ( it.hasNext() ) {
237 final PhylogenyNode n = it.next();
238 if ( n.getNodeData().isHasSequence()
239 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
246 final public static void launchWebBrowser( final URI uri,
247 final String frame_name ) throws IOException {
249 // This requires Java 1.6:
250 // =======================
251 // boolean no_desktop = false;
253 // if ( Desktop.isDesktopSupported() ) {
254 // System.out.println( "desktop supported" );
255 // final Desktop dt = Desktop.getDesktop();
259 // no_desktop = true;
262 // catch ( final Exception ex ) {
263 // ex.printStackTrace();
264 // no_desktop = true;
266 // catch ( final Error er ) {
267 // er.printStackTrace();
268 // no_desktop = true;
270 // if ( no_desktop ) {
271 // System.out.println( "desktop not supported" );
273 openUrlInWebBrowser( uri.toString() );
275 catch ( final Exception e ) {
276 throw new IOException( e );
282 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
283 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
284 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
285 for( final PhylogenyNode n : descs ) {
286 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
287 tax_set.add( n.getNodeData().getTaxonomy() );
293 public final static void printWarningMessage( final String name, final String message ) {
294 System.out.println( "[" + name + "] > " + message );
297 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
298 final boolean phyloxml_validate_against_xsd,
299 final boolean replace_underscores,
300 final boolean internal_numbers_are_confidences,
301 final TAXONOMY_EXTRACTION taxonomy_extraction,
302 final boolean midpoint_reroot )
303 throws FileNotFoundException, IOException {
304 final PhylogenyParser parser;
305 boolean nhx_or_nexus = false;
306 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
307 parser = new TolParser();
310 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
311 if ( parser instanceof NHXParser ) {
313 final NHXParser nhx = ( NHXParser ) parser;
314 nhx.setReplaceUnderscores( replace_underscores );
315 nhx.setIgnoreQuotes( false );
316 nhx.setTaxonomyExtraction( taxonomy_extraction );
318 else if ( parser instanceof NexusPhylogeniesParser ) {
320 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
321 nex.setReplaceUnderscores( replace_underscores );
322 nex.setIgnoreQuotes( false );
325 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
326 Phylogeny[] phys = null;
328 phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
330 catch ( final KeyManagementException e ) {
331 throw new IOException( e.getMessage() );
333 catch ( final NoSuchAlgorithmException e ) {
334 throw new IOException( e.getMessage() );
336 if ( phys != null ) {
337 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
338 for( final Phylogeny phy : phys ) {
339 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
342 if ( midpoint_reroot ) {
343 for( final Phylogeny phy : phys ) {
344 PhylogenyMethods.midpointRoot( phy );
345 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
352 final public static void showErrorMessage( final Component parent, final String error_msg ) {
353 printAppletMessage( AptxConstants.PRG_NAME, error_msg );
354 JOptionPane.showMessageDialog( parent, error_msg, "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
355 + "] Error", JOptionPane.ERROR_MESSAGE );
358 public static void writePhylogenyToGraphicsFile( final File intree,
362 final GraphicsExportType type,
363 final Configuration config ) throws IOException {
364 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
365 Phylogeny[] phys = null;
366 phys = PhylogenyMethods.readPhylogenies( parser, intree );
367 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
370 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
374 final GraphicsExportType type,
375 final Configuration config ) throws IOException {
376 final Phylogeny[] phys = new Phylogeny[ 1 ];
378 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
379 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
380 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
384 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
387 final TreePanel tree_panel,
388 final ControlPanel ac,
389 final GraphicsExportType type,
390 final Options options ) throws IOException {
391 tree_panel.calcParametersForPainting( width, height );
392 tree_panel.resetPreferredSize();
393 tree_panel.repaint();
394 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
395 RenderingHints.VALUE_RENDER_QUALITY );
396 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
397 if ( options.isAntialiasPrint() ) {
398 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
399 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
402 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
403 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
405 final Phylogeny phylogeny = tree_panel.getPhylogeny();
406 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
409 if ( outfile.isDirectory() ) {
410 throw new IOException( "\"" + outfile + "\" is a directory" );
412 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
413 final Graphics2D g2d = buffered_img.createGraphics();
414 g2d.setRenderingHints( rendering_hints );
415 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
416 if ( type == GraphicsExportType.TIFF ) {
417 writeToTiff( outfile, buffered_img );
420 ImageIO.write( buffered_img, type.toString(), outfile );
425 final private static char normalizeCharForRGB( char c ) {
428 c = c > 255 ? 255 : c;
433 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
434 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
435 InvocationTargetException, InterruptedException {
436 final String os = System.getProperty( "os.name" );
437 final Runtime runtime = Runtime.getRuntime();
438 if ( os.toLowerCase().startsWith( "win" ) ) {
439 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
441 else if ( ForesterUtil.isMac() ) {
442 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
443 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
444 open_url.invoke( null, new Object[] { url } );
447 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
448 String browser = null;
449 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
450 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
451 browser = browsers[ i ];
454 if ( browser == null ) {
455 throw new IOException( "could not find a web browser to open [" + url + "] in" );
458 runtime.exec( new String[] { browser, url } );
463 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
464 final String default_name,
465 final String full_path,
466 final Configuration configuration,
467 final MainPanel main_panel ) {
468 if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
469 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
470 + " phylogenies,\ngoing to load only the first " + AptxConstants.MAX_TREES_TO_LOAD, AptxConstants.PRG_NAME
471 + " more than " + AptxConstants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
474 for( final Phylogeny phy : phys ) {
475 if ( !phy.isEmpty() ) {
476 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
478 String my_name_for_file = "";
479 if ( phys.length > 1 ) {
480 if ( !ForesterUtil.isEmpty( default_name ) ) {
481 my_name = new String( default_name );
483 if ( !ForesterUtil.isEmpty( full_path ) ) {
484 my_name_for_file = new String( full_path );
486 else if ( !ForesterUtil.isEmpty( default_name ) ) {
487 my_name_for_file = new String( default_name );
490 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
491 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
492 my_name_for_file.length() );
493 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
495 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
496 my_name_for_file += "_";
498 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
499 my_name_for_file += phy.getName().replaceAll( " ", "_" );
501 else if ( phy.getIdentifier() != null ) {
502 final StringBuffer sb = new StringBuffer();
503 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
504 sb.append( phy.getIdentifier().getProvider() );
507 sb.append( phy.getIdentifier().getValue() );
508 my_name_for_file += sb;
511 my_name_for_file += i;
513 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
514 && ( phy.getIdentifier() == null ) ) {
515 my_name = my_name + " [" + i + "]";
517 if ( !ForesterUtil.isEmpty( suffix ) ) {
518 my_name_for_file += suffix;
522 if ( !ForesterUtil.isEmpty( default_name ) ) {
523 my_name = new String( default_name );
525 my_name_for_file = "";
526 if ( !ForesterUtil.isEmpty( full_path ) ) {
527 my_name_for_file = new String( full_path );
529 else if ( !ForesterUtil.isEmpty( default_name ) ) {
530 my_name_for_file = new String( default_name );
532 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
533 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
534 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
536 else if ( phy.getIdentifier() != null ) {
537 final StringBuffer sb = new StringBuffer();
538 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
539 sb.append( phy.getIdentifier().getProvider() );
542 sb.append( phy.getIdentifier().getValue() );
543 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
547 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
548 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
549 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
556 final static void addPhylogenyToPanel( final Phylogeny[] phys,
557 final Configuration configuration,
558 final MainPanel main_panel ) {
559 final Phylogeny phy = phys[ 0 ];
560 main_panel.addPhylogenyInPanel( phy, configuration );
561 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
564 // Returns true if the specified format name can be written
565 final static boolean canWriteFormat( final String format_name ) {
566 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
567 return iter.hasNext();
570 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
571 final StringBuilder desc = new StringBuilder();
572 if ( ( phy != null ) && !phy.isEmpty() ) {
574 if ( treefile != null ) {
576 f = treefile.getCanonicalPath();
578 catch ( final IOException e ) {
579 //Not important, ignore.
581 if ( !ForesterUtil.isEmpty( f ) ) {
582 desc.append( "Path: " );
587 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
588 desc.append( "Name: " );
589 desc.append( phy.getName() );
592 if ( phy.getIdentifier() != null ) {
593 desc.append( "Id: " );
594 desc.append( phy.getIdentifier().toString() );
597 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
598 desc.append( "Description: " );
599 desc.append( phy.getDescription() );
602 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
603 desc.append( "Distance Unit: " );
604 desc.append( phy.getDistanceUnit() );
607 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
608 desc.append( "Type: " );
609 desc.append( phy.getType() );
612 desc.append( "Rooted: " );
613 desc.append( phy.isRooted() );
615 desc.append( "Rerootable: " );
616 desc.append( phy.isRerootable() );
618 desc.append( "Nodes: " );
619 desc.append( phy.getNodeCount() );
621 desc.append( "External nodes: " );
622 desc.append( phy.getNumberOfExternalNodes() );
624 desc.append( "Internal nodes: " );
625 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
627 desc.append( "Internal nodes with polytomies: " );
628 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
630 desc.append( "Branches: " );
631 desc.append( phy.getNumberOfBranches() );
633 desc.append( "Depth: " );
634 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
636 desc.append( "Maximum distance to root: " );
637 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
639 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
640 if ( taxs != null ) {
641 desc.append( "Distinct external taxonomies: " );
642 desc.append( taxs.size() );
644 for( final Taxonomy t : taxs ) {
645 System.out.println( t.toString() );
648 final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
649 if ( bs.getN() > 3 ) {
651 desc.append( "Branch-length statistics: " );
653 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
655 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
657 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
658 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
660 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
662 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
664 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
666 final AsciiHistogram histo = new AsciiHistogram( bs );
667 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
670 final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
671 if ( ds.getN() > 2 ) {
673 desc.append( "Descendants per node statistics: " );
675 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
677 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
678 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
680 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
682 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
685 List<DescriptiveStatistics> css = null;
687 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
689 catch ( final IllegalArgumentException e ) {
690 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
692 if ( ( css != null ) && ( css.size() > 0 ) ) {
694 for( int i = 0; i < css.size(); ++i ) {
695 final DescriptiveStatistics cs = css.get( i );
696 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
697 if ( css.size() > 1 ) {
698 desc.append( "Support statistics " + ( i + 1 ) + ": " );
701 desc.append( "Support statistics: " );
703 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
705 desc.append( " Type: " + cs.getDescription() );
708 desc.append( " Branches with support: " + cs.getN() );
710 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
712 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
713 if ( cs.getN() > 2 ) {
714 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
717 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
719 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
725 return desc.toString();
733 * to message to be printed
735 final static void dieWithSystemError( final String message ) {
736 System.out.println();
737 System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
738 System.out.println( "Please contact the authors." );
739 System.out.println( AptxConstants.PRG_NAME + " needs to close." );
740 System.out.println();
744 final static String[] getAllPossibleRanks() {
745 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
747 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
748 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
749 str_array[ i++ ] = e;
755 final static String[] getAllPossibleRanks(final Map<String, Integer> present_ranks) {
756 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
758 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
759 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
760 if ( present_ranks != null && present_ranks.containsKey( e ) ) {
761 str_array[ i++ ] = e + " (" + present_ranks.get(e) + ")";
764 str_array[ i++ ] = e;
771 final static String[] getAllRanks( final Phylogeny tree ) {
772 final SortedSet<String> ranks = new TreeSet<String>();
773 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
774 final PhylogenyNode n = it.next();
775 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
776 ranks.add( n.getNodeData().getTaxonomy().getRank() );
779 return ForesterUtil.stringSetToArray( ranks );
782 final static String[] getAvailableFontFamiliesSorted() {
783 return AVAILABLE_FONT_FAMILIES_SORTED;
786 final static boolean isUsOrCanada() {
788 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
792 catch ( final Exception e ) {
797 final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t,
798 final ControlPanel cp ) {
799 if ( ( t != null ) && !t.isEmpty() ) {
800 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
803 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
804 cp.setDrawPhylogramEnabled( false );
807 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
809 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
812 if ( cp.getDisplayAsUnalignedPhylogramRb() != null ) {
813 cp.setDrawPhylogramEnabled( true );
818 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
819 final ControlPanel atv_control,
820 final Configuration configuration ) {
821 if ( ( t != null ) && !t.isEmpty() ) {
822 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
824 atv_control.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
825 atv_control.setDrawPhylogramEnabled( false );
827 if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
828 && atv_control.getUseVisualStylesCb() != null ) {
829 atv_control.getUseVisualStylesCb().setSelected( true );
831 if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
832 && t.getFirstExternalNode().getBranchData().getBranchWidth().getValue()
833 != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
834 && atv_control.getUseBranchWidthsCb() != null ) {
835 atv_control.getUseBranchWidthsCb().setSelected( true );
839 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
840 if ( atv_control.getDisplayAsAlignedPhylogramRb() != null ) {
842 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
844 atv_control.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
847 atv_control.setDrawPhylogramEnabled( true );
850 atv_control.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
854 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
855 if ( atv_control.getWriteConfidenceCb() != null ) {
856 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
857 atv_control.setCheckbox( Configuration.write_confidence_values, true );
860 atv_control.setCheckbox( Configuration.write_confidence_values, false );
864 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
865 if ( atv_control.getShowEventsCb() != null ) {
866 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
867 atv_control.setCheckbox( Configuration.write_events, true );
870 atv_control.setCheckbox( Configuration.write_events, false );
877 final static void openWebsite( final String url ) throws IOException {
879 AptxUtil.launchWebBrowser( new URI( url ), AptxConstants.PRG_NAME );
881 catch ( final Exception e ) {
882 throw new IOException( e );
886 final static void outOfMemoryError( final OutOfMemoryError e ) {
887 System.err.println();
888 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
889 System.err.println();
891 System.err.println();
892 JOptionPane.showMessageDialog( null,
893 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
894 + "\n\nError: " + e.getLocalizedMessage(),
895 "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
896 JOptionPane.ERROR_MESSAGE );
900 final static void printAppletMessage( final String applet_name, final String message ) {
901 System.out.println( "[" + applet_name + "] > " + message );
904 final static void removeBranchColors( final Phylogeny phy ) {
905 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
906 it.next().getBranchData().setBranchColor( null );
910 final static void removeVisualStyles( final Phylogeny phy ) {
911 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
912 it.next().getNodeData().setNodeVisualData( null );
916 final static void unexpectedError( final Error e ) {
917 System.err.println();
918 e.printStackTrace( System.err );
919 System.err.println();
920 final StringBuffer sb = new StringBuffer();
921 for( final StackTraceElement s : e.getStackTrace() ) {
922 sb.append( s + "\n" );
925 .showMessageDialog( null,
926 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
927 + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
929 "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
930 JOptionPane.ERROR_MESSAGE );
934 final static void unexpectedException( final Exception e ) {
935 System.err.println();
936 e.printStackTrace( System.err );
937 System.err.println();
938 final StringBuffer sb = new StringBuffer();
939 for( final StackTraceElement s : e.getStackTrace() ) {
940 sb.append( s + "\n" );
942 JOptionPane.showMessageDialog( null,
943 "An unexpected exception has occured. \nPlease contact: "
944 + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
946 "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
947 JOptionPane.ERROR_MESSAGE );
950 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
953 final TreePanel tree_panel,
954 final ControlPanel ac,
955 final GraphicsExportType type,
956 final Options options ) throws IOException {
958 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
959 RenderingHints.VALUE_RENDER_QUALITY );
960 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
961 if ( options.isAntialiasPrint() ) {
962 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
963 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
966 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
967 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
969 final Phylogeny phylogeny = tree_panel.getPhylogeny();
970 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
973 Rectangle visible = null;
974 // if ( !options.isGraphicsExportUsingActualSize() ) {
975 // width = options.getPrintSizeX();
976 // height = options.getPrintSizeY();
978 /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
979 visible = tree_panel.getVisibleRect();
980 width = visible.width;
981 height = visible.height;
983 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
984 Graphics2D g2d = buffered_img.createGraphics();
985 g2d.setRenderingHints( rendering_hints );
988 if ( options.isGraphicsExportVisibleOnly() ) {
989 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
994 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
995 ImageIO.write( buffered_img, type.toString(), baos );
998 if ( !options.isGraphicsExportUsingActualSize() ) {
999 tree_panel.getMainPanel().getControlPanel().showWhole();
1001 String msg = baos.toString();
1002 if ( ( width > 0 ) && ( height > 0 ) ) {
1003 msg += " [size: " + width + ", " + height + "]";
1008 final static String writePhylogenyToGraphicsFile( final String file_name,
1011 final TreePanel tree_panel,
1012 final ControlPanel ac,
1013 final GraphicsExportType type,
1014 final Options options ) throws IOException {
1016 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1017 RenderingHints.VALUE_RENDER_QUALITY );
1018 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1019 if ( options.isAntialiasPrint() ) {
1020 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1021 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1024 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1025 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1027 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1028 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1031 final File file = new File( file_name );
1032 if ( file.isDirectory() ) {
1033 throw new IOException( "\"" + file_name + "\" is a directory" );
1035 Rectangle visible = null;
1036 // if ( !options.isGraphicsExportUsingActualSize() ) {
1037 // width = options.getPrintSizeX();
1038 // height = options.getPrintSizeY();
1040 /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1041 visible = tree_panel.getVisibleRect();
1042 width = visible.width;
1043 height = visible.height;
1045 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1046 Graphics2D g2d = buffered_img.createGraphics();
1047 g2d.setRenderingHints( rendering_hints );
1050 if ( options.isGraphicsExportVisibleOnly() ) {
1051 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1052 g2d.setClip( null );
1056 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1057 if ( type == GraphicsExportType.TIFF ) {
1058 writeToTiff( file, buffered_img );
1061 ImageIO.write( buffered_img, type.toString(), file );
1065 if ( !options.isGraphicsExportUsingActualSize() ) {
1066 tree_panel.getMainPanel().getControlPanel().showWhole();
1068 String msg = file.toString();
1069 if ( ( width > 0 ) && ( height > 0 ) ) {
1070 msg += " [size: " + width + ", " + height + "]";
1075 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1076 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1077 ImageWriter writer = null;
1078 ImageOutputStream ios = null;
1079 // Find an appropriate writer:
1080 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1081 if ( it.hasNext() ) {
1085 throw new IOException( "failed to get TIFF image writer" );
1088 ios = ImageIO.createImageOutputStream( file );
1089 writer.setOutput( ios );
1090 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1091 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1092 // see writeParam.getCompressionTypes() for available compression type
1094 image_write_param.setCompressionType( "PackBits" );
1095 final String t[] = image_write_param.getCompressionTypes();
1096 for( final String string : t ) {
1097 System.out.println( string );
1099 // Convert to an IIOImage:
1100 final IIOImage iio_image = new IIOImage( image, null, null );
1101 writer.write( null, iio_image, image_write_param );
1104 final static Map<String, Integer> getRankCounts(final Phylogeny tree) {
1105 final Map<String, Integer> present_ranks = new HashMap<String, Integer>();
1107 if ( ( tree != null ) && !tree.isEmpty() ) {
1108 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
1109 final PhylogenyNode n = it.next();
1110 if ( !n.isExternal() && n.getNodeData().isHasTaxonomy()
1111 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) && !n.isRoot() ) {
1112 final String rank = n.getNodeData().getTaxonomy().getRank().toLowerCase();
1113 if (present_ranks.containsKey( rank ) ) {
1114 present_ranks.put( rank, present_ranks.get( rank ) + 1 );
1117 present_ranks.put( rank, 1 );
1122 return present_ranks;