JAL-2852 added framework for saving as EPS file
[jalview.git] / forester / java / src / org / forester / archaeopteryx / AptxUtil.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // All rights reserved
8 //
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.
13 //
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.
18 //
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
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
25
26 package org.forester.archaeopteryx;
27
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;
36 import java.io.File;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.lang.reflect.InvocationTargetException;
40 import java.lang.reflect.Method;
41 import java.net.URI;
42 import java.net.URL;
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;
52 import java.util.Map;
53 import java.util.Set;
54 import java.util.SortedSet;
55 import java.util.TreeSet;
56
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;
64
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;
83
84 public final class AptxUtil {
85
86     public static enum GraphicsExportType {
87                                            BMP( "bmp" ),
88                                            GIF( "gif" ),
89                                            JPG( "jpg" ),
90                                            PDF( "pdf" ),
91                                            PNG( "png" ),
92                                            EPS("eps"),
93                                            TIFF( "tif" );
94             
95
96         private final String _suffix;
97
98         private GraphicsExportType( final String suffix ) {
99             _suffix = suffix;
100         }
101
102         @Override
103         public String toString() {
104             return _suffix;
105         }
106     }
107     private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
108             .getAvailableFontFamilyNames();
109     static {
110         Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
111     }
112
113     final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
114         final String my_str = str.toUpperCase();
115         char first = my_str.charAt( 0 );
116         char second = ' ';
117         char third = ' ';
118         if ( my_str.length() > 1 ) {
119             if ( is_taxonomy ) {
120                 second = my_str.charAt( 1 );
121             }
122             else {
123                 second = my_str.charAt( my_str.length() - 1 );
124             }
125             if ( is_taxonomy ) {
126                 if ( my_str.length() > 2 ) {
127                     if ( my_str.indexOf( " " ) > 0 ) {
128                         third = my_str.charAt( my_str.indexOf( " " ) + 1 );
129                     }
130                     else {
131                         third = my_str.charAt( 2 );
132                     }
133                 }
134             }
135             else if ( my_str.length() > 2 ) {
136                 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
137             }
138         }
139         first = normalizeCharForRGB( first );
140         second = normalizeCharForRGB( second );
141         third = normalizeCharForRGB( third );
142         if ( ( first > 200 ) && ( second > 200 ) && ( third > 200 ) ) {
143             first = 0;
144         }
145         else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
146             second = 255;
147         }
148         else if ( Math.abs( first - second ) < 40 && Math.abs( second - third ) < 40 ) {
149             third = 255;
150         }
151         return new Color( first, second, third );
152     }
153
154     public static MaskFormatter createMaskFormatter( final String s ) {
155         MaskFormatter formatter = null;
156         try {
157             formatter = new MaskFormatter( s );
158         }
159         catch ( final ParseException e ) {
160             throw new IllegalArgumentException( e );
161         }
162         return formatter;
163     }
164
165     final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
166         final PhylogenyNodeIterator it = phy.iteratorPostorder();
167         while ( it.hasNext() ) {
168             if ( it.next().getNodeData().isHasEvent() ) {
169                 return true;
170             }
171         }
172         return false;
173     }
174
175     /**
176      * Returns true if at least one branch has a length larger than zero.
177      *
178      *
179      * @param phy
180      */
181     final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
182         final PhylogenyNodeIterator it = phy.iteratorPostorder();
183         while ( it.hasNext() ) {
184             if ( it.next().getDistanceToParent() > 0.0 ) {
185                 return true;
186             }
187         }
188         return false;
189     }
190
191     final static public boolean isHasAtLeast50PercentBranchLengthLargerThanZero( final Phylogeny phy ) {
192         final PhylogenyNodeIterator it = phy.iteratorPostorder();
193         int positive = 0;
194         int total = 0;
195         while ( it.hasNext() ) {
196             if ( it.next().getDistanceToParent() > 0.0 ) {
197                 ++positive;
198             }
199             ++total;
200         }
201         if ( total == 0 ) {
202             return false;
203         }
204         return (((( double ) positive) / total) >= 0.5 );
205     }
206
207     final static public boolean isHasNoBranchLengthSmallerThanZero( final Phylogeny phy ) {
208         final PhylogenyNodeIterator it = phy.iteratorPostorder();
209         while ( it.hasNext() ) {
210             final PhylogenyNode n = it.next();
211             if ( n.getDistanceToParent() < 0.0 && !n.isRoot() ) {
212                 return false;
213             }
214         }
215         return true;
216     }
217
218     final static public boolean isHasAtLeastOneBranchWithSupportSD( final Phylogeny phy ) {
219         final PhylogenyNodeIterator it = phy.iteratorPostorder();
220         while ( it.hasNext() ) {
221             final PhylogenyNode n = it.next();
222             if ( n.getBranchData().isHasConfidences() ) {
223                 final List<Confidence> c = n.getBranchData().getConfidences();
224                 for( final Confidence confidence : c ) {
225                     if ( confidence.getStandardDeviation() > 0 ) {
226                         return true;
227                     }
228                 }
229             }
230         }
231         return false;
232     }
233
234     final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
235         final PhylogenyNodeIterator it = phy.iteratorPostorder();
236         while ( it.hasNext() ) {
237             if ( it.next().getBranchData().isHasConfidences() ) {
238                 return true;
239             }
240         }
241         return false;
242     }
243
244     final static public boolean isHasAtLeastOneNodeWithScientificName( final Phylogeny phy ) {
245         final PhylogenyNodeIterator it = phy.iteratorPostorder();
246         while ( it.hasNext() ) {
247             final PhylogenyNode n = it.next();
248             if ( n.getNodeData().isHasTaxonomy()
249                     && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
250                 return true;
251             }
252         }
253         return false;
254     }
255
256     final static public boolean isHasAtLeastOneNodeWithSequenceAnnotation( final Phylogeny phy ) {
257         final PhylogenyNodeIterator it = phy.iteratorPostorder();
258         while ( it.hasNext() ) {
259             final PhylogenyNode n = it.next();
260             if ( n.getNodeData().isHasSequence()
261                     && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getAnnotations() ) ) {
262                 return true;
263             }
264         }
265         return false;
266     }
267
268     final public static void launchWebBrowser( final URI uri, final String frame_name ) throws IOException {
269         // This requires Java 1.6:
270         // =======================
271         // boolean no_desktop = false;
272         // try {
273         // if ( Desktop.isDesktopSupported() ) {
274         // System.out.println( "desktop supported" );
275         // final Desktop dt = Desktop.getDesktop();
276         // dt.browse( uri );
277         // }
278         // else {
279         // no_desktop = true;
280         // }
281         // }
282         // catch ( final Exception ex ) {
283         // ex.printStackTrace();
284         // no_desktop = true;
285         // }
286         // catch ( final Error er ) {
287         // er.printStackTrace();
288         // no_desktop = true;
289         // }
290         // if ( no_desktop ) {
291         // System.out.println( "desktop not supported" );
292         try {
293             openUrlInWebBrowser( uri.toString() );
294         }
295         catch ( final Exception e ) {
296             throw new IOException( e );
297         }
298         // }
299     }
300
301     public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
302         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
303         final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
304         for( final PhylogenyNode n : descs ) {
305             if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
306                 tax_set.add( n.getNodeData().getTaxonomy() );
307             }
308         }
309         return tax_set;
310     }
311
312     public final static void printWarningMessage( final String name, final String message ) {
313         System.out.println( "[" + name + "] > " + message );
314     }
315
316     final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
317                                                             final boolean phyloxml_validate_against_xsd,
318                                                             final boolean replace_underscores,
319                                                             final boolean internal_numbers_are_confidences,
320                                                             final TAXONOMY_EXTRACTION taxonomy_extraction,
321                                                             final boolean midpoint_reroot )
322             throws FileNotFoundException, IOException {
323         final PhylogenyParser parser;
324         boolean nhx_or_nexus = false;
325         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
326             parser = new TolParser();
327         }
328         else {
329             parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
330             if ( parser instanceof NHXParser ) {
331                 nhx_or_nexus = true;
332                 final NHXParser nhx = ( NHXParser ) parser;
333                 nhx.setReplaceUnderscores( replace_underscores );
334                 nhx.setIgnoreQuotes( false );
335                 nhx.setTaxonomyExtraction( taxonomy_extraction );
336             }
337             else if ( parser instanceof NexusPhylogeniesParser ) {
338                 nhx_or_nexus = true;
339                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
340                 nex.setReplaceUnderscores( replace_underscores );
341                 nex.setIgnoreQuotes( false );
342             }
343         }
344         AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
345         Phylogeny[] phys = null;
346         try {
347             phys = ForesterUtil.readPhylogeniesFromUrl( url, parser );
348         }
349         catch ( final KeyManagementException e ) {
350             throw new IOException( e.getMessage() );
351         }
352         catch ( final NoSuchAlgorithmException e ) {
353             throw new IOException( e.getMessage() );
354         }
355         if ( phys != null ) {
356             if ( nhx_or_nexus && internal_numbers_are_confidences ) {
357                 for( final Phylogeny phy : phys ) {
358                     PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
359                 }
360             }
361             if ( midpoint_reroot ) {
362                 for( final Phylogeny phy : phys ) {
363                     PhylogenyMethods.midpointRoot( phy );
364                     PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
365                 }
366             }
367         }
368         return phys;
369     }
370
371     final public static void showErrorMessage( final Component parent, final String error_msg ) {
372         printAppletMessage( AptxConstants.PRG_NAME, error_msg );
373         JOptionPane.showMessageDialog( parent,
374                                        error_msg,
375                                        "[" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + "] Error",
376                                        JOptionPane.ERROR_MESSAGE );
377     }
378
379     public static void writePhylogenyToGraphicsFile( final File intree,
380                                                      final File outfile,
381                                                      final int width,
382                                                      final int height,
383                                                      final GraphicsExportType type,
384                                                      final Configuration config )
385             throws IOException {
386         final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
387         Phylogeny[] phys = null;
388         phys = PhylogenyMethods.readPhylogenies( parser, intree );
389         writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
390     }
391
392     public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
393                                                      final File outfile,
394                                                      final int width,
395                                                      final int height,
396                                                      final GraphicsExportType type,
397                                                      final Configuration config )
398             throws IOException {
399         final Phylogeny[] phys = new Phylogeny[ 1 ];
400         phys[ 0 ] = phy;
401         final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
402         AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile,
403                                                              width,
404                                                              height,
405                                                              mf.getMainPanel().getCurrentTreePanel(),
406                                                              mf.getMainPanel().getControlPanel(),
407                                                              type,
408                                                              mf.getOptions() );
409         mf.end();
410     }
411
412     public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
413                                                                          final int width,
414                                                                          final int height,
415                                                                          final TreePanel tree_panel,
416                                                                          final ControlPanel ac,
417                                                                          final GraphicsExportType type,
418                                                                          final Options options )
419             throws IOException {
420         tree_panel.calcParametersForPainting( width, height );
421         tree_panel.resetPreferredSize();
422         tree_panel.repaint();
423         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
424                                                                    RenderingHints.VALUE_RENDER_QUALITY );
425         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
426         if ( options.isAntialiasPrint() ) {
427             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
428             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
429         }
430         else {
431             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
432             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
433         }
434         final Phylogeny phylogeny = tree_panel.getPhylogeny();
435         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
436             return;
437         }
438         if ( outfile.isDirectory() ) {
439             throw new IOException( "\"" + outfile + "\" is a directory" );
440         }
441         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
442         final Graphics2D g2d = buffered_img.createGraphics();
443         g2d.setRenderingHints( rendering_hints );
444         tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
445         if ( type == GraphicsExportType.TIFF ) {
446             writeToTiff( outfile, buffered_img );
447         }
448         else {
449             ImageIO.write( buffered_img, type.toString(), outfile );
450         }
451         g2d.dispose();
452     }
453
454     final private static char normalizeCharForRGB( char c ) {
455         c -= 65;
456         c *= 10.2;
457         c = c > 255 ? 255 : c;
458         c = c < 0 ? 0 : c;
459         return c;
460     }
461
462     final private static void openUrlInWebBrowser( final String url )
463             throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException,
464             IllegalArgumentException, IllegalAccessException, InvocationTargetException, InterruptedException {
465         final String os = System.getProperty( "os.name" );
466         final Runtime runtime = Runtime.getRuntime();
467         if ( os.toLowerCase().startsWith( "win" ) ) {
468             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
469         }
470         else if ( ForesterUtil.isMac() ) {
471             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
472             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
473             open_url.invoke( null, new Object[] { url } );
474         }
475         else {
476             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
477             String browser = null;
478             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
479                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
480                     browser = browsers[ i ];
481                 }
482             }
483             if ( browser == null ) {
484                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
485             }
486             else {
487                 runtime.exec( new String[] { browser, url } );
488             }
489         }
490     }
491
492     final static void addPhylogeniesToTabs( final Phylogeny[] phys,
493                                             final String default_name,
494                                             final String full_path,
495                                             final Configuration configuration,
496                                             final MainPanel main_panel ) {
497         if ( phys.length > AptxConstants.MAX_TREES_TO_LOAD ) {
498             JOptionPane.showMessageDialog( main_panel,
499                                            "Attempt to load " + phys.length
500                                                    + " phylogenies,\ngoing to load only the first "
501                                                    + AptxConstants.MAX_TREES_TO_LOAD,
502                                            AptxConstants.PRG_NAME + " more than " + AptxConstants.MAX_TREES_TO_LOAD
503                                                    + " phylogenies",
504                                            JOptionPane.WARNING_MESSAGE );
505         }
506         int i = 1;
507         for( final Phylogeny phy : phys ) {
508             if ( !phy.isEmpty() ) {
509                 if ( i <= AptxConstants.MAX_TREES_TO_LOAD ) {
510                     String my_name = "";
511                     String my_name_for_file = "";
512                     if ( phys.length > 1 ) {
513                         if ( !ForesterUtil.isEmpty( default_name ) ) {
514                             my_name = new String( default_name );
515                         }
516                         if ( !ForesterUtil.isEmpty( full_path ) ) {
517                             my_name_for_file = new String( full_path );
518                         }
519                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
520                             my_name_for_file = new String( default_name );
521                         }
522                         String suffix = "";
523                         if ( my_name_for_file.indexOf( '.' ) > 0 ) {
524                             suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
525                                                                  my_name_for_file.length() );
526                             my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
527                         }
528                         if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
529                             my_name_for_file += "_";
530                         }
531                         if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
532                             my_name_for_file += phy.getName().replaceAll( " ", "_" );
533                         }
534                         else if ( phy.getIdentifier() != null ) {
535                             final StringBuffer sb = new StringBuffer();
536                             if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
537                                 sb.append( phy.getIdentifier().getProvider() );
538                                 sb.append( "_" );
539                             }
540                             sb.append( phy.getIdentifier().getValue() );
541                             my_name_for_file += sb;
542                         }
543                         else {
544                             my_name_for_file += i;
545                         }
546                         if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
547                                 && ( phy.getIdentifier() == null ) ) {
548                             my_name = my_name + " [" + i + "]";
549                         }
550                         if ( !ForesterUtil.isEmpty( suffix ) ) {
551                             my_name_for_file += suffix;
552                         }
553                     }
554                     else {
555                         if ( !ForesterUtil.isEmpty( default_name ) ) {
556                             my_name = new String( default_name );
557                         }
558                         my_name_for_file = "";
559                         if ( !ForesterUtil.isEmpty( full_path ) ) {
560                             my_name_for_file = new String( full_path );
561                         }
562                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
563                             my_name_for_file = new String( default_name );
564                         }
565                         if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
566                             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
567                                 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
568                             }
569                             else if ( phy.getIdentifier() != null ) {
570                                 final StringBuffer sb = new StringBuffer();
571                                 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
572                                     sb.append( phy.getIdentifier().getProvider() );
573                                     sb.append( "_" );
574                                 }
575                                 sb.append( phy.getIdentifier().getValue() );
576                                 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
577                             }
578                         }
579                     }
580                     main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
581                     main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
582                     lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
583                     ++i;
584                 }
585             }
586         }
587     }
588
589     final static void addPhylogenyToPanel( final Phylogeny[] phys,
590                                            final Configuration configuration,
591                                            final MainPanel main_panel ) {
592         final Phylogeny phy = phys[ 0 ];
593         main_panel.addPhylogenyInPanel( phy, configuration );
594         lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
595     }
596
597     // Returns true if the specified format name can be written
598     final static boolean canWriteFormat( final String format_name ) {
599         final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
600         return iter.hasNext();
601     }
602
603     final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
604         final StringBuilder desc = new StringBuilder();
605         if ( ( phy != null ) && !phy.isEmpty() ) {
606             String f = null;
607             if ( treefile != null ) {
608                 try {
609                     f = treefile.getCanonicalPath();
610                 }
611                 catch ( final IOException e ) {
612                     //Not important, ignore.
613                 }
614                 if ( !ForesterUtil.isEmpty( f ) ) {
615                     desc.append( "Path: " );
616                     desc.append( f );
617                     desc.append( "\n" );
618                 }
619             }
620             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
621                 desc.append( "Name: " );
622                 desc.append( phy.getName() );
623                 desc.append( "\n" );
624             }
625             if ( phy.getIdentifier() != null ) {
626                 desc.append( "Id: " );
627                 desc.append( phy.getIdentifier().toString() );
628                 desc.append( "\n" );
629             }
630             if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
631                 desc.append( "Description: " );
632                 desc.append( phy.getDescription() );
633                 desc.append( "\n" );
634             }
635             if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
636                 desc.append( "Distance Unit: " );
637                 desc.append( phy.getDistanceUnit() );
638                 desc.append( "\n" );
639             }
640             if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
641                 desc.append( "Type: " );
642                 desc.append( phy.getType() );
643                 desc.append( "\n" );
644             }
645             desc.append( "Rooted: " );
646             desc.append( phy.isRooted() );
647             desc.append( "\n" );
648             desc.append( "Rerootable: " );
649             desc.append( phy.isRerootable() );
650             desc.append( "\n" );
651             desc.append( "Nodes: " );
652             desc.append( phy.getNodeCount() );
653             desc.append( "\n" );
654             desc.append( "External nodes: " );
655             desc.append( phy.getNumberOfExternalNodes() );
656             desc.append( "\n" );
657             desc.append( "Internal nodes: " );
658             desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
659             desc.append( "\n" );
660             desc.append( "Internal nodes with polytomies: " );
661             desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
662             desc.append( "\n" );
663             desc.append( "Branches: " );
664             desc.append( phy.getNumberOfBranches() );
665             desc.append( "\n" );
666             desc.append( "Depth: " );
667             desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
668             desc.append( "\n" );
669             desc.append( "Maximum distance to root: " );
670             desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
671             desc.append( "\n" );
672             final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
673             if ( taxs != null ) {
674                 desc.append( "Distinct external taxonomies: " );
675                 desc.append( taxs.size() );
676             }
677             for( final Taxonomy t : taxs ) {
678                 System.out.println( t.toString() );
679             }
680             desc.append( "\n" );
681             final DescriptiveStatistics bs = PhylogenyMethods.calculateBranchLengthStatistics( phy );
682             if ( bs.getN() > 3 ) {
683                 desc.append( "\n" );
684                 desc.append( "Branch-length statistics: " );
685                 desc.append( "\n" );
686                 desc.append( "    Number of branches with non-negative branch-lengths: " + bs.getN() );
687                 desc.append( "\n" );
688                 desc.append( "    Median: " + ForesterUtil.round( bs.median(), 6 ) );
689                 desc.append( "\n" );
690                 desc.append( "    Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
691                         + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
692                 desc.append( "\n" );
693                 desc.append( "    Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
694                 desc.append( "\n" );
695                 desc.append( "    Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
696                 desc.append( "\n" );
697                 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
698                     desc.append( "\n" );
699                     final AsciiHistogram histo = new AsciiHistogram( bs );
700                     desc.append( histo.toStringBuffer( 12, '#', 40, 7, "    " ) );
701                 }
702             }
703             final DescriptiveStatistics ds = PhylogenyMethods.calculateNumberOfDescendantsPerNodeStatistics( phy );
704             if ( ds.getN() > 2 ) {
705                 desc.append( "\n" );
706                 desc.append( "Descendants per node statistics: " );
707                 desc.append( "\n" );
708                 desc.append( "    Median: " + ForesterUtil.round( ds.median(), 6 ) );
709                 desc.append( "\n" );
710                 desc.append( "    Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
711                         + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
712                 desc.append( "\n" );
713                 desc.append( "    Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
714                 desc.append( "\n" );
715                 desc.append( "    Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
716                 desc.append( "\n" );
717             }
718             List<DescriptiveStatistics> css = null;
719             try {
720                 css = PhylogenyMethods.calculateConfidenceStatistics( phy );
721             }
722             catch ( final IllegalArgumentException e ) {
723                 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, e.getMessage() );
724             }
725             if ( ( css != null ) && ( css.size() > 0 ) ) {
726                 desc.append( "\n" );
727                 for( int i = 0; i < css.size(); ++i ) {
728                     final DescriptiveStatistics cs = css.get( i );
729                     if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
730                         if ( css.size() > 1 ) {
731                             desc.append( "Support statistics " + ( i + 1 ) + ": " );
732                         }
733                         else {
734                             desc.append( "Support statistics: " );
735                         }
736                         if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
737                             desc.append( "\n" );
738                             desc.append( "    Type: " + cs.getDescription() );
739                         }
740                         desc.append( "\n" );
741                         desc.append( "    Branches with support: " + cs.getN() );
742                         desc.append( "\n" );
743                         desc.append( "    Median: " + ForesterUtil.round( cs.median(), 6 ) );
744                         desc.append( "\n" );
745                         desc.append( "    Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
746                         if ( cs.getN() > 2 ) {
747                             desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
748                         }
749                         desc.append( "\n" );
750                         desc.append( "    Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
751                         desc.append( "\n" );
752                         desc.append( "    Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
753                         desc.append( "\n" );
754                     }
755                 }
756             }
757         }
758         return desc.toString();
759     }
760
761     /**
762      * Exits with -1.
763      *
764      *
765      * @param message
766      *            to message to be printed
767      */
768     final static void dieWithSystemError( final String message ) {
769         System.out.println();
770         System.out.println( AptxConstants.PRG_NAME + " encountered the following system error: " + message );
771         System.out.println( "Please contact the authors." );
772         System.out.println( AptxConstants.PRG_NAME + " needs to close." );
773         System.out.println();
774         System.exit( -1 );
775     }
776
777     final static String[] getAllPossibleRanks() {
778         final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
779         int i = 0;
780         for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
781             if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
782                 str_array[ i++ ] = e;
783             }
784         }
785         return str_array;
786     }
787
788     final static String[] getAllPossibleRanks( final Map<String, Integer> present_ranks ) {
789         final String[] str_array = new String[ TaxonomyUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
790         int i = 0;
791         for( final String e : TaxonomyUtil.TAXONOMY_RANKS_LIST ) {
792             if ( !e.equals( TaxonomyUtil.UNKNOWN ) && !e.equals( TaxonomyUtil.OTHER ) ) {
793                 if ( present_ranks != null && present_ranks.containsKey( e ) ) {
794                     str_array[ i++ ] = e + " (" + present_ranks.get( e ) + ")";
795                 }
796                 else {
797                     str_array[ i++ ] = e;
798                 }
799             }
800         }
801         return str_array;
802     }
803
804     final static String[] getAllRanks( final Phylogeny tree ) {
805         final SortedSet<String> ranks = new TreeSet<String>();
806         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
807             final PhylogenyNode n = it.next();
808             if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
809                 ranks.add( n.getNodeData().getTaxonomy().getRank() );
810             }
811         }
812         return ForesterUtil.stringSetToArray( ranks );
813     }
814
815     final static String[] getAvailableFontFamiliesSorted() {
816         return AVAILABLE_FONT_FAMILIES_SORTED;
817     }
818
819     final static boolean isUsOrCanada() {
820         try {
821             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
822                 return true;
823             }
824         }
825         catch ( final Exception e ) {
826             return false;
827         }
828         return false;
829     }
830
831     final static void lookAtRealBranchLengthsForAptxControlSettings( final Phylogeny t, final ControlPanel cp ) {
832         if ( ( t != null ) && !t.isEmpty() ) {
833             final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
834             if ( !has_bl ) {
835                 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
836                 cp.setDrawPhylogramEnabled( false );
837             }
838             else {
839                 final boolean has_all_bl = AptxUtil.isHasNoBranchLengthSmallerThanZero( t );
840                 if ( has_all_bl ) {
841                     cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
842                 }
843                 if ( cp.getDisplayAsUnalignedPhylogramRb() != null ) {
844                     cp.setDrawPhylogramEnabled( true );
845                 }
846             }
847         }
848     }
849
850     public final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
851                                                                       final ControlPanel cp,
852                                                                       final Configuration configuration ) {
853         if ( ( t != null ) && !t.isEmpty() ) {
854             final boolean has_bl = AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t );
855             if ( !has_bl ) {
856                 cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
857                 cp.setDrawPhylogramEnabled( false );
858             }
859             if ( t.getFirstExternalNode().getBranchData().getBranchColor() != null
860                     && cp.getUseVisualStylesCb() != null ) {
861                 cp.getUseVisualStylesCb().setSelected( true );
862             }
863             if ( t.getFirstExternalNode().getBranchData().getBranchWidth() != null
864                     && t.getFirstExternalNode().getBranchData().getBranchWidth()
865                             .getValue() != BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE
866                     && cp.getUseBranchWidthsCb() != null ) {
867                 cp.getUseBranchWidthsCb().setSelected( true );
868             }
869             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
870                 if ( cp.getDisplayAsAlignedPhylogramRb() != null ) {
871                     if ( has_bl ) {
872                         final boolean has_mostly_bl = AptxUtil.isHasAtLeast50PercentBranchLengthLargerThanZero( t );
873                         if ( has_mostly_bl ) {
874                             cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.UNALIGNED_PHYLOGRAM );
875                         }
876                         cp.setDrawPhylogramEnabled( true );
877                     }
878                     else {
879                         cp.setTreeDisplayType( Options.PHYLOGENY_DISPLAY_TYPE.CLADOGRAM );
880                     }
881                 }
882             }
883             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
884                 if ( cp.getWriteConfidenceCb() != null ) {
885                     if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
886                         cp.setCheckbox( Configuration.write_confidence_values, true );
887                     }
888                     else {
889                         cp.setCheckbox( Configuration.write_confidence_values, false );
890                     }
891                 }
892             }
893             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
894                 if ( cp.getShowEventsCb() != null ) {
895                     if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
896                         cp.setCheckbox( Configuration.write_events, true );
897                     }
898                     else {
899                         cp.setCheckbox( Configuration.write_events, false );
900                     }
901                 }
902             }
903         }
904     }
905
906     final static void openWebsite( final String url ) throws IOException {
907         try {
908             AptxUtil.launchWebBrowser( new URI( url ), AptxConstants.PRG_NAME );
909         }
910         catch ( final Exception e ) {
911             throw new IOException( e );
912         }
913     }
914
915     final static void outOfMemoryError( final OutOfMemoryError e ) {
916         System.err.println();
917         System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
918         System.err.println();
919         e.printStackTrace();
920         System.err.println();
921         JOptionPane.showMessageDialog( null,
922                                        "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
923                                                + "\n\nError: " + e.getLocalizedMessage(),
924                                        "Out of Memory Error [" + AptxConstants.PRG_NAME + " " + AptxConstants.VERSION
925                                                + "]",
926                                        JOptionPane.ERROR_MESSAGE );
927         System.exit( -1 );
928     }
929
930     final static void printAppletMessage( final String applet_name, final String message ) {
931         System.out.println( "[" + applet_name + "] > " + message );
932     }
933
934     final static void removeBranchColors( final Phylogeny phy ) {
935         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
936             it.next().getBranchData().setBranchColor( null );
937         }
938     }
939
940     final static void removeVisualStyles( final Phylogeny phy ) {
941         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
942             it.next().getNodeData().setNodeVisualData( null );
943         }
944     }
945
946     final static void unexpectedError( final Error e ) {
947         System.err.println();
948         e.printStackTrace( System.err );
949         System.err.println();
950         final StringBuffer sb = new StringBuffer();
951         for( final StackTraceElement s : e.getStackTrace() ) {
952             sb.append( s + "\n" );
953         }
954         JOptionPane.showMessageDialog( null,
955                                        "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
956                                                + AptxConstants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage()
957                                                + "\n" + sb,
958                                        "Unexpected Severe Error [" + AptxConstants.PRG_NAME + " "
959                                                + AptxConstants.VERSION + "]",
960                                        JOptionPane.ERROR_MESSAGE );
961         System.exit( -1 );
962     }
963
964     final static void unexpectedException( final Exception e ) {
965         System.err.println();
966         e.printStackTrace( System.err );
967         System.err.println();
968         final StringBuffer sb = new StringBuffer();
969         for( final StackTraceElement s : e.getStackTrace() ) {
970             sb.append( s + "\n" );
971         }
972         JOptionPane.showMessageDialog( null,
973                                        "An unexpected exception has occured. \nPlease contact: "
974                                                + AptxConstants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
975                                                + "\n" + sb,
976                                        "Unexpected Exception [" + AptxConstants.PRG_NAME + AptxConstants.VERSION + "]",
977                                        JOptionPane.ERROR_MESSAGE );
978     }
979
980     final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
981                                                                        int width,
982                                                                        int height,
983                                                                        final TreePanel tree_panel,
984                                                                        final ControlPanel ac,
985                                                                        final GraphicsExportType type,
986                                                                        final Options options )
987             throws IOException {
988         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
989                                                                    RenderingHints.VALUE_RENDER_QUALITY );
990         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
991         if ( options.isAntialiasPrint() ) {
992             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
993             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
994         }
995         else {
996             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
997             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
998         }
999         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1000         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1001             return "";
1002         }
1003         Rectangle visible = null;
1004         //        if ( !options.isGraphicsExportUsingActualSize() ) {
1005         //            width = options.getPrintSizeX();
1006         //            height = options.getPrintSizeY();
1007         //        }
1008         /* else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1009             visible = tree_panel.getVisibleRect();
1010             width = visible.width;
1011             height = visible.height;
1012         }
1013         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1014         Graphics2D g2d = buffered_img.createGraphics();
1015         g2d.setRenderingHints( rendering_hints );
1016         int x = 0;
1017         int y = 0;
1018         if ( options.isGraphicsExportVisibleOnly() ) {
1019             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1020             g2d.setClip( null );
1021             x = visible.x;
1022             y = visible.y;
1023         }
1024         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1025         ImageIO.write( buffered_img, type.toString(), baos );
1026         g2d.dispose();
1027         System.gc();
1028         if ( !options.isGraphicsExportUsingActualSize() ) {
1029             tree_panel.getMainPanel().getControlPanel().showWhole();
1030         }
1031         String msg = baos.toString();
1032         if ( ( width > 0 ) && ( height > 0 ) ) {
1033             msg += " [size: " + width + ", " + height + "]";
1034         }
1035         return msg;
1036     }
1037
1038     final static String writePhylogenyToGraphicsFile( final String file_name,
1039                                                       int width,
1040                                                       int height,
1041                                                       final TreePanel tree_panel,
1042                                                       final ControlPanel ac,
1043                                                       final GraphicsExportType type,
1044                                                       final Options options )
1045             throws IOException {
1046         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1047                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1048         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1049         if ( options.isAntialiasPrint() ) {
1050             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1051             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1052         }
1053         else {
1054             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1055             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1056         }
1057         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1058         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1059             return "";
1060         }
1061         final File file = new File( file_name );
1062         if ( file.isDirectory() ) {
1063             throw new IOException( "\"" + file_name + "\" is a directory" );
1064         }
1065         Rectangle visible = null;
1066         //        if ( !options.isGraphicsExportUsingActualSize() ) {
1067         //            width = options.getPrintSizeX();
1068         //            height = options.getPrintSizeY();
1069         //        }
1070         /*else*/ if ( options.isGraphicsExportVisibleOnly() ) {
1071             visible = tree_panel.getVisibleRect();
1072             width = visible.width;
1073             height = visible.height;
1074         }
1075         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1076         Graphics2D g2d = buffered_img.createGraphics();
1077         g2d.setRenderingHints( rendering_hints );
1078         int x = 0;
1079         int y = 0;
1080         if ( options.isGraphicsExportVisibleOnly() ) {
1081             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1082             g2d.setClip( null );
1083             x = visible.x;
1084             y = visible.y;
1085         }
1086         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1087         if ( type == GraphicsExportType.TIFF ) {
1088             writeToTiff( file, buffered_img );
1089         }
1090         else if (type == GraphicsExportType.EPS) {
1091             writeToEps();
1092         }
1093         else {
1094             ImageIO.write( buffered_img, type.toString(), file );
1095         }
1096         g2d.dispose();
1097         System.gc();
1098         if ( !options.isGraphicsExportUsingActualSize() ) {
1099             tree_panel.getMainPanel().getControlPanel().showWhole();
1100         }
1101         String msg = file.toString();
1102         if ( ( width > 0 ) && ( height > 0 ) ) {
1103             msg += " [size: " + width + ", " + height + "]";
1104         }
1105         return msg;
1106     }
1107     final static void writeToEps() {
1108         
1109     }
1110
1111     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1112         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1113         ImageWriter writer = null;
1114         ImageOutputStream ios = null;
1115         // Find an appropriate writer:
1116         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1117         if ( it.hasNext() ) {
1118             writer = it.next();
1119         }
1120         else {
1121             throw new IOException( "failed to get TIFF image writer" );
1122         }
1123         // Setup writer:
1124         ios = ImageIO.createImageOutputStream( file );
1125         writer.setOutput( ios );
1126         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1127         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1128         // see writeParam.getCompressionTypes() for available compression type
1129         // strings.
1130         image_write_param.setCompressionType( "PackBits" );
1131         final String t[] = image_write_param.getCompressionTypes();
1132         for( final String string : t ) {
1133             System.out.println( string );
1134         }
1135         // Convert to an IIOImage:
1136         final IIOImage iio_image = new IIOImage( image, null, null );
1137         writer.write( null, iio_image, image_write_param );
1138     }
1139
1140     final static Map<String, Integer> getRankCounts( final Phylogeny tree ) {
1141         final Map<String, Integer> present_ranks = new HashMap<String, Integer>();
1142         if ( ( tree != null ) && !tree.isEmpty() ) {
1143             for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
1144                 final PhylogenyNode n = it.next();
1145                 if ( !n.isExternal() && n.getNodeData().isHasTaxonomy()
1146                         && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) && !n.isRoot() ) {
1147                     final String rank = n.getNodeData().getTaxonomy().getRank().toLowerCase();
1148                     if ( present_ranks.containsKey( rank ) ) {
1149                         present_ranks.put( rank, present_ranks.get( rank ) + 1 );
1150                     }
1151                     else {
1152                         present_ranks.put( rank, 1 );
1153                     }
1154                 }
1155             }
1156         }
1157         return present_ranks;
1158     }
1159 }