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: www.phylosoft.org/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.lang.reflect.InvocationTargetException;
40 import java.lang.reflect.Method;
43 import java.text.ParseException;
44 import java.util.Arrays;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
48 import java.util.Locale;
51 import java.util.SortedSet;
52 import java.util.TreeSet;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
56 import javax.imageio.IIOImage;
57 import javax.imageio.ImageIO;
58 import javax.imageio.ImageWriteParam;
59 import javax.imageio.ImageWriter;
60 import javax.imageio.stream.ImageOutputStream;
61 import javax.swing.JApplet;
62 import javax.swing.JOptionPane;
63 import javax.swing.text.MaskFormatter;
65 import org.forester.analysis.TaxonomyDataManager;
66 import org.forester.io.parsers.PhylogenyParser;
67 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
68 import org.forester.io.parsers.nhx.NHXParser;
69 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
70 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
71 import org.forester.io.parsers.tol.TolParser;
72 import org.forester.io.parsers.util.ParserUtils;
73 import org.forester.phylogeny.Phylogeny;
74 import org.forester.phylogeny.PhylogenyMethods;
75 import org.forester.phylogeny.PhylogenyNode;
76 import org.forester.phylogeny.data.Accession;
77 import org.forester.phylogeny.data.BranchColor;
78 import org.forester.phylogeny.data.Taxonomy;
79 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
80 import org.forester.phylogeny.factories.PhylogenyFactory;
81 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
82 import org.forester.phylogeny.iterators.PreorderTreeIterator;
83 import org.forester.util.AsciiHistogram;
84 import org.forester.util.DescriptiveStatistics;
85 import org.forester.util.ForesterUtil;
86 import org.forester.ws.seqdb.UniProtTaxonomy;
88 public final class AptxUtil {
90 private final static Pattern seq_identifier_pattern_1 = Pattern
91 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
92 private final static Pattern seq_identifier_pattern_2 = Pattern
93 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
94 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
95 .getAvailableFontFamilyNames();
97 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
100 public static MaskFormatter createMaskFormatter( final String s ) {
101 MaskFormatter formatter = null;
103 formatter = new MaskFormatter( s );
105 catch ( final ParseException e ) {
106 throw new IllegalArgumentException( e );
111 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
112 final PhylogenyNodeIterator it = phy.iteratorPostorder();
113 while ( it.hasNext() ) {
114 if ( it.next().getNodeData().isHasEvent() ) {
122 * Returns true if at least one branch has a length larger than zero.
127 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
128 final PhylogenyNodeIterator it = phy.iteratorPostorder();
129 while ( it.hasNext() ) {
130 if ( it.next().getDistanceToParent() > 0.0 ) {
137 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
138 final PhylogenyNodeIterator it = phy.iteratorPostorder();
139 while ( it.hasNext() ) {
140 if ( it.next().getBranchData().isHasConfidences() ) {
147 final public static void launchWebBrowser( final URI uri,
148 final boolean is_applet,
149 final JApplet applet,
150 final String frame_name ) throws IOException {
152 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
155 // This requires Java 1.6:
156 // =======================
157 // boolean no_desktop = false;
159 // if ( Desktop.isDesktopSupported() ) {
160 // System.out.println( "desktop supported" );
161 // final Desktop dt = Desktop.getDesktop();
165 // no_desktop = true;
168 // catch ( final Exception ex ) {
169 // ex.printStackTrace();
170 // no_desktop = true;
172 // catch ( final Error er ) {
173 // er.printStackTrace();
174 // no_desktop = true;
176 // if ( no_desktop ) {
177 // System.out.println( "desktop not supported" );
179 openUrlInWebBrowser( uri.toString() );
181 catch ( final Exception e ) {
182 throw new IOException( e );
188 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
189 final String n = sequence_name.trim();
190 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
193 if ( matcher1.matches() ) {
194 group1 = matcher1.group( 1 );
195 group2 = matcher1.group( 2 );
198 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
199 if ( matcher2.matches() ) {
200 group1 = matcher2.group( 1 );
201 group2 = matcher2.group( 2 );
204 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
207 return new Accession( group2, group1 );
210 public final static void printWarningMessage( final String name, final String message ) {
211 System.out.println( "[" + name + "] > " + message );
214 final public static void showErrorMessage( final Component parent, final String error_msg ) {
215 printAppletMessage( Constants.PRG_NAME, error_msg );
216 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
217 + "] Error", JOptionPane.ERROR_MESSAGE );
220 public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
221 final PhylogenyNode node,
222 final List<String> data ) {
223 final StringBuilder sb = new StringBuilder();
224 if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
225 showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
227 if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
228 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
229 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
231 if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
232 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
233 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
235 if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
236 && ( node.getNodeData().getSequence().getAccession() != null )
237 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
238 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
240 if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
241 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
242 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
244 if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
245 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
246 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
248 if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
249 && node.getNodeData().isHasSequence()
250 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
251 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
253 final String s = sb.toString().trim();
254 if ( !ForesterUtil.isEmpty( s ) ) {
259 public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
260 if ( sb.length() > 0 ) {
266 final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
267 JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
270 public static void writePhylogenyToGraphicsFile( final File intree,
274 final GraphicsExportType type,
275 final Configuration config ) throws IOException {
276 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
277 Phylogeny[] phys = null;
278 phys = PhylogenyMethods.readPhylogenies( parser, intree );
279 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
282 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
286 final GraphicsExportType type,
287 final Configuration config ) throws IOException {
288 final Phylogeny[] phys = new Phylogeny[ 1 ];
290 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
291 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
292 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
296 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
299 final TreePanel tree_panel,
300 final ControlPanel ac,
301 final GraphicsExportType type,
302 final Options options ) throws IOException {
303 tree_panel.setParametersForPainting( width, height, true );
304 tree_panel.resetPreferredSize();
305 tree_panel.repaint();
306 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
307 RenderingHints.VALUE_RENDER_QUALITY );
308 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
309 if ( options.isAntialiasPrint() ) {
310 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
311 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
314 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
315 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
317 final Phylogeny phylogeny = tree_panel.getPhylogeny();
318 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
321 if ( outfile.isDirectory() ) {
322 throw new IOException( "\"" + outfile + "\" is a directory" );
324 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
325 final Graphics2D g2d = buffered_img.createGraphics();
326 g2d.setRenderingHints( rendering_hints );
327 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
328 if ( type == GraphicsExportType.TIFF ) {
329 writeToTiff( outfile, buffered_img );
332 ImageIO.write( buffered_img, type.toString(), outfile );
337 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
338 final String default_name,
339 final String full_path,
340 final Configuration configuration,
341 final MainPanel main_panel ) {
342 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
343 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
344 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
345 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
348 for( final Phylogeny phy : phys ) {
349 if ( !phy.isEmpty() ) {
350 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
352 String my_name_for_file = "";
353 if ( phys.length > 1 ) {
354 if ( !ForesterUtil.isEmpty( default_name ) ) {
355 my_name = new String( default_name );
357 if ( !ForesterUtil.isEmpty( full_path ) ) {
358 my_name_for_file = new String( full_path );
360 else if ( !ForesterUtil.isEmpty( default_name ) ) {
361 my_name_for_file = new String( default_name );
364 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
365 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
366 my_name_for_file.length() );
367 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
369 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
370 my_name_for_file += "_";
372 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
373 my_name_for_file += phy.getName().replaceAll( " ", "_" );
375 else if ( phy.getIdentifier() != null ) {
376 final StringBuffer sb = new StringBuffer();
377 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
378 sb.append( phy.getIdentifier().getProvider() );
381 sb.append( phy.getIdentifier().getValue() );
382 my_name_for_file += sb;
385 my_name_for_file += i;
387 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
388 && ( phy.getIdentifier() == null ) ) {
389 my_name = my_name + " [" + i + "]";
391 if ( !ForesterUtil.isEmpty( suffix ) ) {
392 my_name_for_file += suffix;
396 if ( !ForesterUtil.isEmpty( default_name ) ) {
397 my_name = new String( default_name );
399 my_name_for_file = "";
400 if ( !ForesterUtil.isEmpty( full_path ) ) {
401 my_name_for_file = new String( full_path );
403 else if ( !ForesterUtil.isEmpty( default_name ) ) {
404 my_name_for_file = new String( default_name );
406 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
407 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
408 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
410 else if ( phy.getIdentifier() != null ) {
411 final StringBuffer sb = new StringBuffer();
412 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
413 sb.append( phy.getIdentifier().getProvider() );
416 sb.append( phy.getIdentifier().getValue() );
417 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
421 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
422 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
423 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
430 final static void addPhylogenyToPanel( final Phylogeny[] phys,
431 final Configuration configuration,
432 final MainPanel main_panel ) {
433 final Phylogeny phy = phys[ 0 ];
434 main_panel.addPhylogenyInPanel( phy, configuration );
435 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
438 final static Color calculateColorFromString( final String str ) {
439 final String species_uc = str.toUpperCase();
440 char first = species_uc.charAt( 0 );
443 if ( species_uc.length() > 1 ) {
444 second = species_uc.charAt( 1 );
445 if ( species_uc.length() > 2 ) {
446 if ( species_uc.indexOf( " " ) > 0 ) {
447 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
450 third = species_uc.charAt( 2 );
454 first = AptxUtil.normalizeCharForRGB( first );
455 second = AptxUtil.normalizeCharForRGB( second );
456 third = AptxUtil.normalizeCharForRGB( third );
457 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
460 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
463 return new Color( first, second, third );
466 // Returns true if the specified format name can be written
467 final static boolean canWriteFormat( final String format_name ) {
468 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
469 return iter.hasNext();
472 final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
473 boolean inferred = false;
474 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
475 final PhylogenyNode n = it.next();
476 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
477 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
478 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
479 AptxUtil.collapseSubtree( n, true );
480 if ( !n.getNodeData().isHasTaxonomy() ) {
481 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
482 .getTaxonomy().copy() );
487 n.setCollapse( false );
492 phy.setRerootable( false );
496 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
497 node.setCollapse( collapse );
498 if ( node.isExternal() ) {
501 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
502 while ( it.hasNext() ) {
503 it.next().setCollapse( collapse );
507 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
508 double max_conf = 0.0;
509 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
510 final PhylogenyNode n = it.next();
511 n.getBranchData().setBranchColor( null );
512 if ( n.getBranchData().isHasConfidences() ) {
513 final double conf = PhylogenyMethods.getConfidenceValue( n );
514 if ( conf > max_conf ) {
519 if ( max_conf > 0.0 ) {
520 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
521 final Color br = tree_panel.getTreeColorSet().getBranchColor();
522 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
523 final PhylogenyNode n = it.next();
524 if ( n.getBranchData().isHasConfidences() ) {
525 final double conf = PhylogenyMethods.getConfidenceValue( n );
526 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
527 colorizeSubtree( n, c );
533 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
534 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
535 it.next().getBranchData().setBranchColor( null );
537 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
538 final PhylogenyNode n = it.next();
539 if ( !n.getBranchData().isHasBranchColor() ) {
540 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
542 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
543 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
544 for( final PhylogenyNode desc : descs ) {
546 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
553 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
554 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
555 int colorizations = 0;
556 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
557 final PhylogenyNode n = it.next();
558 if ( n.getNodeData().isHasTaxonomy()
559 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
560 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
561 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
562 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
563 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
564 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
566 colorizeSubtree( n, c );
568 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
569 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
574 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
575 final PhylogenyNode node = it.next();
576 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
577 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
578 boolean success = false;
579 if ( !true_lineage_to_color_map.isEmpty() ) {
580 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
581 if ( true_lineage_to_color_map.containsKey( lin ) ) {
582 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
590 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
591 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
592 final Taxonomy temp_tax = new Taxonomy();
593 temp_tax.setScientificName( lin );
594 if ( lineage_to_rank_map.containsKey( lin )
595 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
596 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
597 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
598 colorizeSubtree( node, c );
600 true_lineage_to_color_map.put( lin, c.getValue() );
604 UniProtTaxonomy up = null;
606 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
608 catch ( final Exception e ) {
611 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
612 lineage_to_rank_map.put( lin, up.getRank() );
613 if ( up.getRank().equalsIgnoreCase( rank ) ) {
614 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
615 colorizeSubtree( node, c );
617 true_lineage_to_color_map.put( lin, c.getValue() );
626 return colorizations;
629 final static String createBasicInformation( final Phylogeny phy ) {
630 final StringBuilder desc = new StringBuilder();
631 if ( ( phy != null ) && !phy.isEmpty() ) {
632 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
633 desc.append( "Name: " );
634 desc.append( phy.getName() );
637 if ( phy.getIdentifier() != null ) {
638 desc.append( "Id: " );
639 desc.append( phy.getIdentifier() );
642 desc.append( "Rooted: " );
643 desc.append( phy.isRooted() );
645 desc.append( "Rerootable: " );
646 desc.append( phy.isRerootable() );
648 desc.append( "Node sum: " );
649 desc.append( phy.getNodeCount() );
651 desc.append( "External node sum: " );
652 desc.append( phy.getNumberOfExternalNodes() );
654 desc.append( "Internal node sum: " );
655 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
657 desc.append( "Branche sum: " );
658 desc.append( phy.getNumberOfBranches() );
660 desc.append( "Depth: " );
661 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
663 desc.append( "Maximum distance to root: " );
664 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
666 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
667 if ( taxs != null ) {
668 desc.append( "Distinct external taxonomies: " );
669 desc.append( taxs.size() );
672 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
673 if ( bs.getN() > 3 ) {
675 desc.append( "Branch-length statistics: " );
677 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
679 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
681 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
683 desc.append( " SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
685 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
687 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
689 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
691 final AsciiHistogram histo = new AsciiHistogram( bs );
692 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
695 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
696 if ( ds.getN() > 2 ) {
698 desc.append( "Descendants per node statistics: " );
700 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
702 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
704 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
706 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
708 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
711 List<DescriptiveStatistics> css = null;
713 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
715 catch ( final IllegalArgumentException e ) {
716 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
718 if ( ( css != null ) && ( css.size() > 0 ) ) {
720 for( int i = 0; i < css.size(); ++i ) {
721 final DescriptiveStatistics cs = css.get( i );
722 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
723 if ( css.size() > 1 ) {
724 desc.append( "Support statistics " + ( i + 1 ) + ": " );
727 desc.append( "Support statistics: " );
729 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
731 desc.append( " Type: " + cs.getDescription() );
734 desc.append( " Branches with support: " + cs.getN() );
736 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
738 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
740 if ( cs.getN() > 2 ) {
741 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
744 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
746 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
752 return desc.toString();
760 * to message to be printed
762 final static void dieWithSystemError( final String message ) {
763 System.out.println();
764 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
765 System.out.println( "Please contact the authors." );
766 System.out.println( Constants.PRG_NAME + " needs to close." );
767 System.out.println();
771 final static String[] getAllPossibleRanks() {
772 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
774 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
775 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
776 str_array[ i++ ] = e;
782 final static String[] getAllRanks( final Phylogeny tree ) {
783 final SortedSet<String> ranks = new TreeSet<String>();
784 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
785 final PhylogenyNode n = it.next();
786 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
787 ranks.add( n.getNodeData().getTaxonomy().getRank() );
790 return ForesterUtil.stringSetToArray( ranks );
793 final static String[] getAvailableFontFamiliesSorted() {
794 return AVAILABLE_FONT_FAMILIES_SORTED;
797 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
798 if ( !node.getNodeData().isHasEvent() ) {
801 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
807 final static boolean isJava15() {
809 final String s = ForesterUtil.JAVA_VERSION;
810 return s.startsWith( "1.5" );
812 catch ( final Exception e ) {
813 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
818 final static boolean isMac() {
820 final String s = ForesterUtil.OS_NAME.toLowerCase();
821 return s.startsWith( "mac" );
823 catch ( final Exception e ) {
824 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
829 final static boolean isUsOrCanada() {
831 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
835 catch ( final Exception e ) {
841 final static boolean isWindows() {
843 final String s = ForesterUtil.OS_NAME.toLowerCase();
844 return s.indexOf( "win" ) > -1;
846 catch ( final Exception e ) {
847 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
852 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
853 final ControlPanel atv_control,
854 final Configuration configuration ) {
855 if ( ( t != null ) && !t.isEmpty() ) {
856 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
857 atv_control.setDrawPhylogram( false );
858 atv_control.setDrawPhylogramEnabled( false );
860 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
861 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
862 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
863 atv_control.setDrawPhylogram( true );
864 atv_control.setDrawPhylogramEnabled( true );
867 atv_control.setDrawPhylogram( false );
871 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
872 if ( atv_control.getWriteConfidenceCb() != null ) {
873 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
874 atv_control.setCheckbox( Configuration.write_confidence_values, true );
877 atv_control.setCheckbox( Configuration.write_confidence_values, false );
881 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
882 if ( atv_control.getShowEventsCb() != null ) {
883 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
884 atv_control.setCheckbox( Configuration.write_events, true );
887 atv_control.setCheckbox( Configuration.write_events, false );
894 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
896 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
898 catch ( final Exception e ) {
899 throw new IOException( e );
903 final static void printAppletMessage( final String applet_name, final String message ) {
904 System.out.println( "[" + applet_name + "] > " + message );
907 final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
908 final boolean phyloxml_validate_against_xsd,
909 final boolean replace_underscores,
910 final boolean internal_numbers_are_confidences,
911 final TAXONOMY_EXTRACTION taxonomy_extraction )
912 throws FileNotFoundException, IOException {
913 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
914 final PhylogenyParser parser;
915 boolean nhx_or_nexus = false;
916 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
917 parser = new TolParser();
920 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
921 if ( parser instanceof NHXParser ) {
923 final NHXParser nhx = ( NHXParser ) parser;
924 nhx.setReplaceUnderscores( replace_underscores );
925 nhx.setIgnoreQuotes( false );
926 nhx.setTaxonomyExtraction( taxonomy_extraction );
928 else if ( parser instanceof NexusPhylogeniesParser ) {
930 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
931 nex.setReplaceUnderscores( replace_underscores );
932 nex.setIgnoreQuotes( false );
935 final Phylogeny[] phys = factory.create( url.openStream(), parser );
936 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
937 for( final Phylogeny phy : phys ) {
938 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
944 final static void removeBranchColors( final Phylogeny phy ) {
945 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
946 it.next().getBranchData().setBranchColor( null );
950 final static void unexpectedError( final Error err ) {
951 err.printStackTrace();
952 final StringBuffer sb = new StringBuffer();
953 for( final StackTraceElement s : err.getStackTrace() ) {
954 sb.append( s + "\n" );
957 .showMessageDialog( null,
958 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
959 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
960 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
961 JOptionPane.ERROR_MESSAGE );
965 final static void unexpectedException( final Exception ex ) {
966 ex.printStackTrace();
967 final StringBuffer sb = new StringBuffer();
968 for( final StackTraceElement s : ex.getStackTrace() ) {
969 sb.append( s + "\n" );
971 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
972 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
973 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
976 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
979 final TreePanel tree_panel,
980 final ControlPanel ac,
981 final GraphicsExportType type,
982 final Options options ) throws IOException {
983 if ( !options.isGraphicsExportUsingActualSize() ) {
984 if ( options.isGraphicsExportVisibleOnly() ) {
985 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
987 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
988 tree_panel.resetPreferredSize();
989 tree_panel.repaint();
991 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
992 RenderingHints.VALUE_RENDER_QUALITY );
993 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
994 if ( options.isAntialiasPrint() ) {
995 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
996 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
999 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1000 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1002 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1003 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1006 Rectangle visible = null;
1007 if ( !options.isGraphicsExportUsingActualSize() ) {
1008 width = options.getPrintSizeX();
1009 height = options.getPrintSizeY();
1011 else if ( options.isGraphicsExportVisibleOnly() ) {
1012 visible = tree_panel.getVisibleRect();
1013 width = visible.width;
1014 height = visible.height;
1016 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1017 Graphics2D g2d = buffered_img.createGraphics();
1018 g2d.setRenderingHints( rendering_hints );
1021 if ( options.isGraphicsExportVisibleOnly() ) {
1022 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1023 g2d.setClip( null );
1027 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1028 ImageIO.write( buffered_img, type.toString(), baos );
1031 if ( !options.isGraphicsExportUsingActualSize() ) {
1032 tree_panel.getMainPanel().getControlPanel().showWhole();
1034 String msg = baos.toString();
1035 if ( ( width > 0 ) && ( height > 0 ) ) {
1036 msg += " [size: " + width + ", " + height + "]";
1041 final static String writePhylogenyToGraphicsFile( final String file_name,
1044 final TreePanel tree_panel,
1045 final ControlPanel ac,
1046 final GraphicsExportType type,
1047 final Options options ) throws IOException {
1048 if ( !options.isGraphicsExportUsingActualSize() ) {
1049 if ( options.isGraphicsExportVisibleOnly() ) {
1050 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1052 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1053 tree_panel.resetPreferredSize();
1054 tree_panel.repaint();
1056 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1057 RenderingHints.VALUE_RENDER_QUALITY );
1058 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1059 if ( options.isAntialiasPrint() ) {
1060 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1061 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1064 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1065 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1067 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1068 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1071 final File file = new File( file_name );
1072 if ( file.isDirectory() ) {
1073 throw new IOException( "\"" + file_name + "\" is a directory" );
1075 Rectangle visible = null;
1076 if ( !options.isGraphicsExportUsingActualSize() ) {
1077 width = options.getPrintSizeX();
1078 height = options.getPrintSizeY();
1080 else if ( options.isGraphicsExportVisibleOnly() ) {
1081 visible = tree_panel.getVisibleRect();
1082 width = visible.width;
1083 height = visible.height;
1085 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1086 Graphics2D g2d = buffered_img.createGraphics();
1087 g2d.setRenderingHints( rendering_hints );
1090 if ( options.isGraphicsExportVisibleOnly() ) {
1091 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1092 g2d.setClip( null );
1096 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1097 if ( type == GraphicsExportType.TIFF ) {
1098 writeToTiff( file, buffered_img );
1101 ImageIO.write( buffered_img, type.toString(), file );
1105 if ( !options.isGraphicsExportUsingActualSize() ) {
1106 tree_panel.getMainPanel().getControlPanel().showWhole();
1108 String msg = file.toString();
1109 if ( ( width > 0 ) && ( height > 0 ) ) {
1110 msg += " [size: " + width + ", " + height + "]";
1115 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1116 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1117 ImageWriter writer = null;
1118 ImageOutputStream ios = null;
1119 // Find an appropriate writer:
1120 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1121 if ( it.hasNext() ) {
1125 throw new IOException( "failed to get TIFF image writer" );
1128 ios = ImageIO.createImageOutputStream( file );
1129 writer.setOutput( ios );
1130 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1131 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1132 // see writeParam.getCompressionTypes() for available compression type
1134 image_write_param.setCompressionType( "PackBits" );
1135 final String t[] = image_write_param.getCompressionTypes();
1136 for( final String string : t ) {
1137 System.out.println( string );
1139 // Convert to an IIOImage:
1140 final IIOImage iio_image = new IIOImage( image, null, null );
1141 writer.write( null, iio_image, image_write_param );
1144 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1145 node.getBranchData().setBranchColor( c );
1146 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1147 for( final PhylogenyNode desc : descs ) {
1148 desc.getBranchData().setBranchColor( c );
1152 final private static char normalizeCharForRGB( char c ) {
1155 c = c > 255 ? 255 : c;
1160 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1161 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1162 InvocationTargetException, InterruptedException {
1163 final String os = System.getProperty( "os.name" );
1164 final Runtime runtime = Runtime.getRuntime();
1165 if ( os.toLowerCase().startsWith( "win" ) ) {
1166 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1168 else if ( isMac() ) {
1169 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1170 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1171 open_url.invoke( null, new Object[] { url } );
1174 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1175 String browser = null;
1176 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1177 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1178 browser = browsers[ i ];
1181 if ( browser == null ) {
1182 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1185 runtime.exec( new String[] { browser, url } );
1190 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1191 // static void openDDBJRest() throws IOException {
1193 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1195 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1196 // //make connection
1197 // URLConnection urlc = url.openConnection();
1199 // urlc.setDoOutput( true );
1200 // urlc.setAllowUserInteraction( false );
1202 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1203 // ps.print( query );
1206 // BufferedReader br = new BufferedReader( new InputStreamReader(
1207 // urlc.getInputStream() ) );
1209 // while ( ( l = br.readLine() ) != null ) {
1210 // System.out.println( l );
1214 public static enum GraphicsExportType {
1215 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1217 private final String _suffix;
1219 private GraphicsExportType( final String suffix ) {
1224 public String toString() {