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 {
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 > 200 ) && ( second > 200 ) && ( third > 200 ) ) {
138 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
141 else if ( Math.abs( first - second ) < 40 && Math.abs( second - third ) < 40 ) {
144 return new Color( first, second, third );
147 public static MaskFormatter createMaskFormatter( final String s ) {
148 MaskFormatter formatter = null;
150 formatter = new MaskFormatter( s );
152 catch ( final ParseException e ) {
153 throw new IllegalArgumentException( e );
158 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
159 final PhylogenyNodeIterator it = phy.iteratorPostorder();
160 while ( it.hasNext() ) {
161 if ( it.next().getNodeData().isHasEvent() ) {
169 * Returns true if at least one branch has a length larger than zero.
174 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
175 final PhylogenyNodeIterator it = phy.iteratorPostorder();
176 while ( it.hasNext() ) {
177 if ( it.next().getDistanceToParent() > 0.0 ) {
184 final static public boolean isHasNoBranchLengthSmallerThanZero( final Phylogeny phy ) {
185 final PhylogenyNodeIterator it = phy.iteratorPostorder();
186 while ( it.hasNext() ) {
187 final PhylogenyNode n = it.next();
188 if ( n.getDistanceToParent() < 0.0 && !n.isRoot() ) {
195 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
196 final PhylogenyNodeIterator it = phy.iteratorPostorder();
197 while ( it.hasNext() ) {
198 final PhylogenyNode n = it.next();
199 if ( n.getBranchData().isHasConfidences() ) {
200 final List<Confidence> c = n.getBranchData().getConfidences();
201 for( final Confidence confidence : c ) {
202 if ( confidence.getStandardDeviation() > 0 ) {
211 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
212 final PhylogenyNodeIterator it = phy.iteratorPostorder();
213 while ( it.hasNext() ) {
214 if ( it.next().getBranchData().isHasConfidences() ) {
221 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
222 final PhylogenyNodeIterator it = phy.iteratorPostorder();
223 while ( it.hasNext() ) {
224 final PhylogenyNode n = it.next();
225 if ( n.getNodeData().isHasTaxonomy()
226 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
233 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
234 final PhylogenyNodeIterator it = phy.iteratorPostorder();
235 while ( it.hasNext() ) {
236 final PhylogenyNode n = it.next();
237 if ( n.getNodeData().isHasSequence()
238 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
245 final public static void launchWebBrowser( final URI uri,
246 final String frame_name ) throws IOException {
248 // This requires Java 1.6:
249 // =======================
250 // boolean no_desktop = false;
252 // if ( Desktop.isDesktopSupported() ) {
253 // System.out.println( "desktop supported" );
254 // final Desktop dt = Desktop.getDesktop();
258 // no_desktop = true;
261 // catch ( final Exception ex ) {
262 // ex.printStackTrace();
263 // no_desktop = true;
265 // catch ( final Error er ) {
266 // er.printStackTrace();
267 // no_desktop = true;
269 // if ( no_desktop ) {
270 // System.out.println( "desktop not supported" );
272 openUrlInWebBrowser( uri.toString() );
274 catch ( final Exception e ) {
275 throw new IOException( e );
281 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
282 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
283 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
284 for( final PhylogenyNode n : descs ) {
285 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
286 tax_set.add( n.getNodeData().getTaxonomy() );
292 public final static void printWarningMessage( final String name, final String message ) {
293 System.out.println( "[" + name + "] > " + message );
296 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
297 final boolean phyloxml_validate_against_xsd,
298 final boolean replace_underscores,
299 final boolean internal_numbers_are_confidences,
300 final TAXONOMY_EXTRACTION taxonomy_extraction,
301 final boolean midpoint_reroot )
302 throws FileNotFoundException, IOException {
303 final PhylogenyParser parser;
304 boolean nhx_or_nexus = false;
305 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
306 parser = new TolParser();
309 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
310 if ( parser instanceof NHXParser ) {
312 final NHXParser nhx = ( NHXParser ) parser;
313 nhx.setReplaceUnderscores( replace_underscores );
314 nhx.setIgnoreQuotes( false );
315 nhx.setTaxonomyExtraction( taxonomy_extraction );
317 else if ( parser instanceof NexusPhylogeniesParser ) {
319 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
320 nex.setReplaceUnderscores( replace_underscores );
321 nex.setIgnoreQuotes( false );
324 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
325 Phylogeny[] phys = null;
327 phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
329 catch ( final KeyManagementException e ) {
330 throw new IOException( e.getMessage() );
332 catch ( final NoSuchAlgorithmException e ) {
333 throw new IOException( e.getMessage() );
335 if ( phys != null ) {
336 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
337 for( final Phylogeny phy : phys ) {
338 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
341 if ( midpoint_reroot ) {
342 for( final Phylogeny phy : phys ) {
343 PhylogenyMethods.midpointRoot( phy );
344 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
351 final public static void showErrorMessage( final Component parent, final String error_msg ) {
352 printAppletMessage( AptxConstants.PRG_NAME, error_msg );
353 JOptionPane.showMessageDialog( parent, error_msg, "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
354 + "] Error", JOptionPane.ERROR_MESSAGE );
357 public static void writePhylogenyToGraphicsFile( final File intree,
361 final GraphicsExportType type,
362 final Configuration config ) throws IOException {
363 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
364 Phylogeny[] phys = null;
365 phys = PhylogenyMethods.readPhylogenies( parser, intree );
366 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
369 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
373 final GraphicsExportType type,
374 final Configuration config ) throws IOException {
375 final Phylogeny[] phys = new Phylogeny[ 1 ];
377 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
378 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
379 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
383 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
386 final TreePanel tree_panel,
387 final ControlPanel ac,
388 final GraphicsExportType type,
389 final Options options ) throws IOException {
390 tree_panel.calcParametersForPainting( width, height );
391 tree_panel.resetPreferredSize();
392 tree_panel.repaint();
393 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
394 RenderingHints.VALUE_RENDER_QUALITY );
395 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
396 if ( options.isAntialiasPrint() ) {
397 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
398 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
401 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
402 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
404 final Phylogeny phylogeny = tree_panel.getPhylogeny();
405 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
408 if ( outfile.isDirectory() ) {
409 throw new IOException( "\"" + outfile + "\" is a directory" );
411 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
412 final Graphics2D g2d = buffered_img.createGraphics();
413 g2d.setRenderingHints( rendering_hints );
414 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
415 if ( type == GraphicsExportType.TIFF ) {
416 writeToTiff( outfile, buffered_img );
419 ImageIO.write( buffered_img, type.toString(), outfile );
424 final private static char normalizeCharForRGB( char c ) {
427 c = c > 255 ? 255 : c;
432 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
433 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
434 InvocationTargetException, InterruptedException {
435 final String os = System.getProperty( "os.name" );
436 final Runtime runtime = Runtime.getRuntime();
437 if ( os.toLowerCase().startsWith( "win" ) ) {
438 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
440 else if ( ForesterUtil.isMac() ) {
441 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
442 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
443 open_url.invoke( null, new Object[] { url } );
446 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
447 String browser = null;
448 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
449 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
450 browser = browsers[ i ];
453 if ( browser == null ) {
454 throw new IOException( "could not find a web browser to open [" + url + "] in" );
457 runtime.exec( new String[] { browser, url } );
462 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
463 final String default_name,
464 final String full_path,
465 final Configuration configuration,
466 final MainPanel main_panel ) {
467 if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
468 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
469 + " phylogenies,\ngoing to load only the first " + AptxConstants.MAX_TREES_TO_LOAD, AptxConstants.PRG_NAME
470 + " more than " + AptxConstants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
473 for( final Phylogeny phy : phys ) {
474 if ( !phy.isEmpty() ) {
475 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
477 String my_name_for_file = "";
478 if ( phys.length > 1 ) {
479 if ( !ForesterUtil.isEmpty( default_name ) ) {
480 my_name = new String( default_name );
482 if ( !ForesterUtil.isEmpty( full_path ) ) {
483 my_name_for_file = new String( full_path );
485 else if ( !ForesterUtil.isEmpty( default_name ) ) {
486 my_name_for_file = new String( default_name );
489 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
490 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
491 my_name_for_file.length() );
492 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
494 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
495 my_name_for_file += "_";
497 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
498 my_name_for_file += phy.getName().replaceAll( " ", "_" );
500 else if ( phy.getIdentifier() != null ) {
501 final StringBuffer sb = new StringBuffer();
502 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
503 sb.append( phy.getIdentifier().getProvider() );
506 sb.append( phy.getIdentifier().getValue() );
507 my_name_for_file += sb;
510 my_name_for_file += i;
512 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
513 && ( phy.getIdentifier() == null ) ) {
514 my_name = my_name + " [" + i + "]";
516 if ( !ForesterUtil.isEmpty( suffix ) ) {
517 my_name_for_file += suffix;
521 if ( !ForesterUtil.isEmpty( default_name ) ) {
522 my_name = new String( default_name );
524 my_name_for_file = "";
525 if ( !ForesterUtil.isEmpty( full_path ) ) {
526 my_name_for_file = new String( full_path );
528 else if ( !ForesterUtil.isEmpty( default_name ) ) {
529 my_name_for_file = new String( default_name );
531 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
532 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
533 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
535 else if ( phy.getIdentifier() != null ) {
536 final StringBuffer sb = new StringBuffer();
537 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
538 sb.append( phy.getIdentifier().getProvider() );
541 sb.append( phy.getIdentifier().getValue() );
542 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
546 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
547 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
548 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
555 final static void addPhylogenyToPanel( final Phylogeny[] phys,
556 final Configuration configuration,
557 final MainPanel main_panel ) {
558 final Phylogeny phy = phys[ 0 ];
559 main_panel.addPhylogenyInPanel( phy, configuration );
560 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
563 // Returns true if the specified format name can be written
564 final static boolean canWriteFormat( final String format_name ) {
565 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
566 return iter.hasNext();
569 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
570 final StringBuilder desc = new StringBuilder();
571 if ( ( phy != null ) && !phy.isEmpty() ) {
573 if ( treefile != null ) {
575 f = treefile.getCanonicalPath();
577 catch ( final IOException e ) {
578 //Not important, ignore.
580 if ( !ForesterUtil.isEmpty( f ) ) {
581 desc.append( "Path: " );
586 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
587 desc.append( "Name: " );
588 desc.append( phy.getName() );
591 if ( phy.getIdentifier() != null ) {
592 desc.append( "Id: " );
593 desc.append( phy.getIdentifier().toString() );
596 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
597 desc.append( "Description: " );
598 desc.append( phy.getDescription() );
601 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
602 desc.append( "Distance Unit: " );
603 desc.append( phy.getDistanceUnit() );
606 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
607 desc.append( "Type: " );
608 desc.append( phy.getType() );
611 desc.append( "Rooted: " );
612 desc.append( phy.isRooted() );
614 desc.append( "Rerootable: " );
615 desc.append( phy.isRerootable() );
617 desc.append( "Nodes: " );
618 desc.append( phy.getNodeCount() );
620 desc.append( "External nodes: " );
621 desc.append( phy.getNumberOfExternalNodes() );
623 desc.append( "Internal nodes: " );
624 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
626 desc.append( "Internal nodes with polytomies: " );
627 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
629 desc.append( "Branches: " );
630 desc.append( phy.getNumberOfBranches() );
632 desc.append( "Depth: " );
633 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
635 desc.append( "Maximum distance to root: " );
636 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
638 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
639 if ( taxs != null ) {
640 desc.append( "Distinct external taxonomies: " );
641 desc.append( taxs.size() );
643 for( final Taxonomy t : taxs ) {
644 System.out.println( t.toString() );
647 final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
648 if ( bs.getN() > 3 ) {
650 desc.append( "Branch-length statistics: " );
652 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
654 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
656 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
657 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
659 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
661 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
663 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
665 final AsciiHistogram histo = new AsciiHistogram( bs );
666 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
669 final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
670 if ( ds.getN() > 2 ) {
672 desc.append( "Descendants per node statistics: " );
674 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
676 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
677 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
679 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
681 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
684 List<DescriptiveStatistics> css = null;
686 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
688 catch ( final IllegalArgumentException e ) {
689 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
691 if ( ( css != null ) && ( css.size() > 0 ) ) {
693 for( int i = 0; i < css.size(); ++i ) {
694 final DescriptiveStatistics cs = css.get( i );
695 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
696 if ( css.size() > 1 ) {
697 desc.append( "Support statistics " + ( i + 1 ) + ": " );
700 desc.append( "Support statistics: " );
702 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
704 desc.append( " Type: " + cs.getDescription() );
707 desc.append( " Branches with support: " + cs.getN() );
709 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
711 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
712 if ( cs.getN() > 2 ) {
713 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
716 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
718 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
724 return desc.toString();
732 * to message to be printed
734 final static void dieWithSystemError( final String message ) {
735 System.out.println();
736 System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
737 System.out.println( "Please contact the authors." );
738 System.out.println( AptxConstants.PRG_NAME + " needs to close." );
739 System.out.println();
743 final static String[] getAllPossibleRanks() {
744 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
746 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
747 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
748 str_array[ i++ ] = e;
754 final static String[] getAllPossibleRanks(final Map<String, Integer> present_ranks) {
755 final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
757 for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
758 if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
759 if ( present_ranks != null && present_ranks.containsKey( e ) ) {
760 str_array[ i++ ] = e + " (" + present_ranks.get(e) + ")";
763 str_array[ i++ ] = e;
770 final static String[] getAllRanks( final Phylogeny tree ) {
771 final SortedSet<String> ranks = new TreeSet<String>();
772 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
773 final PhylogenyNode n = it.next();
774 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
775 ranks.add( n.getNodeData().getTaxonomy().getRank() );
778 return ForesterUtil.stringSetToArray( ranks );
781 final static String[] getAvailableFontFamiliesSorted() {
782 return AVAILABLE_FONT_FAMILIES_SORTED;
785 final static boolean isUsOrCanada() {
787 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
791 catch ( final Exception e ) {
796 final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t,
797 final ControlPanel cp ) {
798 if ( ( t != null ) && !t.isEmpty() ) {
799 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
802 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
803 cp.setDrawPhylogramEnabled( false );
806 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
808 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
811 if ( cp.getDisplayAsUnalignedPhylogramRb() != null ) {
812 cp.setDrawPhylogramEnabled( true );
817 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
818 final ControlPanel atv_control,
819 final Configuration configuration ) {
820 if ( ( t != null ) && !t.isEmpty() ) {
821 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
823 atv_control.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
824 atv_control.setDrawPhylogramEnabled( false );
826 if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
827 && atv_control.getUseVisualStylesCb() != null ) {
828 atv_control.getUseVisualStylesCb().setSelected( true );
830 if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
831 && t.getFirstExternalNode().getBranchData().getBranchWidth().getValue()
832 != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
833 && atv_control.getUseBranchWidthsCb() != null ) {
834 atv_control.getUseBranchWidthsCb().setSelected( true );
838 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
839 if ( atv_control.getDisplayAsAlignedPhylogramRb() != null ) {
841 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
843 atv_control.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
846 atv_control.setDrawPhylogramEnabled( true );
849 atv_control.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
853 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
854 if ( atv_control.getWriteConfidenceCb() != null ) {
855 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
856 atv_control.setCheckbox( Configuration.write_confidence_values, true );
859 atv_control.setCheckbox( Configuration.write_confidence_values, false );
863 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
864 if ( atv_control.getShowEventsCb() != null ) {
865 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
866 atv_control.setCheckbox( Configuration.write_events, true );
869 atv_control.setCheckbox( Configuration.write_events, false );
876 final static void openWebsite( final String url ) throws IOException {
878 AptxUtil.launchWebBrowser( new URI( url ), AptxConstants.PRG_NAME );
880 catch ( final Exception e ) {
881 throw new IOException( e );
885 final static void outOfMemoryError( final OutOfMemoryError e ) {
886 System.err.println();
887 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
888 System.err.println();
890 System.err.println();
891 JOptionPane.showMessageDialog( null,
892 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
893 + "\n\nError: " + e.getLocalizedMessage(),
894 "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
895 JOptionPane.ERROR_MESSAGE );
899 final static void printAppletMessage( final String applet_name, final String message ) {
900 System.out.println( "[" + applet_name + "] > " + message );
903 final static void removeBranchColors( final Phylogeny phy ) {
904 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
905 it.next().getBranchData().setBranchColor( null );
909 final static void removeVisualStyles( final Phylogeny phy ) {
910 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
911 it.next().getNodeData().setNodeVisualData( null );
915 final static void unexpectedError( final Error e ) {
916 System.err.println();
917 e.printStackTrace( System.err );
918 System.err.println();
919 final StringBuffer sb = new StringBuffer();
920 for( final StackTraceElement s : e.getStackTrace() ) {
921 sb.append( s + "\n" );
924 .showMessageDialog( null,
925 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
926 + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
928 "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
929 JOptionPane.ERROR_MESSAGE );
933 final static void unexpectedException( final Exception e ) {
934 System.err.println();
935 e.printStackTrace( System.err );
936 System.err.println();
937 final StringBuffer sb = new StringBuffer();
938 for( final StackTraceElement s : e.getStackTrace() ) {
939 sb.append( s + "\n" );
941 JOptionPane.showMessageDialog( null,
942 "An unexpected exception has occured. \nPlease contact: "
943 + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
945 "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
946 JOptionPane.ERROR_MESSAGE );
949 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
952 final TreePanel tree_panel,
953 final ControlPanel ac,
954 final GraphicsExportType type,
955 final Options options ) throws IOException {
957 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
958 RenderingHints.VALUE_RENDER_QUALITY );
959 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
960 if ( options.isAntialiasPrint() ) {
961 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
962 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
965 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
966 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
968 final Phylogeny phylogeny = tree_panel.getPhylogeny();
969 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
972 Rectangle visible = null;
973 // if ( !options.isGraphicsExportUsingActualSize() ) {
974 // width = options.getPrintSizeX();
975 // height = options.getPrintSizeY();
977 /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
978 visible = tree_panel.getVisibleRect();
979 width = visible.width;
980 height = visible.height;
982 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
983 Graphics2D g2d = buffered_img.createGraphics();
984 g2d.setRenderingHints( rendering_hints );
987 if ( options.isGraphicsExportVisibleOnly() ) {
988 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
993 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
994 ImageIO.write( buffered_img, type.toString(), baos );
997 if ( !options.isGraphicsExportUsingActualSize() ) {
998 tree_panel.getMainPanel().getControlPanel().showWhole();
1000 String msg = baos.toString();
1001 if ( ( width > 0 ) && ( height > 0 ) ) {
1002 msg += " [size: " + width + ", " + height + "]";
1007 final static String writePhylogenyToGraphicsFile( final String file_name,
1010 final TreePanel tree_panel,
1011 final ControlPanel ac,
1012 final GraphicsExportType type,
1013 final Options options ) throws IOException {
1015 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1016 RenderingHints.VALUE_RENDER_QUALITY );
1017 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1018 if ( options.isAntialiasPrint() ) {
1019 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1020 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1023 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1024 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1026 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1027 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1030 final File file = new File( file_name );
1031 if ( file.isDirectory() ) {
1032 throw new IOException( "\"" + file_name + "\" is a directory" );
1034 Rectangle visible = null;
1035 // if ( !options.isGraphicsExportUsingActualSize() ) {
1036 // width = options.getPrintSizeX();
1037 // height = options.getPrintSizeY();
1039 /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1040 visible = tree_panel.getVisibleRect();
1041 width = visible.width;
1042 height = visible.height;
1044 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1045 Graphics2D g2d = buffered_img.createGraphics();
1046 g2d.setRenderingHints( rendering_hints );
1049 if ( options.isGraphicsExportVisibleOnly() ) {
1050 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1051 g2d.setClip( null );
1055 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1056 if ( type == GraphicsExportType.TIFF ) {
1057 writeToTiff( file, buffered_img );
1060 ImageIO.write( buffered_img, type.toString(), file );
1064 if ( !options.isGraphicsExportUsingActualSize() ) {
1065 tree_panel.getMainPanel().getControlPanel().showWhole();
1067 String msg = file.toString();
1068 if ( ( width > 0 ) && ( height > 0 ) ) {
1069 msg += " [size: " + width + ", " + height + "]";
1074 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1075 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1076 ImageWriter writer = null;
1077 ImageOutputStream ios = null;
1078 // Find an appropriate writer:
1079 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1080 if ( it.hasNext() ) {
1084 throw new IOException( "failed to get TIFF image writer" );
1087 ios = ImageIO.createImageOutputStream( file );
1088 writer.setOutput( ios );
1089 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1090 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1091 // see writeParam.getCompressionTypes() for available compression type
1093 image_write_param.setCompressionType( "PackBits" );
1094 final String t[] = image_write_param.getCompressionTypes();
1095 for( final String string : t ) {
1096 System.out.println( string );
1098 // Convert to an IIOImage:
1099 final IIOImage iio_image = new IIOImage( image, null, null );
1100 writer.write( null, iio_image, image_write_param );
1103 final static Map<String, Integer> getRankCounts(final Phylogeny tree) {
1104 final Map<String, Integer> present_ranks = new HashMap<String, Integer>();
1106 if ( ( tree != null ) && !tree.isEmpty() ) {
1107 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
1108 final PhylogenyNode n = it.next();
1109 if ( !n.isExternal() && n.getNodeData().isHasTaxonomy()
1110 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) && !n.isRoot() ) {
1111 final String rank = n.getNodeData().getTaxonomy().getRank().toLowerCase();
1112 if (present_ranks.containsKey( rank ) ) {
1113 present_ranks.put( rank, present_ranks.get( rank ) + 1 );
1116 present_ranks.put( rank, 1 );
1121 return present_ranks;