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.phyloxml.PhyloXmlUtil;
68 import org.forester.io.parsers.tol.TolParser;
69 import org.forester.io.parsers.util.ParserUtils;
70 import org.forester.phylogeny.Phylogeny;
71 import org.forester.phylogeny.PhylogenyMethods;
72 import org.forester.phylogeny.PhylogenyNode;
73 import org.forester.phylogeny.data.Accession;
74 import org.forester.phylogeny.data.BranchColor;
75 import org.forester.phylogeny.data.Taxonomy;
76 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
77 import org.forester.phylogeny.factories.PhylogenyFactory;
78 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
79 import org.forester.phylogeny.iterators.PreorderTreeIterator;
80 import org.forester.util.AsciiHistogram;
81 import org.forester.util.DescriptiveStatistics;
82 import org.forester.util.ForesterUtil;
83 import org.forester.ws.seqdb.UniProtTaxonomy;
85 public final class AptxUtil {
87 private final static Pattern seq_identifier_pattern_1 = Pattern
88 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
89 private final static Pattern seq_identifier_pattern_2 = Pattern
90 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
91 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
92 .getAvailableFontFamilyNames();
94 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
97 public static MaskFormatter createMaskFormatter( final String s ) {
98 MaskFormatter formatter = null;
100 formatter = new MaskFormatter( s );
102 catch ( final ParseException e ) {
103 throw new IllegalArgumentException( e );
108 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
109 final PhylogenyNodeIterator it = phy.iteratorPostorder();
110 while ( it.hasNext() ) {
111 if ( it.next().getNodeData().isHasEvent() ) {
119 * Returns true if at least one branch has a length larger than zero.
124 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
125 final PhylogenyNodeIterator it = phy.iteratorPostorder();
126 while ( it.hasNext() ) {
127 if ( it.next().getDistanceToParent() > 0.0 ) {
134 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
135 final PhylogenyNodeIterator it = phy.iteratorPostorder();
136 while ( it.hasNext() ) {
137 if ( it.next().getBranchData().isHasConfidences() ) {
144 final public static void launchWebBrowser( final URI uri,
145 final boolean is_applet,
146 final JApplet applet,
147 final String frame_name ) throws IOException {
149 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
152 // This requires Java 1.6:
153 // =======================
154 // boolean no_desktop = false;
156 // if ( Desktop.isDesktopSupported() ) {
157 // System.out.println( "desktop supported" );
158 // final Desktop dt = Desktop.getDesktop();
162 // no_desktop = true;
165 // catch ( final Exception ex ) {
166 // ex.printStackTrace();
167 // no_desktop = true;
169 // catch ( final Error er ) {
170 // er.printStackTrace();
171 // no_desktop = true;
173 // if ( no_desktop ) {
174 // System.out.println( "desktop not supported" );
176 openUrlInWebBrowser( uri.toString() );
178 catch ( final Exception e ) {
179 throw new IOException( e );
185 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
186 final String n = sequence_name.trim();
187 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
190 if ( matcher1.matches() ) {
191 group1 = matcher1.group( 1 );
192 group2 = matcher1.group( 2 );
195 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
196 if ( matcher2.matches() ) {
197 group1 = matcher2.group( 1 );
198 group2 = matcher2.group( 2 );
201 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
204 return new Accession( group2, group1 );
207 public final static void printWarningMessage( final String name, final String message ) {
208 System.out.println( "[" + name + "] > " + message );
211 final public static void showErrorMessage( final Component parent, final String error_msg ) {
212 printAppletMessage( Constants.PRG_NAME, error_msg );
213 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
214 + "] Error", JOptionPane.ERROR_MESSAGE );
217 public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
218 final PhylogenyNode node,
219 final List<String> data ) {
220 final StringBuilder sb = new StringBuilder();
221 if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
222 showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
224 if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
225 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
226 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
228 if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
229 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
230 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
232 if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
233 && ( node.getNodeData().getSequence().getAccession() != null )
234 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
235 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
237 if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
238 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
239 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
241 if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
242 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
243 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
245 if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
246 && node.getNodeData().isHasSequence()
247 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
248 showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
250 final String s = sb.toString().trim();
251 if ( !ForesterUtil.isEmpty( s ) ) {
256 public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
257 if ( sb.length() > 0 ) {
263 final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
264 JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
267 public static void writePhylogenyToGraphicsFile( final File intree,
271 final GraphicsExportType type,
272 final Configuration config ) throws IOException {
273 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
274 Phylogeny[] phys = null;
275 phys = PhylogenyMethods.readPhylogenies( parser, intree );
276 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
279 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
283 final GraphicsExportType type,
284 final Configuration config ) throws IOException {
285 final Phylogeny[] phys = new Phylogeny[ 1 ];
287 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
288 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
289 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
293 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
296 final TreePanel tree_panel,
297 final ControlPanel ac,
298 final GraphicsExportType type,
299 final Options options ) throws IOException {
300 tree_panel.setParametersForPainting( width, height, true );
301 tree_panel.resetPreferredSize();
302 tree_panel.repaint();
303 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
304 RenderingHints.VALUE_RENDER_QUALITY );
305 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
306 if ( options.isAntialiasPrint() ) {
307 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
308 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
311 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
312 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
314 final Phylogeny phylogeny = tree_panel.getPhylogeny();
315 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
318 if ( outfile.isDirectory() ) {
319 throw new IOException( "\"" + outfile + "\" is a directory" );
321 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
322 final Graphics2D g2d = buffered_img.createGraphics();
323 g2d.setRenderingHints( rendering_hints );
324 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
325 if ( type == GraphicsExportType.TIFF ) {
326 writeToTiff( outfile, buffered_img );
329 ImageIO.write( buffered_img, type.toString(), outfile );
334 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
335 final String default_name,
336 final String full_path,
337 final Configuration configuration,
338 final MainPanel main_panel ) {
339 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
340 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
341 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
342 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
345 for( final Phylogeny phy : phys ) {
346 if ( !phy.isEmpty() ) {
347 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
349 String my_name_for_file = "";
350 if ( phys.length > 1 ) {
351 if ( !ForesterUtil.isEmpty( default_name ) ) {
352 my_name = new String( default_name );
354 if ( !ForesterUtil.isEmpty( full_path ) ) {
355 my_name_for_file = new String( full_path );
357 else if ( !ForesterUtil.isEmpty( default_name ) ) {
358 my_name_for_file = new String( default_name );
361 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
362 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
363 my_name_for_file.length() );
364 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
366 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
367 my_name_for_file += "_";
369 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
370 my_name_for_file += phy.getName().replaceAll( " ", "_" );
372 else if ( phy.getIdentifier() != null ) {
373 final StringBuffer sb = new StringBuffer();
374 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
375 sb.append( phy.getIdentifier().getProvider() );
378 sb.append( phy.getIdentifier().getValue() );
379 my_name_for_file += sb;
382 my_name_for_file += i;
384 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
385 && ( phy.getIdentifier() == null ) ) {
386 my_name = my_name + " [" + i + "]";
388 if ( !ForesterUtil.isEmpty( suffix ) ) {
389 my_name_for_file += suffix;
393 if ( !ForesterUtil.isEmpty( default_name ) ) {
394 my_name = new String( default_name );
396 my_name_for_file = "";
397 if ( !ForesterUtil.isEmpty( full_path ) ) {
398 my_name_for_file = new String( full_path );
400 else if ( !ForesterUtil.isEmpty( default_name ) ) {
401 my_name_for_file = new String( default_name );
403 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
404 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
405 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
407 else if ( phy.getIdentifier() != null ) {
408 final StringBuffer sb = new StringBuffer();
409 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
410 sb.append( phy.getIdentifier().getProvider() );
413 sb.append( phy.getIdentifier().getValue() );
414 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
418 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
419 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
420 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
427 final static void addPhylogenyToPanel( final Phylogeny[] phys,
428 final Configuration configuration,
429 final MainPanel main_panel ) {
430 final Phylogeny phy = phys[ 0 ];
431 main_panel.addPhylogenyInPanel( phy, configuration );
432 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
435 final static Color calculateColorFromString( final String str ) {
436 final String species_uc = str.toUpperCase();
437 char first = species_uc.charAt( 0 );
440 if ( species_uc.length() > 1 ) {
441 second = species_uc.charAt( 1 );
442 if ( species_uc.length() > 2 ) {
443 if ( species_uc.indexOf( " " ) > 0 ) {
444 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
447 third = species_uc.charAt( 2 );
451 first = AptxUtil.normalizeCharForRGB( first );
452 second = AptxUtil.normalizeCharForRGB( second );
453 third = AptxUtil.normalizeCharForRGB( third );
454 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
457 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
460 return new Color( first, second, third );
463 // Returns true if the specified format name can be written
464 final static boolean canWriteFormat( final String format_name ) {
465 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
466 return iter.hasNext();
469 final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
470 boolean inferred = false;
471 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
472 final PhylogenyNode n = it.next();
473 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
474 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
475 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
476 AptxUtil.collapseSubtree( n, true );
477 if ( !n.getNodeData().isHasTaxonomy() ) {
478 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
479 .getTaxonomy().copy() );
484 n.setCollapse( false );
489 phy.setRerootable( false );
493 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
494 node.setCollapse( collapse );
495 if ( node.isExternal() ) {
498 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
499 while ( it.hasNext() ) {
500 it.next().setCollapse( collapse );
504 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
505 double max_conf = 0.0;
506 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
507 final PhylogenyNode n = it.next();
508 n.getBranchData().setBranchColor( null );
509 if ( n.getBranchData().isHasConfidences() ) {
510 final double conf = PhylogenyMethods.getConfidenceValue( n );
511 if ( conf > max_conf ) {
516 if ( max_conf > 0.0 ) {
517 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
518 final Color br = tree_panel.getTreeColorSet().getBranchColor();
519 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
520 final PhylogenyNode n = it.next();
521 if ( n.getBranchData().isHasConfidences() ) {
522 final double conf = PhylogenyMethods.getConfidenceValue( n );
523 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
524 colorizeSubtree( n, c );
530 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
531 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
532 it.next().getBranchData().setBranchColor( null );
534 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
535 final PhylogenyNode n = it.next();
536 if ( !n.getBranchData().isHasBranchColor() ) {
537 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
539 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
540 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
541 for( final PhylogenyNode desc : descs ) {
543 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
550 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
551 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
552 int colorizations = 0;
553 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
554 final PhylogenyNode n = it.next();
555 if ( n.getNodeData().isHasTaxonomy()
556 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
557 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
558 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
559 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
560 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
561 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
563 colorizeSubtree( n, c );
565 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
566 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
571 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
572 final PhylogenyNode node = it.next();
573 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
574 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
575 boolean success = false;
576 if ( !true_lineage_to_color_map.isEmpty() ) {
577 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
578 if ( true_lineage_to_color_map.containsKey( lin ) ) {
579 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
587 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
588 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
589 final Taxonomy temp_tax = new Taxonomy();
590 temp_tax.setScientificName( lin );
591 if ( lineage_to_rank_map.containsKey( lin )
592 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
593 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
594 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
595 colorizeSubtree( node, c );
597 true_lineage_to_color_map.put( lin, c.getValue() );
601 UniProtTaxonomy up = null;
603 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
605 catch ( final Exception e ) {
608 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
609 lineage_to_rank_map.put( lin, up.getRank() );
610 if ( up.getRank().equalsIgnoreCase( rank ) ) {
611 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
612 colorizeSubtree( node, c );
614 true_lineage_to_color_map.put( lin, c.getValue() );
623 return colorizations;
626 final static String createBasicInformation( final Phylogeny phy ) {
627 final StringBuilder desc = new StringBuilder();
628 if ( ( phy != null ) && !phy.isEmpty() ) {
629 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
630 desc.append( "Name: " );
631 desc.append( phy.getName() );
634 if ( phy.getIdentifier() != null ) {
635 desc.append( "Id: " );
636 desc.append( phy.getIdentifier() );
639 desc.append( "Rooted: " );
640 desc.append( phy.isRooted() );
642 desc.append( "Rerootable: " );
643 desc.append( phy.isRerootable() );
645 desc.append( "Node sum: " );
646 desc.append( phy.getNodeCount() );
648 desc.append( "External node sum: " );
649 desc.append( phy.getNumberOfExternalNodes() );
651 desc.append( "Internal node sum: " );
652 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
654 desc.append( "Branche sum: " );
655 desc.append( phy.getNumberOfBranches() );
657 desc.append( "Depth: " );
658 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
660 desc.append( "Maximum distance to root: " );
661 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
663 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
664 if ( taxs != null ) {
665 desc.append( "Distinct external taxonomies: " );
666 desc.append( taxs.size() );
669 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
670 if ( bs.getN() > 3 ) {
672 desc.append( "Branch-length statistics: " );
674 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
676 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
678 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
680 desc.append( " SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
682 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
684 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
686 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
688 final AsciiHistogram histo = new AsciiHistogram( bs );
689 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
692 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
693 if ( ds.getN() > 2 ) {
695 desc.append( "Descendants per node statistics: " );
697 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
699 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
701 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
703 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
705 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
708 List<DescriptiveStatistics> css = null;
710 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
712 catch ( final IllegalArgumentException e ) {
713 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
715 if ( ( css != null ) && ( css.size() > 0 ) ) {
717 for( int i = 0; i < css.size(); ++i ) {
718 final DescriptiveStatistics cs = css.get( i );
719 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
720 if ( css.size() > 1 ) {
721 desc.append( "Support statistics " + ( i + 1 ) + ": " );
724 desc.append( "Support statistics: " );
726 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
728 desc.append( " Type: " + cs.getDescription() );
731 desc.append( " Branches with support: " + cs.getN() );
733 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
735 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
737 if ( cs.getN() > 2 ) {
738 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
741 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
743 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
749 return desc.toString();
757 * to message to be printed
759 final static void dieWithSystemError( final String message ) {
760 System.out.println();
761 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
762 System.out.println( "Please contact the authors." );
763 System.out.println( Constants.PRG_NAME + " needs to close." );
764 System.out.println();
768 final static String[] getAllPossibleRanks() {
769 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
771 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
772 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
773 str_array[ i++ ] = e;
779 final static String[] getAllRanks( final Phylogeny tree ) {
780 final SortedSet<String> ranks = new TreeSet<String>();
781 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
782 final PhylogenyNode n = it.next();
783 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
784 ranks.add( n.getNodeData().getTaxonomy().getRank() );
787 return ForesterUtil.stringSetToArray( ranks );
790 final static String[] getAvailableFontFamiliesSorted() {
791 return AVAILABLE_FONT_FAMILIES_SORTED;
794 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
795 if ( !node.getNodeData().isHasEvent() ) {
798 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
804 final static boolean isJava15() {
806 final String s = ForesterUtil.JAVA_VERSION;
807 return s.startsWith( "1.5" );
809 catch ( final Exception e ) {
810 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
815 final static boolean isMac() {
817 final String s = ForesterUtil.OS_NAME.toLowerCase();
818 return s.startsWith( "mac" );
820 catch ( final Exception e ) {
821 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
826 final static boolean isUsOrCanada() {
828 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
832 catch ( final Exception e ) {
838 final static boolean isWindows() {
840 final String s = ForesterUtil.OS_NAME.toLowerCase();
841 return s.indexOf( "win" ) > -1;
843 catch ( final Exception e ) {
844 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
849 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
850 final ControlPanel atv_control,
851 final Configuration configuration ) {
852 if ( ( t != null ) && !t.isEmpty() ) {
853 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
854 atv_control.setDrawPhylogram( false );
855 atv_control.setDrawPhylogramEnabled( false );
857 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
858 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
859 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
860 atv_control.setDrawPhylogram( true );
861 atv_control.setDrawPhylogramEnabled( true );
864 atv_control.setDrawPhylogram( false );
868 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
869 if ( atv_control.getWriteConfidenceCb() != null ) {
870 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
871 atv_control.setCheckbox( Configuration.write_confidence_values, true );
874 atv_control.setCheckbox( Configuration.write_confidence_values, false );
878 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
879 if ( atv_control.getShowEventsCb() != null ) {
880 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
881 atv_control.setCheckbox( Configuration.write_events, true );
884 atv_control.setCheckbox( Configuration.write_events, false );
891 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
893 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
895 catch ( final Exception e ) {
896 throw new IOException( e );
900 final static void printAppletMessage( final String applet_name, final String message ) {
901 System.out.println( "[" + applet_name + "] > " + message );
904 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
905 throws FileNotFoundException, IOException {
906 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
907 PhylogenyParser parser = null;
908 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
909 parser = new TolParser();
912 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
914 return factory.create( url.openStream(), parser );
917 final static void removeBranchColors( final Phylogeny phy ) {
918 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
919 it.next().getBranchData().setBranchColor( null );
923 final static void unexpectedError( final Error err ) {
924 err.printStackTrace();
925 final StringBuffer sb = new StringBuffer();
926 for( final StackTraceElement s : err.getStackTrace() ) {
927 sb.append( s + "\n" );
930 .showMessageDialog( null,
931 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
932 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
933 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
934 JOptionPane.ERROR_MESSAGE );
938 final static void unexpectedException( final Exception ex ) {
939 ex.printStackTrace();
940 final StringBuffer sb = new StringBuffer();
941 for( final StackTraceElement s : ex.getStackTrace() ) {
942 sb.append( s + "\n" );
944 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
945 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
946 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
949 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
952 final TreePanel tree_panel,
953 final ControlPanel ac,
954 final GraphicsExportType type,
955 final Options options ) throws IOException {
956 if ( !options.isGraphicsExportUsingActualSize() ) {
957 if ( options.isGraphicsExportVisibleOnly() ) {
958 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
960 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
961 tree_panel.resetPreferredSize();
962 tree_panel.repaint();
964 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
965 RenderingHints.VALUE_RENDER_QUALITY );
966 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
967 if ( options.isAntialiasPrint() ) {
968 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
969 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
972 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
973 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
975 final Phylogeny phylogeny = tree_panel.getPhylogeny();
976 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
979 Rectangle visible = null;
980 if ( !options.isGraphicsExportUsingActualSize() ) {
981 width = options.getPrintSizeX();
982 height = options.getPrintSizeY();
984 else if ( options.isGraphicsExportVisibleOnly() ) {
985 visible = tree_panel.getVisibleRect();
986 width = visible.width;
987 height = visible.height;
989 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
990 Graphics2D g2d = buffered_img.createGraphics();
991 g2d.setRenderingHints( rendering_hints );
994 if ( options.isGraphicsExportVisibleOnly() ) {
995 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1000 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1001 ImageIO.write( buffered_img, type.toString(), baos );
1004 if ( !options.isGraphicsExportUsingActualSize() ) {
1005 tree_panel.getMainPanel().getControlPanel().showWhole();
1007 String msg = baos.toString();
1008 if ( ( width > 0 ) && ( height > 0 ) ) {
1009 msg += " [size: " + width + ", " + height + "]";
1014 final static String writePhylogenyToGraphicsFile( final String file_name,
1017 final TreePanel tree_panel,
1018 final ControlPanel ac,
1019 final GraphicsExportType type,
1020 final Options options ) throws IOException {
1021 if ( !options.isGraphicsExportUsingActualSize() ) {
1022 if ( options.isGraphicsExportVisibleOnly() ) {
1023 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1025 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1026 tree_panel.resetPreferredSize();
1027 tree_panel.repaint();
1029 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1030 RenderingHints.VALUE_RENDER_QUALITY );
1031 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1032 if ( options.isAntialiasPrint() ) {
1033 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1034 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1037 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1038 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1040 final Phylogeny phylogeny = tree_panel.getPhylogeny();
1041 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1044 final File file = new File( file_name );
1045 if ( file.isDirectory() ) {
1046 throw new IOException( "\"" + file_name + "\" is a directory" );
1048 Rectangle visible = null;
1049 if ( !options.isGraphicsExportUsingActualSize() ) {
1050 width = options.getPrintSizeX();
1051 height = options.getPrintSizeY();
1053 else if ( options.isGraphicsExportVisibleOnly() ) {
1054 visible = tree_panel.getVisibleRect();
1055 width = visible.width;
1056 height = visible.height;
1058 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1059 Graphics2D g2d = buffered_img.createGraphics();
1060 g2d.setRenderingHints( rendering_hints );
1063 if ( options.isGraphicsExportVisibleOnly() ) {
1064 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1065 g2d.setClip( null );
1069 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1070 if ( type == GraphicsExportType.TIFF ) {
1071 writeToTiff( file, buffered_img );
1074 ImageIO.write( buffered_img, type.toString(), file );
1078 if ( !options.isGraphicsExportUsingActualSize() ) {
1079 tree_panel.getMainPanel().getControlPanel().showWhole();
1081 String msg = file.toString();
1082 if ( ( width > 0 ) && ( height > 0 ) ) {
1083 msg += " [size: " + width + ", " + height + "]";
1088 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1089 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1090 ImageWriter writer = null;
1091 ImageOutputStream ios = null;
1092 // Find an appropriate writer:
1093 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1094 if ( it.hasNext() ) {
1098 throw new IOException( "failed to get TIFF image writer" );
1101 ios = ImageIO.createImageOutputStream( file );
1102 writer.setOutput( ios );
1103 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1104 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1105 // see writeParam.getCompressionTypes() for available compression type
1107 image_write_param.setCompressionType( "PackBits" );
1108 final String t[] = image_write_param.getCompressionTypes();
1109 for( final String string : t ) {
1110 System.out.println( string );
1112 // Convert to an IIOImage:
1113 final IIOImage iio_image = new IIOImage( image, null, null );
1114 writer.write( null, iio_image, image_write_param );
1117 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1118 node.getBranchData().setBranchColor( c );
1119 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1120 for( final PhylogenyNode desc : descs ) {
1121 desc.getBranchData().setBranchColor( c );
1125 final private static char normalizeCharForRGB( char c ) {
1128 c = c > 255 ? 255 : c;
1133 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1134 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1135 InvocationTargetException, InterruptedException {
1136 final String os = System.getProperty( "os.name" );
1137 final Runtime runtime = Runtime.getRuntime();
1138 if ( os.toLowerCase().startsWith( "win" ) ) {
1139 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1141 else if ( isMac() ) {
1142 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1143 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1144 open_url.invoke( null, new Object[] { url } );
1147 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1148 String browser = null;
1149 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1150 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1151 browser = browsers[ i ];
1154 if ( browser == null ) {
1155 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1158 runtime.exec( new String[] { browser, url } );
1163 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1164 // static void openDDBJRest() throws IOException {
1166 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1168 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1169 // //make connection
1170 // URLConnection urlc = url.openConnection();
1172 // urlc.setDoOutput( true );
1173 // urlc.setAllowUserInteraction( false );
1175 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1176 // ps.print( query );
1179 // BufferedReader br = new BufferedReader( new InputStreamReader(
1180 // urlc.getInputStream() ) );
1182 // while ( ( l = br.readLine() ) != null ) {
1183 // System.out.println( l );
1187 public static enum GraphicsExportType {
1188 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1190 private final String _suffix;
1192 private GraphicsExportType( final String suffix ) {
1197 public String toString() {