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.Confidence;
76 import org.forester.phylogeny.data.Taxonomy;
77 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
78 import org.forester.util.AsciiHistogram;
79 import org.forester.util.DescriptiveStatistics;
80 import org.forester.util.ForesterUtil;
82 public final class AptxUtil {
84 public static enum GraphicsExportType {
85 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
87 private final String _suffix;
89 private GraphicsExportType( final String suffix ) {
94 public String toString() {
98 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
99 .getAvailableFontFamilyNames();
101 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
104 final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
105 final String my_str = str.toUpperCase();
106 char first = my_str.charAt( 0 );
109 if ( my_str.length() > 1 ) {
111 second = my_str.charAt( 1 );
114 second = my_str.charAt( my_str.length() - 1 );
117 if ( my_str.length() > 2 ) {
118 if ( my_str.indexOf( " " ) > 0 ) {
119 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
122 third = my_str.charAt( 2 );
126 else if ( my_str.length() > 2 ) {
127 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
130 first = normalizeCharForRGB( first );
131 second = normalizeCharForRGB( second );
132 third = normalizeCharForRGB( third );
133 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
136 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
139 return new Color( first, second, third );
142 public static MaskFormatter createMaskFormatter( final String s ) {
143 MaskFormatter formatter = null;
145 formatter = new MaskFormatter( s );
147 catch ( final ParseException e ) {
148 throw new IllegalArgumentException( e );
153 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
154 final PhylogenyNodeIterator it = phy.iteratorPostorder();
155 while ( it.hasNext() ) {
156 if ( it.next().getNodeData().isHasEvent() ) {
164 * Returns true if at least one branch has a length larger than zero.
169 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
170 final PhylogenyNodeIterator it = phy.iteratorPostorder();
171 while ( it.hasNext() ) {
172 if ( it.next().getDistanceToParent() > 0.0 ) {
179 final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
180 final PhylogenyNodeIterator it = phy.iteratorPostorder();
181 while ( it.hasNext() ) {
182 final PhylogenyNode n = it.next();
183 if ( n.getBranchData().isHasConfidences() ) {
184 final List<Confidence> c = n.getBranchData().getConfidences();
185 for( final Confidence confidence : c ) {
186 if ( confidence.getStandardDeviation() > 0 ) {
195 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
196 final PhylogenyNodeIterator it = phy.iteratorPostorder();
197 while ( it.hasNext() ) {
198 if ( it.next().getBranchData().isHasConfidences() ) {
205 final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
206 final PhylogenyNodeIterator it = phy.iteratorPostorder();
207 while ( it.hasNext() ) {
208 final PhylogenyNode n = it.next();
209 if ( n.getNodeData().isHasTaxonomy()
210 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
217 final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
218 final PhylogenyNodeIterator it = phy.iteratorPostorder();
219 while ( it.hasNext() ) {
220 final PhylogenyNode n = it.next();
221 if ( n.getNodeData().isHasSequence()
222 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
229 final public static void launchWebBrowser( final URI uri,
230 final boolean is_applet,
231 final JApplet applet,
232 final String frame_name ) throws IOException {
234 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
237 // This requires Java 1.6:
238 // =======================
239 // boolean no_desktop = false;
241 // if ( Desktop.isDesktopSupported() ) {
242 // System.out.println( "desktop supported" );
243 // final Desktop dt = Desktop.getDesktop();
247 // no_desktop = true;
250 // catch ( final Exception ex ) {
251 // ex.printStackTrace();
252 // no_desktop = true;
254 // catch ( final Error er ) {
255 // er.printStackTrace();
256 // no_desktop = true;
258 // if ( no_desktop ) {
259 // System.out.println( "desktop not supported" );
261 openUrlInWebBrowser( uri.toString() );
263 catch ( final Exception e ) {
264 throw new IOException( e );
270 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
271 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
272 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
273 for( final PhylogenyNode n : descs ) {
274 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
275 tax_set.add( n.getNodeData().getTaxonomy() );
281 public final static void printWarningMessage( final String name, final String message ) {
282 System.out.println( "[" + name + "] > " + message );
285 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
286 final boolean phyloxml_validate_against_xsd,
287 final boolean replace_underscores,
288 final boolean internal_numbers_are_confidences,
289 final TAXONOMY_EXTRACTION taxonomy_extraction,
290 final boolean midpoint_reroot )
291 throws FileNotFoundException, IOException {
292 final PhylogenyParser parser;
293 boolean nhx_or_nexus = false;
294 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
295 parser = new TolParser();
298 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
299 if ( parser instanceof NHXParser ) {
301 final NHXParser nhx = ( NHXParser ) parser;
302 nhx.setReplaceUnderscores( replace_underscores );
303 nhx.setIgnoreQuotes( false );
304 nhx.setTaxonomyExtraction( taxonomy_extraction );
306 else if ( parser instanceof NexusPhylogeniesParser ) {
308 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
309 nex.setReplaceUnderscores( replace_underscores );
310 nex.setIgnoreQuotes( false );
313 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
314 Phylogeny[] phys = null;
316 phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
318 catch ( final KeyManagementException e ) {
319 throw new IOException( e.getMessage() );
321 catch ( final NoSuchAlgorithmException e ) {
322 throw new IOException( e.getMessage() );
324 if ( phys != null ) {
325 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
326 for( final Phylogeny phy : phys ) {
327 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
330 if ( midpoint_reroot ) {
331 for( final Phylogeny phy : phys ) {
332 PhylogenyMethods.midpointRoot( phy );
333 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
340 final public static void showErrorMessage( final Component parent, final String error_msg ) {
341 printAppletMessage( AptxConstants.PRG_NAME, error_msg );
342 JOptionPane.showMessageDialog( parent, error_msg, "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
343 + "] Error", JOptionPane.ERROR_MESSAGE );
346 public static void writePhylogenyToGraphicsFile( final File intree,
350 final GraphicsExportType type,
351 final Configuration config ) throws IOException {
352 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
353 Phylogeny[] phys = null;
354 phys = PhylogenyMethods.readPhylogenies( parser, intree );
355 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
358 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
362 final GraphicsExportType type,
363 final Configuration config ) throws IOException {
364 final Phylogeny[] phys = new Phylogeny[ 1 ];
366 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
367 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
368 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
372 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
375 final TreePanel tree_panel,
376 final ControlPanel ac,
377 final GraphicsExportType type,
378 final Options options ) throws IOException {
379 tree_panel.calcParametersForPainting( width, height );
380 tree_panel.resetPreferredSize();
381 tree_panel.repaint();
382 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
383 RenderingHints.VALUE_RENDER_QUALITY );
384 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
385 if ( options.isAntialiasPrint() ) {
386 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
387 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
390 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
391 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
393 final Phylogeny phylogeny = tree_panel.getPhylogeny();
394 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
397 if ( outfile.isDirectory() ) {
398 throw new IOException( "\"" + outfile + "\" is a directory" );
400 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
401 final Graphics2D g2d = buffered_img.createGraphics();
402 g2d.setRenderingHints( rendering_hints );
403 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
404 if ( type == GraphicsExportType.TIFF ) {
405 writeToTiff( outfile, buffered_img );
408 ImageIO.write( buffered_img, type.toString(), outfile );
413 final private static char normalizeCharForRGB( char c ) {
416 c = c > 255 ? 255 : c;
421 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
422 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
423 InvocationTargetException, InterruptedException {
424 final String os = System.getProperty( "os.name" );
425 final Runtime runtime = Runtime.getRuntime();
426 if ( os.toLowerCase().startsWith( "win" ) ) {
427 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
429 else if ( ForesterUtil.isMac() ) {
430 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
431 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
432 open_url.invoke( null, new Object[] { url } );
435 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
436 String browser = null;
437 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
438 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
439 browser = browsers[ i ];
442 if ( browser == null ) {
443 throw new IOException( "could not find a web browser to open [" + url + "] in" );
446 runtime.exec( new String[] { browser, url } );
451 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
452 final String default_name,
453 final String full_path,
454 final Configuration configuration,
455 final MainPanel main_panel ) {
456 if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
457 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
458 + " phylogenies,\ngoing to load only the first " + AptxConstants.MAX_TREES_TO_LOAD, AptxConstants.PRG_NAME
459 + " more than " + AptxConstants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
462 for( final Phylogeny phy : phys ) {
463 if ( !phy.isEmpty() ) {
464 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
466 String my_name_for_file = "";
467 if ( phys.length > 1 ) {
468 if ( !ForesterUtil.isEmpty( default_name ) ) {
469 my_name = new String( default_name );
471 if ( !ForesterUtil.isEmpty( full_path ) ) {
472 my_name_for_file = new String( full_path );
474 else if ( !ForesterUtil.isEmpty( default_name ) ) {
475 my_name_for_file = new String( default_name );
478 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
479 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
480 my_name_for_file.length() );
481 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
483 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
484 my_name_for_file += "_";
486 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
487 my_name_for_file += phy.getName().replaceAll( " ", "_" );
489 else if ( phy.getIdentifier() != null ) {
490 final StringBuffer sb = new StringBuffer();
491 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
492 sb.append( phy.getIdentifier().getProvider() );
495 sb.append( phy.getIdentifier().getValue() );
496 my_name_for_file += sb;
499 my_name_for_file += i;
501 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
502 && ( phy.getIdentifier() == null ) ) {
503 my_name = my_name + " [" + i + "]";
505 if ( !ForesterUtil.isEmpty( suffix ) ) {
506 my_name_for_file += suffix;
510 if ( !ForesterUtil.isEmpty( default_name ) ) {
511 my_name = new String( default_name );
513 my_name_for_file = "";
514 if ( !ForesterUtil.isEmpty( full_path ) ) {
515 my_name_for_file = new String( full_path );
517 else if ( !ForesterUtil.isEmpty( default_name ) ) {
518 my_name_for_file = new String( default_name );
520 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
521 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
522 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
524 else if ( phy.getIdentifier() != null ) {
525 final StringBuffer sb = new StringBuffer();
526 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
527 sb.append( phy.getIdentifier().getProvider() );
530 sb.append( phy.getIdentifier().getValue() );
531 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
535 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
536 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
537 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
544 final static void addPhylogenyToPanel( final Phylogeny[] phys,
545 final Configuration configuration,
546 final MainPanel main_panel ) {
547 final Phylogeny phy = phys[ 0 ];
548 main_panel.addPhylogenyInPanel( phy, configuration );
549 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
552 // Returns true if the specified format name can be written
553 final static boolean canWriteFormat( final String format_name ) {
554 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
555 return iter.hasNext();
558 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
559 final StringBuilder desc = new StringBuilder();
560 if ( ( phy != null ) && !phy.isEmpty() ) {
562 if ( treefile != null ) {
564 f = treefile.getCanonicalPath();
566 catch ( final IOException e ) {
567 //Not important, ignore.
569 if ( !ForesterUtil.isEmpty( f ) ) {
570 desc.append( "Path: " );
575 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
576 desc.append( "Name: " );
577 desc.append( phy.getName() );
580 if ( phy.getIdentifier() != null ) {
581 desc.append( "Id: " );
582 desc.append( phy.getIdentifier().toString() );
585 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
586 desc.append( "Description: " );
587 desc.append( phy.getDescription() );
590 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
591 desc.append( "Distance Unit: " );
592 desc.append( phy.getDistanceUnit() );
595 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
596 desc.append( "Type: " );
597 desc.append( phy.getType() );
600 desc.append( "Rooted: " );
601 desc.append( phy.isRooted() );
603 desc.append( "Rerootable: " );
604 desc.append( phy.isRerootable() );
606 desc.append( "Nodes: " );
607 desc.append( phy.getNodeCount() );
609 desc.append( "External nodes: " );
610 desc.append( phy.getNumberOfExternalNodes() );
612 desc.append( "Internal nodes: " );
613 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
615 desc.append( "Internal nodes with polytomies: " );
616 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
618 desc.append( "Branches: " );
619 desc.append( phy.getNumberOfBranches() );
621 desc.append( "Depth: " );
622 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
624 desc.append( "Maximum distance to root: " );
625 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
627 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
628 if ( taxs != null ) {
629 desc.append( "Distinct external taxonomies: " );
630 desc.append( taxs.size() );
632 for( final Taxonomy t : taxs ) {
633 System.out.println( t.toString() );
636 final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
637 if ( bs.getN() > 3 ) {
639 desc.append( "Branch-length statistics: " );
641 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
643 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
645 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
646 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
648 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
650 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
652 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
654 final AsciiHistogram histo = new AsciiHistogram( bs );
655 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
658 final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
659 if ( ds.getN() > 2 ) {
661 desc.append( "Descendants per node statistics: " );
663 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
665 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
666 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
668 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
670 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
673 List<DescriptiveStatistics> css = null;
675 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
677 catch ( final IllegalArgumentException e ) {
678 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
680 if ( ( css != null ) && ( css.size() > 0 ) ) {
682 for( int i = 0; i < css.size(); ++i ) {
683 final DescriptiveStatistics cs = css.get( i );
684 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
685 if ( css.size() > 1 ) {
686 desc.append( "Support statistics " + ( i + 1 ) + ": " );
689 desc.append( "Support statistics: " );
691 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
693 desc.append( " Type: " + cs.getDescription() );
696 desc.append( " Branches with support: " + cs.getN() );
698 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
700 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
701 if ( cs.getN() > 2 ) {
702 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
705 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
707 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
713 return desc.toString();
721 * to message to be printed
723 final static void dieWithSystemError( final String message ) {
724 System.out.println();
725 System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
726 System.out.println( "Please contact the authors." );
727 System.out.println( AptxConstants.PRG_NAME + " needs to close." );
728 System.out.println();
732 final static String[] getAllPossibleRanks() {
733 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
735 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
736 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
737 str_array[ i++ ] = e;
743 final static String[] getAllRanks( final Phylogeny tree ) {
744 final SortedSet<String> ranks = new TreeSet<String>();
745 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
746 final PhylogenyNode n = it.next();
747 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
748 ranks.add( n.getNodeData().getTaxonomy().getRank() );
751 return ForesterUtil.stringSetToArray( ranks );
754 final static String[] getAvailableFontFamiliesSorted() {
755 return AVAILABLE_FONT_FAMILIES_SORTED;
758 final static boolean isUsOrCanada() {
760 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
764 catch ( final Exception e ) {
769 final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t,
770 final ControlPanel cp ) {
771 if ( ( t != null ) && !t.isEmpty() ) {
772 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
774 cp.setDrawPhylogram( false );
775 cp.setDrawPhylogramEnabled( false );
777 else if ( cp.getDisplayAsPhylogramCb() != null ) {
778 cp.setDrawPhylogramEnabled( true );
782 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
783 final ControlPanel atv_control,
784 final Configuration configuration ) {
785 if ( ( t != null ) && !t.isEmpty() ) {
786 final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
788 atv_control.setDrawPhylogram( false );
789 atv_control.setDrawPhylogramEnabled( false );
791 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
792 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
794 atv_control.setDrawPhylogram( true );
795 atv_control.setDrawPhylogramEnabled( true );
798 atv_control.setDrawPhylogram( false );
802 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
803 if ( atv_control.getWriteConfidenceCb() != null ) {
804 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
805 atv_control.setCheckbox( Configuration.write_confidence_values, true );
808 atv_control.setCheckbox( Configuration.write_confidence_values, false );
812 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
813 if ( atv_control.getShowEventsCb() != null ) {
814 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
815 atv_control.setCheckbox( Configuration.write_events, true );
818 atv_control.setCheckbox( Configuration.write_events, false );
825 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
827 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, AptxConstants.PRG_NAME );
829 catch ( final Exception e ) {
830 throw new IOException( e );
834 final static void outOfMemoryError( final OutOfMemoryError e ) {
835 System.err.println();
836 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
837 System.err.println();
839 System.err.println();
840 JOptionPane.showMessageDialog( null,
841 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
842 + "\n\nError: " + e.getLocalizedMessage(),
843 "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
844 JOptionPane.ERROR_MESSAGE );
848 final static void printAppletMessage( final String applet_name, final String message ) {
849 System.out.println( "[" + applet_name + "] > " + message );
852 final static void removeBranchColors( final Phylogeny phy ) {
853 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
854 it.next().getBranchData().setBranchColor( null );
858 final static void removeVisualStyles( final Phylogeny phy ) {
859 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
860 it.next().getNodeData().setNodeVisualData( null );
864 final static void unexpectedError( final Error e ) {
865 System.err.println();
866 e.printStackTrace( System.err );
867 System.err.println();
868 final StringBuffer sb = new StringBuffer();
869 for( final StackTraceElement s : e.getStackTrace() ) {
870 sb.append( s + "\n" );
873 .showMessageDialog( null,
874 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
875 + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
877 "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "]",
878 JOptionPane.ERROR_MESSAGE );
882 final static void unexpectedException( final Exception e ) {
883 System.err.println();
884 e.printStackTrace( System.err );
885 System.err.println();
886 final StringBuffer sb = new StringBuffer();
887 for( final StackTraceElement s : e.getStackTrace() ) {
888 sb.append( s + "\n" );
890 JOptionPane.showMessageDialog( null,
891 "An unexpected exception has occured. \nPlease contact: "
892 + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
894 "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
895 JOptionPane.ERROR_MESSAGE );
898 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
901 final TreePanel tree_panel,
902 final ControlPanel ac,
903 final GraphicsExportType type,
904 final Options options ) throws IOException {
905 if ( !options.isGraphicsExportUsingActualSize() ) {
906 if ( options.isGraphicsExportVisibleOnly() ) {
907 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
909 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY() );
910 tree_panel.resetPreferredSize();
911 tree_panel.repaint();
913 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
914 RenderingHints.VALUE_RENDER_QUALITY );
915 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
916 if ( options.isAntialiasPrint() ) {
917 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
918 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
921 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
922 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
924 final Phylogeny phylogeny = tree_panel.getPhylogeny();
925 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
928 Rectangle visible = null;
929 if ( !options.isGraphicsExportUsingActualSize() ) {
930 width = options.getPrintSizeX();
931 height = options.getPrintSizeY();
933 else if ( options.isGraphicsExportVisibleOnly() ) {
934 visible = tree_panel.getVisibleRect();
935 width = visible.width;
936 height = visible.height;
938 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
939 Graphics2D g2d = buffered_img.createGraphics();
940 g2d.setRenderingHints( rendering_hints );
943 if ( options.isGraphicsExportVisibleOnly() ) {
944 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
949 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
950 ImageIO.write( buffered_img, type.toString(), baos );
953 if ( !options.isGraphicsExportUsingActualSize() ) {
954 tree_panel.getMainPanel().getControlPanel().showWhole();
956 String msg = baos.toString();
957 if ( ( width > 0 ) && ( height > 0 ) ) {
958 msg += " [size: " + width + ", " + height + "]";
963 final static String writePhylogenyToGraphicsFile( final String file_name,
966 final TreePanel tree_panel,
967 final ControlPanel ac,
968 final GraphicsExportType type,
969 final Options options ) throws IOException {
970 if ( !options.isGraphicsExportUsingActualSize() ) {
971 if ( options.isGraphicsExportVisibleOnly() ) {
972 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
974 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY() );
975 tree_panel.resetPreferredSize();
976 tree_panel.repaint();
978 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
979 RenderingHints.VALUE_RENDER_QUALITY );
980 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
981 if ( options.isAntialiasPrint() ) {
982 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
983 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
986 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
987 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
989 final Phylogeny phylogeny = tree_panel.getPhylogeny();
990 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
993 final File file = new File( file_name );
994 if ( file.isDirectory() ) {
995 throw new IOException( "\"" + file_name + "\" is a directory" );
997 Rectangle visible = null;
998 if ( !options.isGraphicsExportUsingActualSize() ) {
999 width = options.getPrintSizeX();
1000 height = options.getPrintSizeY();
1002 else if ( options.isGraphicsExportVisibleOnly() ) {
1003 visible = tree_panel.getVisibleRect();
1004 width = visible.width;
1005 height = visible.height;
1007 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1008 Graphics2D g2d = buffered_img.createGraphics();
1009 g2d.setRenderingHints( rendering_hints );
1012 if ( options.isGraphicsExportVisibleOnly() ) {
1013 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1014 g2d.setClip( null );
1018 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1019 if ( type == GraphicsExportType.TIFF ) {
1020 writeToTiff( file, buffered_img );
1023 ImageIO.write( buffered_img, type.toString(), file );
1027 if ( !options.isGraphicsExportUsingActualSize() ) {
1028 tree_panel.getMainPanel().getControlPanel().showWhole();
1030 String msg = file.toString();
1031 if ( ( width > 0 ) && ( height > 0 ) ) {
1032 msg += " [size: " + width + ", " + height + "]";
1037 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1038 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1039 ImageWriter writer = null;
1040 ImageOutputStream ios = null;
1041 // Find an appropriate writer:
1042 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1043 if ( it.hasNext() ) {
1047 throw new IOException( "failed to get TIFF image writer" );
1050 ios = ImageIO.createImageOutputStream( file );
1051 writer.setOutput( ios );
1052 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1053 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1054 // see writeParam.getCompressionTypes() for available compression type
1056 image_write_param.setCompressionType( "PackBits" );
1057 final String t[] = image_write_param.getCompressionTypes();
1058 for( final String string : t ) {
1059 System.out.println( string );
1061 // Convert to an IIOImage:
1062 final IIOImage iio_image = new IIOImage( image, null, null );
1063 writer.write( null, iio_image, image_write_param );