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.phylogeny;
28 import java.awt.Color;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collections;
34 import java.util.Comparator;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.SortedMap;
41 import java.util.TreeMap;
43 import org.forester.io.parsers.PhylogenyParser;
44 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
45 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
46 import org.forester.io.parsers.util.PhylogenyParserException;
47 import org.forester.phylogeny.data.BranchColor;
48 import org.forester.phylogeny.data.BranchWidth;
49 import org.forester.phylogeny.data.Confidence;
50 import org.forester.phylogeny.data.DomainArchitecture;
51 import org.forester.phylogeny.data.Event;
52 import org.forester.phylogeny.data.Identifier;
53 import org.forester.phylogeny.data.PhylogenyDataUtil;
54 import org.forester.phylogeny.data.Sequence;
55 import org.forester.phylogeny.data.Taxonomy;
56 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
57 import org.forester.phylogeny.factories.PhylogenyFactory;
58 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
59 import org.forester.util.BasicDescriptiveStatistics;
60 import org.forester.util.DescriptiveStatistics;
61 import org.forester.util.FailedConditionCheckException;
62 import org.forester.util.ForesterUtil;
64 public class PhylogenyMethods {
66 private static PhylogenyMethods _instance = null;
67 private PhylogenyNode _farthest_1 = null;
68 private PhylogenyNode _farthest_2 = null;
70 private PhylogenyMethods() {
71 // Hidden constructor.
75 * Calculates the distance between PhylogenyNodes node1 and node2.
80 * @return distance between node1 and node2
82 public double calculateDistance( final PhylogenyNode node1, final PhylogenyNode node2 ) {
83 final PhylogenyNode lca = calculateLCA( node1, node2 );
84 final PhylogenyNode n1 = node1;
85 final PhylogenyNode n2 = node2;
86 return ( PhylogenyMethods.getDistance( n1, lca ) + PhylogenyMethods.getDistance( n2, lca ) );
89 public double calculateFurthestDistance( final Phylogeny phylogeny ) {
90 if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
95 PhylogenyNode node_1 = null;
96 PhylogenyNode node_2 = null;
97 double farthest_d = -Double.MAX_VALUE;
98 final PhylogenyMethods methods = PhylogenyMethods.getInstance();
99 final List<PhylogenyNode> ext_nodes = phylogeny.getRoot().getAllExternalDescendants();
100 for( int i = 1; i < ext_nodes.size(); ++i ) {
101 for( int j = 0; j < i; ++j ) {
102 final double d = methods.calculateDistance( ext_nodes.get( i ), ext_nodes.get( j ) );
104 throw new RuntimeException( "distance cannot be negative" );
106 if ( d > farthest_d ) {
108 node_1 = ext_nodes.get( i );
109 node_2 = ext_nodes.get( j );
113 _farthest_1 = node_1;
114 _farthest_2 = node_2;
118 final public static Event getEventAtLCA( final PhylogenyNode n1, final PhylogenyNode n2 ) {
119 return calculateLCA( n1, n2 ).getNodeData().getEvent();
123 public Object clone() throws CloneNotSupportedException {
124 throw new CloneNotSupportedException();
127 public PhylogenyNode getFarthestNode1() {
131 public PhylogenyNode getFarthestNode2() {
135 final public static void deleteNonOrthologousExternalNodes( final Phylogeny phy, final PhylogenyNode n ) {
136 if ( n.isInternal() ) {
137 throw new IllegalArgumentException( "node is not external" );
139 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
140 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
141 final PhylogenyNode i = it.next();
142 if ( !PhylogenyMethods.getEventAtLCA( n, i ).isSpeciation() ) {
146 for( final PhylogenyNode d : to_delete ) {
147 phy.deleteSubtree( d, true );
149 phy.clearHashIdToNodeMap();
150 phy.externalNodesHaveChanged();
154 * Returns the LCA of PhylogenyNodes node1 and node2.
159 * @return LCA of node1 and node2
161 public final static PhylogenyNode calculateLCA( PhylogenyNode node1, PhylogenyNode node2 ) {
162 if ( node1 == node2 ) {
165 if ( ( node1.getParent() == node2.getParent() ) ) {
166 return node1.getParent();
168 int depth1 = node1.calculateDepth();
169 int depth2 = node2.calculateDepth();
170 while ( ( depth1 > -1 ) && ( depth2 > -1 ) ) {
171 if ( depth1 > depth2 ) {
172 node1 = node1.getParent();
175 else if ( depth2 > depth1 ) {
176 node2 = node2.getParent();
180 if ( node1 == node2 ) {
183 node1 = node1.getParent();
184 node2 = node2.getParent();
189 throw new IllegalArgumentException( "illegal attempt to calculate LCA of two nodes which do not share a common root" );
192 public static final void preOrderReId( final Phylogeny phy ) {
193 if ( phy.isEmpty() ) {
196 phy.setIdToNodeMap( null );
197 int i = PhylogenyNode.getNodeCount();
198 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
199 it.next().setId( i++ );
201 PhylogenyNode.setNodeCount( i );
205 * Returns the LCA of PhylogenyNodes node1 and node2.
206 * Precondition: ids are in pre-order (or level-order).
211 * @return LCA of node1 and node2
213 public final static PhylogenyNode calculateLCAonTreeWithIdsInPreOrder( PhylogenyNode node1, PhylogenyNode node2 ) {
214 while ( node1 != node2 ) {
215 if ( node1.getId() > node2.getId() ) {
216 node1 = node1.getParent();
219 node2 = node2.getParent();
226 * Returns all orthologs of the external PhylogenyNode n of this Phylogeny.
227 * Orthologs are returned as List of node references.
229 * PRECONDITION: This tree must be binary and rooted, and speciation -
230 * duplication need to be assigned for each of its internal Nodes.
232 * Returns null if this Phylogeny is empty or if n is internal.
234 * external PhylogenyNode whose orthologs are to be returned
235 * @return Vector of references to all orthologous Nodes of PhylogenyNode n
236 * of this Phylogeny, null if this Phylogeny is empty or if n is
239 public final static List<PhylogenyNode> getOrthologousNodes( final Phylogeny phy, final PhylogenyNode node ) {
240 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
241 PhylogenyMethods.preOrderReId( phy );
242 final PhylogenyNodeIterator it = phy.iteratorExternalForward();
243 while ( it.hasNext() ) {
244 final PhylogenyNode temp_node = it.next();
245 if ( ( temp_node != node ) && !calculateLCAonTreeWithIdsInPreOrder( node, temp_node ).isDuplication() ) {
246 nodes.add( temp_node );
252 public static final HashMap<String, PhylogenyNode> createNameToExtNodeMap( final Phylogeny phy ) {
253 final HashMap<String, PhylogenyNode> nodes = new HashMap<String, PhylogenyNode>();
254 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
255 final PhylogenyNode n = iter.next();
256 nodes.put( n.getName(), n );
261 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
262 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
263 final Phylogeny[] trees = factory.create( file, parser );
264 if ( ( trees == null ) || ( trees.length == 0 ) ) {
265 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
270 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List<File> files )
272 final List<Phylogeny> tree_list = new ArrayList<Phylogeny>();
273 for( final File file : files ) {
274 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
275 final Phylogeny[] trees = factory.create( file, parser );
276 if ( ( trees == null ) || ( trees.length == 0 ) ) {
277 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
279 tree_list.addAll( Arrays.asList( trees ) );
281 return tree_list.toArray( new Phylogeny[ tree_list.size() ] );
284 final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy ) {
285 final PhylogenyNodeIterator it = phy.iteratorPostorder();
286 while ( it.hasNext() ) {
287 final PhylogenyNode n = it.next();
288 if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) {
289 if ( !ForesterUtil.isEmpty( n.getName() ) ) {
292 d = Double.parseDouble( n.getName() );
294 catch ( final Exception e ) {
298 n.getBranchData().addConfidence( new Confidence( d, "" ) );
306 final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) {
307 final PhylogenyNodeIterator it = phy.iteratorPostorder();
308 while ( it.hasNext() ) {
309 final PhylogenyNode n = it.next();
310 if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) {
313 value = Double.parseDouble( n.getName() );
315 catch ( final NumberFormatException e ) {
316 throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: "
317 + e.getLocalizedMessage() );
319 if ( value >= 0.0 ) {
320 n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) );
327 final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) {
328 class PhylogenyNodeSortTaxonomyPriority implements Comparator<PhylogenyNode> {
331 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
332 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
333 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
334 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
335 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
336 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
338 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
339 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
340 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
341 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
343 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
344 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
345 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
346 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
349 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
350 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
351 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
352 return n1.getNodeData().getSequence().getName().toLowerCase()
353 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
355 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
356 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
357 return n1.getNodeData().getSequence().getSymbol()
358 .compareTo( n2.getNodeData().getSequence().getSymbol() );
360 if ( ( n1.getNodeData().getSequence().getAccession() != null )
361 && ( n2.getNodeData().getSequence().getAccession() != null )
362 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
363 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
364 return n1.getNodeData().getSequence().getAccession().getValue()
365 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
368 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
369 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
374 class PhylogenyNodeSortSequencePriority implements Comparator<PhylogenyNode> {
377 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
378 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
379 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
380 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
381 return n1.getNodeData().getSequence().getName().toLowerCase()
382 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
384 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
385 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
386 return n1.getNodeData().getSequence().getSymbol()
387 .compareTo( n2.getNodeData().getSequence().getSymbol() );
389 if ( ( n1.getNodeData().getSequence().getAccession() != null )
390 && ( n2.getNodeData().getSequence().getAccession() != null )
391 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
392 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
393 return n1.getNodeData().getSequence().getAccession().getValue()
394 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
397 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
398 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
399 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
400 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
401 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
403 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
404 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
405 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
406 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
408 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
409 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
410 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
411 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
414 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
415 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
420 class PhylogenyNodeSortNodeNamePriority implements Comparator<PhylogenyNode> {
423 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
424 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
425 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
427 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
428 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
429 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
430 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
431 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
433 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
434 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
435 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
436 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
438 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
439 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
440 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
441 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
444 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
445 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
446 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
447 return n1.getNodeData().getSequence().getName().toLowerCase()
448 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
450 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
451 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
452 return n1.getNodeData().getSequence().getSymbol()
453 .compareTo( n2.getNodeData().getSequence().getSymbol() );
455 if ( ( n1.getNodeData().getSequence().getAccession() != null )
456 && ( n2.getNodeData().getSequence().getAccession() != null )
457 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
458 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
459 return n1.getNodeData().getSequence().getAccession().getValue()
460 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
466 Comparator<PhylogenyNode> c;
469 c = new PhylogenyNodeSortSequencePriority();
472 c = new PhylogenyNodeSortNodeNamePriority();
475 c = new PhylogenyNodeSortTaxonomyPriority();
477 final List<PhylogenyNode> descs = node.getDescendants();
478 Collections.sort( descs, c );
480 for( final PhylogenyNode desc : descs ) {
481 node.setChildNode( i++, desc );
485 final static public void transferNodeNameToField( final Phylogeny phy,
486 final PhylogenyMethods.PhylogenyNodeField field,
487 final boolean external_only ) throws PhyloXmlDataFormatException {
488 final PhylogenyNodeIterator it = phy.iteratorPostorder();
489 while ( it.hasNext() ) {
490 final PhylogenyNode n = it.next();
491 if ( external_only && n.isInternal() ) {
494 final String name = n.getName().trim();
495 if ( !ForesterUtil.isEmpty( name ) ) {
499 setTaxonomyCode( n, name );
501 case TAXONOMY_SCIENTIFIC_NAME:
503 if ( !n.getNodeData().isHasTaxonomy() ) {
504 n.getNodeData().setTaxonomy( new Taxonomy() );
506 n.getNodeData().getTaxonomy().setScientificName( name );
508 case TAXONOMY_COMMON_NAME:
510 if ( !n.getNodeData().isHasTaxonomy() ) {
511 n.getNodeData().setTaxonomy( new Taxonomy() );
513 n.getNodeData().getTaxonomy().setCommonName( name );
515 case SEQUENCE_SYMBOL:
517 if ( !n.getNodeData().isHasSequence() ) {
518 n.getNodeData().setSequence( new Sequence() );
520 n.getNodeData().getSequence().setSymbol( name );
524 if ( !n.getNodeData().isHasSequence() ) {
525 n.getNodeData().setSequence( new Sequence() );
527 n.getNodeData().getSequence().setName( name );
529 case TAXONOMY_ID_UNIPROT_1: {
530 if ( !n.getNodeData().isHasTaxonomy() ) {
531 n.getNodeData().setTaxonomy( new Taxonomy() );
534 final int i = name.indexOf( '_' );
536 id = name.substring( 0, i );
541 n.getNodeData().getTaxonomy()
542 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
545 case TAXONOMY_ID_UNIPROT_2: {
546 if ( !n.getNodeData().isHasTaxonomy() ) {
547 n.getNodeData().setTaxonomy( new Taxonomy() );
550 final int i = name.indexOf( '_' );
552 id = name.substring( i + 1, name.length() );
557 n.getNodeData().getTaxonomy()
558 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
562 if ( !n.getNodeData().isHasTaxonomy() ) {
563 n.getNodeData().setTaxonomy( new Taxonomy() );
565 n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) );
573 static double addPhylogenyDistances( final double a, final double b ) {
574 if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
577 else if ( a >= 0.0 ) {
580 else if ( b >= 0.0 ) {
583 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
586 // Helper for getUltraParalogousNodes( PhylogenyNode ).
587 public static boolean areAllChildrenDuplications( final PhylogenyNode n ) {
588 if ( n.isExternal() ) {
592 if ( n.isDuplication() ) {
594 for( final PhylogenyNode desc : n.getDescendants() ) {
595 if ( !areAllChildrenDuplications( desc ) ) {
607 public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) {
608 if ( node.isExternal() ) {
612 for( PhylogenyNode d : node.getAllExternalDescendants() ) {
614 while ( d != node ) {
615 if ( d.isCollapse() ) {
630 public static int calculateMaxDepth( final Phylogeny phy ) {
632 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
633 final PhylogenyNode node = iter.next();
634 final int steps = node.calculateDepth();
642 public static double calculateMaxDistanceToRoot( final Phylogeny phy ) {
644 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
645 final PhylogenyNode node = iter.next();
646 final double d = node.calculateDistanceToRoot();
654 public static int countNumberOfPolytomies( final Phylogeny phy ) {
656 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
657 final PhylogenyNode n = iter.next();
658 if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) {
665 public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) {
666 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
667 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
668 final PhylogenyNode n = iter.next();
669 if ( !n.isExternal() ) {
670 stats.addValue( n.getNumberOfDescendants() );
676 public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) {
677 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
678 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
679 final PhylogenyNode n = iter.next();
680 if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) {
681 stats.addValue( n.getDistanceToParent() );
687 public static List<DescriptiveStatistics> calculatConfidenceStatistics( final Phylogeny phy ) {
688 final List<DescriptiveStatistics> stats = new ArrayList<DescriptiveStatistics>();
689 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
690 final PhylogenyNode n = iter.next();
691 if ( !n.isExternal() && !n.isRoot() ) {
692 if ( n.getBranchData().isHasConfidences() ) {
693 for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) {
694 final Confidence c = n.getBranchData().getConfidences().get( i );
695 if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) {
696 stats.add( i, new BasicDescriptiveStatistics() );
698 if ( !ForesterUtil.isEmpty( c.getType() ) ) {
699 if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) {
700 if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) {
701 throw new IllegalArgumentException( "support values in node [" + n.toString()
702 + "] appear inconsistently ordered" );
705 stats.get( i ).setDescription( c.getType() );
707 stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 );
716 * Returns the set of distinct taxonomies of
717 * all external nodes of node.
718 * If at least one the external nodes has no taxonomy,
722 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
723 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
724 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
725 for( final PhylogenyNode n : descs ) {
726 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
729 tax_set.add( n.getNodeData().getTaxonomy() );
735 * Returns a map of distinct taxonomies of
736 * all external nodes of node.
737 * If at least one of the external nodes has no taxonomy,
741 public static SortedMap<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
742 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
743 final SortedMap<Taxonomy, Integer> tax_map = new TreeMap<Taxonomy, Integer>();
744 for( final PhylogenyNode n : descs ) {
745 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
748 final Taxonomy t = n.getNodeData().getTaxonomy();
749 if ( tax_map.containsKey( t ) ) {
750 tax_map.put( t, tax_map.get( t ) + 1 );
759 public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) {
760 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
762 for( final PhylogenyNode n : descs ) {
763 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
771 * Deep copies the phylogeny originating from this node.
773 static PhylogenyNode copySubTree( final PhylogenyNode source ) {
774 if ( source == null ) {
778 final PhylogenyNode newnode = source.copyNodeData();
779 if ( !source.isExternal() ) {
780 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
781 newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
789 * Shallow copies the phylogeny originating from this node.
791 static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
792 if ( source == null ) {
796 final PhylogenyNode newnode = source.copyNodeDataShallow();
797 if ( !source.isExternal() ) {
798 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
799 newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
806 public static void deleteExternalNodesNegativeSelection( final Set<Integer> to_delete, final Phylogeny phy ) {
807 phy.clearHashIdToNodeMap();
808 for( final Integer id : to_delete ) {
809 phy.deleteSubtree( phy.getNode( id ), true );
811 phy.clearHashIdToNodeMap();
812 phy.externalNodesHaveChanged();
815 public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
816 throws IllegalArgumentException {
817 for( final String element : node_names_to_delete ) {
818 if ( ForesterUtil.isEmpty( element ) ) {
821 List<PhylogenyNode> nodes = null;
822 nodes = p.getNodes( element );
823 final Iterator<PhylogenyNode> it = nodes.iterator();
824 while ( it.hasNext() ) {
825 final PhylogenyNode n = it.next();
826 if ( !n.isExternal() ) {
827 throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" );
829 p.deleteSubtree( n, true );
832 p.clearHashIdToNodeMap();
833 p.externalNodesHaveChanged();
836 public static void deleteExternalNodesPositiveSelection( final Set<Taxonomy> species_to_keep, final Phylogeny phy ) {
837 // final Set<Integer> to_delete = new HashSet<Integer>();
838 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
839 final PhylogenyNode n = it.next();
840 if ( n.getNodeData().isHasTaxonomy() ) {
841 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
842 //to_delete.add( n.getNodeId() );
843 phy.deleteSubtree( n, true );
847 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
850 phy.clearHashIdToNodeMap();
851 phy.externalNodesHaveChanged();
854 public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
855 final Phylogeny p ) {
856 final PhylogenyNodeIterator it = p.iteratorExternalForward();
857 final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
859 Arrays.sort( node_names_to_keep );
860 while ( it.hasNext() ) {
861 final String curent_name = it.next().getName();
862 if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
863 to_delete[ i++ ] = curent_name;
866 PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
867 final List<String> deleted = new ArrayList<String>();
868 for( final String n : to_delete ) {
869 if ( !ForesterUtil.isEmpty( n ) ) {
876 public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
877 final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
878 final Set<Integer> encountered = new HashSet<Integer>();
879 if ( !node.isExternal() ) {
880 final List<PhylogenyNode> exts = node.getAllExternalDescendants();
881 for( PhylogenyNode current : exts ) {
882 descs.add( current );
883 while ( current != node ) {
884 current = current.getParent();
885 if ( encountered.contains( current.getId() ) ) {
888 descs.add( current );
889 encountered.add( current.getId() );
903 public static Color getBranchColorValue( final PhylogenyNode node ) {
904 if ( node.getBranchData().getBranchColor() == null ) {
907 return node.getBranchData().getBranchColor().getValue();
913 public static double getBranchWidthValue( final PhylogenyNode node ) {
914 if ( !node.getBranchData().isHasBranchWidth() ) {
915 return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
917 return node.getBranchData().getBranchWidth().getValue();
923 public static double getConfidenceValue( final PhylogenyNode node ) {
924 if ( !node.getBranchData().isHasConfidences() ) {
925 return Confidence.CONFIDENCE_DEFAULT_VALUE;
927 return node.getBranchData().getConfidence( 0 ).getValue();
933 public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
934 if ( !node.getBranchData().isHasConfidences() ) {
935 return new double[ 0 ];
937 final double[] values = new double[ node.getBranchData().getConfidences().size() ];
939 for( final Confidence c : node.getBranchData().getConfidences() ) {
940 values[ i++ ] = c.getValue();
946 * Calculates the distance between PhylogenyNodes n1 and n2.
947 * PRECONDITION: n1 is a descendant of n2.
952 * @return distance between n1 and n2
954 private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
957 if ( n1.getDistanceToParent() > 0.0 ) {
958 d += n1.getDistanceToParent();
966 * Returns taxonomy t if all external descendants have
967 * the same taxonomy t, null otherwise.
970 public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
971 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
973 for( final PhylogenyNode n : descs ) {
974 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
977 else if ( tax == null ) {
978 tax = n.getNodeData().getTaxonomy();
980 else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
987 public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
988 final List<PhylogenyNode> children = node.getAllExternalDescendants();
989 PhylogenyNode farthest = null;
990 double longest = -Double.MAX_VALUE;
991 for( final PhylogenyNode child : children ) {
992 if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
994 longest = PhylogenyMethods.getDistance( child, node );
1000 public static PhylogenyMethods getInstance() {
1001 if ( PhylogenyMethods._instance == null ) {
1002 PhylogenyMethods._instance = new PhylogenyMethods();
1004 return PhylogenyMethods._instance;
1008 * Returns the largest confidence value found on phy.
1010 static public double getMaximumConfidenceValue( final Phylogeny phy ) {
1011 double max = -Double.MAX_VALUE;
1012 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1013 final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
1014 if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
1021 static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
1022 int min = Integer.MAX_VALUE;
1025 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1027 if ( n.isInternal() ) {
1028 d = n.getNumberOfDescendants();
1038 * Convenience method for display purposes.
1039 * Not intended for algorithms.
1041 public static String getSpecies( final PhylogenyNode node ) {
1042 if ( !node.getNodeData().isHasTaxonomy() ) {
1045 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
1046 return node.getNodeData().getTaxonomy().getScientificName();
1048 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1049 return node.getNodeData().getTaxonomy().getTaxonomyCode();
1052 return node.getNodeData().getTaxonomy().getCommonName();
1057 * Returns all Nodes which are connected to external PhylogenyNode n of this
1058 * Phylogeny by a path containing only speciation events. We call these
1059 * "super orthologs". Nodes are returned as Vector of references to Nodes.
1061 * PRECONDITION: This tree must be binary and rooted, and speciation -
1062 * duplication need to be assigned for each of its internal Nodes.
1064 * Returns null if this Phylogeny is empty or if n is internal.
1066 * external PhylogenyNode whose strictly speciation related Nodes
1067 * are to be returned
1068 * @return Vector of references to all strictly speciation related Nodes of
1069 * PhylogenyNode n of this Phylogeny, null if this Phylogeny is
1070 * empty or if n is internal
1072 public static List<PhylogenyNode> getSuperOrthologousNodes( final PhylogenyNode n ) {
1074 PhylogenyNode node = n, deepest = null;
1075 final List<PhylogenyNode> v = new ArrayList<PhylogenyNode>();
1076 if ( !node.isExternal() ) {
1079 while ( !node.isRoot() && !node.getParent().isDuplication() ) {
1080 node = node.getParent();
1083 deepest.setIndicatorsToZero();
1085 if ( !node.isExternal() ) {
1086 if ( node.getIndicator() == 0 ) {
1087 node.setIndicator( ( byte ) 1 );
1088 if ( !node.isDuplication() ) {
1089 node = node.getChildNode1();
1092 if ( node.getIndicator() == 1 ) {
1093 node.setIndicator( ( byte ) 2 );
1094 if ( !node.isDuplication() ) {
1095 node = node.getChildNode2();
1098 if ( ( node != deepest ) && ( node.getIndicator() == 2 ) ) {
1099 node = node.getParent();
1106 if ( node != deepest ) {
1107 node = node.getParent();
1110 node.setIndicator( ( byte ) 2 );
1113 } while ( ( node != deepest ) || ( deepest.getIndicator() != 2 ) );
1118 * Convenience method for display purposes.
1119 * Not intended for algorithms.
1121 public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
1122 if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
1125 return node.getNodeData().getTaxonomy().getIdentifier().getValue();
1129 * Returns all Nodes which are connected to external PhylogenyNode n of this
1130 * Phylogeny by a path containing, and leading to, only duplication events.
1131 * We call these "ultra paralogs". Nodes are returned as Vector of
1132 * references to Nodes.
1134 * PRECONDITION: This tree must be binary and rooted, and speciation -
1135 * duplication need to be assigned for each of its internal Nodes.
1137 * Returns null if this Phylogeny is empty or if n is internal.
1139 * (Last modified: 10/06/01)
1142 * external PhylogenyNode whose ultra paralogs are to be returned
1143 * @return Vector of references to all ultra paralogs of PhylogenyNode n of
1144 * this Phylogeny, null if this Phylogeny is empty or if n is
1147 public static List<PhylogenyNode> getUltraParalogousNodes( final PhylogenyNode n ) {
1149 PhylogenyNode node = n;
1150 if ( !node.isExternal() ) {
1153 while ( !node.isRoot() && node.getParent().isDuplication() && areAllChildrenDuplications( node.getParent() ) ) {
1154 node = node.getParent();
1156 final List<PhylogenyNode> nodes = node.getAllExternalDescendants();
1161 public static String inferCommonPartOfScientificNameOfDescendants( final PhylogenyNode node ) {
1162 final List<PhylogenyNode> descs = node.getDescendants();
1164 for( final PhylogenyNode n : descs ) {
1165 if ( !n.getNodeData().isHasTaxonomy()
1166 || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1169 else if ( sn == null ) {
1170 sn = n.getNodeData().getTaxonomy().getScientificName().trim();
1173 String sn_current = n.getNodeData().getTaxonomy().getScientificName().trim();
1174 if ( !sn.equals( sn_current ) ) {
1175 boolean overlap = false;
1176 while ( ( sn.indexOf( ' ' ) >= 0 ) || ( sn_current.indexOf( ' ' ) >= 0 ) ) {
1177 if ( ForesterUtil.countChars( sn, ' ' ) > ForesterUtil.countChars( sn_current, ' ' ) ) {
1178 sn = sn.substring( 0, sn.lastIndexOf( ' ' ) ).trim();
1181 sn_current = sn_current.substring( 0, sn_current.lastIndexOf( ' ' ) ).trim();
1183 if ( sn.equals( sn_current ) ) {
1197 public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
1198 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
1199 if ( node.getChildNode( i ).isExternal() ) {
1207 * This is case insensitive.
1210 public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
1211 final String[] providers ) {
1212 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
1213 final String my_tax_prov = tax.getIdentifier().getProvider();
1214 for( final String provider : providers ) {
1215 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
1226 private static boolean match( final String s,
1228 final boolean case_sensitive,
1229 final boolean partial ) {
1230 if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
1233 String my_s = s.trim();
1234 String my_query = query.trim();
1235 if ( !case_sensitive ) {
1236 my_s = my_s.toLowerCase();
1237 my_query = my_query.toLowerCase();
1240 return my_s.indexOf( my_query ) >= 0;
1243 return my_s.equals( my_query );
1247 public static void midpointRoot( final Phylogeny phylogeny ) {
1248 if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
1251 final PhylogenyMethods methods = getInstance();
1252 final double farthest_d = methods.calculateFurthestDistance( phylogeny );
1253 final PhylogenyNode f1 = methods.getFarthestNode1();
1254 final PhylogenyNode f2 = methods.getFarthestNode2();
1255 if ( farthest_d <= 0.0 ) {
1258 double x = farthest_d / 2.0;
1259 PhylogenyNode n = f1;
1260 if ( PhylogenyMethods.getDistance( f1, phylogeny.getRoot() ) < PhylogenyMethods.getDistance( f2, phylogeny
1264 while ( ( x > n.getDistanceToParent() ) && !n.isRoot() ) {
1265 x -= ( n.getDistanceToParent() > 0 ? n.getDistanceToParent() : 0 );
1268 phylogeny.reRoot( n, x );
1269 phylogeny.recalculateNumberOfExternalDescendants( true );
1270 final PhylogenyNode a = getFurthestDescendant( phylogeny.getRoot().getChildNode1() );
1271 final PhylogenyNode b = getFurthestDescendant( phylogeny.getRoot().getChildNode2() );
1272 final double da = getDistance( a, phylogeny.getRoot() );
1273 final double db = getDistance( b, phylogeny.getRoot() );
1274 if ( Math.abs( da - db ) > 0.000001 ) {
1275 throw new FailedConditionCheckException( "this should not have happened: midpoint rooting failed: da="
1276 + da + ", db=" + db + ", diff=" + Math.abs( da - db ) );
1280 public static void normalizeBootstrapValues( final Phylogeny phylogeny,
1281 final double max_bootstrap_value,
1282 final double max_normalized_value ) {
1283 for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
1284 final PhylogenyNode node = iter.next();
1285 if ( node.isInternal() ) {
1286 final double confidence = getConfidenceValue( node );
1287 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
1288 if ( confidence >= max_bootstrap_value ) {
1289 setBootstrapConfidence( node, max_normalized_value );
1292 setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
1299 public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
1300 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1301 if ( phy.isEmpty() ) {
1304 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1305 nodes.add( iter.next() );
1310 public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
1311 for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
1312 final PhylogenyNode node = iter.next();
1317 if ( node.isInternal() ) {
1318 //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
1319 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
1320 final PhylogenyNode child_node = node.getChildNode( i );
1321 final Color child_color = getBranchColorValue( child_node );
1322 if ( child_color != null ) {
1324 red += child_color.getRed();
1325 green += child_color.getGreen();
1326 blue += child_color.getBlue();
1329 setBranchColorValue( node,
1330 new Color( ForesterUtil.roundToInt( red / n ),
1331 ForesterUtil.roundToInt( green / n ),
1332 ForesterUtil.roundToInt( blue / n ) ) );
1337 public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
1338 if ( remove_me.isRoot() ) {
1339 throw new IllegalArgumentException( "ill advised attempt to remove root node" );
1341 if ( remove_me.isExternal() ) {
1342 phylogeny.deleteSubtree( remove_me, false );
1343 phylogeny.clearHashIdToNodeMap();
1344 phylogeny.externalNodesHaveChanged();
1347 final PhylogenyNode parent = remove_me.getParent();
1348 final List<PhylogenyNode> descs = remove_me.getDescendants();
1349 parent.removeChildNode( remove_me );
1350 for( final PhylogenyNode desc : descs ) {
1351 parent.addAsChild( desc );
1352 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
1353 desc.getDistanceToParent() ) );
1355 remove_me.setParent( null );
1356 phylogeny.clearHashIdToNodeMap();
1357 phylogeny.externalNodesHaveChanged();
1361 public static List<PhylogenyNode> searchData( final String query,
1362 final Phylogeny phy,
1363 final boolean case_sensitive,
1364 final boolean partial,
1365 final boolean search_domains ) {
1366 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1367 if ( phy.isEmpty() || ( query == null ) ) {
1370 if ( ForesterUtil.isEmpty( query ) ) {
1373 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1374 final PhylogenyNode node = iter.next();
1375 boolean match = false;
1376 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1379 else if ( node.getNodeData().isHasTaxonomy()
1380 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1383 else if ( node.getNodeData().isHasTaxonomy()
1384 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1387 else if ( node.getNodeData().isHasTaxonomy()
1388 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1391 else if ( node.getNodeData().isHasTaxonomy()
1392 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1393 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1399 else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1400 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1401 I: for( final String syn : syns ) {
1402 if ( match( syn, query, case_sensitive, partial ) ) {
1408 if ( !match && node.getNodeData().isHasSequence()
1409 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1412 if ( !match && node.getNodeData().isHasSequence()
1413 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1417 && node.getNodeData().isHasSequence()
1418 && ( node.getNodeData().getSequence().getAccession() != null )
1419 && match( node.getNodeData().getSequence().getAccession().getValue(),
1425 if ( search_domains && !match && node.getNodeData().isHasSequence()
1426 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1427 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1428 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1429 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1435 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1436 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1437 I: while ( it.hasNext() ) {
1438 if ( match( it.next(), query, case_sensitive, partial ) ) {
1443 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1444 I: while ( it.hasNext() ) {
1445 if ( match( it.next(), query, case_sensitive, partial ) ) {
1458 public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1459 final Phylogeny phy,
1460 final boolean case_sensitive,
1461 final boolean partial,
1462 final boolean search_domains ) {
1463 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1464 if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1467 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1468 final PhylogenyNode node = iter.next();
1469 boolean all_matched = true;
1470 for( final String query : queries ) {
1471 boolean match = false;
1472 if ( ForesterUtil.isEmpty( query ) ) {
1475 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1478 else if ( node.getNodeData().isHasTaxonomy()
1479 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1482 else if ( node.getNodeData().isHasTaxonomy()
1483 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1486 else if ( node.getNodeData().isHasTaxonomy()
1487 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1490 else if ( node.getNodeData().isHasTaxonomy()
1491 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1492 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1498 else if ( node.getNodeData().isHasTaxonomy()
1499 && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1500 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1501 I: for( final String syn : syns ) {
1502 if ( match( syn, query, case_sensitive, partial ) ) {
1508 if ( !match && node.getNodeData().isHasSequence()
1509 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1512 if ( !match && node.getNodeData().isHasSequence()
1513 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1517 && node.getNodeData().isHasSequence()
1518 && ( node.getNodeData().getSequence().getAccession() != null )
1519 && match( node.getNodeData().getSequence().getAccession().getValue(),
1525 if ( search_domains && !match && node.getNodeData().isHasSequence()
1526 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1527 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1528 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1529 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1535 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1536 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1537 I: while ( it.hasNext() ) {
1538 if ( match( it.next(), query, case_sensitive, partial ) ) {
1543 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1544 I: while ( it.hasNext() ) {
1545 if ( match( it.next(), query, case_sensitive, partial ) ) {
1552 all_matched = false;
1556 if ( all_matched ) {
1564 * Convenience method.
1565 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1567 public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1568 setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1571 public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1572 if ( node.getBranchData().getBranchColor() == null ) {
1573 node.getBranchData().setBranchColor( new BranchColor() );
1575 node.getBranchData().getBranchColor().setValue( color );
1579 * Convenience method
1581 public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1582 node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1586 * Convenience method.
1587 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1589 public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1590 setConfidence( node, confidence_value, "" );
1594 * Convenience method.
1595 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1597 public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1598 Confidence c = null;
1599 if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1600 c = node.getBranchData().getConfidence( 0 );
1603 c = new Confidence();
1604 node.getBranchData().addConfidence( c );
1607 c.setValue( confidence_value );
1610 public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1611 if ( !node.getNodeData().isHasTaxonomy() ) {
1612 node.getNodeData().setTaxonomy( new Taxonomy() );
1614 node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1618 * Convenience method to set the taxonomy code of a phylogeny node.
1622 * @param taxonomy_code
1623 * @throws PhyloXmlDataFormatException
1625 public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code )
1626 throws PhyloXmlDataFormatException {
1627 if ( !node.getNodeData().isHasTaxonomy() ) {
1628 node.getNodeData().setTaxonomy( new Taxonomy() );
1630 node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1634 * Removes from Phylogeny to_be_stripped all external Nodes which are
1635 * associated with a species NOT found in Phylogeny reference.
1638 * a reference Phylogeny
1639 * @param to_be_stripped
1640 * Phylogeny to be stripped
1641 * @return number of external nodes removed from to_be_stripped
1643 public static int taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference, final Phylogeny to_be_stripped ) {
1644 final Set<String> ref_ext_taxo = new HashSet<String>();
1645 for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1646 final PhylogenyNode n = it.next();
1647 if ( !n.getNodeData().isHasTaxonomy() ) {
1648 throw new IllegalArgumentException( "no taxonomic data in node: " + n );
1650 // ref_ext_taxo.add( getSpecies( n ) );
1651 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1652 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() );
1654 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1655 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1658 final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1659 for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1660 final PhylogenyNode n = it.next();
1661 if ( !n.getNodeData().isHasTaxonomy() ) {
1662 nodes_to_delete.add( n );
1664 else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) )
1665 && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1666 nodes_to_delete.add( n );
1669 for( final PhylogenyNode phylogenyNode : nodes_to_delete ) {
1670 to_be_stripped.deleteSubtree( phylogenyNode, true );
1672 to_be_stripped.clearHashIdToNodeMap();
1673 to_be_stripped.externalNodesHaveChanged();
1674 return nodes_to_delete.size();
1678 * Arranges the order of childern for each node of this Phylogeny in such a
1679 * way that either the branch with more children is on top (right) or on
1680 * bottom (left), dependent on the value of boolean order.
1683 * decides in which direction to order
1686 public static void orderAppearance( final PhylogenyNode n,
1687 final boolean order,
1688 final boolean order_ext_alphabetically,
1689 final DESCENDANT_SORT_PRIORITY pri ) {
1690 if ( n.isExternal() ) {
1694 PhylogenyNode temp = null;
1695 if ( ( n.getNumberOfDescendants() == 2 )
1696 && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
1697 && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
1698 temp = n.getChildNode1();
1699 n.setChild1( n.getChildNode2() );
1700 n.setChild2( temp );
1702 else if ( order_ext_alphabetically ) {
1703 boolean all_ext = true;
1704 for( final PhylogenyNode i : n.getDescendants() ) {
1705 if ( !i.isExternal() ) {
1711 PhylogenyMethods.sortNodeDescendents( n, pri );
1714 for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
1715 orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri );
1720 public static enum PhylogenyNodeField {
1723 TAXONOMY_SCIENTIFIC_NAME,
1724 TAXONOMY_COMMON_NAME,
1727 TAXONOMY_ID_UNIPROT_1,
1728 TAXONOMY_ID_UNIPROT_2,
1732 public static enum TAXONOMY_EXTRACTION {
1733 NO, YES, PFAM_STYLE_ONLY;
1736 public static enum DESCENDANT_SORT_PRIORITY {
1737 TAXONOMY, SEQUENCE, NODE_NAME;