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