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.ArrayList;
47 import java.util.Arrays;
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.Iterator;
51 import java.util.List;
52 import java.util.Locale;
54 import java.util.Map.Entry;
56 import java.util.SortedMap;
57 import java.util.SortedSet;
58 import java.util.TreeMap;
59 import java.util.TreeSet;
60 import java.util.regex.Matcher;
61 import java.util.regex.Pattern;
63 import javax.imageio.IIOImage;
64 import javax.imageio.ImageIO;
65 import javax.imageio.ImageWriteParam;
66 import javax.imageio.ImageWriter;
67 import javax.imageio.stream.ImageOutputStream;
68 import javax.swing.JApplet;
69 import javax.swing.JOptionPane;
70 import javax.swing.text.MaskFormatter;
72 import org.forester.analysis.TaxonomyDataManager;
73 import org.forester.io.parsers.PhylogenyParser;
74 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
75 import org.forester.io.parsers.nhx.NHXParser;
76 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
77 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
78 import org.forester.io.parsers.tol.TolParser;
79 import org.forester.io.parsers.util.ParserUtils;
80 import org.forester.phylogeny.Phylogeny;
81 import org.forester.phylogeny.PhylogenyMethods;
82 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
83 import org.forester.phylogeny.PhylogenyNode;
84 import org.forester.phylogeny.data.Accession;
85 import org.forester.phylogeny.data.Annotation;
86 import org.forester.phylogeny.data.BranchColor;
87 import org.forester.phylogeny.data.Taxonomy;
88 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
89 import org.forester.phylogeny.factories.PhylogenyFactory;
90 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
91 import org.forester.phylogeny.iterators.PreorderTreeIterator;
92 import org.forester.util.AsciiHistogram;
93 import org.forester.util.DescriptiveStatistics;
94 import org.forester.util.ForesterConstants;
95 import org.forester.util.ForesterUtil;
96 import org.forester.util.SequenceIdParser;
97 import org.forester.ws.seqdb.UniProtTaxonomy;
99 public final class AptxUtil {
101 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
102 .getAvailableFontFamilyNames();
103 private final static Pattern seq_identifier_pattern_1 = Pattern
104 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
105 private final static Pattern seq_identifier_pattern_2 = Pattern
106 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
108 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
111 public static MaskFormatter createMaskFormatter( final String s ) {
112 MaskFormatter formatter = null;
114 formatter = new MaskFormatter( s );
116 catch ( final ParseException e ) {
117 throw new IllegalArgumentException( e );
122 public final static String createUriForSeqWeb( final PhylogenyNode node,
123 final Configuration conf,
124 final TreePanel tp ) {
125 String uri_str = null;
126 final String upkb = ForesterUtil.extractUniProtKbProteinSeqIdentifier( node );
127 if ( !ForesterUtil.isEmpty( upkb ) ) {
129 uri_str = ForesterUtil.UNIPROT_KB + URLEncoder.encode( upkb, ForesterConstants.UTF8 );
131 catch ( final UnsupportedEncodingException e ) {
132 showErrorMessage( tp, e.toString() );
136 if ( ForesterUtil.isEmpty( uri_str ) ) {
137 final String v = ForesterUtil.extractGenbankAccessor( node );
138 if ( !ForesterUtil.isEmpty( v ) ) {
140 if ( SequenceIdParser.isProtein( v ) ) {
141 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
144 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
147 catch ( final UnsupportedEncodingException e ) {
148 showErrorMessage( tp, e.toString() );
153 if ( ForesterUtil.isEmpty( uri_str ) ) {
154 final String v = ForesterUtil.extractRefSeqAccessorAccessor( node );
155 if ( !ForesterUtil.isEmpty( v ) ) {
157 if ( SequenceIdParser.isProtein( v ) ) {
158 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
161 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
164 catch ( final UnsupportedEncodingException e ) {
165 showErrorMessage( tp, e.toString() );
170 if ( ForesterUtil.isEmpty( uri_str ) ) {
171 final String v = ForesterUtil.extractGInumber( node );
172 if ( !ForesterUtil.isEmpty( v ) ) {
174 uri_str = ForesterUtil.NCBI_GI + URLEncoder.encode( v, ForesterConstants.UTF8 );
176 catch ( final UnsupportedEncodingException e ) {
177 showErrorMessage( tp, e.toString() );
185 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
186 final PhylogenyNodeIterator it = phy.iteratorPostorder();
187 while ( it.hasNext() ) {
188 if ( it.next().getNodeData().isHasEvent() ) {
196 * Returns true if at least one branch has a length larger than zero.
201 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
202 final PhylogenyNodeIterator it = phy.iteratorPostorder();
203 while ( it.hasNext() ) {
204 if ( it.next().getDistanceToParent() > 0.0 ) {
211 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
212 final PhylogenyNodeIterator it = phy.iteratorPostorder();
213 while ( it.hasNext() ) {
214 if ( it.next().getBranchData().isHasConfidences() ) {
221 final public static void launchWebBrowser( final URI uri,
222 final boolean is_applet,
223 final JApplet applet,
224 final String frame_name ) throws IOException {
226 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
229 // This requires Java 1.6:
230 // =======================
231 // boolean no_desktop = false;
233 // if ( Desktop.isDesktopSupported() ) {
234 // System.out.println( "desktop supported" );
235 // final Desktop dt = Desktop.getDesktop();
239 // no_desktop = true;
242 // catch ( final Exception ex ) {
243 // ex.printStackTrace();
244 // no_desktop = true;
246 // catch ( final Error er ) {
247 // er.printStackTrace();
248 // no_desktop = true;
250 // if ( no_desktop ) {
251 // System.out.println( "desktop not supported" );
253 openUrlInWebBrowser( uri.toString() );
255 catch ( final Exception e ) {
256 throw new IOException( e );
262 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
263 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
264 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
265 for( final PhylogenyNode n : descs ) {
266 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
267 tax_set.add( n.getNodeData().getTaxonomy() );
274 * Returns the set of distinct taxonomies of
275 * all external nodes of node.
276 * If at least one the external nodes has no taxonomy,
280 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
281 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
282 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
283 for( final PhylogenyNode n : descs ) {
284 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
287 tax_set.add( n.getNodeData().getTaxonomy() );
292 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
293 final String n = sequence_name.trim();
294 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
297 if ( matcher1.matches() ) {
298 group1 = matcher1.group( 1 );
299 group2 = matcher1.group( 2 );
302 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
303 if ( matcher2.matches() ) {
304 group1 = matcher2.group( 1 );
305 group2 = matcher2.group( 2 );
308 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
311 return new Accession( group2, group1 );
314 public final static void printWarningMessage( final String name, final String message ) {
315 System.out.println( "[" + name + "] > " + message );
318 final public static void showErrorMessage( final Component parent, final String error_msg ) {
319 printAppletMessage( Constants.PRG_NAME, error_msg );
320 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
321 + "] Error", JOptionPane.ERROR_MESSAGE );
324 public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
325 final PhylogenyNode node,
326 final List<String> data ) {
327 final StringBuilder sb = new StringBuilder();
328 if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
329 showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
331 if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
332 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
333 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
335 if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
336 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
337 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
339 if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
340 && ( node.getNodeData().getSequence().getAccession() != null )
341 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
342 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
344 if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
345 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
346 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
348 if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
349 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
350 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
352 if ( cp.isShowTaxonomyCommonNames() && node.getNodeData().isHasTaxonomy()
353 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getCommonName() ) ) {
354 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getCommonName(), sb );
356 if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
357 && node.getNodeData().isHasSequence()
358 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
359 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
361 final String s = sb.toString().trim();
362 if ( !ForesterUtil.isEmpty( s ) ) {
367 public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
368 if ( sb.length() > 0 ) {
374 final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
375 JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
378 public static void writePhylogenyToGraphicsFile( final File intree,
382 final GraphicsExportType type,
383 final Configuration config ) throws IOException {
384 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
385 Phylogeny[] phys = null;
386 phys = PhylogenyMethods.readPhylogenies( parser, intree );
387 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
390 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
394 final GraphicsExportType type,
395 final Configuration config ) throws IOException {
396 final Phylogeny[] phys = new Phylogeny[ 1 ];
398 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
399 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
400 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
404 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
407 final TreePanel tree_panel,
408 final ControlPanel ac,
409 final GraphicsExportType type,
410 final Options options ) throws IOException {
411 tree_panel.calcParametersForPainting( width, height, true );
412 tree_panel.resetPreferredSize();
413 tree_panel.repaint();
414 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
415 RenderingHints.VALUE_RENDER_QUALITY );
416 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
417 if ( options.isAntialiasPrint() ) {
418 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
419 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
422 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
423 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
425 final Phylogeny phylogeny = tree_panel.getPhylogeny();
426 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
429 if ( outfile.isDirectory() ) {
430 throw new IOException( "\"" + outfile + "\" is a directory" );
432 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
433 final Graphics2D g2d = buffered_img.createGraphics();
434 g2d.setRenderingHints( rendering_hints );
435 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
436 if ( type == GraphicsExportType.TIFF ) {
437 writeToTiff( outfile, buffered_img );
440 ImageIO.write( buffered_img, type.toString(), outfile );
445 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
446 final String default_name,
447 final String full_path,
448 final Configuration configuration,
449 final MainPanel main_panel ) {
450 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
451 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
452 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
453 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
456 for( final Phylogeny phy : phys ) {
457 if ( !phy.isEmpty() ) {
458 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
460 String my_name_for_file = "";
461 if ( phys.length > 1 ) {
462 if ( !ForesterUtil.isEmpty( default_name ) ) {
463 my_name = new String( default_name );
465 if ( !ForesterUtil.isEmpty( full_path ) ) {
466 my_name_for_file = new String( full_path );
468 else if ( !ForesterUtil.isEmpty( default_name ) ) {
469 my_name_for_file = new String( default_name );
472 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
473 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
474 my_name_for_file.length() );
475 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
477 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
478 my_name_for_file += "_";
480 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
481 my_name_for_file += phy.getName().replaceAll( " ", "_" );
483 else if ( phy.getIdentifier() != null ) {
484 final StringBuffer sb = new StringBuffer();
485 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
486 sb.append( phy.getIdentifier().getProvider() );
489 sb.append( phy.getIdentifier().getValue() );
490 my_name_for_file += sb;
493 my_name_for_file += i;
495 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
496 && ( phy.getIdentifier() == null ) ) {
497 my_name = my_name + " [" + i + "]";
499 if ( !ForesterUtil.isEmpty( suffix ) ) {
500 my_name_for_file += suffix;
504 if ( !ForesterUtil.isEmpty( default_name ) ) {
505 my_name = new String( default_name );
507 my_name_for_file = "";
508 if ( !ForesterUtil.isEmpty( full_path ) ) {
509 my_name_for_file = new String( full_path );
511 else if ( !ForesterUtil.isEmpty( default_name ) ) {
512 my_name_for_file = new String( default_name );
514 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
515 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
516 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
518 else if ( phy.getIdentifier() != null ) {
519 final StringBuffer sb = new StringBuffer();
520 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
521 sb.append( phy.getIdentifier().getProvider() );
524 sb.append( phy.getIdentifier().getValue() );
525 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
529 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
530 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
531 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
538 final static void addPhylogenyToPanel( final Phylogeny[] phys,
539 final Configuration configuration,
540 final MainPanel main_panel ) {
541 final Phylogeny phy = phys[ 0 ];
542 main_panel.addPhylogenyInPanel( phy, configuration );
543 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
546 final static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
547 final String my_str = str.toUpperCase();
548 char first = my_str.charAt( 0 );
551 if ( my_str.length() > 1 ) {
553 second = my_str.charAt( 1 );
556 second = my_str.charAt( my_str.length() - 1 );
559 if ( my_str.length() > 2 ) {
560 if ( my_str.indexOf( " " ) > 0 ) {
561 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
564 third = my_str.charAt( 2 );
568 else if ( my_str.length() > 2 ) {
569 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
572 first = AptxUtil.normalizeCharForRGB( first );
573 second = AptxUtil.normalizeCharForRGB( second );
574 third = AptxUtil.normalizeCharForRGB( third );
575 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
578 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
581 return new Color( first, second, third );
584 // Returns true if the specified format name can be written
585 final static boolean canWriteFormat( final String format_name ) {
586 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
587 return iter.hasNext();
590 final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
591 boolean inferred = false;
592 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
593 final PhylogenyNode n = it.next();
594 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
595 final Set<Taxonomy> taxs = obtainDistinctTaxonomies( n );
596 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
597 AptxUtil.collapseSubtree( n, true );
598 if ( !n.getNodeData().isHasTaxonomy() ) {
599 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
600 .getTaxonomy().copy() );
605 n.setCollapse( false );
610 phy.setRerootable( false );
614 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
615 node.setCollapse( collapse );
616 if ( node.isExternal() ) {
619 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
620 while ( it.hasNext() ) {
621 it.next().setCollapse( collapse );
625 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
626 double max_conf = 0.0;
627 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
628 final PhylogenyNode n = it.next();
629 n.getBranchData().setBranchColor( null );
630 if ( n.getBranchData().isHasConfidences() ) {
631 final double conf = PhylogenyMethods.getConfidenceValue( n );
632 if ( conf > max_conf ) {
637 if ( max_conf > 0.0 ) {
638 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
639 final Color br = tree_panel.getTreeColorSet().getBranchColor();
640 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
641 final PhylogenyNode n = it.next();
642 if ( n.getBranchData().isHasConfidences() ) {
643 final double conf = PhylogenyMethods.getConfidenceValue( n );
644 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
645 colorizeSubtree( n, c );
651 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
652 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
653 it.next().getBranchData().setBranchColor( null );
655 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
656 final PhylogenyNode n = it.next();
657 if ( !n.getBranchData().isHasBranchColor() ) {
658 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
660 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
661 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
662 for( final PhylogenyNode desc : descs ) {
664 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
671 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
672 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
673 int colorizations = 0;
674 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
675 final PhylogenyNode n = it.next();
676 if ( n.getNodeData().isHasTaxonomy()
677 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
678 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
679 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
680 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
681 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
682 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
684 colorizeSubtree( n, c );
686 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
687 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
692 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
693 final PhylogenyNode node = it.next();
694 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
695 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
696 boolean success = false;
697 if ( !true_lineage_to_color_map.isEmpty() ) {
698 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
699 if ( true_lineage_to_color_map.containsKey( lin ) ) {
700 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
708 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
709 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
710 final Taxonomy temp_tax = new Taxonomy();
711 temp_tax.setScientificName( lin );
712 if ( lineage_to_rank_map.containsKey( lin )
713 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
714 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
715 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
716 colorizeSubtree( node, c );
718 true_lineage_to_color_map.put( lin, c.getValue() );
722 UniProtTaxonomy up = null;
724 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
726 catch ( final Exception e ) {
729 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
730 lineage_to_rank_map.put( lin, up.getRank() );
731 if ( up.getRank().equalsIgnoreCase( rank ) ) {
732 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
733 colorizeSubtree( node, c );
735 true_lineage_to_color_map.put( lin, c.getValue() );
744 return colorizations;
747 final static String createAnnotationString( final SortedSet<Annotation> annotations, final boolean show_ref_sources ) {
748 final SortedMap<String, List<Annotation>> m = new TreeMap<String, List<Annotation>>();
749 for( final Annotation an : annotations ) {
750 final String ref_source = ForesterUtil.isEmpty( an.getRefSource() ) ? "?" : an.getRefSource();
751 if ( !m.containsKey( ref_source ) ) {
752 m.put( ref_source, new ArrayList<Annotation>() );
754 m.get( ref_source ).add( an );
756 final StringBuilder sb = new StringBuilder();
757 for( final Entry<String, List<Annotation>> e : m.entrySet() ) {
758 final String ref_source = e.getKey();
759 final List<Annotation> ans = e.getValue();
760 if ( m.size() > 1 ) {
763 if ( show_ref_sources && !ref_source.equals( "?" ) ) {
764 sb.append( ref_source );
767 for( int i = 0; i < ans.size(); ++i ) {
768 final Annotation an = ans.get( i );
769 if ( !ForesterUtil.isEmpty( an.getRefValue() ) ) {
770 sb.append( an.getRefValue() );
773 if ( !ForesterUtil.isEmpty( an.getDesc() ) ) {
774 sb.append( an.getDesc() );
776 if ( sb.charAt( sb.length() - 1 ) == ' ' ) {
777 sb.deleteCharAt( sb.length() - 1 );
779 if ( i < ans.size() - 1 ) {
783 if ( m.size() > 1 ) {
787 return sb.toString();
790 final static String createBasicInformation( final Phylogeny phy ) {
791 final StringBuilder desc = new StringBuilder();
792 if ( ( phy != null ) && !phy.isEmpty() ) {
793 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
794 desc.append( "Name: " );
795 desc.append( phy.getName() );
798 if ( phy.getIdentifier() != null ) {
799 desc.append( "Id: " );
800 desc.append( phy.getIdentifier().toString() );
803 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
804 desc.append( "Description: " );
805 desc.append( phy.getDescription() );
808 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
809 desc.append( "Distance Unit: " );
810 desc.append( phy.getDistanceUnit() );
813 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
814 desc.append( "Type: " );
815 desc.append( phy.getType() );
818 desc.append( "Rooted: " );
819 desc.append( phy.isRooted() );
821 desc.append( "Rerootable: " );
822 desc.append( phy.isRerootable() );
824 desc.append( "Nodes: " );
825 desc.append( phy.getNodeCount() );
827 desc.append( "External nodes: " );
828 desc.append( phy.getNumberOfExternalNodes() );
830 desc.append( "Internal nodes: " );
831 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
833 desc.append( "Internal nodes with polytomies: " );
834 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
836 desc.append( "Branches: " );
837 desc.append( phy.getNumberOfBranches() );
839 desc.append( "Depth: " );
840 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
842 desc.append( "Maximum distance to root: " );
843 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
845 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
846 if ( taxs != null ) {
847 desc.append( "Distinct external taxonomies: " );
848 desc.append( taxs.size() );
850 for( final Taxonomy t : taxs ) {
851 System.out.println( t.toString() );
854 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
855 if ( bs.getN() > 3 ) {
857 desc.append( "Branch-length statistics: " );
859 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
861 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
863 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
864 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
866 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
868 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
870 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
872 final AsciiHistogram histo = new AsciiHistogram( bs );
873 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
876 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
877 if ( ds.getN() > 2 ) {
879 desc.append( "Descendants per node statistics: " );
881 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
883 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) + " (stdev: "
884 + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) + ")" );
886 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
888 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
891 List<DescriptiveStatistics> css = null;
893 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
895 catch ( final IllegalArgumentException e ) {
896 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
898 if ( ( css != null ) && ( css.size() > 0 ) ) {
900 for( int i = 0; i < css.size(); ++i ) {
901 final DescriptiveStatistics cs = css.get( i );
902 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
903 if ( css.size() > 1 ) {
904 desc.append( "Support statistics " + ( i + 1 ) + ": " );
907 desc.append( "Support statistics: " );
909 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
911 desc.append( " Type: " + cs.getDescription() );
914 desc.append( " Branches with support: " + cs.getN() );
916 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
918 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
919 if ( cs.getN() > 2 ) {
920 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
923 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
925 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
931 return desc.toString();
939 * to message to be printed
941 final static void dieWithSystemError( final String message ) {
942 System.out.println();
943 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
944 System.out.println( "Please contact the authors." );
945 System.out.println( Constants.PRG_NAME + " needs to close." );
946 System.out.println();
950 final static String[] getAllPossibleRanks() {
951 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
953 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
954 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
955 str_array[ i++ ] = e;
961 final static String[] getAllRanks( final Phylogeny tree ) {
962 final SortedSet<String> ranks = new TreeSet<String>();
963 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
964 final PhylogenyNode n = it.next();
965 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
966 ranks.add( n.getNodeData().getTaxonomy().getRank() );
969 return ForesterUtil.stringSetToArray( ranks );
972 final static String[] getAvailableFontFamiliesSorted() {
973 return AVAILABLE_FONT_FAMILIES_SORTED;
976 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
977 if ( !node.getNodeData().isHasEvent() ) {
980 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
986 final static boolean isUsOrCanada() {
988 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
992 catch ( final Exception e ) {
998 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
999 final ControlPanel atv_control,
1000 final Configuration configuration ) {
1001 if ( ( t != null ) && !t.isEmpty() ) {
1002 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
1003 atv_control.setDrawPhylogram( false );
1004 atv_control.setDrawPhylogramEnabled( false );
1006 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
1007 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
1008 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
1009 atv_control.setDrawPhylogram( true );
1010 atv_control.setDrawPhylogramEnabled( true );
1013 atv_control.setDrawPhylogram( false );
1017 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
1018 if ( atv_control.getWriteConfidenceCb() != null ) {
1019 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
1020 atv_control.setCheckbox( Configuration.write_confidence_values, true );
1023 atv_control.setCheckbox( Configuration.write_confidence_values, false );
1027 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
1028 if ( atv_control.getShowEventsCb() != null ) {
1029 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
1030 atv_control.setCheckbox( Configuration.write_events, true );
1033 atv_control.setCheckbox( Configuration.write_events, false );
1040 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
1042 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
1044 catch ( final Exception e ) {
1045 throw new IOException( e );
1049 final static void outOfMemoryError( final OutOfMemoryError e ) {
1050 System.err.println();
1051 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
1052 System.err.println();
1053 e.printStackTrace();
1054 System.err.println();
1055 JOptionPane.showMessageDialog( null,
1056 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
1057 + "\n\nError: " + e.getLocalizedMessage(),
1058 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1059 JOptionPane.ERROR_MESSAGE );
1063 final static void printAppletMessage( final String applet_name, final String message ) {
1064 System.out.println( "[" + applet_name + "] > " + message );
1067 final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
1068 final boolean phyloxml_validate_against_xsd,
1069 final boolean replace_underscores,
1070 final boolean internal_numbers_are_confidences,
1071 final TAXONOMY_EXTRACTION taxonomy_extraction,
1072 final boolean midpoint_reroot ) throws FileNotFoundException,
1074 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1075 final PhylogenyParser parser;
1076 boolean nhx_or_nexus = false;
1077 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1078 parser = new TolParser();
1081 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
1082 if ( parser instanceof NHXParser ) {
1083 nhx_or_nexus = true;
1084 final NHXParser nhx = ( NHXParser ) parser;
1085 nhx.setReplaceUnderscores( replace_underscores );
1086 nhx.setIgnoreQuotes( false );
1087 nhx.setTaxonomyExtraction( taxonomy_extraction );
1089 else if ( parser instanceof NexusPhylogeniesParser ) {
1090 nhx_or_nexus = true;
1091 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1092 nex.setReplaceUnderscores( replace_underscores );
1093 nex.setIgnoreQuotes( false );
1096 final Phylogeny[] phys = factory.create( url.openStream(), parser );
1097 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
1098 for( final Phylogeny phy : phys ) {
1099 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1102 if ( midpoint_reroot ) {
1103 for( final Phylogeny phy : phys ) {
1104 PhylogenyMethods.midpointRoot( phy );
1105 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
1111 final static void removeBranchColors( final Phylogeny phy ) {
1112 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1113 it.next().getBranchData().setBranchColor( null );
1117 final static void unexpectedError( final Error e ) {
1118 System.err.println();
1119 e.printStackTrace( System.err );
1120 System.err.println();
1121 final StringBuffer sb = new StringBuffer();
1122 for( final StackTraceElement s : e.getStackTrace() ) {
1123 sb.append( s + "\n" );
1126 .showMessageDialog( null,
1127 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
1128 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
1130 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1131 JOptionPane.ERROR_MESSAGE );
1135 final static void unexpectedException( final Exception e ) {
1136 System.err.println();
1137 e.printStackTrace( System.err );
1138 System.err.println();
1139 final StringBuffer sb = new StringBuffer();
1140 for( final StackTraceElement s : e.getStackTrace() ) {
1141 sb.append( s + "\n" );
1143 JOptionPane.showMessageDialog( null,
1144 "An unexpected exception has occured. \nPlease contact: "
1145 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
1147 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
1148 JOptionPane.ERROR_MESSAGE );
1151 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1154 final TreePanel tree_panel,
1155 final ControlPanel ac,
1156 final GraphicsExportType type,
1157 final Options options ) throws IOException {
1158 if ( !options.isGraphicsExportUsingActualSize() ) {
1159 if ( options.isGraphicsExportVisibleOnly() ) {
1160 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1162 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1163 tree_panel.resetPreferredSize();
1164 tree_panel.repaint();
1166 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1167 RenderingHints.VALUE_RENDER_QUALITY );
1168 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1169 if ( options.isAntialiasPrint() ) {
1170 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1171 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1174 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1175 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1177 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1178 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1181 Rectangle visible = null;
1182 if ( !options.isGraphicsExportUsingActualSize() ) {
1183 width = options.getPrintSizeX();
1184 height = options.getPrintSizeY();
1186 else if ( options.isGraphicsExportVisibleOnly() ) {
1187 visible = tree_panel.getVisibleRect();
1188 width = visible.width;
1189 height = visible.height;
1191 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1192 Graphics2D g2d = buffered_img.createGraphics();
1193 g2d.setRenderingHints( rendering_hints );
1196 if ( options.isGraphicsExportVisibleOnly() ) {
1197 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1198 g2d.setClip( null );
1202 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1203 ImageIO.write( buffered_img, type.toString(), baos );
1206 if ( !options.isGraphicsExportUsingActualSize() ) {
1207 tree_panel.getMainPanel().getControlPanel().showWhole();
1209 String msg = baos.toString();
1210 if ( ( width > 0 ) && ( height > 0 ) ) {
1211 msg += " [size: " + width + ", " + height + "]";
1216 final static String writePhylogenyToGraphicsFile( final String file_name,
1219 final TreePanel tree_panel,
1220 final ControlPanel ac,
1221 final GraphicsExportType type,
1222 final Options options ) throws IOException {
1223 if ( !options.isGraphicsExportUsingActualSize() ) {
1224 if ( options.isGraphicsExportVisibleOnly() ) {
1225 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1227 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1228 tree_panel.resetPreferredSize();
1229 tree_panel.repaint();
1231 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1232 RenderingHints.VALUE_RENDER_QUALITY );
1233 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1234 if ( options.isAntialiasPrint() ) {
1235 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1236 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1239 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1240 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1242 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1243 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1246 final File file = new File( file_name );
1247 if ( file.isDirectory() ) {
1248 throw new IOException( "\"" + file_name + "\" is a directory" );
1250 Rectangle visible = null;
1251 if ( !options.isGraphicsExportUsingActualSize() ) {
1252 width = options.getPrintSizeX();
1253 height = options.getPrintSizeY();
1255 else if ( options.isGraphicsExportVisibleOnly() ) {
1256 visible = tree_panel.getVisibleRect();
1257 width = visible.width;
1258 height = visible.height;
1260 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1261 Graphics2D g2d = buffered_img.createGraphics();
1262 g2d.setRenderingHints( rendering_hints );
1265 if ( options.isGraphicsExportVisibleOnly() ) {
1266 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1267 g2d.setClip( null );
1271 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1272 if ( type == GraphicsExportType.TIFF ) {
1273 writeToTiff( file, buffered_img );
1276 ImageIO.write( buffered_img, type.toString(), file );
1280 if ( !options.isGraphicsExportUsingActualSize() ) {
1281 tree_panel.getMainPanel().getControlPanel().showWhole();
1283 String msg = file.toString();
1284 if ( ( width > 0 ) && ( height > 0 ) ) {
1285 msg += " [size: " + width + ", " + height + "]";
1290 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1291 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1292 ImageWriter writer = null;
1293 ImageOutputStream ios = null;
1294 // Find an appropriate writer:
1295 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1296 if ( it.hasNext() ) {
1300 throw new IOException( "failed to get TIFF image writer" );
1303 ios = ImageIO.createImageOutputStream( file );
1304 writer.setOutput( ios );
1305 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1306 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1307 // see writeParam.getCompressionTypes() for available compression type
1309 image_write_param.setCompressionType( "PackBits" );
1310 final String t[] = image_write_param.getCompressionTypes();
1311 for( final String string : t ) {
1312 System.out.println( string );
1314 // Convert to an IIOImage:
1315 final IIOImage iio_image = new IIOImage( image, null, null );
1316 writer.write( null, iio_image, image_write_param );
1319 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1320 node.getBranchData().setBranchColor( c );
1321 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1322 for( final PhylogenyNode desc : descs ) {
1323 desc.getBranchData().setBranchColor( c );
1327 final private static char normalizeCharForRGB( char c ) {
1330 c = c > 255 ? 255 : c;
1335 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1336 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1337 InvocationTargetException, InterruptedException {
1338 final String os = System.getProperty( "os.name" );
1339 final Runtime runtime = Runtime.getRuntime();
1340 if ( os.toLowerCase().startsWith( "win" ) ) {
1341 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1343 else if ( ForesterUtil.isMac() ) {
1344 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1345 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1346 open_url.invoke( null, new Object[] { url } );
1349 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1350 String browser = null;
1351 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1352 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1353 browser = browsers[ i ];
1356 if ( browser == null ) {
1357 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1360 runtime.exec( new String[] { browser, url } );
1365 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1366 // static void openDDBJRest() throws IOException {
1368 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1370 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1371 // //make connection
1372 // URLConnection urlc = url.openConnection();
1374 // urlc.setDoOutput( true );
1375 // urlc.setAllowUserInteraction( false );
1377 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1378 // ps.print( query );
1381 // BufferedReader br = new BufferedReader( new InputStreamReader(
1382 // urlc.getInputStream() ) );
1384 // while ( ( l = br.readLine() ) != null ) {
1385 // System.out.println( l );
1389 public static enum GraphicsExportType {
1390 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
1392 private final String _suffix;
1394 private GraphicsExportType( final String suffix ) {
1399 public String toString() {