2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
26 package org.forester.archaeopteryx;
28 import java.awt.Color;
29 import java.awt.Component;
30 import java.awt.Graphics2D;
31 import java.awt.GraphicsEnvironment;
32 import java.awt.Rectangle;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.io.ByteArrayOutputStream;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.io.UnsupportedEncodingException;
40 import java.lang.reflect.InvocationTargetException;
41 import java.lang.reflect.Method;
44 import java.net.URLEncoder;
45 import java.text.ParseException;
46 import java.util.Arrays;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Locale;
54 import java.util.SortedSet;
55 import java.util.TreeSet;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
59 import javax.imageio.IIOImage;
60 import javax.imageio.ImageIO;
61 import javax.imageio.ImageWriteParam;
62 import javax.imageio.ImageWriter;
63 import javax.imageio.stream.ImageOutputStream;
64 import javax.swing.JApplet;
65 import javax.swing.JOptionPane;
66 import javax.swing.text.MaskFormatter;
68 import org.forester.analysis.TaxonomyDataManager;
69 import org.forester.io.parsers.PhylogenyParser;
70 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
71 import org.forester.io.parsers.nhx.NHXParser;
72 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
73 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
74 import org.forester.io.parsers.tol.TolParser;
75 import org.forester.io.parsers.util.ParserUtils;
76 import org.forester.phylogeny.Phylogeny;
77 import org.forester.phylogeny.PhylogenyMethods;
78 import org.forester.phylogeny.PhylogenyNode;
79 import org.forester.phylogeny.data.Accession;
80 import org.forester.phylogeny.data.BranchColor;
81 import org.forester.phylogeny.data.Taxonomy;
82 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
83 import org.forester.phylogeny.factories.PhylogenyFactory;
84 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
85 import org.forester.phylogeny.iterators.PreorderTreeIterator;
86 import org.forester.util.AsciiHistogram;
87 import org.forester.util.DescriptiveStatistics;
88 import org.forester.util.ForesterConstants;
89 import org.forester.util.ForesterUtil;
90 import org.forester.util.SequenceIdParser;
91 import org.forester.ws.seqdb.UniProtTaxonomy;
93 public final class AptxUtil {
95 private final static Pattern seq_identifier_pattern_1 = Pattern
96 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
97 private final static Pattern seq_identifier_pattern_2 = Pattern
98 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
99 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
100 .getAvailableFontFamilyNames();
102 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
105 public final static String createUriForSeqWeb( final PhylogenyNode node,
106 final Configuration conf,
107 final TreePanel tp ) {
108 String uri_str = null;
109 final String upkb = ForesterUtil.extractUniProtKbProteinSeqIdentifier( node );
110 if ( !ForesterUtil.isEmpty( upkb ) ) {
112 uri_str = ForesterUtil.UNIPROT_KB + URLEncoder.encode( upkb, ForesterConstants.UTF8 );
114 catch ( final UnsupportedEncodingException e ) {
115 showErrorMessage( tp, e.toString() );
119 if ( ForesterUtil.isEmpty( uri_str ) ) {
120 final String v = ForesterUtil.extractGenbankAccessor( node );
121 if ( !ForesterUtil.isEmpty( v ) ) {
123 if ( SequenceIdParser.isProtein( v ) ) {
124 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
127 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
130 catch ( final UnsupportedEncodingException e ) {
131 showErrorMessage( tp, e.toString() );
136 if ( ForesterUtil.isEmpty( uri_str ) ) {
137 final String v = ForesterUtil.extractRefSeqAccessorAccessor( node );
138 if ( !ForesterUtil.isEmpty( v ) ) {
140 if ( SequenceIdParser.isProtein( v ) ) {
141 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
144 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
147 catch ( final UnsupportedEncodingException e ) {
148 showErrorMessage( tp, e.toString() );
156 public static MaskFormatter createMaskFormatter( final String s ) {
157 MaskFormatter formatter = null;
159 formatter = new MaskFormatter( s );
161 catch ( final ParseException e ) {
162 throw new IllegalArgumentException( e );
167 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
168 final PhylogenyNodeIterator it = phy.iteratorPostorder();
169 while ( it.hasNext() ) {
170 if ( it.next().getNodeData().isHasEvent() ) {
178 * Returns true if at least one branch has a length larger than zero.
183 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
184 final PhylogenyNodeIterator it = phy.iteratorPostorder();
185 while ( it.hasNext() ) {
186 if ( it.next().getDistanceToParent() > 0.0 ) {
193 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
194 final PhylogenyNodeIterator it = phy.iteratorPostorder();
195 while ( it.hasNext() ) {
196 if ( it.next().getBranchData().isHasConfidences() ) {
203 final public static void launchWebBrowser( final URI uri,
204 final boolean is_applet,
205 final JApplet applet,
206 final String frame_name ) throws IOException {
208 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
211 // This requires Java 1.6:
212 // =======================
213 // boolean no_desktop = false;
215 // if ( Desktop.isDesktopSupported() ) {
216 // System.out.println( "desktop supported" );
217 // final Desktop dt = Desktop.getDesktop();
221 // no_desktop = true;
224 // catch ( final Exception ex ) {
225 // ex.printStackTrace();
226 // no_desktop = true;
228 // catch ( final Error er ) {
229 // er.printStackTrace();
230 // no_desktop = true;
232 // if ( no_desktop ) {
233 // System.out.println( "desktop not supported" );
235 openUrlInWebBrowser( uri.toString() );
237 catch ( final Exception e ) {
238 throw new IOException( e );
244 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
245 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
246 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
247 for( final PhylogenyNode n : descs ) {
248 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
249 tax_set.add( n.getNodeData().getTaxonomy() );
256 * Returns the set of distinct taxonomies of
257 * all external nodes of node.
258 * If at least one the external nodes has no taxonomy,
262 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
263 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
264 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
265 for( final PhylogenyNode n : descs ) {
266 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
269 tax_set.add( n.getNodeData().getTaxonomy() );
274 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
275 final String n = sequence_name.trim();
276 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
279 if ( matcher1.matches() ) {
280 group1 = matcher1.group( 1 );
281 group2 = matcher1.group( 2 );
284 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
285 if ( matcher2.matches() ) {
286 group1 = matcher2.group( 1 );
287 group2 = matcher2.group( 2 );
290 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
293 return new Accession( group2, group1 );
296 public final static void printWarningMessage( final String name, final String message ) {
297 System.out.println( "[" + name + "] > " + message );
300 final public static void showErrorMessage( final Component parent, final String error_msg ) {
301 printAppletMessage( Constants.PRG_NAME, error_msg );
302 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
303 + "] Error", JOptionPane.ERROR_MESSAGE );
306 public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
307 final PhylogenyNode node,
308 final List<String> data ) {
309 final StringBuilder sb = new StringBuilder();
310 if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
311 showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
313 if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
314 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
315 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
317 if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
318 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
319 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
321 if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
322 && ( node.getNodeData().getSequence().getAccession() != null )
323 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
324 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
326 if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
327 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
328 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
330 if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
331 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
332 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
334 if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
335 && node.getNodeData().isHasSequence()
336 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
337 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
339 final String s = sb.toString().trim();
340 if ( !ForesterUtil.isEmpty( s ) ) {
345 public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
346 if ( sb.length() > 0 ) {
352 final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
353 JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
356 public static void writePhylogenyToGraphicsFile( final File intree,
360 final GraphicsExportType type,
361 final Configuration config ) throws IOException {
362 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
363 Phylogeny[] phys = null;
364 phys = PhylogenyMethods.readPhylogenies( parser, intree );
365 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
368 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
372 final GraphicsExportType type,
373 final Configuration config ) throws IOException {
374 final Phylogeny[] phys = new Phylogeny[ 1 ];
376 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
377 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
378 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
382 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
385 final TreePanel tree_panel,
386 final ControlPanel ac,
387 final GraphicsExportType type,
388 final Options options ) throws IOException {
389 tree_panel.calcParametersForPainting( width, height, true );
390 tree_panel.resetPreferredSize();
391 tree_panel.repaint();
392 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
393 RenderingHints.VALUE_RENDER_QUALITY );
394 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
395 if ( options.isAntialiasPrint() ) {
396 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
397 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
400 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
401 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
403 final Phylogeny phylogeny = tree_panel.getPhylogeny();
404 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
407 if ( outfile.isDirectory() ) {
408 throw new IOException( "\"" + outfile + "\" is a directory" );
410 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
411 final Graphics2D g2d = buffered_img.createGraphics();
412 g2d.setRenderingHints( rendering_hints );
413 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
414 if ( type == GraphicsExportType.TIFF ) {
415 writeToTiff( outfile, buffered_img );
418 ImageIO.write( buffered_img, type.toString(), outfile );
423 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
424 final String default_name,
425 final String full_path,
426 final Configuration configuration,
427 final MainPanel main_panel ) {
428 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
429 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
430 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
431 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
434 for( final Phylogeny phy : phys ) {
435 if ( !phy.isEmpty() ) {
436 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
438 String my_name_for_file = "";
439 if ( phys.length > 1 ) {
440 if ( !ForesterUtil.isEmpty( default_name ) ) {
441 my_name = new String( default_name );
443 if ( !ForesterUtil.isEmpty( full_path ) ) {
444 my_name_for_file = new String( full_path );
446 else if ( !ForesterUtil.isEmpty( default_name ) ) {
447 my_name_for_file = new String( default_name );
450 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
451 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
452 my_name_for_file.length() );
453 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
455 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
456 my_name_for_file += "_";
458 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
459 my_name_for_file += phy.getName().replaceAll( " ", "_" );
461 else if ( phy.getIdentifier() != null ) {
462 final StringBuffer sb = new StringBuffer();
463 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
464 sb.append( phy.getIdentifier().getProvider() );
467 sb.append( phy.getIdentifier().getValue() );
468 my_name_for_file += sb;
471 my_name_for_file += i;
473 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
474 && ( phy.getIdentifier() == null ) ) {
475 my_name = my_name + " [" + i + "]";
477 if ( !ForesterUtil.isEmpty( suffix ) ) {
478 my_name_for_file += suffix;
482 if ( !ForesterUtil.isEmpty( default_name ) ) {
483 my_name = new String( default_name );
485 my_name_for_file = "";
486 if ( !ForesterUtil.isEmpty( full_path ) ) {
487 my_name_for_file = new String( full_path );
489 else if ( !ForesterUtil.isEmpty( default_name ) ) {
490 my_name_for_file = new String( default_name );
492 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
493 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
494 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
496 else if ( phy.getIdentifier() != null ) {
497 final StringBuffer sb = new StringBuffer();
498 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
499 sb.append( phy.getIdentifier().getProvider() );
502 sb.append( phy.getIdentifier().getValue() );
503 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
507 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
508 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
509 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
516 final static void addPhylogenyToPanel( final Phylogeny[] phys,
517 final Configuration configuration,
518 final MainPanel main_panel ) {
519 final Phylogeny phy = phys[ 0 ];
520 main_panel.addPhylogenyInPanel( phy, configuration );
521 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
524 final static Color calculateColorFromString( final String str ) {
525 final String species_uc = str.toUpperCase();
526 char first = species_uc.charAt( 0 );
529 if ( species_uc.length() > 1 ) {
530 second = species_uc.charAt( 1 );
531 if ( species_uc.length() > 2 ) {
532 if ( species_uc.indexOf( " " ) > 0 ) {
533 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
536 third = species_uc.charAt( 2 );
540 first = AptxUtil.normalizeCharForRGB( first );
541 second = AptxUtil.normalizeCharForRGB( second );
542 third = AptxUtil.normalizeCharForRGB( third );
543 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
546 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
549 return new Color( first, second, third );
552 // Returns true if the specified format name can be written
553 final static boolean canWriteFormat( final String format_name ) {
554 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
555 return iter.hasNext();
558 final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
559 boolean inferred = false;
560 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
561 final PhylogenyNode n = it.next();
562 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
563 final Set<Taxonomy> taxs = obtainDistinctTaxonomies( n );
564 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
565 AptxUtil.collapseSubtree( n, true );
566 if ( !n.getNodeData().isHasTaxonomy() ) {
567 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
568 .getTaxonomy().copy() );
573 n.setCollapse( false );
578 phy.setRerootable( false );
582 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
583 node.setCollapse( collapse );
584 if ( node.isExternal() ) {
587 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
588 while ( it.hasNext() ) {
589 it.next().setCollapse( collapse );
593 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
594 double max_conf = 0.0;
595 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
596 final PhylogenyNode n = it.next();
597 n.getBranchData().setBranchColor( null );
598 if ( n.getBranchData().isHasConfidences() ) {
599 final double conf = PhylogenyMethods.getConfidenceValue( n );
600 if ( conf > max_conf ) {
605 if ( max_conf > 0.0 ) {
606 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
607 final Color br = tree_panel.getTreeColorSet().getBranchColor();
608 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
609 final PhylogenyNode n = it.next();
610 if ( n.getBranchData().isHasConfidences() ) {
611 final double conf = PhylogenyMethods.getConfidenceValue( n );
612 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
613 colorizeSubtree( n, c );
619 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
620 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
621 it.next().getBranchData().setBranchColor( null );
623 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
624 final PhylogenyNode n = it.next();
625 if ( !n.getBranchData().isHasBranchColor() ) {
626 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
628 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
629 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
630 for( final PhylogenyNode desc : descs ) {
632 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
639 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
640 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
641 int colorizations = 0;
642 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
643 final PhylogenyNode n = it.next();
644 if ( n.getNodeData().isHasTaxonomy()
645 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
646 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
647 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
648 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
649 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
650 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
652 colorizeSubtree( n, c );
654 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
655 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
660 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
661 final PhylogenyNode node = it.next();
662 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
663 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
664 boolean success = false;
665 if ( !true_lineage_to_color_map.isEmpty() ) {
666 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
667 if ( true_lineage_to_color_map.containsKey( lin ) ) {
668 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
676 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
677 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
678 final Taxonomy temp_tax = new Taxonomy();
679 temp_tax.setScientificName( lin );
680 if ( lineage_to_rank_map.containsKey( lin )
681 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
682 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
683 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
684 colorizeSubtree( node, c );
686 true_lineage_to_color_map.put( lin, c.getValue() );
690 UniProtTaxonomy up = null;
692 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
694 catch ( final Exception e ) {
697 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
698 lineage_to_rank_map.put( lin, up.getRank() );
699 if ( up.getRank().equalsIgnoreCase( rank ) ) {
700 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
701 colorizeSubtree( node, c );
703 true_lineage_to_color_map.put( lin, c.getValue() );
712 return colorizations;
715 final static String createBasicInformation( final Phylogeny phy ) {
716 final StringBuilder desc = new StringBuilder();
717 if ( ( phy != null ) && !phy.isEmpty() ) {
718 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
719 desc.append( "Name: " );
720 desc.append( phy.getName() );
723 if ( phy.getIdentifier() != null ) {
724 desc.append( "Id: " );
725 desc.append( phy.getIdentifier().toString() );
728 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
729 desc.append( "Description: " );
730 desc.append( phy.getDescription() );
733 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
734 desc.append( "Distance Unit: " );
735 desc.append( phy.getDistanceUnit() );
738 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
739 desc.append( "Type: " );
740 desc.append( phy.getType() );
743 desc.append( "Rooted: " );
744 desc.append( phy.isRooted() );
746 desc.append( "Rerootable: " );
747 desc.append( phy.isRerootable() );
749 desc.append( "Nodes: " );
750 desc.append( phy.getNodeCount() );
752 desc.append( "External nodes: " );
753 desc.append( phy.getNumberOfExternalNodes() );
755 desc.append( "Internal nodes: " );
756 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
758 desc.append( "Internal nodes with polytomies: " );
759 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
761 desc.append( "Branches: " );
762 desc.append( phy.getNumberOfBranches() );
764 desc.append( "Depth: " );
765 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
767 desc.append( "Maximum distance to root: " );
768 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
770 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
771 if ( taxs != null ) {
772 desc.append( "Distinct external taxonomies: " );
773 desc.append( taxs.size() );
776 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
777 if ( bs.getN() > 3 ) {
779 desc.append( "Branch-length statistics: " );
781 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
783 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
785 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
787 desc.append( " SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
789 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
791 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
793 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
795 final AsciiHistogram histo = new AsciiHistogram( bs );
796 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
799 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
800 if ( ds.getN() > 2 ) {
802 desc.append( "Descendants per node statistics: " );
804 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
806 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
808 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
810 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
812 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
815 List<DescriptiveStatistics> css = null;
817 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
819 catch ( final IllegalArgumentException e ) {
820 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
822 if ( ( css != null ) && ( css.size() > 0 ) ) {
824 for( int i = 0; i < css.size(); ++i ) {
825 final DescriptiveStatistics cs = css.get( i );
826 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
827 if ( css.size() > 1 ) {
828 desc.append( "Support statistics " + ( i + 1 ) + ": " );
831 desc.append( "Support statistics: " );
833 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
835 desc.append( " Type: " + cs.getDescription() );
838 desc.append( " Branches with support: " + cs.getN() );
840 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
842 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
844 if ( cs.getN() > 2 ) {
845 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
848 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
850 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
856 return desc.toString();
864 * to message to be printed
866 final static void dieWithSystemError( final String message ) {
867 System.out.println();
868 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
869 System.out.println( "Please contact the authors." );
870 System.out.println( Constants.PRG_NAME + " needs to close." );
871 System.out.println();
875 final static String[] getAllPossibleRanks() {
876 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
878 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
879 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
880 str_array[ i++ ] = e;
886 final static String[] getAllRanks( final Phylogeny tree ) {
887 final SortedSet<String> ranks = new TreeSet<String>();
888 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
889 final PhylogenyNode n = it.next();
890 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
891 ranks.add( n.getNodeData().getTaxonomy().getRank() );
894 return ForesterUtil.stringSetToArray( ranks );
897 final static String[] getAvailableFontFamiliesSorted() {
898 return AVAILABLE_FONT_FAMILIES_SORTED;
901 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
902 if ( !node.getNodeData().isHasEvent() ) {
905 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
911 final static boolean isMac() {
913 final String s = ForesterUtil.OS_NAME.toLowerCase();
914 return s.startsWith( "mac" );
916 catch ( final Exception e ) {
917 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
922 final static boolean isUsOrCanada() {
924 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
928 catch ( final Exception e ) {
934 final static boolean isWindows() {
936 final String s = ForesterUtil.OS_NAME.toLowerCase();
937 return s.indexOf( "win" ) > -1;
939 catch ( final Exception e ) {
940 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
945 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
946 final ControlPanel atv_control,
947 final Configuration configuration ) {
948 if ( ( t != null ) && !t.isEmpty() ) {
949 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
950 atv_control.setDrawPhylogram( false );
951 atv_control.setDrawPhylogramEnabled( false );
953 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
954 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
955 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
956 atv_control.setDrawPhylogram( true );
957 atv_control.setDrawPhylogramEnabled( true );
960 atv_control.setDrawPhylogram( false );
964 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
965 if ( atv_control.getWriteConfidenceCb() != null ) {
966 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
967 atv_control.setCheckbox( Configuration.write_confidence_values, true );
970 atv_control.setCheckbox( Configuration.write_confidence_values, false );
974 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
975 if ( atv_control.getShowEventsCb() != null ) {
976 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
977 atv_control.setCheckbox( Configuration.write_events, true );
980 atv_control.setCheckbox( Configuration.write_events, false );
987 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
989 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
991 catch ( final Exception e ) {
992 throw new IOException( e );
996 final static void outOfMemoryError( final OutOfMemoryError e ) {
997 System.err.println();
998 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
999 System.err.println();
1000 e.printStackTrace();
1001 System.err.println();
1002 JOptionPane.showMessageDialog( null,
1003 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
1004 + "\n\nError: " + e.getLocalizedMessage(),
1005 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1006 JOptionPane.ERROR_MESSAGE );
1010 final static void printAppletMessage( final String applet_name, final String message ) {
1011 System.out.println( "[" + applet_name + "] > " + message );
1014 final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
1015 final boolean phyloxml_validate_against_xsd,
1016 final boolean replace_underscores,
1017 final boolean internal_numbers_are_confidences,
1018 final TAXONOMY_EXTRACTION taxonomy_extraction )
1019 throws FileNotFoundException, IOException {
1020 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1021 final PhylogenyParser parser;
1022 boolean nhx_or_nexus = false;
1023 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1024 parser = new TolParser();
1027 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
1028 if ( parser instanceof NHXParser ) {
1029 nhx_or_nexus = true;
1030 final NHXParser nhx = ( NHXParser ) parser;
1031 nhx.setReplaceUnderscores( replace_underscores );
1032 nhx.setIgnoreQuotes( false );
1033 nhx.setTaxonomyExtraction( taxonomy_extraction );
1035 else if ( parser instanceof NexusPhylogeniesParser ) {
1036 nhx_or_nexus = true;
1037 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1038 nex.setReplaceUnderscores( replace_underscores );
1039 nex.setIgnoreQuotes( false );
1042 final Phylogeny[] phys = factory.create( url.openStream(), parser );
1043 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
1044 for( final Phylogeny phy : phys ) {
1045 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1051 final static void removeBranchColors( final Phylogeny phy ) {
1052 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1053 it.next().getBranchData().setBranchColor( null );
1057 final static void unexpectedError( final Error e ) {
1058 System.err.println();
1059 e.printStackTrace( System.err );
1060 System.err.println();
1061 final StringBuffer sb = new StringBuffer();
1062 for( final StackTraceElement s : e.getStackTrace() ) {
1063 sb.append( s + "\n" );
1066 .showMessageDialog( null,
1067 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
1068 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
1070 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1071 JOptionPane.ERROR_MESSAGE );
1075 final static void unexpectedException( final Exception e ) {
1076 System.err.println();
1077 e.printStackTrace( System.err );
1078 System.err.println();
1079 final StringBuffer sb = new StringBuffer();
1080 for( final StackTraceElement s : e.getStackTrace() ) {
1081 sb.append( s + "\n" );
1083 JOptionPane.showMessageDialog( null,
1084 "An unexpected exception has occured. \nPlease contact: "
1085 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
1087 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
1088 JOptionPane.ERROR_MESSAGE );
1091 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1094 final TreePanel tree_panel,
1095 final ControlPanel ac,
1096 final GraphicsExportType type,
1097 final Options options ) throws IOException {
1098 if ( !options.isGraphicsExportUsingActualSize() ) {
1099 if ( options.isGraphicsExportVisibleOnly() ) {
1100 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1102 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1103 tree_panel.resetPreferredSize();
1104 tree_panel.repaint();
1106 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1107 RenderingHints.VALUE_RENDER_QUALITY );
1108 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1109 if ( options.isAntialiasPrint() ) {
1110 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1111 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1114 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1115 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1117 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1118 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1121 Rectangle visible = null;
1122 if ( !options.isGraphicsExportUsingActualSize() ) {
1123 width = options.getPrintSizeX();
1124 height = options.getPrintSizeY();
1126 else if ( options.isGraphicsExportVisibleOnly() ) {
1127 visible = tree_panel.getVisibleRect();
1128 width = visible.width;
1129 height = visible.height;
1131 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1132 Graphics2D g2d = buffered_img.createGraphics();
1133 g2d.setRenderingHints( rendering_hints );
1136 if ( options.isGraphicsExportVisibleOnly() ) {
1137 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1138 g2d.setClip( null );
1142 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1143 ImageIO.write( buffered_img, type.toString(), baos );
1146 if ( !options.isGraphicsExportUsingActualSize() ) {
1147 tree_panel.getMainPanel().getControlPanel().showWhole();
1149 String msg = baos.toString();
1150 if ( ( width > 0 ) && ( height > 0 ) ) {
1151 msg += " [size: " + width + ", " + height + "]";
1156 final static String writePhylogenyToGraphicsFile( final String file_name,
1159 final TreePanel tree_panel,
1160 final ControlPanel ac,
1161 final GraphicsExportType type,
1162 final Options options ) throws IOException {
1163 if ( !options.isGraphicsExportUsingActualSize() ) {
1164 if ( options.isGraphicsExportVisibleOnly() ) {
1165 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1167 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1168 tree_panel.resetPreferredSize();
1169 tree_panel.repaint();
1171 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1172 RenderingHints.VALUE_RENDER_QUALITY );
1173 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1174 if ( options.isAntialiasPrint() ) {
1175 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1176 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1179 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1180 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1182 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1183 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1186 final File file = new File( file_name );
1187 if ( file.isDirectory() ) {
1188 throw new IOException( "\"" + file_name + "\" is a directory" );
1190 Rectangle visible = null;
1191 if ( !options.isGraphicsExportUsingActualSize() ) {
1192 width = options.getPrintSizeX();
1193 height = options.getPrintSizeY();
1195 else if ( options.isGraphicsExportVisibleOnly() ) {
1196 visible = tree_panel.getVisibleRect();
1197 width = visible.width;
1198 height = visible.height;
1200 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1201 Graphics2D g2d = buffered_img.createGraphics();
1202 g2d.setRenderingHints( rendering_hints );
1205 if ( options.isGraphicsExportVisibleOnly() ) {
1206 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1207 g2d.setClip( null );
1211 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1212 if ( type == GraphicsExportType.TIFF ) {
1213 writeToTiff( file, buffered_img );
1216 ImageIO.write( buffered_img, type.toString(), file );
1220 if ( !options.isGraphicsExportUsingActualSize() ) {
1221 tree_panel.getMainPanel().getControlPanel().showWhole();
1223 String msg = file.toString();
1224 if ( ( width > 0 ) && ( height > 0 ) ) {
1225 msg += " [size: " + width + ", " + height + "]";
1230 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1231 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1232 ImageWriter writer = null;
1233 ImageOutputStream ios = null;
1234 // Find an appropriate writer:
1235 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1236 if ( it.hasNext() ) {
1240 throw new IOException( "failed to get TIFF image writer" );
1243 ios = ImageIO.createImageOutputStream( file );
1244 writer.setOutput( ios );
1245 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1246 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1247 // see writeParam.getCompressionTypes() for available compression type
1249 image_write_param.setCompressionType( "PackBits" );
1250 final String t[] = image_write_param.getCompressionTypes();
1251 for( final String string : t ) {
1252 System.out.println( string );
1254 // Convert to an IIOImage:
1255 final IIOImage iio_image = new IIOImage( image, null, null );
1256 writer.write( null, iio_image, image_write_param );
1259 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1260 node.getBranchData().setBranchColor( c );
1261 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1262 for( final PhylogenyNode desc : descs ) {
1263 desc.getBranchData().setBranchColor( c );
1267 final private static char normalizeCharForRGB( char c ) {
1270 c = c > 255 ? 255 : c;
1275 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1276 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1277 InvocationTargetException, InterruptedException {
1278 final String os = System.getProperty( "os.name" );
1279 final Runtime runtime = Runtime.getRuntime();
1280 if ( os.toLowerCase().startsWith( "win" ) ) {
1281 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1283 else if ( isMac() ) {
1284 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1285 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1286 open_url.invoke( null, new Object[] { url } );
1289 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1290 String browser = null;
1291 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1292 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1293 browser = browsers[ i ];
1296 if ( browser == null ) {
1297 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1300 runtime.exec( new String[] { browser, url } );
1305 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1306 // static void openDDBJRest() throws IOException {
1308 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1310 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1311 // //make connection
1312 // URLConnection urlc = url.openConnection();
1314 // urlc.setDoOutput( true );
1315 // urlc.setAllowUserInteraction( false );
1317 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1318 // ps.print( query );
1321 // BufferedReader br = new BufferedReader( new InputStreamReader(
1322 // urlc.getInputStream() ) );
1324 // while ( ( l = br.readLine() ) != null ) {
1325 // System.out.println( l );
1329 public static enum GraphicsExportType {
1330 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1332 private final String _suffix;
1334 private GraphicsExportType( final String suffix ) {
1339 public String toString() {