2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
26 package org.forester.archaeopteryx;
28 import java.awt.Color;
29 import java.awt.Component;
30 import java.awt.Graphics2D;
31 import java.awt.GraphicsEnvironment;
32 import java.awt.Rectangle;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.io.ByteArrayOutputStream;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.lang.reflect.InvocationTargetException;
41 import java.lang.reflect.Method;
44 import java.net.URLConnection;
45 import java.text.ParseException;
46 import java.util.Arrays;
47 import java.util.HashSet;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Locale;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
55 import javax.imageio.IIOImage;
56 import javax.imageio.ImageIO;
57 import javax.imageio.ImageWriteParam;
58 import javax.imageio.ImageWriter;
59 import javax.imageio.stream.ImageOutputStream;
60 import javax.swing.JApplet;
61 import javax.swing.JOptionPane;
62 import javax.swing.text.MaskFormatter;
64 import org.forester.io.parsers.PhylogenyParser;
65 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
66 import org.forester.io.parsers.nhx.NHXParser;
67 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
68 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
69 import org.forester.io.parsers.tol.TolParser;
70 import org.forester.io.parsers.util.ParserUtils;
71 import org.forester.phylogeny.Phylogeny;
72 import org.forester.phylogeny.PhylogenyMethods;
73 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
74 import org.forester.phylogeny.PhylogenyNode;
75 import org.forester.phylogeny.data.Confidence;
76 import org.forester.phylogeny.data.Taxonomy;
77 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
78 import org.forester.phylogeny.factories.PhylogenyFactory;
79 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
80 import org.forester.util.AsciiHistogram;
81 import org.forester.util.DescriptiveStatistics;
82 import org.forester.util.ForesterUtil;
84 public final class AptxUtil {
86 public static enum GraphicsExportType {
87 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
89 private final String _suffix;
91 private GraphicsExportType( final String suffix ) {
96 public String toString() {
100 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
101 .getAvailableFontFamilyNames();
103 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
106 final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
107 final String my_str = str.toUpperCase();
108 char first = my_str.charAt( 0 );
111 if ( my_str.length() > 1 ) {
113 second = my_str.charAt( 1 );
116 second = my_str.charAt( my_str.length() - 1 );
119 if ( my_str.length() > 2 ) {
120 if ( my_str.indexOf( " " ) > 0 ) {
121 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
124 third = my_str.charAt( 2 );
128 else if ( my_str.length() > 2 ) {
129 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
132 first = normalizeCharForRGB( first );
133 second = normalizeCharForRGB( second );
134 third = normalizeCharForRGB( third );
135 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
138 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
141 return new Color( first, second, third );
144 public static MaskFormatter createMaskFormatter( final String s ) {
145 MaskFormatter formatter = null;
147 formatter = new MaskFormatter( s );
149 catch ( final ParseException e ) {
150 throw new IllegalArgumentException( e );
155 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
156 final PhylogenyNodeIterator it = phy.iteratorPostorder();
157 while ( it.hasNext() ) {
158 if ( it.next().getNodeData().isHasEvent() ) {
166 * Returns true if at least one branch has a length larger than zero.
171 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
172 final PhylogenyNodeIterator it = phy.iteratorPostorder();
173 while ( it.hasNext() ) {
174 if ( it.next().getDistanceToParent() > 0.0 ) {
181 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
182 final PhylogenyNodeIterator it = phy.iteratorPostorder();
183 while ( it.hasNext() ) {
184 final PhylogenyNode n = it.next();
185 if ( n.getBranchData().isHasConfidences() ) {
186 final List<Confidence> c = n.getBranchData().getConfidences();
187 for( final Confidence confidence : c ) {
188 if ( confidence.getStandardDeviation() > 0 ) {
197 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
198 final PhylogenyNodeIterator it = phy.iteratorPostorder();
199 while ( it.hasNext() ) {
200 if ( it.next().getBranchData().isHasConfidences() ) {
207 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
208 final PhylogenyNodeIterator it = phy.iteratorPostorder();
209 while ( it.hasNext() ) {
210 final PhylogenyNode n = it.next();
211 if ( n.getNodeData().isHasTaxonomy()
212 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
219 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
220 final PhylogenyNodeIterator it = phy.iteratorPostorder();
221 while ( it.hasNext() ) {
222 final PhylogenyNode n = it.next();
223 if ( n.getNodeData().isHasSequence()
224 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
231 final public static void launchWebBrowser( final URI uri,
232 final boolean is_applet,
233 final JApplet applet,
234 final String frame_name ) throws IOException {
236 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
239 // This requires Java 1.6:
240 // =======================
241 // boolean no_desktop = false;
243 // if ( Desktop.isDesktopSupported() ) {
244 // System.out.println( "desktop supported" );
245 // final Desktop dt = Desktop.getDesktop();
249 // no_desktop = true;
252 // catch ( final Exception ex ) {
253 // ex.printStackTrace();
254 // no_desktop = true;
256 // catch ( final Error er ) {
257 // er.printStackTrace();
258 // no_desktop = true;
260 // if ( no_desktop ) {
261 // System.out.println( "desktop not supported" );
263 openUrlInWebBrowser( uri.toString() );
265 catch ( final Exception e ) {
266 throw new IOException( e );
272 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
273 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
274 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
275 for( final PhylogenyNode n : descs ) {
276 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
277 tax_set.add( n.getNodeData().getTaxonomy() );
283 public final static void printWarningMessage( final String name, final String message ) {
284 System.out.println( "[" + name + "] > " + message );
287 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
288 final boolean phyloxml_validate_against_xsd,
289 final boolean replace_underscores,
290 final boolean internal_numbers_are_confidences,
291 final TAXONOMY_EXTRACTION taxonomy_extraction,
292 final boolean midpoint_reroot )
293 throws FileNotFoundException, IOException {
294 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
295 final PhylogenyParser parser;
296 boolean nhx_or_nexus = false;
297 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
298 parser = new TolParser();
301 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
302 if ( parser instanceof NHXParser ) {
304 final NHXParser nhx = ( NHXParser ) parser;
305 nhx.setReplaceUnderscores( replace_underscores );
306 nhx.setIgnoreQuotes( false );
307 nhx.setTaxonomyExtraction( taxonomy_extraction );
309 else if ( parser instanceof NexusPhylogeniesParser ) {
311 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
312 nex.setReplaceUnderscores( replace_underscores );
313 nex.setIgnoreQuotes( false );
316 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
317 final URLConnection url_connection = url.openConnection();
318 url_connection.setDefaultUseCaches( false );
319 final InputStream i = url_connection.getInputStream();
320 final Phylogeny[] phys = factory.create( i, parser );
322 if ( phys != null ) {
323 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
324 for( final Phylogeny phy : phys ) {
325 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
328 if ( midpoint_reroot ) {
329 for( final Phylogeny phy : phys ) {
330 PhylogenyMethods.midpointRoot( phy );
331 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
338 final public static void showErrorMessage( final Component parent, final String error_msg ) {
339 printAppletMessage( Constants.PRG_NAME, error_msg );
340 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
341 + "] Error", JOptionPane.ERROR_MESSAGE );
344 public static void writePhylogenyToGraphicsFile( final File intree,
348 final GraphicsExportType type,
349 final Configuration config ) throws IOException {
350 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
351 Phylogeny[] phys = null;
352 phys = PhylogenyMethods.readPhylogenies( parser, intree );
353 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
356 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
360 final GraphicsExportType type,
361 final Configuration config ) throws IOException {
362 final Phylogeny[] phys = new Phylogeny[ 1 ];
364 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
365 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
366 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
370 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
373 final TreePanel tree_panel,
374 final ControlPanel ac,
375 final GraphicsExportType type,
376 final Options options ) throws IOException {
377 tree_panel.calcParametersForPainting( width, height );
378 tree_panel.resetPreferredSize();
379 tree_panel.repaint();
380 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
381 RenderingHints.VALUE_RENDER_QUALITY );
382 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
383 if ( options.isAntialiasPrint() ) {
384 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
385 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
388 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
389 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
391 final Phylogeny phylogeny = tree_panel.getPhylogeny();
392 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
395 if ( outfile.isDirectory() ) {
396 throw new IOException( "\"" + outfile + "\" is a directory" );
398 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
399 final Graphics2D g2d = buffered_img.createGraphics();
400 g2d.setRenderingHints( rendering_hints );
401 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
402 if ( type == GraphicsExportType.TIFF ) {
403 writeToTiff( outfile, buffered_img );
406 ImageIO.write( buffered_img, type.toString(), outfile );
411 final private static char normalizeCharForRGB( char c ) {
414 c = c > 255 ? 255 : c;
419 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
420 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
421 InvocationTargetException, InterruptedException {
422 final String os = System.getProperty( "os.name" );
423 final Runtime runtime = Runtime.getRuntime();
424 if ( os.toLowerCase().startsWith( "win" ) ) {
425 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
427 else if ( ForesterUtil.isMac() ) {
428 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
429 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
430 open_url.invoke( null, new Object[] { url } );
433 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
434 String browser = null;
435 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
436 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
437 browser = browsers[ i ];
440 if ( browser == null ) {
441 throw new IOException( "could not find a web browser to open [" + url + "] in" );
444 runtime.exec( new String[] { browser, url } );
449 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
450 final String default_name,
451 final String full_path,
452 final Configuration configuration,
453 final MainPanel main_panel ) {
454 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
455 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
456 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
457 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
460 for( final Phylogeny phy : phys ) {
461 if ( !phy.isEmpty() ) {
462 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
464 String my_name_for_file = "";
465 if ( phys.length > 1 ) {
466 if ( !ForesterUtil.isEmpty( default_name ) ) {
467 my_name = new String( default_name );
469 if ( !ForesterUtil.isEmpty( full_path ) ) {
470 my_name_for_file = new String( full_path );
472 else if ( !ForesterUtil.isEmpty( default_name ) ) {
473 my_name_for_file = new String( default_name );
476 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
477 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
478 my_name_for_file.length() );
479 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
481 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
482 my_name_for_file += "_";
484 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
485 my_name_for_file += phy.getName().replaceAll( " ", "_" );
487 else if ( phy.getIdentifier() != null ) {
488 final StringBuffer sb = new StringBuffer();
489 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
490 sb.append( phy.getIdentifier().getProvider() );
493 sb.append( phy.getIdentifier().getValue() );
494 my_name_for_file += sb;
497 my_name_for_file += i;
499 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
500 && ( phy.getIdentifier() == null ) ) {
501 my_name = my_name + " [" + i + "]";
503 if ( !ForesterUtil.isEmpty( suffix ) ) {
504 my_name_for_file += suffix;
508 if ( !ForesterUtil.isEmpty( default_name ) ) {
509 my_name = new String( default_name );
511 my_name_for_file = "";
512 if ( !ForesterUtil.isEmpty( full_path ) ) {
513 my_name_for_file = new String( full_path );
515 else if ( !ForesterUtil.isEmpty( default_name ) ) {
516 my_name_for_file = new String( default_name );
518 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
519 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
520 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
522 else if ( phy.getIdentifier() != null ) {
523 final StringBuffer sb = new StringBuffer();
524 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
525 sb.append( phy.getIdentifier().getProvider() );
528 sb.append( phy.getIdentifier().getValue() );
529 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
533 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
534 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
535 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
542 final static void addPhylogenyToPanel( final Phylogeny[] phys,
543 final Configuration configuration,
544 final MainPanel main_panel ) {
545 final Phylogeny phy = phys[ 0 ];
546 main_panel.addPhylogenyInPanel( phy, configuration );
547 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
550 // Returns true if the specified format name can be written
551 final static boolean canWriteFormat( final String format_name ) {
552 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
553 return iter.hasNext();
556 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
557 final StringBuilder desc = new StringBuilder();
558 if ( ( phy != null ) && !phy.isEmpty() ) {
560 if ( treefile != null ) {
562 f = treefile.getCanonicalPath();
564 catch ( final IOException e ) {
565 //Not important, ignore.
567 if ( !ForesterUtil.isEmpty( f ) ) {
568 desc.append( "Path: " );
573 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
574 desc.append( "Name: " );
575 desc.append( phy.getName() );
578 if ( phy.getIdentifier() != null ) {
579 desc.append( "Id: " );
580 desc.append( phy.getIdentifier().toString() );
583 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
584 desc.append( "Description: " );
585 desc.append( phy.getDescription() );
588 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
589 desc.append( "Distance Unit: " );
590 desc.append( phy.getDistanceUnit() );
593 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
594 desc.append( "Type: " );
595 desc.append( phy.getType() );
598 desc.append( "Rooted: " );
599 desc.append( phy.isRooted() );
601 desc.append( "Rerootable: " );
602 desc.append( phy.isRerootable() );
604 desc.append( "Nodes: " );
605 desc.append( phy.getNodeCount() );
607 desc.append( "External nodes: " );
608 desc.append( phy.getNumberOfExternalNodes() );
610 desc.append( "Internal nodes: " );
611 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
613 desc.append( "Internal nodes with polytomies: " );
614 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
616 desc.append( "Branches: " );
617 desc.append( phy.getNumberOfBranches() );
619 desc.append( "Depth: " );
620 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
622 desc.append( "Maximum distance to root: " );
623 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
625 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
626 if ( taxs != null ) {
627 desc.append( "Distinct external taxonomies: " );
628 desc.append( taxs.size() );
630 for( final Taxonomy t : taxs ) {
631 System.out.println( t.toString() );
634 final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
635 if ( bs.getN() > 3 ) {
637 desc.append( "Branch-length statistics: " );
639 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
641 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
643 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
644 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
646 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
648 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
650 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
652 final AsciiHistogram histo = new AsciiHistogram( bs );
653 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
656 final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
657 if ( ds.getN() > 2 ) {
659 desc.append( "Descendants per node statistics: " );
661 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
663 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
664 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
666 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
668 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
671 List<DescriptiveStatistics> css = null;
673 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
675 catch ( final IllegalArgumentException e ) {
676 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
678 if ( ( css != null ) && ( css.size() > 0 ) ) {
680 for( int i = 0; i < css.size(); ++i ) {
681 final DescriptiveStatistics cs = css.get( i );
682 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
683 if ( css.size() > 1 ) {
684 desc.append( "Support statistics " + ( i + 1 ) + ": " );
687 desc.append( "Support statistics: " );
689 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
691 desc.append( " Type: " + cs.getDescription() );
694 desc.append( " Branches with support: " + cs.getN() );
696 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
698 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
699 if ( cs.getN() > 2 ) {
700 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
703 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
705 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
711 return desc.toString();
719 * to message to be printed
721 final static void dieWithSystemError( final String message ) {
722 System.out.println();
723 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
724 System.out.println( "Please contact the authors." );
725 System.out.println( Constants.PRG_NAME + " needs to close." );
726 System.out.println();
730 final static String[] getAllPossibleRanks() {
731 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
733 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
734 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
735 str_array[ i++ ] = e;
741 final static String[] getAllRanks( final Phylogeny tree ) {
742 final SortedSet<String> ranks = new TreeSet<String>();
743 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
744 final PhylogenyNode n = it.next();
745 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
746 ranks.add( n.getNodeData().getTaxonomy().getRank() );
749 return ForesterUtil.stringSetToArray( ranks );
752 final static String[] getAvailableFontFamiliesSorted() {
753 return AVAILABLE_FONT_FAMILIES_SORTED;
756 final static boolean isUsOrCanada() {
758 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
762 catch ( final Exception e ) {
768 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
769 final ControlPanel atv_control,
770 final Configuration configuration ) {
771 if ( ( t != null ) && !t.isEmpty() ) {
772 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
773 atv_control.setDrawPhylogram( false );
774 atv_control.setDrawPhylogramEnabled( false );
776 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
777 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
778 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
779 atv_control.setDrawPhylogram( true );
780 atv_control.setDrawPhylogramEnabled( true );
783 atv_control.setDrawPhylogram( false );
787 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
788 if ( atv_control.getWriteConfidenceCb() != null ) {
789 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
790 atv_control.setCheckbox( Configuration.write_confidence_values, true );
793 atv_control.setCheckbox( Configuration.write_confidence_values, false );
797 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
798 if ( atv_control.getShowEventsCb() != null ) {
799 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
800 atv_control.setCheckbox( Configuration.write_events, true );
803 atv_control.setCheckbox( Configuration.write_events, false );
810 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
812 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
814 catch ( final Exception e ) {
815 throw new IOException( e );
819 final static void outOfMemoryError( final OutOfMemoryError e ) {
820 System.err.println();
821 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
822 System.err.println();
824 System.err.println();
825 JOptionPane.showMessageDialog( null,
826 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
827 + "\n\nError: " + e.getLocalizedMessage(),
828 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
829 JOptionPane.ERROR_MESSAGE );
833 final static void printAppletMessage( final String applet_name, final String message ) {
834 System.out.println( "[" + applet_name + "] > " + message );
837 final static void removeBranchColors( final Phylogeny phy ) {
838 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
839 it.next().getBranchData().setBranchColor( null );
843 final static void removeVisualStyles( final Phylogeny phy ) {
844 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
845 it.next().getNodeData().setNodeVisualData( null );
849 final static void unexpectedError( final Error e ) {
850 System.err.println();
851 e.printStackTrace( System.err );
852 System.err.println();
853 final StringBuffer sb = new StringBuffer();
854 for( final StackTraceElement s : e.getStackTrace() ) {
855 sb.append( s + "\n" );
858 .showMessageDialog( null,
859 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
860 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
862 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
863 JOptionPane.ERROR_MESSAGE );
867 final static void unexpectedException( final Exception e ) {
868 System.err.println();
869 e.printStackTrace( System.err );
870 System.err.println();
871 final StringBuffer sb = new StringBuffer();
872 for( final StackTraceElement s : e.getStackTrace() ) {
873 sb.append( s + "\n" );
875 JOptionPane.showMessageDialog( null,
876 "An unexpected exception has occured. \nPlease contact: "
877 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
879 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
880 JOptionPane.ERROR_MESSAGE );
883 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
886 final TreePanel tree_panel,
887 final ControlPanel ac,
888 final GraphicsExportType type,
889 final Options options ) throws IOException {
890 if ( !options.isGraphicsExportUsingActualSize() ) {
891 if ( options.isGraphicsExportVisibleOnly() ) {
892 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
894 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY() );
895 tree_panel.resetPreferredSize();
896 tree_panel.repaint();
898 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
899 RenderingHints.VALUE_RENDER_QUALITY );
900 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
901 if ( options.isAntialiasPrint() ) {
902 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
903 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
906 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
907 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
909 final Phylogeny phylogeny = tree_panel.getPhylogeny();
910 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
913 Rectangle visible = null;
914 if ( !options.isGraphicsExportUsingActualSize() ) {
915 width = options.getPrintSizeX();
916 height = options.getPrintSizeY();
918 else if ( options.isGraphicsExportVisibleOnly() ) {
919 visible = tree_panel.getVisibleRect();
920 width = visible.width;
921 height = visible.height;
923 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
924 Graphics2D g2d = buffered_img.createGraphics();
925 g2d.setRenderingHints( rendering_hints );
928 if ( options.isGraphicsExportVisibleOnly() ) {
929 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
934 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
935 ImageIO.write( buffered_img, type.toString(), baos );
938 if ( !options.isGraphicsExportUsingActualSize() ) {
939 tree_panel.getMainPanel().getControlPanel().showWhole();
941 String msg = baos.toString();
942 if ( ( width > 0 ) && ( height > 0 ) ) {
943 msg += " [size: " + width + ", " + height + "]";
948 final static String writePhylogenyToGraphicsFile( final String file_name,
951 final TreePanel tree_panel,
952 final ControlPanel ac,
953 final GraphicsExportType type,
954 final Options options ) throws IOException {
955 if ( !options.isGraphicsExportUsingActualSize() ) {
956 if ( options.isGraphicsExportVisibleOnly() ) {
957 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
959 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY() );
960 tree_panel.resetPreferredSize();
961 tree_panel.repaint();
963 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
964 RenderingHints.VALUE_RENDER_QUALITY );
965 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
966 if ( options.isAntialiasPrint() ) {
967 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
968 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
971 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
972 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
974 final Phylogeny phylogeny = tree_panel.getPhylogeny();
975 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
978 final File file = new File( file_name );
979 if ( file.isDirectory() ) {
980 throw new IOException( "\"" + file_name + "\" is a directory" );
982 Rectangle visible = null;
983 if ( !options.isGraphicsExportUsingActualSize() ) {
984 width = options.getPrintSizeX();
985 height = options.getPrintSizeY();
987 else if ( options.isGraphicsExportVisibleOnly() ) {
988 visible = tree_panel.getVisibleRect();
989 width = visible.width;
990 height = visible.height;
992 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
993 Graphics2D g2d = buffered_img.createGraphics();
994 g2d.setRenderingHints( rendering_hints );
997 if ( options.isGraphicsExportVisibleOnly() ) {
998 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1003 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1004 if ( type == GraphicsExportType.TIFF ) {
1005 writeToTiff( file, buffered_img );
1008 ImageIO.write( buffered_img, type.toString(), file );
1012 if ( !options.isGraphicsExportUsingActualSize() ) {
1013 tree_panel.getMainPanel().getControlPanel().showWhole();
1015 String msg = file.toString();
1016 if ( ( width > 0 ) && ( height > 0 ) ) {
1017 msg += " [size: " + width + ", " + height + "]";
1022 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1023 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1024 ImageWriter writer = null;
1025 ImageOutputStream ios = null;
1026 // Find an appropriate writer:
1027 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1028 if ( it.hasNext() ) {
1032 throw new IOException( "failed to get TIFF image writer" );
1035 ios = ImageIO.createImageOutputStream( file );
1036 writer.setOutput( ios );
1037 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1038 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1039 // see writeParam.getCompressionTypes() for available compression type
1041 image_write_param.setCompressionType( "PackBits" );
1042 final String t[] = image_write_param.getCompressionTypes();
1043 for( final String string : t ) {
1044 System.out.println( string );
1046 // Convert to an IIOImage:
1047 final IIOImage iio_image = new IIOImage( image, null, null );
1048 writer.write( null, iio_image, image_write_param );