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