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
28 package org.forester.archaeopteryx;
30 import java.awt.Color;
31 import java.awt.Component;
32 import java.awt.Graphics2D;
33 import java.awt.GraphicsEnvironment;
34 import java.awt.Rectangle;
35 import java.awt.RenderingHints;
36 import java.awt.image.BufferedImage;
37 import java.io.ByteArrayOutputStream;
39 import java.io.FileNotFoundException;
40 import java.io.IOException;
41 import java.lang.reflect.InvocationTargetException;
42 import java.lang.reflect.Method;
45 import java.text.ParseException;
46 import java.util.Arrays;
47 import java.util.HashMap;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Locale;
53 import java.util.SortedSet;
54 import java.util.TreeSet;
55 import java.util.regex.Matcher;
56 import java.util.regex.Pattern;
58 import javax.imageio.IIOImage;
59 import javax.imageio.ImageIO;
60 import javax.imageio.ImageWriteParam;
61 import javax.imageio.ImageWriter;
62 import javax.imageio.stream.ImageOutputStream;
63 import javax.swing.JApplet;
64 import javax.swing.JOptionPane;
65 import javax.swing.text.MaskFormatter;
67 import org.forester.analysis.TaxonomyDataManager;
68 import org.forester.io.parsers.PhylogenyParser;
69 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
70 import org.forester.io.parsers.nhx.NHXParser;
71 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
72 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
73 import org.forester.io.parsers.tol.TolParser;
74 import org.forester.io.parsers.util.ParserUtils;
75 import org.forester.phylogeny.Phylogeny;
76 import org.forester.phylogeny.PhylogenyMethods;
77 import org.forester.phylogeny.PhylogenyNode;
78 import org.forester.phylogeny.data.Accession;
79 import org.forester.phylogeny.data.BranchColor;
80 import org.forester.phylogeny.data.Taxonomy;
81 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
82 import org.forester.phylogeny.factories.PhylogenyFactory;
83 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
84 import org.forester.phylogeny.iterators.PreorderTreeIterator;
85 import org.forester.util.AsciiHistogram;
86 import org.forester.util.DescriptiveStatistics;
87 import org.forester.util.ForesterUtil;
88 import org.forester.ws.seqdb.UniProtTaxonomy;
90 public final class AptxUtil {
92 private final static Pattern seq_identifier_pattern_1 = Pattern
93 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
94 private final static Pattern seq_identifier_pattern_2 = Pattern
95 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
96 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
97 .getAvailableFontFamilyNames();
99 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
102 public static MaskFormatter createMaskFormatter( final String s ) {
103 MaskFormatter formatter = null;
105 formatter = new MaskFormatter( s );
107 catch ( final ParseException e ) {
108 throw new IllegalArgumentException( e );
113 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
114 final PhylogenyNodeIterator it = phy.iteratorPostorder();
115 while ( it.hasNext() ) {
116 if ( it.next().getNodeData().isHasEvent() ) {
124 * Returns true if at least one branch has a length larger than zero.
129 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
130 final PhylogenyNodeIterator it = phy.iteratorPostorder();
131 while ( it.hasNext() ) {
132 if ( it.next().getDistanceToParent() > 0.0 ) {
139 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
140 final PhylogenyNodeIterator it = phy.iteratorPostorder();
141 while ( it.hasNext() ) {
142 if ( it.next().getBranchData().isHasConfidences() ) {
149 final public static void launchWebBrowser( final URI uri,
150 final boolean is_applet,
151 final JApplet applet,
152 final String frame_name ) throws IOException {
154 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
157 // This requires Java 1.6:
158 // =======================
159 // boolean no_desktop = false;
161 // if ( Desktop.isDesktopSupported() ) {
162 // System.out.println( "desktop supported" );
163 // final Desktop dt = Desktop.getDesktop();
167 // no_desktop = true;
170 // catch ( final Exception ex ) {
171 // ex.printStackTrace();
172 // no_desktop = true;
174 // catch ( final Error er ) {
175 // er.printStackTrace();
176 // no_desktop = true;
178 // if ( no_desktop ) {
179 // System.out.println( "desktop not supported" );
181 openUrlInWebBrowser( uri.toString() );
183 catch ( final Exception e ) {
184 throw new IOException( e );
190 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
191 final String n = sequence_name.trim();
192 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
195 if ( matcher1.matches() ) {
196 group1 = matcher1.group( 1 );
197 group2 = matcher1.group( 2 );
200 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
201 if ( matcher2.matches() ) {
202 group1 = matcher2.group( 1 );
203 group2 = matcher2.group( 2 );
206 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
209 return new Accession( group2, group1 );
212 public final static void printWarningMessage( final String name, final String message ) {
213 System.out.println( "[" + name + "] > " + message );
216 final public static void showErrorMessage( final Component parent, final String error_msg ) {
217 printAppletMessage( Constants.PRG_NAME, error_msg );
218 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
219 + "] Error", JOptionPane.ERROR_MESSAGE );
222 public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
223 final PhylogenyNode node,
224 final List<String> data ) {
225 final StringBuilder sb = new StringBuilder();
226 if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
227 showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
229 if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
230 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
231 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
233 if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
234 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
235 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
237 if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
238 && ( node.getNodeData().getSequence().getAccession() != null )
239 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
240 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
242 if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
243 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
244 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
246 if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
247 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
248 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
250 if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
251 && node.getNodeData().isHasSequence()
252 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
253 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
255 final String s = sb.toString().trim();
256 if ( !ForesterUtil.isEmpty( s ) ) {
261 public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
262 if ( sb.length() > 0 ) {
268 final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
269 JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
272 public static void writePhylogenyToGraphicsFile( final File intree,
276 final GraphicsExportType type,
277 final Configuration config ) throws IOException {
278 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
279 Phylogeny[] phys = null;
280 phys = PhylogenyMethods.readPhylogenies( parser, intree );
281 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
284 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
288 final GraphicsExportType type,
289 final Configuration config ) throws IOException {
290 final Phylogeny[] phys = new Phylogeny[ 1 ];
292 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
293 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
294 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
298 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
301 final TreePanel tree_panel,
302 final ControlPanel ac,
303 final GraphicsExportType type,
304 final Options options ) throws IOException {
305 tree_panel.setParametersForPainting( width, height, true );
306 tree_panel.resetPreferredSize();
307 tree_panel.repaint();
308 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
309 RenderingHints.VALUE_RENDER_QUALITY );
310 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
311 if ( options.isAntialiasPrint() ) {
312 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
313 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
316 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
317 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
319 final Phylogeny phylogeny = tree_panel.getPhylogeny();
320 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
323 if ( outfile.isDirectory() ) {
324 throw new IOException( "\"" + outfile + "\" is a directory" );
326 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
327 final Graphics2D g2d = buffered_img.createGraphics();
328 g2d.setRenderingHints( rendering_hints );
329 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
330 if ( type == GraphicsExportType.TIFF ) {
331 writeToTiff( outfile, buffered_img );
334 ImageIO.write( buffered_img, type.toString(), outfile );
339 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
340 final String default_name,
341 final String full_path,
342 final Configuration configuration,
343 final MainPanel main_panel ) {
344 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
345 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
346 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
347 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
350 for( final Phylogeny phy : phys ) {
351 if ( !phy.isEmpty() ) {
352 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
354 String my_name_for_file = "";
355 if ( phys.length > 1 ) {
356 if ( !ForesterUtil.isEmpty( default_name ) ) {
357 my_name = new String( default_name );
359 if ( !ForesterUtil.isEmpty( full_path ) ) {
360 my_name_for_file = new String( full_path );
362 else if ( !ForesterUtil.isEmpty( default_name ) ) {
363 my_name_for_file = new String( default_name );
366 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
367 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
368 my_name_for_file.length() );
369 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
371 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
372 my_name_for_file += "_";
374 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
375 my_name_for_file += phy.getName().replaceAll( " ", "_" );
377 else if ( phy.getIdentifier() != null ) {
378 final StringBuffer sb = new StringBuffer();
379 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
380 sb.append( phy.getIdentifier().getProvider() );
383 sb.append( phy.getIdentifier().getValue() );
384 my_name_for_file += sb;
387 my_name_for_file += i;
389 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
390 && ( phy.getIdentifier() == null ) ) {
391 my_name = my_name + " [" + i + "]";
393 if ( !ForesterUtil.isEmpty( suffix ) ) {
394 my_name_for_file += suffix;
398 if ( !ForesterUtil.isEmpty( default_name ) ) {
399 my_name = new String( default_name );
401 my_name_for_file = "";
402 if ( !ForesterUtil.isEmpty( full_path ) ) {
403 my_name_for_file = new String( full_path );
405 else if ( !ForesterUtil.isEmpty( default_name ) ) {
406 my_name_for_file = new String( default_name );
408 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
409 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
410 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
412 else if ( phy.getIdentifier() != null ) {
413 final StringBuffer sb = new StringBuffer();
414 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
415 sb.append( phy.getIdentifier().getProvider() );
418 sb.append( phy.getIdentifier().getValue() );
419 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
423 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
424 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
425 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
432 final static void addPhylogenyToPanel( final Phylogeny[] phys,
433 final Configuration configuration,
434 final MainPanel main_panel ) {
435 final Phylogeny phy = phys[ 0 ];
436 main_panel.addPhylogenyInPanel( phy, configuration );
437 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
440 final static Color calculateColorFromString( final String str ) {
441 final String species_uc = str.toUpperCase();
442 char first = species_uc.charAt( 0 );
445 if ( species_uc.length() > 1 ) {
446 second = species_uc.charAt( 1 );
447 if ( species_uc.length() > 2 ) {
448 if ( species_uc.indexOf( " " ) > 0 ) {
449 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
452 third = species_uc.charAt( 2 );
456 first = AptxUtil.normalizeCharForRGB( first );
457 second = AptxUtil.normalizeCharForRGB( second );
458 third = AptxUtil.normalizeCharForRGB( third );
459 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
462 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
465 return new Color( first, second, third );
468 // Returns true if the specified format name can be written
469 final static boolean canWriteFormat( final String format_name ) {
470 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
471 return iter.hasNext();
474 final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
475 boolean inferred = false;
476 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
477 final PhylogenyNode n = it.next();
478 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
479 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
480 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
481 AptxUtil.collapseSubtree( n, true );
482 if ( !n.getNodeData().isHasTaxonomy() ) {
483 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
484 .getTaxonomy().copy() );
489 n.setCollapse( false );
494 phy.setRerootable( false );
498 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
499 node.setCollapse( collapse );
500 if ( node.isExternal() ) {
503 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
504 while ( it.hasNext() ) {
505 it.next().setCollapse( collapse );
509 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
510 double max_conf = 0.0;
511 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
512 final PhylogenyNode n = it.next();
513 n.getBranchData().setBranchColor( null );
514 if ( n.getBranchData().isHasConfidences() ) {
515 final double conf = PhylogenyMethods.getConfidenceValue( n );
516 if ( conf > max_conf ) {
521 if ( max_conf > 0.0 ) {
522 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
523 final Color br = tree_panel.getTreeColorSet().getBranchColor();
524 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
525 final PhylogenyNode n = it.next();
526 if ( n.getBranchData().isHasConfidences() ) {
527 final double conf = PhylogenyMethods.getConfidenceValue( n );
528 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
529 colorizeSubtree( n, c );
535 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
536 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
537 it.next().getBranchData().setBranchColor( null );
539 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
540 final PhylogenyNode n = it.next();
541 if ( !n.getBranchData().isHasBranchColor() ) {
542 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
544 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
545 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
546 for( final PhylogenyNode desc : descs ) {
548 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
555 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
556 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
557 int colorizations = 0;
558 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
559 final PhylogenyNode n = it.next();
560 if ( n.getNodeData().isHasTaxonomy()
561 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
562 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
563 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
564 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
565 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
566 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
568 colorizeSubtree( n, c );
570 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
571 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
576 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
577 final PhylogenyNode node = it.next();
578 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
579 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
580 boolean success = false;
581 if ( !true_lineage_to_color_map.isEmpty() ) {
582 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
583 if ( true_lineage_to_color_map.containsKey( lin ) ) {
584 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
592 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
593 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
594 final Taxonomy temp_tax = new Taxonomy();
595 temp_tax.setScientificName( lin );
596 if ( lineage_to_rank_map.containsKey( lin )
597 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
598 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
599 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
600 colorizeSubtree( node, c );
602 true_lineage_to_color_map.put( lin, c.getValue() );
606 UniProtTaxonomy up = null;
608 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
610 catch ( final Exception e ) {
613 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
614 lineage_to_rank_map.put( lin, up.getRank() );
615 if ( up.getRank().equalsIgnoreCase( rank ) ) {
616 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
617 colorizeSubtree( node, c );
619 true_lineage_to_color_map.put( lin, c.getValue() );
628 return colorizations;
631 final static String createBasicInformation( final Phylogeny phy ) {
632 final StringBuilder desc = new StringBuilder();
633 if ( ( phy != null ) && !phy.isEmpty() ) {
634 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
635 desc.append( "Name: " );
636 desc.append( phy.getName() );
639 if ( phy.getIdentifier() != null ) {
640 desc.append( "Id: " );
641 desc.append( phy.getIdentifier() );
644 desc.append( "Rooted: " );
645 desc.append( phy.isRooted() );
647 desc.append( "Rerootable: " );
648 desc.append( phy.isRerootable() );
650 desc.append( "Node sum: " );
651 desc.append( phy.getNodeCount() );
653 desc.append( "External node sum: " );
654 desc.append( phy.getNumberOfExternalNodes() );
656 desc.append( "Internal node sum: " );
657 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
659 desc.append( "Branche sum: " );
660 desc.append( phy.getNumberOfBranches() );
662 desc.append( "Depth: " );
663 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
665 desc.append( "Maximum distance to root: " );
666 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
668 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
669 if ( taxs != null ) {
670 desc.append( "Distinct external taxonomies: " );
671 desc.append( taxs.size() );
674 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
675 if ( bs.getN() > 3 ) {
677 desc.append( "Branch-length statistics: " );
679 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
681 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
683 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
685 desc.append( " SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
687 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
689 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
691 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
693 final AsciiHistogram histo = new AsciiHistogram( bs );
694 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
697 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
698 if ( ds.getN() > 2 ) {
700 desc.append( "Descendants per node statistics: " );
702 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
704 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
706 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
708 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
710 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
713 List<DescriptiveStatistics> css = null;
715 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
717 catch ( final IllegalArgumentException e ) {
718 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
720 if ( ( css != null ) && ( css.size() > 0 ) ) {
722 for( int i = 0; i < css.size(); ++i ) {
723 final DescriptiveStatistics cs = css.get( i );
724 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
725 if ( css.size() > 1 ) {
726 desc.append( "Support statistics " + ( i + 1 ) + ": " );
729 desc.append( "Support statistics: " );
731 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
733 desc.append( " Type: " + cs.getDescription() );
736 desc.append( " Branches with support: " + cs.getN() );
738 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
740 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
742 if ( cs.getN() > 2 ) {
743 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
746 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
748 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
754 return desc.toString();
762 * to message to be printed
764 final static void dieWithSystemError( final String message ) {
765 System.out.println();
766 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
767 System.out.println( "Please contact the authors." );
768 System.out.println( Constants.PRG_NAME + " needs to close." );
769 System.out.println();
773 final static String[] getAllPossibleRanks() {
774 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
776 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
777 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
778 str_array[ i++ ] = e;
784 final static String[] getAllRanks( final Phylogeny tree ) {
785 final SortedSet<String> ranks = new TreeSet<String>();
786 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
787 final PhylogenyNode n = it.next();
788 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
789 ranks.add( n.getNodeData().getTaxonomy().getRank() );
792 return ForesterUtil.stringSetToArray( ranks );
795 final static String[] getAvailableFontFamiliesSorted() {
796 return AVAILABLE_FONT_FAMILIES_SORTED;
799 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
800 if ( !node.getNodeData().isHasEvent() ) {
803 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
809 final static boolean isJava15() {
811 final String s = ForesterUtil.JAVA_VERSION;
812 return s.startsWith( "1.5" );
814 catch ( final Exception e ) {
815 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
820 final static boolean isMac() {
822 final String s = ForesterUtil.OS_NAME.toLowerCase();
823 return s.startsWith( "mac" );
825 catch ( final Exception e ) {
826 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
831 final static boolean isUsOrCanada() {
833 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
837 catch ( final Exception e ) {
843 final static boolean isWindows() {
845 final String s = ForesterUtil.OS_NAME.toLowerCase();
846 return s.indexOf( "win" ) > -1;
848 catch ( final Exception e ) {
849 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
854 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
855 final ControlPanel atv_control,
856 final Configuration configuration ) {
857 if ( ( t != null ) && !t.isEmpty() ) {
858 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
859 atv_control.setDrawPhylogram( false );
860 atv_control.setDrawPhylogramEnabled( false );
862 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
863 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
864 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
865 atv_control.setDrawPhylogram( true );
866 atv_control.setDrawPhylogramEnabled( true );
869 atv_control.setDrawPhylogram( false );
873 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
874 if ( atv_control.getWriteConfidenceCb() != null ) {
875 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
876 atv_control.setCheckbox( Configuration.write_confidence_values, true );
879 atv_control.setCheckbox( Configuration.write_confidence_values, false );
883 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
884 if ( atv_control.getShowEventsCb() != null ) {
885 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
886 atv_control.setCheckbox( Configuration.write_events, true );
889 atv_control.setCheckbox( Configuration.write_events, false );
896 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
898 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
900 catch ( final Exception e ) {
901 throw new IOException( e );
905 final static void printAppletMessage( final String applet_name, final String message ) {
906 System.out.println( "[" + applet_name + "] > " + message );
909 final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
910 final boolean phyloxml_validate_against_xsd,
911 final boolean replace_underscores,
912 final boolean internal_numbers_are_confidences,
913 final TAXONOMY_EXTRACTION taxonomy_extraction )
914 throws FileNotFoundException, IOException {
915 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
916 final PhylogenyParser parser;
917 boolean nhx_or_nexus = false;
918 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
919 parser = new TolParser();
922 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
923 if ( parser instanceof NHXParser ) {
925 final NHXParser nhx = ( NHXParser ) parser;
926 nhx.setReplaceUnderscores( replace_underscores );
927 nhx.setIgnoreQuotes( false );
928 nhx.setTaxonomyExtraction( taxonomy_extraction );
930 else if ( parser instanceof NexusPhylogeniesParser ) {
932 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
933 nex.setReplaceUnderscores( replace_underscores );
934 nex.setIgnoreQuotes( false );
937 final Phylogeny[] phys = factory.create( url.openStream(), parser );
938 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
939 for( final Phylogeny phy : phys ) {
940 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
946 final static void removeBranchColors( final Phylogeny phy ) {
947 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
948 it.next().getBranchData().setBranchColor( null );
952 final static void unexpectedError( final Error e ) {
953 System.err.println();
954 e.printStackTrace( System.err );
955 System.err.println();
956 final StringBuffer sb = new StringBuffer();
957 for( final StackTraceElement s : e.getStackTrace() ) {
958 sb.append( s + "\n" );
961 .showMessageDialog( null,
962 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
963 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
965 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
966 JOptionPane.ERROR_MESSAGE );
970 final static void outOfMemoryError( final OutOfMemoryError e ) {
971 System.err.println();
972 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
973 System.err.println();
975 System.err.println();
976 JOptionPane.showMessageDialog( null,
977 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
978 + "\n\nError: " + e.getLocalizedMessage(),
979 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
980 JOptionPane.ERROR_MESSAGE );
984 final static void unexpectedException( final Exception e ) {
985 System.err.println();
986 e.printStackTrace( System.err );
987 System.err.println();
988 final StringBuffer sb = new StringBuffer();
989 for( final StackTraceElement s : e.getStackTrace() ) {
990 sb.append( s + "\n" );
992 JOptionPane.showMessageDialog( null,
993 "An unexpected exception has occured. \nPlease contact: "
994 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
996 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
997 JOptionPane.ERROR_MESSAGE );
1000 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1003 final TreePanel tree_panel,
1004 final ControlPanel ac,
1005 final GraphicsExportType type,
1006 final Options options ) throws IOException {
1007 if ( !options.isGraphicsExportUsingActualSize() ) {
1008 if ( options.isGraphicsExportVisibleOnly() ) {
1009 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1011 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1012 tree_panel.resetPreferredSize();
1013 tree_panel.repaint();
1015 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1016 RenderingHints.VALUE_RENDER_QUALITY );
1017 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1018 if ( options.isAntialiasPrint() ) {
1019 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1020 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1023 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1024 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1026 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1027 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1030 Rectangle visible = null;
1031 if ( !options.isGraphicsExportUsingActualSize() ) {
1032 width = options.getPrintSizeX();
1033 height = options.getPrintSizeY();
1035 else if ( options.isGraphicsExportVisibleOnly() ) {
1036 visible = tree_panel.getVisibleRect();
1037 width = visible.width;
1038 height = visible.height;
1040 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1041 Graphics2D g2d = buffered_img.createGraphics();
1042 g2d.setRenderingHints( rendering_hints );
1045 if ( options.isGraphicsExportVisibleOnly() ) {
1046 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1047 g2d.setClip( null );
1051 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1052 ImageIO.write( buffered_img, type.toString(), baos );
1055 if ( !options.isGraphicsExportUsingActualSize() ) {
1056 tree_panel.getMainPanel().getControlPanel().showWhole();
1058 String msg = baos.toString();
1059 if ( ( width > 0 ) && ( height > 0 ) ) {
1060 msg += " [size: " + width + ", " + height + "]";
1065 final static String writePhylogenyToGraphicsFile( final String file_name,
1068 final TreePanel tree_panel,
1069 final ControlPanel ac,
1070 final GraphicsExportType type,
1071 final Options options ) throws IOException {
1072 if ( !options.isGraphicsExportUsingActualSize() ) {
1073 if ( options.isGraphicsExportVisibleOnly() ) {
1074 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1076 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1077 tree_panel.resetPreferredSize();
1078 tree_panel.repaint();
1080 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1081 RenderingHints.VALUE_RENDER_QUALITY );
1082 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1083 if ( options.isAntialiasPrint() ) {
1084 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1085 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1088 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1089 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1091 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1092 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1095 final File file = new File( file_name );
1096 if ( file.isDirectory() ) {
1097 throw new IOException( "\"" + file_name + "\" is a directory" );
1099 Rectangle visible = null;
1100 if ( !options.isGraphicsExportUsingActualSize() ) {
1101 width = options.getPrintSizeX();
1102 height = options.getPrintSizeY();
1104 else if ( options.isGraphicsExportVisibleOnly() ) {
1105 visible = tree_panel.getVisibleRect();
1106 width = visible.width;
1107 height = visible.height;
1109 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1110 Graphics2D g2d = buffered_img.createGraphics();
1111 g2d.setRenderingHints( rendering_hints );
1114 if ( options.isGraphicsExportVisibleOnly() ) {
1115 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1116 g2d.setClip( null );
1120 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1121 if ( type == GraphicsExportType.TIFF ) {
1122 writeToTiff( file, buffered_img );
1125 ImageIO.write( buffered_img, type.toString(), file );
1129 if ( !options.isGraphicsExportUsingActualSize() ) {
1130 tree_panel.getMainPanel().getControlPanel().showWhole();
1132 String msg = file.toString();
1133 if ( ( width > 0 ) && ( height > 0 ) ) {
1134 msg += " [size: " + width + ", " + height + "]";
1139 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1140 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1141 ImageWriter writer = null;
1142 ImageOutputStream ios = null;
1143 // Find an appropriate writer:
1144 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1145 if ( it.hasNext() ) {
1149 throw new IOException( "failed to get TIFF image writer" );
1152 ios = ImageIO.createImageOutputStream( file );
1153 writer.setOutput( ios );
1154 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1155 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1156 // see writeParam.getCompressionTypes() for available compression type
1158 image_write_param.setCompressionType( "PackBits" );
1159 final String t[] = image_write_param.getCompressionTypes();
1160 for( final String string : t ) {
1161 System.out.println( string );
1163 // Convert to an IIOImage:
1164 final IIOImage iio_image = new IIOImage( image, null, null );
1165 writer.write( null, iio_image, image_write_param );
1168 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1169 node.getBranchData().setBranchColor( c );
1170 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1171 for( final PhylogenyNode desc : descs ) {
1172 desc.getBranchData().setBranchColor( c );
1176 final private static char normalizeCharForRGB( char c ) {
1179 c = c > 255 ? 255 : c;
1184 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1185 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1186 InvocationTargetException, InterruptedException {
1187 final String os = System.getProperty( "os.name" );
1188 final Runtime runtime = Runtime.getRuntime();
1189 if ( os.toLowerCase().startsWith( "win" ) ) {
1190 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1192 else if ( isMac() ) {
1193 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1194 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1195 open_url.invoke( null, new Object[] { url } );
1198 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1199 String browser = null;
1200 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1201 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1202 browser = browsers[ i ];
1205 if ( browser == null ) {
1206 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1209 runtime.exec( new String[] { browser, url } );
1214 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1215 // static void openDDBJRest() throws IOException {
1217 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1219 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1220 // //make connection
1221 // URLConnection urlc = url.openConnection();
1223 // urlc.setDoOutput( true );
1224 // urlc.setAllowUserInteraction( false );
1226 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1227 // ps.print( query );
1230 // BufferedReader br = new BufferedReader( new InputStreamReader(
1231 // urlc.getInputStream() ) );
1233 // while ( ( l = br.readLine() ) != null ) {
1234 // System.out.println( l );
1238 public static enum GraphicsExportType {
1239 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1241 private final String _suffix;
1243 private GraphicsExportType( final String suffix ) {
1248 public String toString() {