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.Sequence;
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 if ( node.getNodeData().isHasSequence() && ( node.getNodeData().getSequence().getAccession() != null )
111 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getSource() )
112 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getValue() )
113 && conf.isHasWebLink( node.getNodeData().getSequence().getAccession().getSource().toLowerCase() ) ) {
114 final Sequence seq = node.getNodeData().getSequence();
115 final String source = seq.getAccession().getSource().toLowerCase();
117 if ( source.toLowerCase().equals( "ncbi" ) ) {
118 url = Constants.NCBI_ALL_DATABASE_SEARCH;
121 final WebLink weblink = conf.getWebLink( source );
122 url = weblink.getUrl().toString();
125 uri_str = url + URLEncoder.encode( seq.getAccession().getValue(), ForesterConstants.UTF8 );
127 catch ( final UnsupportedEncodingException e ) {
128 showErrorMessage( tp, e.toString() );
132 if ( ForesterUtil.isEmpty( uri_str ) ) {
133 final String upkb = ForesterUtil.extractUniProtKbProteinSeqIdentifier( node );
134 if ( !ForesterUtil.isEmpty( upkb ) ) {
136 uri_str = ForesterUtil.UNIPROT_KB + URLEncoder.encode( upkb, ForesterConstants.UTF8 );
138 catch ( final UnsupportedEncodingException e ) {
139 showErrorMessage( tp, e.toString() );
144 if ( ForesterUtil.isEmpty( uri_str ) ) {
145 final String v = ForesterUtil.extractGenbankAccessor( node );
146 if ( !ForesterUtil.isEmpty( v ) ) {
148 if ( SequenceIdParser.isProtein( v ) ) {
149 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
152 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
155 catch ( final UnsupportedEncodingException e ) {
156 showErrorMessage( tp, e.toString() );
161 if ( ForesterUtil.isEmpty( uri_str ) ) {
162 final String v = ForesterUtil.extractRefSeqAccessorAccessor( node );
163 if ( !ForesterUtil.isEmpty( v ) ) {
165 if ( SequenceIdParser.isProtein( v ) ) {
166 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
169 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
172 catch ( final UnsupportedEncodingException e ) {
173 showErrorMessage( tp, e.toString() );
181 public static MaskFormatter createMaskFormatter( final String s ) {
182 MaskFormatter formatter = null;
184 formatter = new MaskFormatter( s );
186 catch ( final ParseException e ) {
187 throw new IllegalArgumentException( e );
192 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
193 final PhylogenyNodeIterator it = phy.iteratorPostorder();
194 while ( it.hasNext() ) {
195 if ( it.next().getNodeData().isHasEvent() ) {
203 * Returns true if at least one branch has a length larger than zero.
208 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
209 final PhylogenyNodeIterator it = phy.iteratorPostorder();
210 while ( it.hasNext() ) {
211 if ( it.next().getDistanceToParent() > 0.0 ) {
218 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
219 final PhylogenyNodeIterator it = phy.iteratorPostorder();
220 while ( it.hasNext() ) {
221 if ( it.next().getBranchData().isHasConfidences() ) {
228 final public static void launchWebBrowser( final URI uri,
229 final boolean is_applet,
230 final JApplet applet,
231 final String frame_name ) throws IOException {
233 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
236 // This requires Java 1.6:
237 // =======================
238 // boolean no_desktop = false;
240 // if ( Desktop.isDesktopSupported() ) {
241 // System.out.println( "desktop supported" );
242 // final Desktop dt = Desktop.getDesktop();
246 // no_desktop = true;
249 // catch ( final Exception ex ) {
250 // ex.printStackTrace();
251 // no_desktop = true;
253 // catch ( final Error er ) {
254 // er.printStackTrace();
255 // no_desktop = true;
257 // if ( no_desktop ) {
258 // System.out.println( "desktop not supported" );
260 openUrlInWebBrowser( uri.toString() );
262 catch ( final Exception e ) {
263 throw new IOException( e );
269 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
270 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
271 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
272 for( final PhylogenyNode n : descs ) {
273 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
274 tax_set.add( n.getNodeData().getTaxonomy() );
281 * Returns the set of distinct taxonomies of
282 * all external nodes of node.
283 * If at least one the external nodes has no taxonomy,
287 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
288 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
289 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
290 for( final PhylogenyNode n : descs ) {
291 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
294 tax_set.add( n.getNodeData().getTaxonomy() );
299 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
300 final String n = sequence_name.trim();
301 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
304 if ( matcher1.matches() ) {
305 group1 = matcher1.group( 1 );
306 group2 = matcher1.group( 2 );
309 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
310 if ( matcher2.matches() ) {
311 group1 = matcher2.group( 1 );
312 group2 = matcher2.group( 2 );
315 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
318 return new Accession( group2, group1 );
321 public final static void printWarningMessage( final String name, final String message ) {
322 System.out.println( "[" + name + "] > " + message );
325 final public static void showErrorMessage( final Component parent, final String error_msg ) {
326 printAppletMessage( Constants.PRG_NAME, error_msg );
327 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
328 + "] Error", JOptionPane.ERROR_MESSAGE );
331 public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
332 final PhylogenyNode node,
333 final List<String> data ) {
334 final StringBuilder sb = new StringBuilder();
335 if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
336 showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
338 if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
339 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
340 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
342 if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
343 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
344 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
346 if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
347 && ( node.getNodeData().getSequence().getAccession() != null )
348 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
349 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
351 if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
352 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
353 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
355 if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
356 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
357 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
359 if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
360 && node.getNodeData().isHasSequence()
361 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
362 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
364 final String s = sb.toString().trim();
365 if ( !ForesterUtil.isEmpty( s ) ) {
370 public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
371 if ( sb.length() > 0 ) {
377 final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
378 JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
381 public static void writePhylogenyToGraphicsFile( final File intree,
385 final GraphicsExportType type,
386 final Configuration config ) throws IOException {
387 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
388 Phylogeny[] phys = null;
389 phys = PhylogenyMethods.readPhylogenies( parser, intree );
390 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
393 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
397 final GraphicsExportType type,
398 final Configuration config ) throws IOException {
399 final Phylogeny[] phys = new Phylogeny[ 1 ];
401 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
402 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
403 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
407 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
410 final TreePanel tree_panel,
411 final ControlPanel ac,
412 final GraphicsExportType type,
413 final Options options ) throws IOException {
414 tree_panel.calcParametersForPainting( width, height, true );
415 tree_panel.resetPreferredSize();
416 tree_panel.repaint();
417 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
418 RenderingHints.VALUE_RENDER_QUALITY );
419 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
420 if ( options.isAntialiasPrint() ) {
421 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
422 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
425 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
426 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
428 final Phylogeny phylogeny = tree_panel.getPhylogeny();
429 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
432 if ( outfile.isDirectory() ) {
433 throw new IOException( "\"" + outfile + "\" is a directory" );
435 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
436 final Graphics2D g2d = buffered_img.createGraphics();
437 g2d.setRenderingHints( rendering_hints );
438 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
439 if ( type == GraphicsExportType.TIFF ) {
440 writeToTiff( outfile, buffered_img );
443 ImageIO.write( buffered_img, type.toString(), outfile );
448 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
449 final String default_name,
450 final String full_path,
451 final Configuration configuration,
452 final MainPanel main_panel ) {
453 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
454 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
455 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
456 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
459 for( final Phylogeny phy : phys ) {
460 if ( !phy.isEmpty() ) {
461 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
463 String my_name_for_file = "";
464 if ( phys.length > 1 ) {
465 if ( !ForesterUtil.isEmpty( default_name ) ) {
466 my_name = new String( default_name );
468 if ( !ForesterUtil.isEmpty( full_path ) ) {
469 my_name_for_file = new String( full_path );
471 else if ( !ForesterUtil.isEmpty( default_name ) ) {
472 my_name_for_file = new String( default_name );
475 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
476 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
477 my_name_for_file.length() );
478 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
480 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
481 my_name_for_file += "_";
483 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
484 my_name_for_file += phy.getName().replaceAll( " ", "_" );
486 else if ( phy.getIdentifier() != null ) {
487 final StringBuffer sb = new StringBuffer();
488 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
489 sb.append( phy.getIdentifier().getProvider() );
492 sb.append( phy.getIdentifier().getValue() );
493 my_name_for_file += sb;
496 my_name_for_file += i;
498 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
499 && ( phy.getIdentifier() == null ) ) {
500 my_name = my_name + " [" + i + "]";
502 if ( !ForesterUtil.isEmpty( suffix ) ) {
503 my_name_for_file += suffix;
507 if ( !ForesterUtil.isEmpty( default_name ) ) {
508 my_name = new String( default_name );
510 my_name_for_file = "";
511 if ( !ForesterUtil.isEmpty( full_path ) ) {
512 my_name_for_file = new String( full_path );
514 else if ( !ForesterUtil.isEmpty( default_name ) ) {
515 my_name_for_file = new String( default_name );
517 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
518 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
519 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
521 else if ( phy.getIdentifier() != null ) {
522 final StringBuffer sb = new StringBuffer();
523 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
524 sb.append( phy.getIdentifier().getProvider() );
527 sb.append( phy.getIdentifier().getValue() );
528 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
532 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
533 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
534 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
541 final static void addPhylogenyToPanel( final Phylogeny[] phys,
542 final Configuration configuration,
543 final MainPanel main_panel ) {
544 final Phylogeny phy = phys[ 0 ];
545 main_panel.addPhylogenyInPanel( phy, configuration );
546 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
549 final static Color calculateColorFromString( final String str ) {
550 final String species_uc = str.toUpperCase();
551 char first = species_uc.charAt( 0 );
554 if ( species_uc.length() > 1 ) {
555 second = species_uc.charAt( 1 );
556 if ( species_uc.length() > 2 ) {
557 if ( species_uc.indexOf( " " ) > 0 ) {
558 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
561 third = species_uc.charAt( 2 );
565 first = AptxUtil.normalizeCharForRGB( first );
566 second = AptxUtil.normalizeCharForRGB( second );
567 third = AptxUtil.normalizeCharForRGB( third );
568 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
571 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
574 return new Color( first, second, third );
577 // Returns true if the specified format name can be written
578 final static boolean canWriteFormat( final String format_name ) {
579 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
580 return iter.hasNext();
583 final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
584 boolean inferred = false;
585 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
586 final PhylogenyNode n = it.next();
587 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
588 final Set<Taxonomy> taxs = obtainDistinctTaxonomies( n );
589 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
590 AptxUtil.collapseSubtree( n, true );
591 if ( !n.getNodeData().isHasTaxonomy() ) {
592 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
593 .getTaxonomy().copy() );
598 n.setCollapse( false );
603 phy.setRerootable( false );
607 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
608 node.setCollapse( collapse );
609 if ( node.isExternal() ) {
612 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
613 while ( it.hasNext() ) {
614 it.next().setCollapse( collapse );
618 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
619 double max_conf = 0.0;
620 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
621 final PhylogenyNode n = it.next();
622 n.getBranchData().setBranchColor( null );
623 if ( n.getBranchData().isHasConfidences() ) {
624 final double conf = PhylogenyMethods.getConfidenceValue( n );
625 if ( conf > max_conf ) {
630 if ( max_conf > 0.0 ) {
631 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
632 final Color br = tree_panel.getTreeColorSet().getBranchColor();
633 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
634 final PhylogenyNode n = it.next();
635 if ( n.getBranchData().isHasConfidences() ) {
636 final double conf = PhylogenyMethods.getConfidenceValue( n );
637 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
638 colorizeSubtree( n, c );
644 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
645 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
646 it.next().getBranchData().setBranchColor( null );
648 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
649 final PhylogenyNode n = it.next();
650 if ( !n.getBranchData().isHasBranchColor() ) {
651 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
653 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
654 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
655 for( final PhylogenyNode desc : descs ) {
657 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
664 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
665 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
666 int colorizations = 0;
667 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
668 final PhylogenyNode n = it.next();
669 if ( n.getNodeData().isHasTaxonomy()
670 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
671 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
672 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
673 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
674 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
675 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
677 colorizeSubtree( n, c );
679 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
680 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
685 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
686 final PhylogenyNode node = it.next();
687 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
688 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
689 boolean success = false;
690 if ( !true_lineage_to_color_map.isEmpty() ) {
691 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
692 if ( true_lineage_to_color_map.containsKey( lin ) ) {
693 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
701 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
702 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
703 final Taxonomy temp_tax = new Taxonomy();
704 temp_tax.setScientificName( lin );
705 if ( lineage_to_rank_map.containsKey( lin )
706 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
707 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
708 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
709 colorizeSubtree( node, c );
711 true_lineage_to_color_map.put( lin, c.getValue() );
715 UniProtTaxonomy up = null;
717 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
719 catch ( final Exception e ) {
722 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
723 lineage_to_rank_map.put( lin, up.getRank() );
724 if ( up.getRank().equalsIgnoreCase( rank ) ) {
725 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
726 colorizeSubtree( node, c );
728 true_lineage_to_color_map.put( lin, c.getValue() );
737 return colorizations;
740 final static String createBasicInformation( final Phylogeny phy ) {
741 final StringBuilder desc = new StringBuilder();
742 if ( ( phy != null ) && !phy.isEmpty() ) {
743 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
744 desc.append( "Name: " );
745 desc.append( phy.getName() );
748 if ( phy.getIdentifier() != null ) {
749 desc.append( "Id: " );
750 desc.append( phy.getIdentifier().toString() );
753 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
754 desc.append( "Description: " );
755 desc.append( phy.getDescription() );
758 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
759 desc.append( "Distance Unit: " );
760 desc.append( phy.getDistanceUnit() );
763 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
764 desc.append( "Type: " );
765 desc.append( phy.getType() );
768 desc.append( "Rooted: " );
769 desc.append( phy.isRooted() );
771 desc.append( "Rerootable: " );
772 desc.append( phy.isRerootable() );
774 desc.append( "Nodes: " );
775 desc.append( phy.getNodeCount() );
777 desc.append( "External nodes: " );
778 desc.append( phy.getNumberOfExternalNodes() );
780 desc.append( "Internal nodes: " );
781 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
783 desc.append( "Internal nodes with polytomies: " );
784 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
786 desc.append( "Branches: " );
787 desc.append( phy.getNumberOfBranches() );
789 desc.append( "Depth: " );
790 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
792 desc.append( "Maximum distance to root: " );
793 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
795 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
796 if ( taxs != null ) {
797 desc.append( "Distinct external taxonomies: " );
798 desc.append( taxs.size() );
801 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
802 if ( bs.getN() > 3 ) {
804 desc.append( "Branch-length statistics: " );
806 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
808 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
810 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
812 desc.append( " SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
814 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
816 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
818 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
820 final AsciiHistogram histo = new AsciiHistogram( bs );
821 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
824 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
825 if ( ds.getN() > 2 ) {
827 desc.append( "Descendants per node statistics: " );
829 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
831 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
833 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
835 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
837 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
840 List<DescriptiveStatistics> css = null;
842 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
844 catch ( final IllegalArgumentException e ) {
845 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
847 if ( ( css != null ) && ( css.size() > 0 ) ) {
849 for( int i = 0; i < css.size(); ++i ) {
850 final DescriptiveStatistics cs = css.get( i );
851 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
852 if ( css.size() > 1 ) {
853 desc.append( "Support statistics " + ( i + 1 ) + ": " );
856 desc.append( "Support statistics: " );
858 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
860 desc.append( " Type: " + cs.getDescription() );
863 desc.append( " Branches with support: " + cs.getN() );
865 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
867 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
869 if ( cs.getN() > 2 ) {
870 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
873 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
875 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
881 return desc.toString();
889 * to message to be printed
891 final static void dieWithSystemError( final String message ) {
892 System.out.println();
893 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
894 System.out.println( "Please contact the authors." );
895 System.out.println( Constants.PRG_NAME + " needs to close." );
896 System.out.println();
900 final static String[] getAllPossibleRanks() {
901 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
903 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
904 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
905 str_array[ i++ ] = e;
911 final static String[] getAllRanks( final Phylogeny tree ) {
912 final SortedSet<String> ranks = new TreeSet<String>();
913 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
914 final PhylogenyNode n = it.next();
915 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
916 ranks.add( n.getNodeData().getTaxonomy().getRank() );
919 return ForesterUtil.stringSetToArray( ranks );
922 final static String[] getAvailableFontFamiliesSorted() {
923 return AVAILABLE_FONT_FAMILIES_SORTED;
926 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
927 if ( !node.getNodeData().isHasEvent() ) {
930 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
936 final static boolean isMac() {
938 final String s = ForesterUtil.OS_NAME.toLowerCase();
939 return s.startsWith( "mac" );
941 catch ( final Exception e ) {
942 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
947 final static boolean isUsOrCanada() {
949 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
953 catch ( final Exception e ) {
959 final static boolean isWindows() {
961 final String s = ForesterUtil.OS_NAME.toLowerCase();
962 return s.indexOf( "win" ) > -1;
964 catch ( final Exception e ) {
965 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
970 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
971 final ControlPanel atv_control,
972 final Configuration configuration ) {
973 if ( ( t != null ) && !t.isEmpty() ) {
974 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
975 atv_control.setDrawPhylogram( false );
976 atv_control.setDrawPhylogramEnabled( false );
978 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
979 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
980 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
981 atv_control.setDrawPhylogram( true );
982 atv_control.setDrawPhylogramEnabled( true );
985 atv_control.setDrawPhylogram( false );
989 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
990 if ( atv_control.getWriteConfidenceCb() != null ) {
991 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
992 atv_control.setCheckbox( Configuration.write_confidence_values, true );
995 atv_control.setCheckbox( Configuration.write_confidence_values, false );
999 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
1000 if ( atv_control.getShowEventsCb() != null ) {
1001 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
1002 atv_control.setCheckbox( Configuration.write_events, true );
1005 atv_control.setCheckbox( Configuration.write_events, false );
1012 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
1014 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
1016 catch ( final Exception e ) {
1017 throw new IOException( e );
1021 final static void outOfMemoryError( final OutOfMemoryError e ) {
1022 System.err.println();
1023 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
1024 System.err.println();
1025 e.printStackTrace();
1026 System.err.println();
1027 JOptionPane.showMessageDialog( null,
1028 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
1029 + "\n\nError: " + e.getLocalizedMessage(),
1030 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1031 JOptionPane.ERROR_MESSAGE );
1035 final static void printAppletMessage( final String applet_name, final String message ) {
1036 System.out.println( "[" + applet_name + "] > " + message );
1039 final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
1040 final boolean phyloxml_validate_against_xsd,
1041 final boolean replace_underscores,
1042 final boolean internal_numbers_are_confidences,
1043 final TAXONOMY_EXTRACTION taxonomy_extraction )
1044 throws FileNotFoundException, IOException {
1045 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1046 final PhylogenyParser parser;
1047 boolean nhx_or_nexus = false;
1048 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1049 parser = new TolParser();
1052 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
1053 if ( parser instanceof NHXParser ) {
1054 nhx_or_nexus = true;
1055 final NHXParser nhx = ( NHXParser ) parser;
1056 nhx.setReplaceUnderscores( replace_underscores );
1057 nhx.setIgnoreQuotes( false );
1058 nhx.setTaxonomyExtraction( taxonomy_extraction );
1060 else if ( parser instanceof NexusPhylogeniesParser ) {
1061 nhx_or_nexus = true;
1062 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1063 nex.setReplaceUnderscores( replace_underscores );
1064 nex.setIgnoreQuotes( false );
1067 final Phylogeny[] phys = factory.create( url.openStream(), parser );
1068 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
1069 for( final Phylogeny phy : phys ) {
1070 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1076 final static void removeBranchColors( final Phylogeny phy ) {
1077 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1078 it.next().getBranchData().setBranchColor( null );
1082 final static void unexpectedError( final Error e ) {
1083 System.err.println();
1084 e.printStackTrace( System.err );
1085 System.err.println();
1086 final StringBuffer sb = new StringBuffer();
1087 for( final StackTraceElement s : e.getStackTrace() ) {
1088 sb.append( s + "\n" );
1091 .showMessageDialog( null,
1092 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
1093 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
1095 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1096 JOptionPane.ERROR_MESSAGE );
1100 final static void unexpectedException( final Exception e ) {
1101 System.err.println();
1102 e.printStackTrace( System.err );
1103 System.err.println();
1104 final StringBuffer sb = new StringBuffer();
1105 for( final StackTraceElement s : e.getStackTrace() ) {
1106 sb.append( s + "\n" );
1108 JOptionPane.showMessageDialog( null,
1109 "An unexpected exception has occured. \nPlease contact: "
1110 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
1112 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
1113 JOptionPane.ERROR_MESSAGE );
1116 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1119 final TreePanel tree_panel,
1120 final ControlPanel ac,
1121 final GraphicsExportType type,
1122 final Options options ) throws IOException {
1123 if ( !options.isGraphicsExportUsingActualSize() ) {
1124 if ( options.isGraphicsExportVisibleOnly() ) {
1125 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1127 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1128 tree_panel.resetPreferredSize();
1129 tree_panel.repaint();
1131 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1132 RenderingHints.VALUE_RENDER_QUALITY );
1133 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1134 if ( options.isAntialiasPrint() ) {
1135 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1136 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1139 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1140 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1142 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1143 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1146 Rectangle visible = null;
1147 if ( !options.isGraphicsExportUsingActualSize() ) {
1148 width = options.getPrintSizeX();
1149 height = options.getPrintSizeY();
1151 else if ( options.isGraphicsExportVisibleOnly() ) {
1152 visible = tree_panel.getVisibleRect();
1153 width = visible.width;
1154 height = visible.height;
1156 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1157 Graphics2D g2d = buffered_img.createGraphics();
1158 g2d.setRenderingHints( rendering_hints );
1161 if ( options.isGraphicsExportVisibleOnly() ) {
1162 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1163 g2d.setClip( null );
1167 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1168 ImageIO.write( buffered_img, type.toString(), baos );
1171 if ( !options.isGraphicsExportUsingActualSize() ) {
1172 tree_panel.getMainPanel().getControlPanel().showWhole();
1174 String msg = baos.toString();
1175 if ( ( width > 0 ) && ( height > 0 ) ) {
1176 msg += " [size: " + width + ", " + height + "]";
1181 final static String writePhylogenyToGraphicsFile( final String file_name,
1184 final TreePanel tree_panel,
1185 final ControlPanel ac,
1186 final GraphicsExportType type,
1187 final Options options ) throws IOException {
1188 if ( !options.isGraphicsExportUsingActualSize() ) {
1189 if ( options.isGraphicsExportVisibleOnly() ) {
1190 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1192 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1193 tree_panel.resetPreferredSize();
1194 tree_panel.repaint();
1196 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1197 RenderingHints.VALUE_RENDER_QUALITY );
1198 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1199 if ( options.isAntialiasPrint() ) {
1200 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1201 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1204 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1205 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1207 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1208 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1211 final File file = new File( file_name );
1212 if ( file.isDirectory() ) {
1213 throw new IOException( "\"" + file_name + "\" is a directory" );
1215 Rectangle visible = null;
1216 if ( !options.isGraphicsExportUsingActualSize() ) {
1217 width = options.getPrintSizeX();
1218 height = options.getPrintSizeY();
1220 else if ( options.isGraphicsExportVisibleOnly() ) {
1221 visible = tree_panel.getVisibleRect();
1222 width = visible.width;
1223 height = visible.height;
1225 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1226 Graphics2D g2d = buffered_img.createGraphics();
1227 g2d.setRenderingHints( rendering_hints );
1230 if ( options.isGraphicsExportVisibleOnly() ) {
1231 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1232 g2d.setClip( null );
1236 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1237 if ( type == GraphicsExportType.TIFF ) {
1238 writeToTiff( file, buffered_img );
1241 ImageIO.write( buffered_img, type.toString(), file );
1245 if ( !options.isGraphicsExportUsingActualSize() ) {
1246 tree_panel.getMainPanel().getControlPanel().showWhole();
1248 String msg = file.toString();
1249 if ( ( width > 0 ) && ( height > 0 ) ) {
1250 msg += " [size: " + width + ", " + height + "]";
1255 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1256 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1257 ImageWriter writer = null;
1258 ImageOutputStream ios = null;
1259 // Find an appropriate writer:
1260 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1261 if ( it.hasNext() ) {
1265 throw new IOException( "failed to get TIFF image writer" );
1268 ios = ImageIO.createImageOutputStream( file );
1269 writer.setOutput( ios );
1270 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1271 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1272 // see writeParam.getCompressionTypes() for available compression type
1274 image_write_param.setCompressionType( "PackBits" );
1275 final String t[] = image_write_param.getCompressionTypes();
1276 for( final String string : t ) {
1277 System.out.println( string );
1279 // Convert to an IIOImage:
1280 final IIOImage iio_image = new IIOImage( image, null, null );
1281 writer.write( null, iio_image, image_write_param );
1284 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1285 node.getBranchData().setBranchColor( c );
1286 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1287 for( final PhylogenyNode desc : descs ) {
1288 desc.getBranchData().setBranchColor( c );
1292 final private static char normalizeCharForRGB( char c ) {
1295 c = c > 255 ? 255 : c;
1300 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1301 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1302 InvocationTargetException, InterruptedException {
1303 final String os = System.getProperty( "os.name" );
1304 final Runtime runtime = Runtime.getRuntime();
1305 if ( os.toLowerCase().startsWith( "win" ) ) {
1306 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1308 else if ( isMac() ) {
1309 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1310 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1311 open_url.invoke( null, new Object[] { url } );
1314 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1315 String browser = null;
1316 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1317 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1318 browser = browsers[ i ];
1321 if ( browser == null ) {
1322 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1325 runtime.exec( new String[] { browser, url } );
1330 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1331 // static void openDDBJRest() throws IOException {
1333 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1335 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1336 // //make connection
1337 // URLConnection urlc = url.openConnection();
1339 // urlc.setDoOutput( true );
1340 // urlc.setAllowUserInteraction( false );
1342 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1343 // ps.print( query );
1346 // BufferedReader br = new BufferedReader( new InputStreamReader(
1347 // urlc.getInputStream() ) );
1349 // while ( ( l = br.readLine() ) != null ) {
1350 // System.out.println( l );
1354 public static enum GraphicsExportType {
1355 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1357 private final String _suffix;
1359 private GraphicsExportType( final String suffix ) {
1364 public String toString() {