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.io.parsers.PhylogenyParser;
66 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
67 import org.forester.io.parsers.nhx.NHXParser;
68 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
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;
82 import org.forester.util.TaxonomyUtil;
84 public final class AptxUtil {
86 public static enum GraphicsExportType {
96 private final String _suffix;
98 private GraphicsExportType( final String suffix ) {
103 public String toString() {
107 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
108 .getAvailableFontFamilyNames();
110 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
113 final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
114 final String my_str = str.toUpperCase();
115 char first = my_str.charAt( 0 );
118 if ( my_str.length() > 1 ) {
120 second = my_str.charAt( 1 );
123 second = my_str.charAt( my_str.length() - 1 );
126 if ( my_str.length() > 2 ) {
127 if ( my_str.indexOf( " " ) > 0 ) {
128 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
131 third = my_str.charAt( 2 );
135 else if ( my_str.length() > 2 ) {
136 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
139 first = normalizeCharForRGB( first );
140 second = normalizeCharForRGB( second );
141 third = normalizeCharForRGB( third );
142 if ( ( first > 200 ) && ( second > 200 ) && ( third > 200 ) ) {
145 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
148 else if ( Math.abs( first - second ) < 40 && Math.abs( second - third ) < 40 ) {
151 return new Color( first, second, third );
154 public static MaskFormatter createMaskFormatter( final String s ) {
155 MaskFormatter formatter = null;
157 formatter = new MaskFormatter( s );
159 catch ( final ParseException e ) {
160 throw new IllegalArgumentException( e );
165 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
166 final PhylogenyNodeIterator it = phy.iteratorPostorder();
167 while ( it.hasNext() ) {
168 if ( it.next().getNodeData().isHasEvent() ) {
176 * Returns true if at least one branch has a length larger than zero.
181 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
182 final PhylogenyNodeIterator it = phy.iteratorPostorder();
183 while ( it.hasNext() ) {
184 if ( it.next().getDistanceToParent() > 0.0 ) {
191 final static public boolean isHasAtLeast50PercentBranchLengthLargerThanZero( final Phylogeny phy ) {
192 final PhylogenyNodeIterator it = phy.iteratorPostorder();
195 while ( it.hasNext() ) {
196 if ( it.next().getDistanceToParent() > 0.0 ) {
204 return (((( double ) positive) / total) >= 0.5 );
207 final static public boolean isHasNoBranchLengthSmallerThanZero( final Phylogeny phy ) {
208 final PhylogenyNodeIterator it = phy.iteratorPostorder();
209 while ( it.hasNext() ) {
210 final PhylogenyNode n = it.next();
211 if ( n.getDistanceToParent() < 0.0 && !n.isRoot() ) {
218 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
219 final PhylogenyNodeIterator it = phy.iteratorPostorder();
220 while ( it.hasNext() ) {
221 final PhylogenyNode n = it.next();
222 if ( n.getBranchData().isHasConfidences() ) {
223 final List<Confidence> c = n.getBranchData().getConfidences();
224 for( final Confidence confidence : c ) {
225 if ( confidence.getStandardDeviation() > 0 ) {
234 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
235 final PhylogenyNodeIterator it = phy.iteratorPostorder();
236 while ( it.hasNext() ) {
237 if ( it.next().getBranchData().isHasConfidences() ) {
244 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
245 final PhylogenyNodeIterator it = phy.iteratorPostorder();
246 while ( it.hasNext() ) {
247 final PhylogenyNode n = it.next();
248 if ( n.getNodeData().isHasTaxonomy()
249 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
256 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
257 final PhylogenyNodeIterator it = phy.iteratorPostorder();
258 while ( it.hasNext() ) {
259 final PhylogenyNode n = it.next();
260 if ( n.getNodeData().isHasSequence()
261 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
268 final public static void launchWebBrowser( final URI uri, final String frame_name ) throws IOException {
269 // This requires Java 1.6:
270 // =======================
271 // boolean no_desktop = false;
273 // if ( Desktop.isDesktopSupported() ) {
274 // System.out.println( "desktop supported" );
275 // final Desktop dt = Desktop.getDesktop();
279 // no_desktop = true;
282 // catch ( final Exception ex ) {
283 // ex.printStackTrace();
284 // no_desktop = true;
286 // catch ( final Error er ) {
287 // er.printStackTrace();
288 // no_desktop = true;
290 // if ( no_desktop ) {
291 // System.out.println( "desktop not supported" );
293 openUrlInWebBrowser( uri.toString() );
295 catch ( final Exception e ) {
296 throw new IOException( e );
301 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
302 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
303 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
304 for( final PhylogenyNode n : descs ) {
305 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
306 tax_set.add( n.getNodeData().getTaxonomy() );
312 public final static void printWarningMessage( final String name, final String message ) {
313 System.out.println( "[" + name + "] > " + message );
316 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
317 final boolean phyloxml_validate_against_xsd,
318 final boolean replace_underscores,
319 final boolean internal_numbers_are_confidences,
320 final TAXONOMY_EXTRACTION taxonomy_extraction,
321 final boolean midpoint_reroot )
322 throws FileNotFoundException, IOException {
323 final PhylogenyParser parser;
324 boolean nhx_or_nexus = false;
325 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
326 parser = new TolParser();
329 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
330 if ( parser instanceof NHXParser ) {
332 final NHXParser nhx = ( NHXParser ) parser;
333 nhx.setReplaceUnderscores( replace_underscores );
334 nhx.setIgnoreQuotes( false );
335 nhx.setTaxonomyExtraction( taxonomy_extraction );
337 else if ( parser instanceof NexusPhylogeniesParser ) {
339 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
340 nex.setReplaceUnderscores( replace_underscores );
341 nex.setIgnoreQuotes( false );
344 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
345 Phylogeny[] phys = null;
347 phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
349 catch ( final KeyManagementException e ) {
350 throw new IOException( e.getMessage() );
352 catch ( final NoSuchAlgorithmException e ) {
353 throw new IOException( e.getMessage() );
355 if ( phys != null ) {
356 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
357 for( final Phylogeny phy : phys ) {
358 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
361 if ( midpoint_reroot ) {
362 for( final Phylogeny phy : phys ) {
363 PhylogenyMethods.midpointRoot( phy );
364 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
371 final public static void showErrorMessage( final Component parent, final String error_msg ) {
372 printAppletMessage( AptxConstants.PRG_NAME, error_msg );
373 JOptionPane.showMessageDialog( parent,
375 "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "] Error",
376 JOptionPane.ERROR_MESSAGE );
379 public static void writePhylogenyToGraphicsFile( final File intree,
383 final GraphicsExportType type,
384 final Configuration config )
386 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
387 Phylogeny[] phys = null;
388 phys = PhylogenyMethods.readPhylogenies( parser, intree );
389 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
392 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
396 final GraphicsExportType type,
397 final Configuration config )
399 final Phylogeny[] phys = new Phylogeny[ 1 ];
401 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
402 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile,
405 mf.getMainPanel().getCurrentTreePanel(),
406 mf.getMainPanel().getControlPanel(),
412 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
415 final TreePanel tree_panel,
416 final ControlPanel ac,
417 final GraphicsExportType type,
418 final Options options )
420 tree_panel.calcParametersForPainting( width, height );
421 tree_panel.resetPreferredSize();
422 tree_panel.repaint();
423 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
424 RenderingHints.VALUE_RENDER_QUALITY );
425 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
426 if ( options.isAntialiasPrint() ) {
427 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
428 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
431 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
432 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
434 final Phylogeny phylogeny = tree_panel.getPhylogeny();
435 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
438 if ( outfile.isDirectory() ) {
439 throw new IOException( "\"" + outfile + "\" is a directory" );
441 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
442 final Graphics2D g2d = buffered_img.createGraphics();
443 g2d.setRenderingHints( rendering_hints );
444 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
445 if ( type == GraphicsExportType.TIFF ) {
446 writeToTiff( outfile, buffered_img );
449 ImageIO.write( buffered_img, type.toString(), outfile );
454 final private static char normalizeCharForRGB( char c ) {
457 c = c > 255 ? 255 : c;
462 final private static void openUrlInWebBrowser( final String url )
463 throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException,
464 IllegalArgumentException, IllegalAccessException, InvocationTargetException, InterruptedException {
465 final String os = System.getProperty( "os.name" );
466 final Runtime runtime = Runtime.getRuntime();
467 if ( os.toLowerCase().startsWith( "win" ) ) {
468 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
470 else if ( ForesterUtil.isMac() ) {
471 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
472 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
473 open_url.invoke( null, new Object[] { url } );
476 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
477 String browser = null;
478 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
479 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
480 browser = browsers[ i ];
483 if ( browser == null ) {
484 throw new IOException( "could not find a web browser to open [" + url + "] in" );
487 runtime.exec( new String[] { browser, url } );
492 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
493 final String default_name,
494 final String full_path,
495 final Configuration configuration,
496 final MainPanel main_panel ) {
497 if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
498 JOptionPane.showMessageDialog( main_panel,
499 "Attempt to load " + phys.length
500 + " phylogenies,\ngoing to load only the first "
501 + AptxConstants.MAX_TREES_TO_LOAD,
502 AptxConstants.PRG_NAME + " more than " + AptxConstants.MAX_TREES_TO_LOAD
504 JOptionPane.WARNING_MESSAGE );
507 for( final Phylogeny phy : phys ) {
508 if ( !phy.isEmpty() ) {
509 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
511 String my_name_for_file = "";
512 if ( phys.length > 1 ) {
513 if ( !ForesterUtil.isEmpty( default_name ) ) {
514 my_name = new String( default_name );
516 if ( !ForesterUtil.isEmpty( full_path ) ) {
517 my_name_for_file = new String( full_path );
519 else if ( !ForesterUtil.isEmpty( default_name ) ) {
520 my_name_for_file = new String( default_name );
523 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
524 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
525 my_name_for_file.length() );
526 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
528 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
529 my_name_for_file += "_";
531 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
532 my_name_for_file += phy.getName().replaceAll( " ", "_" );
534 else if ( phy.getIdentifier() != null ) {
535 final StringBuffer sb = new StringBuffer();
536 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
537 sb.append( phy.getIdentifier().getProvider() );
540 sb.append( phy.getIdentifier().getValue() );
541 my_name_for_file += sb;
544 my_name_for_file += i;
546 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
547 && ( phy.getIdentifier() == null ) ) {
548 my_name = my_name + " [" + i + "]";
550 if ( !ForesterUtil.isEmpty( suffix ) ) {
551 my_name_for_file += suffix;
555 if ( !ForesterUtil.isEmpty( default_name ) ) {
556 my_name = new String( default_name );
558 my_name_for_file = "";
559 if ( !ForesterUtil.isEmpty( full_path ) ) {
560 my_name_for_file = new String( full_path );
562 else if ( !ForesterUtil.isEmpty( default_name ) ) {
563 my_name_for_file = new String( default_name );
565 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
566 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
567 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
569 else if ( phy.getIdentifier() != null ) {
570 final StringBuffer sb = new StringBuffer();
571 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
572 sb.append( phy.getIdentifier().getProvider() );
575 sb.append( phy.getIdentifier().getValue() );
576 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
580 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
581 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
582 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
589 final static void addPhylogenyToPanel( final Phylogeny[] phys,
590 final Configuration configuration,
591 final MainPanel main_panel ) {
592 final Phylogeny phy = phys[ 0 ];
593 main_panel.addPhylogenyInPanel( phy, configuration );
594 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
597 // Returns true if the specified format name can be written
598 final static boolean canWriteFormat( final String format_name ) {
599 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
600 return iter.hasNext();
603 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
604 final StringBuilder desc = new StringBuilder();
605 if ( ( phy != null ) && !phy.isEmpty() ) {
607 if ( treefile != null ) {
609 f = treefile.getCanonicalPath();
611 catch ( final IOException e ) {
612 //Not important, ignore.
614 if ( !ForesterUtil.isEmpty( f ) ) {
615 desc.append( "Path: " );
620 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
621 desc.append( "Name: " );
622 desc.append( phy.getName() );
625 if ( phy.getIdentifier() != null ) {
626 desc.append( "Id: " );
627 desc.append( phy.getIdentifier().toString() );
630 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
631 desc.append( "Description: " );
632 desc.append( phy.getDescription() );
635 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
636 desc.append( "Distance Unit: " );
637 desc.append( phy.getDistanceUnit() );
640 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
641 desc.append( "Type: " );
642 desc.append( phy.getType() );
645 desc.append( "Rooted: " );
646 desc.append( phy.isRooted() );
648 desc.append( "Rerootable: " );
649 desc.append( phy.isRerootable() );
651 desc.append( "Nodes: " );
652 desc.append( phy.getNodeCount() );
654 desc.append( "External nodes: " );
655 desc.append( phy.getNumberOfExternalNodes() );
657 desc.append( "Internal nodes: " );
658 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
660 desc.append( "Internal nodes with polytomies: " );
661 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
663 desc.append( "Branches: " );
664 desc.append( phy.getNumberOfBranches() );
666 desc.append( "Depth: " );
667 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
669 desc.append( "Maximum distance to root: " );
670 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
672 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
673 if ( taxs != null ) {
674 desc.append( "Distinct external taxonomies: " );
675 desc.append( taxs.size() );
677 for( final Taxonomy t : taxs ) {
678 System.out.println( t.toString() );
681 final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
682 if ( bs.getN() > 3 ) {
684 desc.append( "Branch-length statistics: " );
686 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
688 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
690 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
691 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
693 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
695 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
697 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
699 final AsciiHistogram histo = new AsciiHistogram( bs );
700 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
703 final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
704 if ( ds.getN() > 2 ) {
706 desc.append( "Descendants per node statistics: " );
708 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
710 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
711 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
713 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
715 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
718 List<DescriptiveStatistics> css = null;
720 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
722 catch ( final IllegalArgumentException e ) {
723 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
725 if ( ( css != null ) && ( css.size() > 0 ) ) {
727 for( int i = 0; i < css.size(); ++i ) {
728 final DescriptiveStatistics cs = css.get( i );
729 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
730 if ( css.size() > 1 ) {
731 desc.append( "Support statistics " + ( i + 1 ) + ": " );
734 desc.append( "Support statistics: " );
736 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
738 desc.append( " Type: " + cs.getDescription() );
741 desc.append( " Branches with support: " + cs.getN() );
743 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
745 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
746 if ( cs.getN() > 2 ) {
747 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
750 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
752 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
758 return desc.toString();
766 * to message to be printed
768 final static void dieWithSystemError( final String message ) {
769 System.out.println();
770 System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
771 System.out.println( "Please contact the authors." );
772 System.out.println( AptxConstants.PRG_NAME + " needs to close." );
773 System.out.println();
777 final static String[] getAllPossibleRanks() {
778 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
780 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
781 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
782 str_array[ i++ ] = e;
788 final static String[] getAllPossibleRanks( final Map<String, Integer> present_ranks ) {
789 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
791 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
792 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
793 if ( present_ranks != null && present_ranks.containsKey( e ) ) {
794 str_array[ i++ ] = e + " (" + present_ranks.get( e ) + ")";
797 str_array[ i++ ] = e;
804 final static String[] getAllRanks( final Phylogeny tree ) {
805 final SortedSet<String> ranks = new TreeSet<String>();
806 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
807 final PhylogenyNode n = it.next();
808 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
809 ranks.add( n.getNodeData().getTaxonomy().getRank() );
812 return ForesterUtil.stringSetToArray( ranks );
815 final static String[] getAvailableFontFamiliesSorted() {
816 return AVAILABLE_FONT_FAMILIES_SORTED;
819 final static boolean isUsOrCanada() {
821 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
825 catch ( final Exception e ) {
831 final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t, final ControlPanel cp ) {
832 if ( ( t != null ) && !t.isEmpty() ) {
833 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
835 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
836 cp.setDrawPhylogramEnabled( false );
839 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
841 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
843 if ( cp.getDisplayAsUnalignedPhylogramRb() != null ) {
844 cp.setDrawPhylogramEnabled( true );
850 public final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
851 final ControlPanel cp,
852 final Configuration configuration ) {
853 if ( ( t != null ) && !t.isEmpty() ) {
854 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
856 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
857 cp.setDrawPhylogramEnabled( false );
859 if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
860 && cp.getUseVisualStylesCb() != null ) {
861 cp.getUseVisualStylesCb().setSelected( true );
863 if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
864 && t.getFirstExternalNode().getBranchData().getBranchWidth()
865 .getValue() != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
866 && cp.getUseBranchWidthsCb() != null ) {
867 cp.getUseBranchWidthsCb().setSelected( true );
869 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
870 if ( cp.getDisplayAsAlignedPhylogramRb() != null ) {
872 final boolean has_mostly_bl = AptxUtil.isHasAtLeast50PercentBranchLengthLargerThanZero( t );
873 if ( has_mostly_bl ) {
874 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
876 cp.setDrawPhylogramEnabled( true );
879 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
883 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
884 if ( cp.getWriteConfidenceCb() != null ) {
885 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
886 cp.setCheckbox( Configuration.write_confidence_values, true );
889 cp.setCheckbox( Configuration.write_confidence_values, false );
893 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
894 if ( cp.getShowEventsCb() != null ) {
895 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
896 cp.setCheckbox( Configuration.write_events, true );
899 cp.setCheckbox( Configuration.write_events, false );
906 final static void openWebsite( final String url ) throws IOException {
908 AptxUtil.launchWebBrowser( new URI( url ), AptxConstants.PRG_NAME );
910 catch ( final Exception e ) {
911 throw new IOException( e );
915 final static void outOfMemoryError( final OutOfMemoryError e ) {
916 System.err.println();
917 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
918 System.err.println();
920 System.err.println();
921 JOptionPane.showMessageDialog( null,
922 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
923 + "\n\nError: " + e.getLocalizedMessage(),
924 "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
926 JOptionPane.ERROR_MESSAGE );
930 final static void printAppletMessage( final String applet_name, final String message ) {
931 System.out.println( "[" + applet_name + "] > " + message );
934 final static void removeBranchColors( final Phylogeny phy ) {
935 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
936 it.next().getBranchData().setBranchColor( null );
940 final static void removeVisualStyles( final Phylogeny phy ) {
941 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
942 it.next().getNodeData().setNodeVisualData( null );
946 final static void unexpectedError( final Error e ) {
947 System.err.println();
948 e.printStackTrace( System.err );
949 System.err.println();
950 final StringBuffer sb = new StringBuffer();
951 for( final StackTraceElement s : e.getStackTrace() ) {
952 sb.append( s + "\n" );
954 JOptionPane.showMessageDialog( null,
955 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
956 + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage()
958 "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " "
959 + AptxConstants.VERSION + "]",
960 JOptionPane.ERROR_MESSAGE );
964 final static void unexpectedException( final Exception e ) {
965 System.err.println();
966 e.printStackTrace( System.err );
967 System.err.println();
968 final StringBuffer sb = new StringBuffer();
969 for( final StackTraceElement s : e.getStackTrace() ) {
970 sb.append( s + "\n" );
972 JOptionPane.showMessageDialog( null,
973 "An unexpected exception has occured. \nPlease contact: "
974 + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
976 "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
977 JOptionPane.ERROR_MESSAGE );
980 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
983 final TreePanel tree_panel,
984 final ControlPanel ac,
985 final GraphicsExportType type,
986 final Options options )
988 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
989 RenderingHints.VALUE_RENDER_QUALITY );
990 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
991 if ( options.isAntialiasPrint() ) {
992 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
993 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
996 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
997 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
999 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1000 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1003 Rectangle visible = null;
1004 // if ( !options.isGraphicsExportUsingActualSize() ) {
1005 // width = options.getPrintSizeX();
1006 // height = options.getPrintSizeY();
1008 /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1009 visible = tree_panel.getVisibleRect();
1010 width = visible.width;
1011 height = visible.height;
1013 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1014 Graphics2D g2d = buffered_img.createGraphics();
1015 g2d.setRenderingHints( rendering_hints );
1018 if ( options.isGraphicsExportVisibleOnly() ) {
1019 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1020 g2d.setClip( null );
1024 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1025 ImageIO.write( buffered_img, type.toString(), baos );
1028 if ( !options.isGraphicsExportUsingActualSize() ) {
1029 tree_panel.getMainPanel().getControlPanel().showWhole();
1031 String msg = baos.toString();
1032 if ( ( width > 0 ) && ( height > 0 ) ) {
1033 msg += " [size: " + width + ", " + height + "]";
1038 final static String writePhylogenyToGraphicsFile( final String file_name,
1041 final TreePanel tree_panel,
1042 final ControlPanel ac,
1043 final GraphicsExportType type,
1044 final Options options )
1045 throws IOException {
1046 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1047 RenderingHints.VALUE_RENDER_QUALITY );
1048 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1049 if ( options.isAntialiasPrint() ) {
1050 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1051 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1054 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1055 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1057 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1058 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1061 final File file = new File( file_name );
1062 if ( file.isDirectory() ) {
1063 throw new IOException( "\"" + file_name + "\" is a directory" );
1065 Rectangle visible = null;
1066 // if ( !options.isGraphicsExportUsingActualSize() ) {
1067 // width = options.getPrintSizeX();
1068 // height = options.getPrintSizeY();
1070 /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1071 visible = tree_panel.getVisibleRect();
1072 width = visible.width;
1073 height = visible.height;
1075 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1076 Graphics2D g2d = buffered_img.createGraphics();
1077 g2d.setRenderingHints( rendering_hints );
1080 if ( options.isGraphicsExportVisibleOnly() ) {
1081 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1082 g2d.setClip( null );
1086 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1087 if ( type == GraphicsExportType.TIFF ) {
1088 writeToTiff( file, buffered_img );
1090 else if (type == GraphicsExportType.EPS) {
1094 ImageIO.write( buffered_img, type.toString(), file );
1098 if ( !options.isGraphicsExportUsingActualSize() ) {
1099 tree_panel.getMainPanel().getControlPanel().showWhole();
1101 String msg = file.toString();
1102 if ( ( width > 0 ) && ( height > 0 ) ) {
1103 msg += " [size: " + width + ", " + height + "]";
1107 final static void writeToEps() {
1111 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1112 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1113 ImageWriter writer = null;
1114 ImageOutputStream ios = null;
1115 // Find an appropriate writer:
1116 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1117 if ( it.hasNext() ) {
1121 throw new IOException( "failed to get TIFF image writer" );
1124 ios = ImageIO.createImageOutputStream( file );
1125 writer.setOutput( ios );
1126 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1127 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1128 // see writeParam.getCompressionTypes() for available compression type
1130 image_write_param.setCompressionType( "PackBits" );
1131 final String t[] = image_write_param.getCompressionTypes();
1132 for( final String string : t ) {
1133 System.out.println( string );
1135 // Convert to an IIOImage:
1136 final IIOImage iio_image = new IIOImage( image, null, null );
1137 writer.write( null, iio_image, image_write_param );
1140 final static Map<String, Integer> getRankCounts( final Phylogeny tree ) {
1141 final Map<String, Integer> present_ranks = new HashMap<String, Integer>();
1142 if ( ( tree != null ) && !tree.isEmpty() ) {
1143 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
1144 final PhylogenyNode n = it.next();
1145 if ( !n.isExternal() && n.getNodeData().isHasTaxonomy()
1146 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) && !n.isRoot() ) {
1147 final String rank = n.getNodeData().getTaxonomy().getRank().toLowerCase();
1148 if ( present_ranks.containsKey( rank ) ) {
1149 present_ranks.put( rank, present_ranks.get( rank ) + 1 );
1152 present_ranks.put( rank, 1 );
1157 return present_ranks;