2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
26 package org.forester.archaeopteryx;
28 import java.awt.Color;
29 import java.awt.Component;
30 import java.awt.Graphics2D;
31 import java.awt.GraphicsEnvironment;
32 import java.awt.Rectangle;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.io.ByteArrayOutputStream;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.io.UnsupportedEncodingException;
40 import java.lang.reflect.InvocationTargetException;
41 import java.lang.reflect.Method;
44 import java.net.URLEncoder;
45 import java.text.ParseException;
46 import java.util.Arrays;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Locale;
54 import java.util.SortedSet;
55 import java.util.TreeSet;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
59 import javax.imageio.IIOImage;
60 import javax.imageio.ImageIO;
61 import javax.imageio.ImageWriteParam;
62 import javax.imageio.ImageWriter;
63 import javax.imageio.stream.ImageOutputStream;
64 import javax.swing.JApplet;
65 import javax.swing.JOptionPane;
66 import javax.swing.text.MaskFormatter;
68 import org.forester.analysis.TaxonomyDataManager;
69 import org.forester.io.parsers.PhylogenyParser;
70 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
71 import org.forester.io.parsers.nhx.NHXParser;
72 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
73 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
74 import org.forester.io.parsers.tol.TolParser;
75 import org.forester.io.parsers.util.ParserUtils;
76 import org.forester.phylogeny.Phylogeny;
77 import org.forester.phylogeny.PhylogenyMethods;
78 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
79 import org.forester.phylogeny.PhylogenyNode;
80 import org.forester.phylogeny.data.Accession;
81 import org.forester.phylogeny.data.BranchColor;
82 import org.forester.phylogeny.data.Taxonomy;
83 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
84 import org.forester.phylogeny.factories.PhylogenyFactory;
85 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
86 import org.forester.phylogeny.iterators.PreorderTreeIterator;
87 import org.forester.util.AsciiHistogram;
88 import org.forester.util.DescriptiveStatistics;
89 import org.forester.util.ForesterConstants;
90 import org.forester.util.ForesterUtil;
91 import org.forester.util.SequenceIdParser;
92 import org.forester.ws.seqdb.UniProtTaxonomy;
94 public final class AptxUtil {
96 private final static Pattern seq_identifier_pattern_1 = Pattern
97 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
98 private final static Pattern seq_identifier_pattern_2 = Pattern
99 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
100 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
101 .getAvailableFontFamilyNames();
103 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
106 public final static String createUriForSeqWeb( final PhylogenyNode node,
107 final Configuration conf,
108 final TreePanel tp ) {
109 String uri_str = null;
110 final String upkb = ForesterUtil.extractUniProtKbProteinSeqIdentifier( node );
111 if ( !ForesterUtil.isEmpty( upkb ) ) {
113 uri_str = ForesterUtil.UNIPROT_KB + URLEncoder.encode( upkb, ForesterConstants.UTF8 );
115 catch ( final UnsupportedEncodingException e ) {
116 showErrorMessage( tp, e.toString() );
120 if ( ForesterUtil.isEmpty( uri_str ) ) {
121 final String v = ForesterUtil.extractGenbankAccessor( node );
122 if ( !ForesterUtil.isEmpty( v ) ) {
124 if ( SequenceIdParser.isProtein( v ) ) {
125 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
128 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
131 catch ( final UnsupportedEncodingException e ) {
132 showErrorMessage( tp, e.toString() );
137 if ( ForesterUtil.isEmpty( uri_str ) ) {
138 final String v = ForesterUtil.extractRefSeqAccessorAccessor( node );
139 if ( !ForesterUtil.isEmpty( v ) ) {
141 if ( SequenceIdParser.isProtein( v ) ) {
142 uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
145 uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
148 catch ( final UnsupportedEncodingException e ) {
149 showErrorMessage( tp, e.toString() );
154 if ( ForesterUtil.isEmpty( uri_str ) ) {
155 final String v = ForesterUtil.extractGInumber( node );
156 if ( !ForesterUtil.isEmpty( v ) ) {
158 uri_str = ForesterUtil.NCBI_GI + URLEncoder.encode( v, ForesterConstants.UTF8 );
160 catch ( final UnsupportedEncodingException e ) {
161 showErrorMessage( tp, e.toString() );
169 public static MaskFormatter createMaskFormatter( final String s ) {
170 MaskFormatter formatter = null;
172 formatter = new MaskFormatter( s );
174 catch ( final ParseException e ) {
175 throw new IllegalArgumentException( e );
180 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
181 final PhylogenyNodeIterator it = phy.iteratorPostorder();
182 while ( it.hasNext() ) {
183 if ( it.next().getNodeData().isHasEvent() ) {
191 * Returns true if at least one branch has a length larger than zero.
196 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
197 final PhylogenyNodeIterator it = phy.iteratorPostorder();
198 while ( it.hasNext() ) {
199 if ( it.next().getDistanceToParent() > 0.0 ) {
206 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
207 final PhylogenyNodeIterator it = phy.iteratorPostorder();
208 while ( it.hasNext() ) {
209 if ( it.next().getBranchData().isHasConfidences() ) {
216 final public static void launchWebBrowser( final URI uri,
217 final boolean is_applet,
218 final JApplet applet,
219 final String frame_name ) throws IOException {
221 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
224 // This requires Java 1.6:
225 // =======================
226 // boolean no_desktop = false;
228 // if ( Desktop.isDesktopSupported() ) {
229 // System.out.println( "desktop supported" );
230 // final Desktop dt = Desktop.getDesktop();
234 // no_desktop = true;
237 // catch ( final Exception ex ) {
238 // ex.printStackTrace();
239 // no_desktop = true;
241 // catch ( final Error er ) {
242 // er.printStackTrace();
243 // no_desktop = true;
245 // if ( no_desktop ) {
246 // System.out.println( "desktop not supported" );
248 openUrlInWebBrowser( uri.toString() );
250 catch ( final Exception e ) {
251 throw new IOException( e );
257 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
258 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
259 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
260 for( final PhylogenyNode n : descs ) {
261 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
262 tax_set.add( n.getNodeData().getTaxonomy() );
269 * Returns the set of distinct taxonomies of
270 * all external nodes of node.
271 * If at least one the external nodes has no taxonomy,
275 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
276 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
277 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
278 for( final PhylogenyNode n : descs ) {
279 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
282 tax_set.add( n.getNodeData().getTaxonomy() );
287 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
288 final String n = sequence_name.trim();
289 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
292 if ( matcher1.matches() ) {
293 group1 = matcher1.group( 1 );
294 group2 = matcher1.group( 2 );
297 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
298 if ( matcher2.matches() ) {
299 group1 = matcher2.group( 1 );
300 group2 = matcher2.group( 2 );
303 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
306 return new Accession( group2, group1 );
309 public final static void printWarningMessage( final String name, final String message ) {
310 System.out.println( "[" + name + "] > " + message );
313 final public static void showErrorMessage( final Component parent, final String error_msg ) {
314 printAppletMessage( Constants.PRG_NAME, error_msg );
315 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
316 + "] Error", JOptionPane.ERROR_MESSAGE );
319 public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
320 final PhylogenyNode node,
321 final List<String> data ) {
322 final StringBuilder sb = new StringBuilder();
323 if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
324 showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
326 if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
327 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
328 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
330 if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
331 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
332 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
334 if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
335 && ( node.getNodeData().getSequence().getAccession() != null )
336 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
337 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
339 if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
340 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
341 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
343 if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
344 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
345 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
347 if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
348 && node.getNodeData().isHasSequence()
349 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
350 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
352 final String s = sb.toString().trim();
353 if ( !ForesterUtil.isEmpty( s ) ) {
358 public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
359 if ( sb.length() > 0 ) {
365 final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
366 JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
369 public static void writePhylogenyToGraphicsFile( final File intree,
373 final GraphicsExportType type,
374 final Configuration config ) throws IOException {
375 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
376 Phylogeny[] phys = null;
377 phys = PhylogenyMethods.readPhylogenies( parser, intree );
378 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
381 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
385 final GraphicsExportType type,
386 final Configuration config ) throws IOException {
387 final Phylogeny[] phys = new Phylogeny[ 1 ];
389 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
390 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
391 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
395 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
398 final TreePanel tree_panel,
399 final ControlPanel ac,
400 final GraphicsExportType type,
401 final Options options ) throws IOException {
402 tree_panel.calcParametersForPainting( width, height, true );
403 tree_panel.resetPreferredSize();
404 tree_panel.repaint();
405 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
406 RenderingHints.VALUE_RENDER_QUALITY );
407 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
408 if ( options.isAntialiasPrint() ) {
409 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
410 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
413 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
414 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
416 final Phylogeny phylogeny = tree_panel.getPhylogeny();
417 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
420 if ( outfile.isDirectory() ) {
421 throw new IOException( "\"" + outfile + "\" is a directory" );
423 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
424 final Graphics2D g2d = buffered_img.createGraphics();
425 g2d.setRenderingHints( rendering_hints );
426 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
427 if ( type == GraphicsExportType.TIFF ) {
428 writeToTiff( outfile, buffered_img );
431 ImageIO.write( buffered_img, type.toString(), outfile );
436 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
437 final String default_name,
438 final String full_path,
439 final Configuration configuration,
440 final MainPanel main_panel ) {
441 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
442 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
443 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
444 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
447 for( final Phylogeny phy : phys ) {
448 if ( !phy.isEmpty() ) {
449 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
451 String my_name_for_file = "";
452 if ( phys.length > 1 ) {
453 if ( !ForesterUtil.isEmpty( default_name ) ) {
454 my_name = new String( default_name );
456 if ( !ForesterUtil.isEmpty( full_path ) ) {
457 my_name_for_file = new String( full_path );
459 else if ( !ForesterUtil.isEmpty( default_name ) ) {
460 my_name_for_file = new String( default_name );
463 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
464 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
465 my_name_for_file.length() );
466 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
468 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
469 my_name_for_file += "_";
471 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
472 my_name_for_file += phy.getName().replaceAll( " ", "_" );
474 else if ( phy.getIdentifier() != null ) {
475 final StringBuffer sb = new StringBuffer();
476 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
477 sb.append( phy.getIdentifier().getProvider() );
480 sb.append( phy.getIdentifier().getValue() );
481 my_name_for_file += sb;
484 my_name_for_file += i;
486 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
487 && ( phy.getIdentifier() == null ) ) {
488 my_name = my_name + " [" + i + "]";
490 if ( !ForesterUtil.isEmpty( suffix ) ) {
491 my_name_for_file += suffix;
495 if ( !ForesterUtil.isEmpty( default_name ) ) {
496 my_name = new String( default_name );
498 my_name_for_file = "";
499 if ( !ForesterUtil.isEmpty( full_path ) ) {
500 my_name_for_file = new String( full_path );
502 else if ( !ForesterUtil.isEmpty( default_name ) ) {
503 my_name_for_file = new String( default_name );
505 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
506 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
507 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
509 else if ( phy.getIdentifier() != null ) {
510 final StringBuffer sb = new StringBuffer();
511 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
512 sb.append( phy.getIdentifier().getProvider() );
515 sb.append( phy.getIdentifier().getValue() );
516 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
520 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
521 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
522 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
529 final static void addPhylogenyToPanel( final Phylogeny[] phys,
530 final Configuration configuration,
531 final MainPanel main_panel ) {
532 final Phylogeny phy = phys[ 0 ];
533 main_panel.addPhylogenyInPanel( phy, configuration );
534 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
537 final static Color calculateColorFromString( final String str ) {
538 final String species_uc = str.toUpperCase();
539 char first = species_uc.charAt( 0 );
542 if ( species_uc.length() > 1 ) {
543 second = species_uc.charAt( 1 );
544 if ( species_uc.length() > 2 ) {
545 if ( species_uc.indexOf( " " ) > 0 ) {
546 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
549 third = species_uc.charAt( 2 );
553 first = AptxUtil.normalizeCharForRGB( first );
554 second = AptxUtil.normalizeCharForRGB( second );
555 third = AptxUtil.normalizeCharForRGB( third );
556 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
559 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
562 return new Color( first, second, third );
565 // Returns true if the specified format name can be written
566 final static boolean canWriteFormat( final String format_name ) {
567 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
568 return iter.hasNext();
571 final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
572 boolean inferred = false;
573 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
574 final PhylogenyNode n = it.next();
575 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
576 final Set<Taxonomy> taxs = obtainDistinctTaxonomies( n );
577 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
578 AptxUtil.collapseSubtree( n, true );
579 if ( !n.getNodeData().isHasTaxonomy() ) {
580 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
581 .getTaxonomy().copy() );
586 n.setCollapse( false );
591 phy.setRerootable( false );
595 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
596 node.setCollapse( collapse );
597 if ( node.isExternal() ) {
600 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
601 while ( it.hasNext() ) {
602 it.next().setCollapse( collapse );
606 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
607 double max_conf = 0.0;
608 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
609 final PhylogenyNode n = it.next();
610 n.getBranchData().setBranchColor( null );
611 if ( n.getBranchData().isHasConfidences() ) {
612 final double conf = PhylogenyMethods.getConfidenceValue( n );
613 if ( conf > max_conf ) {
618 if ( max_conf > 0.0 ) {
619 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
620 final Color br = tree_panel.getTreeColorSet().getBranchColor();
621 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
622 final PhylogenyNode n = it.next();
623 if ( n.getBranchData().isHasConfidences() ) {
624 final double conf = PhylogenyMethods.getConfidenceValue( n );
625 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
626 colorizeSubtree( n, c );
632 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
633 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
634 it.next().getBranchData().setBranchColor( null );
636 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
637 final PhylogenyNode n = it.next();
638 if ( !n.getBranchData().isHasBranchColor() ) {
639 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
641 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
642 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
643 for( final PhylogenyNode desc : descs ) {
645 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
652 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
653 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
654 int colorizations = 0;
655 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
656 final PhylogenyNode n = it.next();
657 if ( n.getNodeData().isHasTaxonomy()
658 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
659 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
660 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
661 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
662 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
663 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
665 colorizeSubtree( n, c );
667 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
668 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
673 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
674 final PhylogenyNode node = it.next();
675 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
676 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
677 boolean success = false;
678 if ( !true_lineage_to_color_map.isEmpty() ) {
679 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
680 if ( true_lineage_to_color_map.containsKey( lin ) ) {
681 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
689 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
690 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
691 final Taxonomy temp_tax = new Taxonomy();
692 temp_tax.setScientificName( lin );
693 if ( lineage_to_rank_map.containsKey( lin )
694 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
695 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
696 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
697 colorizeSubtree( node, c );
699 true_lineage_to_color_map.put( lin, c.getValue() );
703 UniProtTaxonomy up = null;
705 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
707 catch ( final Exception e ) {
710 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
711 lineage_to_rank_map.put( lin, up.getRank() );
712 if ( up.getRank().equalsIgnoreCase( rank ) ) {
713 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
714 colorizeSubtree( node, c );
716 true_lineage_to_color_map.put( lin, c.getValue() );
725 return colorizations;
728 final static String createBasicInformation( final Phylogeny phy ) {
729 final StringBuilder desc = new StringBuilder();
730 if ( ( phy != null ) && !phy.isEmpty() ) {
731 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
732 desc.append( "Name: " );
733 desc.append( phy.getName() );
736 if ( phy.getIdentifier() != null ) {
737 desc.append( "Id: " );
738 desc.append( phy.getIdentifier().toString() );
741 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
742 desc.append( "Description: " );
743 desc.append( phy.getDescription() );
746 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
747 desc.append( "Distance Unit: " );
748 desc.append( phy.getDistanceUnit() );
751 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
752 desc.append( "Type: " );
753 desc.append( phy.getType() );
756 desc.append( "Rooted: " );
757 desc.append( phy.isRooted() );
759 desc.append( "Rerootable: " );
760 desc.append( phy.isRerootable() );
762 desc.append( "Nodes: " );
763 desc.append( phy.getNodeCount() );
765 desc.append( "External nodes: " );
766 desc.append( phy.getNumberOfExternalNodes() );
768 desc.append( "Internal nodes: " );
769 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
771 desc.append( "Internal nodes with polytomies: " );
772 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
774 desc.append( "Branches: " );
775 desc.append( phy.getNumberOfBranches() );
777 desc.append( "Depth: " );
778 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
780 desc.append( "Maximum distance to root: " );
781 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
783 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
784 if ( taxs != null ) {
785 desc.append( "Distinct external taxonomies: " );
786 desc.append( taxs.size() );
789 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
790 if ( bs.getN() > 3 ) {
792 desc.append( "Branch-length statistics: " );
794 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
796 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
798 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
799 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
801 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
803 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
805 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
807 final AsciiHistogram histo = new AsciiHistogram( bs );
808 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
811 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
812 if ( ds.getN() > 2 ) {
814 desc.append( "Descendants per node statistics: " );
816 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
818 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) + " (stdev: "
819 + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) + ")" );
821 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
823 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
826 List<DescriptiveStatistics> css = null;
828 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
830 catch ( final IllegalArgumentException e ) {
831 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
833 if ( ( css != null ) && ( css.size() > 0 ) ) {
835 for( int i = 0; i < css.size(); ++i ) {
836 final DescriptiveStatistics cs = css.get( i );
837 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
838 if ( css.size() > 1 ) {
839 desc.append( "Support statistics " + ( i + 1 ) + ": " );
842 desc.append( "Support statistics: " );
844 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
846 desc.append( " Type: " + cs.getDescription() );
849 desc.append( " Branches with support: " + cs.getN() );
851 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
853 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
854 if ( cs.getN() > 2 ) {
855 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
858 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
860 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
866 return desc.toString();
874 * to message to be printed
876 final static void dieWithSystemError( final String message ) {
877 System.out.println();
878 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
879 System.out.println( "Please contact the authors." );
880 System.out.println( Constants.PRG_NAME + " needs to close." );
881 System.out.println();
885 final static String[] getAllPossibleRanks() {
886 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
888 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
889 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
890 str_array[ i++ ] = e;
896 final static String[] getAllRanks( final Phylogeny tree ) {
897 final SortedSet<String> ranks = new TreeSet<String>();
898 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
899 final PhylogenyNode n = it.next();
900 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
901 ranks.add( n.getNodeData().getTaxonomy().getRank() );
904 return ForesterUtil.stringSetToArray( ranks );
907 final static String[] getAvailableFontFamiliesSorted() {
908 return AVAILABLE_FONT_FAMILIES_SORTED;
911 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
912 if ( !node.getNodeData().isHasEvent() ) {
915 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
921 final static boolean isUsOrCanada() {
923 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
927 catch ( final Exception e ) {
933 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
934 final ControlPanel atv_control,
935 final Configuration configuration ) {
936 if ( ( t != null ) && !t.isEmpty() ) {
937 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
938 atv_control.setDrawPhylogram( false );
939 atv_control.setDrawPhylogramEnabled( false );
941 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
942 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
943 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
944 atv_control.setDrawPhylogram( true );
945 atv_control.setDrawPhylogramEnabled( true );
948 atv_control.setDrawPhylogram( false );
952 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
953 if ( atv_control.getWriteConfidenceCb() != null ) {
954 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
955 atv_control.setCheckbox( Configuration.write_confidence_values, true );
958 atv_control.setCheckbox( Configuration.write_confidence_values, false );
962 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
963 if ( atv_control.getShowEventsCb() != null ) {
964 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
965 atv_control.setCheckbox( Configuration.write_events, true );
968 atv_control.setCheckbox( Configuration.write_events, false );
975 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
977 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
979 catch ( final Exception e ) {
980 throw new IOException( e );
984 final static void outOfMemoryError( final OutOfMemoryError e ) {
985 System.err.println();
986 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
987 System.err.println();
989 System.err.println();
990 JOptionPane.showMessageDialog( null,
991 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
992 + "\n\nError: " + e.getLocalizedMessage(),
993 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
994 JOptionPane.ERROR_MESSAGE );
998 final static void printAppletMessage( final String applet_name, final String message ) {
999 System.out.println( "[" + applet_name + "] > " + message );
1002 final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
1003 final boolean phyloxml_validate_against_xsd,
1004 final boolean replace_underscores,
1005 final boolean internal_numbers_are_confidences,
1006 final TAXONOMY_EXTRACTION taxonomy_extraction,
1007 final boolean midpoint_reroot ) throws FileNotFoundException,
1009 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1010 final PhylogenyParser parser;
1011 boolean nhx_or_nexus = false;
1012 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1013 parser = new TolParser();
1016 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
1017 if ( parser instanceof NHXParser ) {
1018 nhx_or_nexus = true;
1019 final NHXParser nhx = ( NHXParser ) parser;
1020 nhx.setReplaceUnderscores( replace_underscores );
1021 nhx.setIgnoreQuotes( false );
1022 nhx.setTaxonomyExtraction( taxonomy_extraction );
1024 else if ( parser instanceof NexusPhylogeniesParser ) {
1025 nhx_or_nexus = true;
1026 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1027 nex.setReplaceUnderscores( replace_underscores );
1028 nex.setIgnoreQuotes( false );
1031 final Phylogeny[] phys = factory.create( url.openStream(), parser );
1032 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
1033 for( final Phylogeny phy : phys ) {
1034 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1037 if ( midpoint_reroot ) {
1038 for( final Phylogeny phy : phys ) {
1039 PhylogenyMethods.midpointRoot( phy );
1040 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
1046 final static void removeBranchColors( final Phylogeny phy ) {
1047 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1048 it.next().getBranchData().setBranchColor( null );
1052 final static void unexpectedError( final Error e ) {
1053 System.err.println();
1054 e.printStackTrace( System.err );
1055 System.err.println();
1056 final StringBuffer sb = new StringBuffer();
1057 for( final StackTraceElement s : e.getStackTrace() ) {
1058 sb.append( s + "\n" );
1061 .showMessageDialog( null,
1062 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
1063 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
1065 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1066 JOptionPane.ERROR_MESSAGE );
1070 final static void unexpectedException( final Exception e ) {
1071 System.err.println();
1072 e.printStackTrace( System.err );
1073 System.err.println();
1074 final StringBuffer sb = new StringBuffer();
1075 for( final StackTraceElement s : e.getStackTrace() ) {
1076 sb.append( s + "\n" );
1078 JOptionPane.showMessageDialog( null,
1079 "An unexpected exception has occured. \nPlease contact: "
1080 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
1082 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
1083 JOptionPane.ERROR_MESSAGE );
1086 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1089 final TreePanel tree_panel,
1090 final ControlPanel ac,
1091 final GraphicsExportType type,
1092 final Options options ) throws IOException {
1093 if ( !options.isGraphicsExportUsingActualSize() ) {
1094 if ( options.isGraphicsExportVisibleOnly() ) {
1095 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1097 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1098 tree_panel.resetPreferredSize();
1099 tree_panel.repaint();
1101 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1102 RenderingHints.VALUE_RENDER_QUALITY );
1103 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1104 if ( options.isAntialiasPrint() ) {
1105 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1106 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1109 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1110 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1112 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1113 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1116 Rectangle visible = null;
1117 if ( !options.isGraphicsExportUsingActualSize() ) {
1118 width = options.getPrintSizeX();
1119 height = options.getPrintSizeY();
1121 else if ( options.isGraphicsExportVisibleOnly() ) {
1122 visible = tree_panel.getVisibleRect();
1123 width = visible.width;
1124 height = visible.height;
1126 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1127 Graphics2D g2d = buffered_img.createGraphics();
1128 g2d.setRenderingHints( rendering_hints );
1131 if ( options.isGraphicsExportVisibleOnly() ) {
1132 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1133 g2d.setClip( null );
1137 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1138 ImageIO.write( buffered_img, type.toString(), baos );
1141 if ( !options.isGraphicsExportUsingActualSize() ) {
1142 tree_panel.getMainPanel().getControlPanel().showWhole();
1144 String msg = baos.toString();
1145 if ( ( width > 0 ) && ( height > 0 ) ) {
1146 msg += " [size: " + width + ", " + height + "]";
1151 final static String writePhylogenyToGraphicsFile( final String file_name,
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 final File file = new File( file_name );
1182 if ( file.isDirectory() ) {
1183 throw new IOException( "\"" + file_name + "\" is a directory" );
1185 Rectangle visible = null;
1186 if ( !options.isGraphicsExportUsingActualSize() ) {
1187 width = options.getPrintSizeX();
1188 height = options.getPrintSizeY();
1190 else if ( options.isGraphicsExportVisibleOnly() ) {
1191 visible = tree_panel.getVisibleRect();
1192 width = visible.width;
1193 height = visible.height;
1195 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1196 Graphics2D g2d = buffered_img.createGraphics();
1197 g2d.setRenderingHints( rendering_hints );
1200 if ( options.isGraphicsExportVisibleOnly() ) {
1201 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1202 g2d.setClip( null );
1206 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1207 if ( type == GraphicsExportType.TIFF ) {
1208 writeToTiff( file, buffered_img );
1211 ImageIO.write( buffered_img, type.toString(), file );
1215 if ( !options.isGraphicsExportUsingActualSize() ) {
1216 tree_panel.getMainPanel().getControlPanel().showWhole();
1218 String msg = file.toString();
1219 if ( ( width > 0 ) && ( height > 0 ) ) {
1220 msg += " [size: " + width + ", " + height + "]";
1225 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1226 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1227 ImageWriter writer = null;
1228 ImageOutputStream ios = null;
1229 // Find an appropriate writer:
1230 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1231 if ( it.hasNext() ) {
1235 throw new IOException( "failed to get TIFF image writer" );
1238 ios = ImageIO.createImageOutputStream( file );
1239 writer.setOutput( ios );
1240 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1241 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1242 // see writeParam.getCompressionTypes() for available compression type
1244 image_write_param.setCompressionType( "PackBits" );
1245 final String t[] = image_write_param.getCompressionTypes();
1246 for( final String string : t ) {
1247 System.out.println( string );
1249 // Convert to an IIOImage:
1250 final IIOImage iio_image = new IIOImage( image, null, null );
1251 writer.write( null, iio_image, image_write_param );
1254 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1255 node.getBranchData().setBranchColor( c );
1256 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1257 for( final PhylogenyNode desc : descs ) {
1258 desc.getBranchData().setBranchColor( c );
1262 final private static char normalizeCharForRGB( char c ) {
1265 c = c > 255 ? 255 : c;
1270 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1271 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1272 InvocationTargetException, InterruptedException {
1273 final String os = System.getProperty( "os.name" );
1274 final Runtime runtime = Runtime.getRuntime();
1275 if ( os.toLowerCase().startsWith( "win" ) ) {
1276 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1278 else if ( ForesterUtil.isMac() ) {
1279 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1280 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1281 open_url.invoke( null, new Object[] { url } );
1284 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1285 String browser = null;
1286 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1287 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1288 browser = browsers[ i ];
1291 if ( browser == null ) {
1292 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1295 runtime.exec( new String[] { browser, url } );
1300 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1301 // static void openDDBJRest() throws IOException {
1303 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1305 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1306 // //make connection
1307 // URLConnection urlc = url.openConnection();
1309 // urlc.setDoOutput( true );
1310 // urlc.setAllowUserInteraction( false );
1312 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1313 // ps.print( query );
1316 // BufferedReader br = new BufferedReader( new InputStreamReader(
1317 // urlc.getInputStream() ) );
1319 // while ( ( l = br.readLine() ) != null ) {
1320 // System.out.println( l );
1324 public static enum GraphicsExportType {
1325 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1327 private final String _suffix;
1329 private GraphicsExportType( final String suffix ) {
1334 public String toString() {