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 isHasNoBranchLengthSmallerThanZero( final Phylogeny phy ) {
181 final PhylogenyNodeIterator it = phy.iteratorPostorder();
182 while ( it.hasNext() ) {
183 final PhylogenyNode n = it.next();
184 if ( n.getDistanceToParent() < 0.0 && !n.isRoot() ) {
191 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
192 final PhylogenyNodeIterator it = phy.iteratorPostorder();
193 while ( it.hasNext() ) {
194 final PhylogenyNode n = it.next();
195 if ( n.getBranchData().isHasConfidences() ) {
196 final List<Confidence> c = n.getBranchData().getConfidences();
197 for( final Confidence confidence : c ) {
198 if ( confidence.getStandardDeviation() > 0 ) {
207 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
208 final PhylogenyNodeIterator it = phy.iteratorPostorder();
209 while ( it.hasNext() ) {
210 if ( it.next().getBranchData().isHasConfidences() ) {
217 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
218 final PhylogenyNodeIterator it = phy.iteratorPostorder();
219 while ( it.hasNext() ) {
220 final PhylogenyNode n = it.next();
221 if ( n.getNodeData().isHasTaxonomy()
222 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
229 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
230 final PhylogenyNodeIterator it = phy.iteratorPostorder();
231 while ( it.hasNext() ) {
232 final PhylogenyNode n = it.next();
233 if ( n.getNodeData().isHasSequence()
234 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
241 final public static void launchWebBrowser( final URI uri,
242 final boolean is_applet,
243 final JApplet applet,
244 final String frame_name ) throws IOException {
246 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
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[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
747 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
748 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
749 str_array[ i++ ] = e;
755 final static String[] getAllRanks( final Phylogeny tree ) {
756 final SortedSet<String> ranks = new TreeSet<String>();
757 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
758 final PhylogenyNode n = it.next();
759 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
760 ranks.add( n.getNodeData().getTaxonomy().getRank() );
763 return ForesterUtil.stringSetToArray( ranks );
766 final static String[] getAvailableFontFamiliesSorted() {
767 return AVAILABLE_FONT_FAMILIES_SORTED;
770 final static boolean isUsOrCanada() {
772 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
776 catch ( final Exception e ) {
781 final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t,
782 final ControlPanel cp ) {
783 if ( ( t != null ) && !t.isEmpty() ) {
784 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
787 cp.setDrawPhylogram( false );
788 cp.setDrawPhylogramEnabled( false );
791 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
792 cp.setDrawPhylogram( has_all_bl );
793 if ( cp.getDisplayAsPhylogramCb() != null ) {
794 cp.setDrawPhylogramEnabled( true );
799 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
800 final ControlPanel atv_control,
801 final Configuration configuration ) {
802 if ( ( t != null ) && !t.isEmpty() ) {
803 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
805 atv_control.setDrawPhylogram( false );
806 atv_control.setDrawPhylogramEnabled( false );
808 if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
809 && atv_control.getUseVisualStylesCb() != null ) {
810 atv_control.getUseVisualStylesCb().setSelected( true );
812 if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
813 && t.getFirstExternalNode().getBranchData().getBranchWidth().getValue()
814 != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
815 && atv_control.getUseBranchWidthsCb() != null ) {
816 atv_control.getUseBranchWidthsCb().setSelected( true );
820 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
821 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
823 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
825 atv_control.setDrawPhylogram( has_all_bl );
826 atv_control.setDrawPhylogramEnabled( true );
829 atv_control.setDrawPhylogram( false );
833 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
834 if ( atv_control.getWriteConfidenceCb() != null ) {
835 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
836 atv_control.setCheckbox( Configuration.write_confidence_values, true );
839 atv_control.setCheckbox( Configuration.write_confidence_values, false );
843 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
844 if ( atv_control.getShowEventsCb() != null ) {
845 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
846 atv_control.setCheckbox( Configuration.write_events, true );
849 atv_control.setCheckbox( Configuration.write_events, false );
856 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
858 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, AptxConstants.PRG_NAME );
860 catch ( final Exception e ) {
861 throw new IOException( e );
865 final static void outOfMemoryError( final OutOfMemoryError e ) {
866 System.err.println();
867 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
868 System.err.println();
870 System.err.println();
871 JOptionPane.showMessageDialog( null,
872 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
873 + "\n\nError: " + e.getLocalizedMessage(),
874 "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
875 JOptionPane.ERROR_MESSAGE );
879 final static void printAppletMessage( final String applet_name, final String message ) {
880 System.out.println( "[" + applet_name + "] > " + message );
883 final static void removeBranchColors( final Phylogeny phy ) {
884 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
885 it.next().getBranchData().setBranchColor( null );
889 final static void removeVisualStyles( final Phylogeny phy ) {
890 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
891 it.next().getNodeData().setNodeVisualData( null );
895 final static void unexpectedError( final Error e ) {
896 System.err.println();
897 e.printStackTrace( System.err );
898 System.err.println();
899 final StringBuffer sb = new StringBuffer();
900 for( final StackTraceElement s : e.getStackTrace() ) {
901 sb.append( s + "\n" );
904 .showMessageDialog( null,
905 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
906 + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
908 "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
909 JOptionPane.ERROR_MESSAGE );
913 final static void unexpectedException( final Exception e ) {
914 System.err.println();
915 e.printStackTrace( System.err );
916 System.err.println();
917 final StringBuffer sb = new StringBuffer();
918 for( final StackTraceElement s : e.getStackTrace() ) {
919 sb.append( s + "\n" );
921 JOptionPane.showMessageDialog( null,
922 "An unexpected exception has occured. \nPlease contact: "
923 + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
925 "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
926 JOptionPane.ERROR_MESSAGE );
929 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
932 final TreePanel tree_panel,
933 final ControlPanel ac,
934 final GraphicsExportType type,
935 final Options options ) throws IOException {
937 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
938 RenderingHints.VALUE_RENDER_QUALITY );
939 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
940 if ( options.isAntialiasPrint() ) {
941 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
942 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
945 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
946 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
948 final Phylogeny phylogeny = tree_panel.getPhylogeny();
949 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
952 Rectangle visible = null;
953 // if ( !options.isGraphicsExportUsingActualSize() ) {
954 // width = options.getPrintSizeX();
955 // height = options.getPrintSizeY();
957 /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
958 visible = tree_panel.getVisibleRect();
959 width = visible.width;
960 height = visible.height;
962 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
963 Graphics2D g2d = buffered_img.createGraphics();
964 g2d.setRenderingHints( rendering_hints );
967 if ( options.isGraphicsExportVisibleOnly() ) {
968 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
973 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
974 ImageIO.write( buffered_img, type.toString(), baos );
977 if ( !options.isGraphicsExportUsingActualSize() ) {
978 tree_panel.getMainPanel().getControlPanel().showWhole();
980 String msg = baos.toString();
981 if ( ( width > 0 ) && ( height > 0 ) ) {
982 msg += " [size: " + width + ", " + height + "]";
987 final static String writePhylogenyToGraphicsFile( final String file_name,
990 final TreePanel tree_panel,
991 final ControlPanel ac,
992 final GraphicsExportType type,
993 final Options options ) throws IOException {
995 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
996 RenderingHints.VALUE_RENDER_QUALITY );
997 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
998 if ( options.isAntialiasPrint() ) {
999 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1000 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1003 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1004 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1006 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1007 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1010 final File file = new File( file_name );
1011 if ( file.isDirectory() ) {
1012 throw new IOException( "\"" + file_name + "\" is a directory" );
1014 Rectangle visible = null;
1015 // if ( !options.isGraphicsExportUsingActualSize() ) {
1016 // width = options.getPrintSizeX();
1017 // height = options.getPrintSizeY();
1019 /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1020 visible = tree_panel.getVisibleRect();
1021 width = visible.width;
1022 height = visible.height;
1024 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1025 Graphics2D g2d = buffered_img.createGraphics();
1026 g2d.setRenderingHints( rendering_hints );
1029 if ( options.isGraphicsExportVisibleOnly() ) {
1030 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1031 g2d.setClip( null );
1035 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1036 if ( type == GraphicsExportType.TIFF ) {
1037 writeToTiff( file, buffered_img );
1040 ImageIO.write( buffered_img, type.toString(), file );
1044 if ( !options.isGraphicsExportUsingActualSize() ) {
1045 tree_panel.getMainPanel().getControlPanel().showWhole();
1047 String msg = file.toString();
1048 if ( ( width > 0 ) && ( height > 0 ) ) {
1049 msg += " [size: " + width + ", " + height + "]";
1054 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1055 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1056 ImageWriter writer = null;
1057 ImageOutputStream ios = null;
1058 // Find an appropriate writer:
1059 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1060 if ( it.hasNext() ) {
1064 throw new IOException( "failed to get TIFF image writer" );
1067 ios = ImageIO.createImageOutputStream( file );
1068 writer.setOutput( ios );
1069 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1070 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1071 // see writeParam.getCompressionTypes() for available compression type
1073 image_write_param.setCompressionType( "PackBits" );
1074 final String t[] = image_write_param.getCompressionTypes();
1075 for( final String string : t ) {
1076 System.out.println( string );
1078 // Convert to an IIOImage:
1079 final IIOImage iio_image = new IIOImage( image, null, null );
1080 writer.write( null, iio_image, image_write_param );