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.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
79 import org.forester.phylogeny.PhylogenyNode;
80 import org.forester.phylogeny.data.Accession;
81 import org.forester.phylogeny.data.BranchColor;
82 import org.forester.phylogeny.data.Taxonomy;
83 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
84 import org.forester.phylogeny.factories.PhylogenyFactory;
85 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
86 import org.forester.phylogeny.iterators.PreorderTreeIterator;
87 import org.forester.util.AsciiHistogram;
88 import org.forester.util.DescriptiveStatistics;
89 import org.forester.util.ForesterConstants;
90 import org.forester.util.ForesterUtil;
91 import org.forester.util.SequenceIdParser;
92 import org.forester.ws.seqdb.UniProtTaxonomy;
94 public final class AptxUtil {
96 private final static Pattern seq_identifier_pattern_1 = Pattern
97 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
98 private final static Pattern seq_identifier_pattern_2 = Pattern
99 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
100 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
101 .getAvailableFontFamilyNames();
103 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
106 public final static String createUriForSeqWeb( final PhylogenyNode node,
107 final Configuration conf,
108 final TreePanel tp ) {
109 String uri_str = null;
110 final String upkb = ForesterUtil.extractUniProtKbProteinSeqIdentifier( node );
111 if ( !ForesterUtil.isEmpty( upkb ) ) {
113 uri_str = ForesterUtil.UNIPROT_KB + URLEncoder.encode( upkb, ForesterConstants.UTF8 );
115 catch ( final UnsupportedEncodingException e ) {
116 showErrorMessage( tp, e.toString() );
120 if ( ForesterUtil.isEmpty( uri_str ) ) {
121 final String v = ForesterUtil.extractGenbankAccessor( node );
122 if ( !ForesterUtil.isEmpty( v ) ) {
124 if ( SequenceIdParser.isProtein( v ) ) {
125 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
128 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
131 catch ( final UnsupportedEncodingException e ) {
132 showErrorMessage( tp, e.toString() );
137 if ( ForesterUtil.isEmpty( uri_str ) ) {
138 final String v = ForesterUtil.extractRefSeqAccessorAccessor( node );
139 if ( !ForesterUtil.isEmpty( v ) ) {
141 if ( SequenceIdParser.isProtein( v ) ) {
142 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
145 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
148 catch ( final UnsupportedEncodingException e ) {
149 showErrorMessage( tp, e.toString() );
154 if ( ForesterUtil.isEmpty( uri_str ) ) {
155 final String v = ForesterUtil.extractGInumber( node );
156 if ( !ForesterUtil.isEmpty( v ) ) {
158 uri_str = ForesterUtil.NCBI_GI + URLEncoder.encode( v, ForesterConstants.UTF8 );
160 catch ( final UnsupportedEncodingException e ) {
161 showErrorMessage( tp, e.toString() );
169 public static MaskFormatter createMaskFormatter( final String s ) {
170 MaskFormatter formatter = null;
172 formatter = new MaskFormatter( s );
174 catch ( final ParseException e ) {
175 throw new IllegalArgumentException( e );
180 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
181 final PhylogenyNodeIterator it = phy.iteratorPostorder();
182 while ( it.hasNext() ) {
183 if ( it.next().getNodeData().isHasEvent() ) {
191 * Returns true if at least one branch has a length larger than zero.
196 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
197 final PhylogenyNodeIterator it = phy.iteratorPostorder();
198 while ( it.hasNext() ) {
199 if ( it.next().getDistanceToParent() > 0.0 ) {
206 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
207 final PhylogenyNodeIterator it = phy.iteratorPostorder();
208 while ( it.hasNext() ) {
209 if ( it.next().getBranchData().isHasConfidences() ) {
216 final public static void launchWebBrowser( final URI uri,
217 final boolean is_applet,
218 final JApplet applet,
219 final String frame_name ) throws IOException {
221 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
224 // This requires Java 1.6:
225 // =======================
226 // boolean no_desktop = false;
228 // if ( Desktop.isDesktopSupported() ) {
229 // System.out.println( "desktop supported" );
230 // final Desktop dt = Desktop.getDesktop();
234 // no_desktop = true;
237 // catch ( final Exception ex ) {
238 // ex.printStackTrace();
239 // no_desktop = true;
241 // catch ( final Error er ) {
242 // er.printStackTrace();
243 // no_desktop = true;
245 // if ( no_desktop ) {
246 // System.out.println( "desktop not supported" );
248 openUrlInWebBrowser( uri.toString() );
250 catch ( final Exception e ) {
251 throw new IOException( e );
257 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
258 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
259 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
260 for( final PhylogenyNode n : descs ) {
261 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
262 tax_set.add( n.getNodeData().getTaxonomy() );
269 * Returns the set of distinct taxonomies of
270 * all external nodes of node.
271 * If at least one the external nodes has no taxonomy,
275 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
276 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
277 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
278 for( final PhylogenyNode n : descs ) {
279 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
282 tax_set.add( n.getNodeData().getTaxonomy() );
287 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
288 final String n = sequence_name.trim();
289 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
292 if ( matcher1.matches() ) {
293 group1 = matcher1.group( 1 );
294 group2 = matcher1.group( 2 );
297 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
298 if ( matcher2.matches() ) {
299 group1 = matcher2.group( 1 );
300 group2 = matcher2.group( 2 );
303 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
306 return new Accession( group2, group1 );
309 public final static void printWarningMessage( final String name, final String message ) {
310 System.out.println( "[" + name + "] > " + message );
313 final public static void showErrorMessage( final Component parent, final String error_msg ) {
314 printAppletMessage( Constants.PRG_NAME, error_msg );
315 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
316 + "] Error", JOptionPane.ERROR_MESSAGE );
319 public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
320 final PhylogenyNode node,
321 final List<String> data ) {
322 final StringBuilder sb = new StringBuilder();
323 if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
324 showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
326 if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
327 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
328 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
330 if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
331 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
332 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
334 if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
335 && ( node.getNodeData().getSequence().getAccession() != null )
336 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
337 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
339 if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
340 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
341 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
343 if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
344 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
345 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
347 if ( cp.isShowTaxonomyCommonNames() && node.getNodeData().isHasTaxonomy()
348 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getCommonName() ) ) {
349 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getCommonName(), sb );
351 if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
352 && node.getNodeData().isHasSequence()
353 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
354 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
356 final String s = sb.toString().trim();
357 if ( !ForesterUtil.isEmpty( s ) ) {
362 public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
363 if ( sb.length() > 0 ) {
369 final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
370 JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
373 public static void writePhylogenyToGraphicsFile( final File intree,
377 final GraphicsExportType type,
378 final Configuration config ) throws IOException {
379 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
380 Phylogeny[] phys = null;
381 phys = PhylogenyMethods.readPhylogenies( parser, intree );
382 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
385 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
389 final GraphicsExportType type,
390 final Configuration config ) throws IOException {
391 final Phylogeny[] phys = new Phylogeny[ 1 ];
393 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
394 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
395 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
399 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
402 final TreePanel tree_panel,
403 final ControlPanel ac,
404 final GraphicsExportType type,
405 final Options options ) throws IOException {
406 tree_panel.calcParametersForPainting( width, height, true );
407 tree_panel.resetPreferredSize();
408 tree_panel.repaint();
409 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
410 RenderingHints.VALUE_RENDER_QUALITY );
411 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
412 if ( options.isAntialiasPrint() ) {
413 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
414 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
417 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
418 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
420 final Phylogeny phylogeny = tree_panel.getPhylogeny();
421 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
424 if ( outfile.isDirectory() ) {
425 throw new IOException( "\"" + outfile + "\" is a directory" );
427 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
428 final Graphics2D g2d = buffered_img.createGraphics();
429 g2d.setRenderingHints( rendering_hints );
430 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
431 if ( type == GraphicsExportType.TIFF ) {
432 writeToTiff( outfile, buffered_img );
435 ImageIO.write( buffered_img, type.toString(), outfile );
440 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
441 final String default_name,
442 final String full_path,
443 final Configuration configuration,
444 final MainPanel main_panel ) {
445 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
446 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
447 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
448 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
451 for( final Phylogeny phy : phys ) {
452 if ( !phy.isEmpty() ) {
453 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
455 String my_name_for_file = "";
456 if ( phys.length > 1 ) {
457 if ( !ForesterUtil.isEmpty( default_name ) ) {
458 my_name = new String( default_name );
460 if ( !ForesterUtil.isEmpty( full_path ) ) {
461 my_name_for_file = new String( full_path );
463 else if ( !ForesterUtil.isEmpty( default_name ) ) {
464 my_name_for_file = new String( default_name );
467 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
468 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
469 my_name_for_file.length() );
470 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
472 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
473 my_name_for_file += "_";
475 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
476 my_name_for_file += phy.getName().replaceAll( " ", "_" );
478 else if ( phy.getIdentifier() != null ) {
479 final StringBuffer sb = new StringBuffer();
480 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
481 sb.append( phy.getIdentifier().getProvider() );
484 sb.append( phy.getIdentifier().getValue() );
485 my_name_for_file += sb;
488 my_name_for_file += i;
490 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
491 && ( phy.getIdentifier() == null ) ) {
492 my_name = my_name + " [" + i + "]";
494 if ( !ForesterUtil.isEmpty( suffix ) ) {
495 my_name_for_file += suffix;
499 if ( !ForesterUtil.isEmpty( default_name ) ) {
500 my_name = new String( default_name );
502 my_name_for_file = "";
503 if ( !ForesterUtil.isEmpty( full_path ) ) {
504 my_name_for_file = new String( full_path );
506 else if ( !ForesterUtil.isEmpty( default_name ) ) {
507 my_name_for_file = new String( default_name );
509 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
510 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
511 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
513 else if ( phy.getIdentifier() != null ) {
514 final StringBuffer sb = new StringBuffer();
515 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
516 sb.append( phy.getIdentifier().getProvider() );
519 sb.append( phy.getIdentifier().getValue() );
520 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
524 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
525 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
526 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
533 final static void addPhylogenyToPanel( final Phylogeny[] phys,
534 final Configuration configuration,
535 final MainPanel main_panel ) {
536 final Phylogeny phy = phys[ 0 ];
537 main_panel.addPhylogenyInPanel( phy, configuration );
538 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
541 final static Color calculateColorFromString( final String str ) {
542 final String species_uc = str.toUpperCase();
543 char first = species_uc.charAt( 0 );
546 if ( species_uc.length() > 1 ) {
547 second = species_uc.charAt( 1 );
548 if ( species_uc.length() > 2 ) {
549 if ( species_uc.indexOf( " " ) > 0 ) {
550 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
553 third = species_uc.charAt( 2 );
557 first = AptxUtil.normalizeCharForRGB( first );
558 second = AptxUtil.normalizeCharForRGB( second );
559 third = AptxUtil.normalizeCharForRGB( third );
560 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
563 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
566 return new Color( first, second, third );
569 // Returns true if the specified format name can be written
570 final static boolean canWriteFormat( final String format_name ) {
571 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
572 return iter.hasNext();
575 final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
576 boolean inferred = false;
577 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
578 final PhylogenyNode n = it.next();
579 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
580 final Set<Taxonomy> taxs = obtainDistinctTaxonomies( n );
581 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
582 AptxUtil.collapseSubtree( n, true );
583 if ( !n.getNodeData().isHasTaxonomy() ) {
584 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
585 .getTaxonomy().copy() );
590 n.setCollapse( false );
595 phy.setRerootable( false );
599 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
600 node.setCollapse( collapse );
601 if ( node.isExternal() ) {
604 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
605 while ( it.hasNext() ) {
606 it.next().setCollapse( collapse );
610 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
611 double max_conf = 0.0;
612 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
613 final PhylogenyNode n = it.next();
614 n.getBranchData().setBranchColor( null );
615 if ( n.getBranchData().isHasConfidences() ) {
616 final double conf = PhylogenyMethods.getConfidenceValue( n );
617 if ( conf > max_conf ) {
622 if ( max_conf > 0.0 ) {
623 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
624 final Color br = tree_panel.getTreeColorSet().getBranchColor();
625 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
626 final PhylogenyNode n = it.next();
627 if ( n.getBranchData().isHasConfidences() ) {
628 final double conf = PhylogenyMethods.getConfidenceValue( n );
629 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
630 colorizeSubtree( n, c );
636 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
637 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
638 it.next().getBranchData().setBranchColor( null );
640 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
641 final PhylogenyNode n = it.next();
642 if ( !n.getBranchData().isHasBranchColor() ) {
643 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
645 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
646 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
647 for( final PhylogenyNode desc : descs ) {
649 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
656 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
657 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
658 int colorizations = 0;
659 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
660 final PhylogenyNode n = it.next();
661 if ( n.getNodeData().isHasTaxonomy()
662 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
663 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
664 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
665 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
666 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
667 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
669 colorizeSubtree( n, c );
671 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
672 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
677 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
678 final PhylogenyNode node = it.next();
679 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
680 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
681 boolean success = false;
682 if ( !true_lineage_to_color_map.isEmpty() ) {
683 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
684 if ( true_lineage_to_color_map.containsKey( lin ) ) {
685 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
693 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
694 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
695 final Taxonomy temp_tax = new Taxonomy();
696 temp_tax.setScientificName( lin );
697 if ( lineage_to_rank_map.containsKey( lin )
698 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
699 && lineage_to_rank_map.get( lin ).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() );
707 UniProtTaxonomy up = null;
709 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
711 catch ( final Exception e ) {
714 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
715 lineage_to_rank_map.put( lin, up.getRank() );
716 if ( up.getRank().equalsIgnoreCase( rank ) ) {
717 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
718 colorizeSubtree( node, c );
720 true_lineage_to_color_map.put( lin, c.getValue() );
729 return colorizations;
732 final static String createBasicInformation( final Phylogeny phy ) {
733 final StringBuilder desc = new StringBuilder();
734 if ( ( phy != null ) && !phy.isEmpty() ) {
735 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
736 desc.append( "Name: " );
737 desc.append( phy.getName() );
740 if ( phy.getIdentifier() != null ) {
741 desc.append( "Id: " );
742 desc.append( phy.getIdentifier().toString() );
745 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
746 desc.append( "Description: " );
747 desc.append( phy.getDescription() );
750 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
751 desc.append( "Distance Unit: " );
752 desc.append( phy.getDistanceUnit() );
755 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
756 desc.append( "Type: " );
757 desc.append( phy.getType() );
760 desc.append( "Rooted: " );
761 desc.append( phy.isRooted() );
763 desc.append( "Rerootable: " );
764 desc.append( phy.isRerootable() );
766 desc.append( "Nodes: " );
767 desc.append( phy.getNodeCount() );
769 desc.append( "External nodes: " );
770 desc.append( phy.getNumberOfExternalNodes() );
772 desc.append( "Internal nodes: " );
773 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
775 desc.append( "Internal nodes with polytomies: " );
776 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
778 desc.append( "Branches: " );
779 desc.append( phy.getNumberOfBranches() );
781 desc.append( "Depth: " );
782 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
784 desc.append( "Maximum distance to root: " );
785 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
787 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
788 if ( taxs != null ) {
789 desc.append( "Distinct external taxonomies: " );
790 desc.append( taxs.size() );
792 for( final Taxonomy t : taxs ) {
793 System.out.println( t.toString() );
796 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
797 if ( bs.getN() > 3 ) {
799 desc.append( "Branch-length statistics: " );
801 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
803 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
805 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
806 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
808 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
810 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
812 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
814 final AsciiHistogram histo = new AsciiHistogram( bs );
815 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
818 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
819 if ( ds.getN() > 2 ) {
821 desc.append( "Descendants per node statistics: " );
823 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
825 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) + " (stdev: "
826 + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) + ")" );
828 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
830 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
833 List<DescriptiveStatistics> css = null;
835 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
837 catch ( final IllegalArgumentException e ) {
838 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
840 if ( ( css != null ) && ( css.size() > 0 ) ) {
842 for( int i = 0; i < css.size(); ++i ) {
843 final DescriptiveStatistics cs = css.get( i );
844 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
845 if ( css.size() > 1 ) {
846 desc.append( "Support statistics " + ( i + 1 ) + ": " );
849 desc.append( "Support statistics: " );
851 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
853 desc.append( " Type: " + cs.getDescription() );
856 desc.append( " Branches with support: " + cs.getN() );
858 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
860 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
861 if ( cs.getN() > 2 ) {
862 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
865 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
867 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
873 return desc.toString();
881 * to message to be printed
883 final static void dieWithSystemError( final String message ) {
884 System.out.println();
885 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
886 System.out.println( "Please contact the authors." );
887 System.out.println( Constants.PRG_NAME + " needs to close." );
888 System.out.println();
892 final static String[] getAllPossibleRanks() {
893 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
895 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
896 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
897 str_array[ i++ ] = e;
903 final static String[] getAllRanks( final Phylogeny tree ) {
904 final SortedSet<String> ranks = new TreeSet<String>();
905 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
906 final PhylogenyNode n = it.next();
907 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
908 ranks.add( n.getNodeData().getTaxonomy().getRank() );
911 return ForesterUtil.stringSetToArray( ranks );
914 final static String[] getAvailableFontFamiliesSorted() {
915 return AVAILABLE_FONT_FAMILIES_SORTED;
918 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
919 if ( !node.getNodeData().isHasEvent() ) {
922 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
928 final static boolean isUsOrCanada() {
930 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
934 catch ( final Exception e ) {
940 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
941 final ControlPanel atv_control,
942 final Configuration configuration ) {
943 if ( ( t != null ) && !t.isEmpty() ) {
944 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
945 atv_control.setDrawPhylogram( false );
946 atv_control.setDrawPhylogramEnabled( false );
948 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
949 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
950 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
951 atv_control.setDrawPhylogram( true );
952 atv_control.setDrawPhylogramEnabled( true );
955 atv_control.setDrawPhylogram( false );
959 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
960 if ( atv_control.getWriteConfidenceCb() != null ) {
961 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
962 atv_control.setCheckbox( Configuration.write_confidence_values, true );
965 atv_control.setCheckbox( Configuration.write_confidence_values, false );
969 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
970 if ( atv_control.getShowEventsCb() != null ) {
971 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
972 atv_control.setCheckbox( Configuration.write_events, true );
975 atv_control.setCheckbox( Configuration.write_events, false );
982 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
984 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
986 catch ( final Exception e ) {
987 throw new IOException( e );
991 final static void outOfMemoryError( final OutOfMemoryError e ) {
992 System.err.println();
993 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
994 System.err.println();
996 System.err.println();
997 JOptionPane.showMessageDialog( null,
998 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
999 + "\n\nError: " + e.getLocalizedMessage(),
1000 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1001 JOptionPane.ERROR_MESSAGE );
1005 final static void printAppletMessage( final String applet_name, final String message ) {
1006 System.out.println( "[" + applet_name + "] > " + message );
1009 final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
1010 final boolean phyloxml_validate_against_xsd,
1011 final boolean replace_underscores,
1012 final boolean internal_numbers_are_confidences,
1013 final TAXONOMY_EXTRACTION taxonomy_extraction,
1014 final boolean midpoint_reroot ) throws FileNotFoundException,
1016 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1017 final PhylogenyParser parser;
1018 boolean nhx_or_nexus = false;
1019 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1020 parser = new TolParser();
1023 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
1024 if ( parser instanceof NHXParser ) {
1025 nhx_or_nexus = true;
1026 final NHXParser nhx = ( NHXParser ) parser;
1027 nhx.setReplaceUnderscores( replace_underscores );
1028 nhx.setIgnoreQuotes( false );
1029 nhx.setTaxonomyExtraction( taxonomy_extraction );
1031 else if ( parser instanceof NexusPhylogeniesParser ) {
1032 nhx_or_nexus = true;
1033 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1034 nex.setReplaceUnderscores( replace_underscores );
1035 nex.setIgnoreQuotes( false );
1038 final Phylogeny[] phys = factory.create( url.openStream(), parser );
1039 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
1040 for( final Phylogeny phy : phys ) {
1041 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1044 if ( midpoint_reroot ) {
1045 for( final Phylogeny phy : phys ) {
1046 PhylogenyMethods.midpointRoot( phy );
1047 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
1053 final static void removeBranchColors( final Phylogeny phy ) {
1054 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1055 it.next().getBranchData().setBranchColor( null );
1059 final static void unexpectedError( final Error e ) {
1060 System.err.println();
1061 e.printStackTrace( System.err );
1062 System.err.println();
1063 final StringBuffer sb = new StringBuffer();
1064 for( final StackTraceElement s : e.getStackTrace() ) {
1065 sb.append( s + "\n" );
1068 .showMessageDialog( null,
1069 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
1070 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
1072 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1073 JOptionPane.ERROR_MESSAGE );
1077 final static void unexpectedException( final Exception e ) {
1078 System.err.println();
1079 e.printStackTrace( System.err );
1080 System.err.println();
1081 final StringBuffer sb = new StringBuffer();
1082 for( final StackTraceElement s : e.getStackTrace() ) {
1083 sb.append( s + "\n" );
1085 JOptionPane.showMessageDialog( null,
1086 "An unexpected exception has occured. \nPlease contact: "
1087 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
1089 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
1090 JOptionPane.ERROR_MESSAGE );
1093 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1096 final TreePanel tree_panel,
1097 final ControlPanel ac,
1098 final GraphicsExportType type,
1099 final Options options ) throws IOException {
1100 if ( !options.isGraphicsExportUsingActualSize() ) {
1101 if ( options.isGraphicsExportVisibleOnly() ) {
1102 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1104 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1105 tree_panel.resetPreferredSize();
1106 tree_panel.repaint();
1108 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1109 RenderingHints.VALUE_RENDER_QUALITY );
1110 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1111 if ( options.isAntialiasPrint() ) {
1112 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1113 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1116 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1117 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1119 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1120 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1123 Rectangle visible = null;
1124 if ( !options.isGraphicsExportUsingActualSize() ) {
1125 width = options.getPrintSizeX();
1126 height = options.getPrintSizeY();
1128 else if ( options.isGraphicsExportVisibleOnly() ) {
1129 visible = tree_panel.getVisibleRect();
1130 width = visible.width;
1131 height = visible.height;
1133 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1134 Graphics2D g2d = buffered_img.createGraphics();
1135 g2d.setRenderingHints( rendering_hints );
1138 if ( options.isGraphicsExportVisibleOnly() ) {
1139 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1140 g2d.setClip( null );
1144 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1145 ImageIO.write( buffered_img, type.toString(), baos );
1148 if ( !options.isGraphicsExportUsingActualSize() ) {
1149 tree_panel.getMainPanel().getControlPanel().showWhole();
1151 String msg = baos.toString();
1152 if ( ( width > 0 ) && ( height > 0 ) ) {
1153 msg += " [size: " + width + ", " + height + "]";
1158 final static String writePhylogenyToGraphicsFile( final String file_name,
1161 final TreePanel tree_panel,
1162 final ControlPanel ac,
1163 final GraphicsExportType type,
1164 final Options options ) throws IOException {
1165 if ( !options.isGraphicsExportUsingActualSize() ) {
1166 if ( options.isGraphicsExportVisibleOnly() ) {
1167 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1169 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1170 tree_panel.resetPreferredSize();
1171 tree_panel.repaint();
1173 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1174 RenderingHints.VALUE_RENDER_QUALITY );
1175 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1176 if ( options.isAntialiasPrint() ) {
1177 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1178 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1181 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1182 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1184 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1185 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1188 final File file = new File( file_name );
1189 if ( file.isDirectory() ) {
1190 throw new IOException( "\"" + file_name + "\" is a directory" );
1192 Rectangle visible = null;
1193 if ( !options.isGraphicsExportUsingActualSize() ) {
1194 width = options.getPrintSizeX();
1195 height = options.getPrintSizeY();
1197 else if ( options.isGraphicsExportVisibleOnly() ) {
1198 visible = tree_panel.getVisibleRect();
1199 width = visible.width;
1200 height = visible.height;
1202 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1203 Graphics2D g2d = buffered_img.createGraphics();
1204 g2d.setRenderingHints( rendering_hints );
1207 if ( options.isGraphicsExportVisibleOnly() ) {
1208 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1209 g2d.setClip( null );
1213 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1214 if ( type == GraphicsExportType.TIFF ) {
1215 writeToTiff( file, buffered_img );
1218 ImageIO.write( buffered_img, type.toString(), file );
1222 if ( !options.isGraphicsExportUsingActualSize() ) {
1223 tree_panel.getMainPanel().getControlPanel().showWhole();
1225 String msg = file.toString();
1226 if ( ( width > 0 ) && ( height > 0 ) ) {
1227 msg += " [size: " + width + ", " + height + "]";
1232 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1233 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1234 ImageWriter writer = null;
1235 ImageOutputStream ios = null;
1236 // Find an appropriate writer:
1237 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1238 if ( it.hasNext() ) {
1242 throw new IOException( "failed to get TIFF image writer" );
1245 ios = ImageIO.createImageOutputStream( file );
1246 writer.setOutput( ios );
1247 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1248 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1249 // see writeParam.getCompressionTypes() for available compression type
1251 image_write_param.setCompressionType( "PackBits" );
1252 final String t[] = image_write_param.getCompressionTypes();
1253 for( final String string : t ) {
1254 System.out.println( string );
1256 // Convert to an IIOImage:
1257 final IIOImage iio_image = new IIOImage( image, null, null );
1258 writer.write( null, iio_image, image_write_param );
1261 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1262 node.getBranchData().setBranchColor( c );
1263 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1264 for( final PhylogenyNode desc : descs ) {
1265 desc.getBranchData().setBranchColor( c );
1269 final private static char normalizeCharForRGB( char c ) {
1272 c = c > 255 ? 255 : c;
1277 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1278 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1279 InvocationTargetException, InterruptedException {
1280 final String os = System.getProperty( "os.name" );
1281 final Runtime runtime = Runtime.getRuntime();
1282 if ( os.toLowerCase().startsWith( "win" ) ) {
1283 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1285 else if ( ForesterUtil.isMac() ) {
1286 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1287 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1288 open_url.invoke( null, new Object[] { url } );
1291 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1292 String browser = null;
1293 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1294 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1295 browser = browsers[ i ];
1298 if ( browser == null ) {
1299 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1302 runtime.exec( new String[] { browser, url } );
1307 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1308 // static void openDDBJRest() throws IOException {
1310 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1312 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1313 // //make connection
1314 // URLConnection urlc = url.openConnection();
1316 // urlc.setDoOutput( true );
1317 // urlc.setAllowUserInteraction( false );
1319 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1320 // ps.print( query );
1323 // BufferedReader br = new BufferedReader( new InputStreamReader(
1324 // urlc.getInputStream() ) );
1326 // while ( ( l = br.readLine() ) != null ) {
1327 // System.out.println( l );
1331 public static enum GraphicsExportType {
1332 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1334 private final String _suffix;
1336 private GraphicsExportType( final String suffix ) {
1341 public String toString() {