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 == null ) {
163 throw new IllegalArgumentException( "first argument (node) is null" );
165 if ( node2 == null ) {
166 throw new IllegalArgumentException( "second argument (node) is null" );
168 if ( node1 == node2 ) {
171 if ( ( node1.getParent() == node2.getParent() ) ) {
172 return node1.getParent();
174 int depth1 = node1.calculateDepth();
175 int depth2 = node2.calculateDepth();
176 while ( ( depth1 > -1 ) && ( depth2 > -1 ) ) {
177 if ( depth1 > depth2 ) {
178 node1 = node1.getParent();
181 else if ( depth2 > depth1 ) {
182 node2 = node2.getParent();
186 if ( node1 == node2 ) {
189 node1 = node1.getParent();
190 node2 = node2.getParent();
195 throw new IllegalArgumentException( "illegal attempt to calculate LCA of two nodes which do not share a common root" );
198 public static final void preOrderReId( final Phylogeny phy ) {
199 if ( phy.isEmpty() ) {
202 phy.setIdToNodeMap( null );
203 int i = PhylogenyNode.getNodeCount();
204 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
205 it.next().setId( i++ );
207 PhylogenyNode.setNodeCount( i );
211 * Returns the LCA of PhylogenyNodes node1 and node2.
212 * Precondition: ids are in pre-order (or level-order).
217 * @return LCA of node1 and node2
219 public final static PhylogenyNode calculateLCAonTreeWithIdsInPreOrder( PhylogenyNode node1, PhylogenyNode node2 ) {
220 if ( node1 == null ) {
221 throw new IllegalArgumentException( "first argument (node) is null" );
223 if ( node2 == null ) {
224 throw new IllegalArgumentException( "second argument (node) is null" );
226 while ( node1 != node2 ) {
227 if ( node1.getId() > node2.getId() ) {
228 node1 = node1.getParent();
231 node2 = node2.getParent();
238 * Returns all orthologs of the external PhylogenyNode n of this Phylogeny.
239 * Orthologs are returned as List of node references.
241 * PRECONDITION: This tree must be binary and rooted, and speciation -
242 * duplication need to be assigned for each of its internal Nodes.
244 * Returns null if this Phylogeny is empty or if n is internal.
246 * external PhylogenyNode whose orthologs are to be returned
247 * @return Vector of references to all orthologous Nodes of PhylogenyNode n
248 * of this Phylogeny, null if this Phylogeny is empty or if n is
251 public final static List<PhylogenyNode> getOrthologousNodes( final Phylogeny phy, final PhylogenyNode node ) {
252 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
253 PhylogenyMethods.preOrderReId( phy );
254 final PhylogenyNodeIterator it = phy.iteratorExternalForward();
255 while ( it.hasNext() ) {
256 final PhylogenyNode temp_node = it.next();
257 if ( ( temp_node != node ) && !calculateLCAonTreeWithIdsInPreOrder( node, temp_node ).isDuplication() ) {
258 nodes.add( temp_node );
264 public static final HashMap<String, PhylogenyNode> createNameToExtNodeMap( final Phylogeny phy ) {
265 final HashMap<String, PhylogenyNode> nodes = new HashMap<String, PhylogenyNode>();
266 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
267 final PhylogenyNode n = iter.next();
268 nodes.put( n.getName(), n );
273 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
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 );
282 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List<File> files )
284 final List<Phylogeny> tree_list = new ArrayList<Phylogeny>();
285 for( final File file : files ) {
286 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
287 final Phylogeny[] trees = factory.create( file, parser );
288 if ( ( trees == null ) || ( trees.length == 0 ) ) {
289 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
291 tree_list.addAll( Arrays.asList( trees ) );
293 return tree_list.toArray( new Phylogeny[ tree_list.size() ] );
296 final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy ) {
297 final PhylogenyNodeIterator it = phy.iteratorPostorder();
298 while ( it.hasNext() ) {
299 final PhylogenyNode n = it.next();
300 if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) {
301 if ( !ForesterUtil.isEmpty( n.getName() ) ) {
304 d = Double.parseDouble( n.getName() );
306 catch ( final Exception e ) {
310 n.getBranchData().addConfidence( new Confidence( d, "" ) );
318 final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) {
319 final PhylogenyNodeIterator it = phy.iteratorPostorder();
320 while ( it.hasNext() ) {
321 final PhylogenyNode n = it.next();
322 if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) {
325 value = Double.parseDouble( n.getName() );
327 catch ( final NumberFormatException e ) {
328 throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: "
329 + e.getLocalizedMessage() );
331 if ( value >= 0.0 ) {
332 n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) );
339 final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) {
340 class PhylogenyNodeSortTaxonomyPriority implements Comparator<PhylogenyNode> {
343 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
344 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
345 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
346 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
347 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
348 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
350 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
351 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
352 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
353 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
355 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
356 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
357 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
358 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
361 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
362 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
363 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
364 return n1.getNodeData().getSequence().getName().toLowerCase()
365 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
367 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
368 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
369 return n1.getNodeData().getSequence().getSymbol()
370 .compareTo( n2.getNodeData().getSequence().getSymbol() );
372 if ( ( n1.getNodeData().getSequence().getAccession() != null )
373 && ( n2.getNodeData().getSequence().getAccession() != null )
374 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
375 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
376 return n1.getNodeData().getSequence().getAccession().getValue()
377 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
380 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
381 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
386 class PhylogenyNodeSortSequencePriority implements Comparator<PhylogenyNode> {
389 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
390 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
391 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
392 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
393 return n1.getNodeData().getSequence().getName().toLowerCase()
394 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
396 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
397 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
398 return n1.getNodeData().getSequence().getSymbol()
399 .compareTo( n2.getNodeData().getSequence().getSymbol() );
401 if ( ( n1.getNodeData().getSequence().getAccession() != null )
402 && ( n2.getNodeData().getSequence().getAccession() != null )
403 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
404 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
405 return n1.getNodeData().getSequence().getAccession().getValue()
406 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
409 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
410 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
411 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
412 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
413 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
415 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
416 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
417 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
418 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
420 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
421 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
422 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
423 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
426 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
427 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
432 class PhylogenyNodeSortNodeNamePriority implements Comparator<PhylogenyNode> {
435 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
436 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
437 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
439 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
440 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
441 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
442 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
443 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
445 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
446 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
447 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
448 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
450 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
451 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
452 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
453 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
456 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
457 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
458 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
459 return n1.getNodeData().getSequence().getName().toLowerCase()
460 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
462 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
463 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
464 return n1.getNodeData().getSequence().getSymbol()
465 .compareTo( n2.getNodeData().getSequence().getSymbol() );
467 if ( ( n1.getNodeData().getSequence().getAccession() != null )
468 && ( n2.getNodeData().getSequence().getAccession() != null )
469 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
470 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
471 return n1.getNodeData().getSequence().getAccession().getValue()
472 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
478 Comparator<PhylogenyNode> c;
481 c = new PhylogenyNodeSortSequencePriority();
484 c = new PhylogenyNodeSortNodeNamePriority();
487 c = new PhylogenyNodeSortTaxonomyPriority();
489 final List<PhylogenyNode> descs = node.getDescendants();
490 Collections.sort( descs, c );
492 for( final PhylogenyNode desc : descs ) {
493 node.setChildNode( i++, desc );
497 final static public void transferNodeNameToField( final Phylogeny phy,
498 final PhylogenyMethods.PhylogenyNodeField field,
499 final boolean external_only ) throws PhyloXmlDataFormatException {
500 final PhylogenyNodeIterator it = phy.iteratorPostorder();
501 while ( it.hasNext() ) {
502 final PhylogenyNode n = it.next();
503 if ( external_only && n.isInternal() ) {
506 final String name = n.getName().trim();
507 if ( !ForesterUtil.isEmpty( name ) ) {
511 setTaxonomyCode( n, name );
513 case TAXONOMY_SCIENTIFIC_NAME:
515 if ( !n.getNodeData().isHasTaxonomy() ) {
516 n.getNodeData().setTaxonomy( new Taxonomy() );
518 n.getNodeData().getTaxonomy().setScientificName( name );
520 case TAXONOMY_COMMON_NAME:
522 if ( !n.getNodeData().isHasTaxonomy() ) {
523 n.getNodeData().setTaxonomy( new Taxonomy() );
525 n.getNodeData().getTaxonomy().setCommonName( name );
527 case SEQUENCE_SYMBOL:
529 if ( !n.getNodeData().isHasSequence() ) {
530 n.getNodeData().setSequence( new Sequence() );
532 n.getNodeData().getSequence().setSymbol( name );
536 if ( !n.getNodeData().isHasSequence() ) {
537 n.getNodeData().setSequence( new Sequence() );
539 n.getNodeData().getSequence().setName( name );
541 case TAXONOMY_ID_UNIPROT_1: {
542 if ( !n.getNodeData().isHasTaxonomy() ) {
543 n.getNodeData().setTaxonomy( new Taxonomy() );
546 final int i = name.indexOf( '_' );
548 id = name.substring( 0, i );
553 n.getNodeData().getTaxonomy()
554 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
557 case TAXONOMY_ID_UNIPROT_2: {
558 if ( !n.getNodeData().isHasTaxonomy() ) {
559 n.getNodeData().setTaxonomy( new Taxonomy() );
562 final int i = name.indexOf( '_' );
564 id = name.substring( i + 1, name.length() );
569 n.getNodeData().getTaxonomy()
570 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
574 if ( !n.getNodeData().isHasTaxonomy() ) {
575 n.getNodeData().setTaxonomy( new Taxonomy() );
577 n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) );
585 static double addPhylogenyDistances( final double a, final double b ) {
586 if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
589 else if ( a >= 0.0 ) {
592 else if ( b >= 0.0 ) {
595 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
598 public final static boolean isAllDecendentsAreDuplications( final PhylogenyNode n ) {
599 if ( n.isExternal() ) {
603 if ( n.isDuplication() ) {
604 for( final PhylogenyNode desc : n.getDescendants() ) {
605 if ( !isAllDecendentsAreDuplications( desc ) ) {
617 public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) {
618 if ( node.isExternal() ) {
622 for( PhylogenyNode d : node.getAllExternalDescendants() ) {
624 while ( d != node ) {
625 if ( d.isCollapse() ) {
640 public static int calculateMaxDepth( final Phylogeny phy ) {
642 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
643 final PhylogenyNode node = iter.next();
644 final int steps = node.calculateDepth();
652 public static double calculateMaxDistanceToRoot( final Phylogeny phy ) {
654 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
655 final PhylogenyNode node = iter.next();
656 final double d = node.calculateDistanceToRoot();
664 public static int countNumberOfPolytomies( final Phylogeny phy ) {
666 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
667 final PhylogenyNode n = iter.next();
668 if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) {
675 public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) {
676 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
677 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
678 final PhylogenyNode n = iter.next();
679 if ( !n.isExternal() ) {
680 stats.addValue( n.getNumberOfDescendants() );
686 public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) {
687 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
688 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
689 final PhylogenyNode n = iter.next();
690 if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) {
691 stats.addValue( n.getDistanceToParent() );
697 public static List<DescriptiveStatistics> calculatConfidenceStatistics( final Phylogeny phy ) {
698 final List<DescriptiveStatistics> stats = new ArrayList<DescriptiveStatistics>();
699 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
700 final PhylogenyNode n = iter.next();
701 if ( !n.isExternal() && !n.isRoot() ) {
702 if ( n.getBranchData().isHasConfidences() ) {
703 for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) {
704 final Confidence c = n.getBranchData().getConfidences().get( i );
705 if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) {
706 stats.add( i, new BasicDescriptiveStatistics() );
708 if ( !ForesterUtil.isEmpty( c.getType() ) ) {
709 if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) {
710 if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) {
711 throw new IllegalArgumentException( "support values in node [" + n.toString()
712 + "] appear inconsistently ordered" );
715 stats.get( i ).setDescription( c.getType() );
717 stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 );
726 * Returns the set of distinct taxonomies of
727 * all external nodes of node.
728 * If at least one the external nodes has no taxonomy,
732 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
733 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
734 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
735 for( final PhylogenyNode n : descs ) {
736 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
739 tax_set.add( n.getNodeData().getTaxonomy() );
745 * Returns a map of distinct taxonomies of
746 * all external nodes of node.
747 * If at least one of the external nodes has no taxonomy,
751 public static SortedMap<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
752 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
753 final SortedMap<Taxonomy, Integer> tax_map = new TreeMap<Taxonomy, Integer>();
754 for( final PhylogenyNode n : descs ) {
755 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
758 final Taxonomy t = n.getNodeData().getTaxonomy();
759 if ( tax_map.containsKey( t ) ) {
760 tax_map.put( t, tax_map.get( t ) + 1 );
769 public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) {
770 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
772 for( final PhylogenyNode n : descs ) {
773 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
781 * Deep copies the phylogeny originating from this node.
783 static PhylogenyNode copySubTree( final PhylogenyNode source ) {
784 if ( source == null ) {
788 final PhylogenyNode newnode = source.copyNodeData();
789 if ( !source.isExternal() ) {
790 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
791 newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
799 * Shallow copies the phylogeny originating from this node.
801 static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
802 if ( source == null ) {
806 final PhylogenyNode newnode = source.copyNodeDataShallow();
807 if ( !source.isExternal() ) {
808 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
809 newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
816 public static void deleteExternalNodesNegativeSelection( final Set<Integer> to_delete, final Phylogeny phy ) {
817 phy.clearHashIdToNodeMap();
818 for( final Integer id : to_delete ) {
819 phy.deleteSubtree( phy.getNode( id ), true );
821 phy.clearHashIdToNodeMap();
822 phy.externalNodesHaveChanged();
825 public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
826 throws IllegalArgumentException {
827 for( final String element : node_names_to_delete ) {
828 if ( ForesterUtil.isEmpty( element ) ) {
831 List<PhylogenyNode> nodes = null;
832 nodes = p.getNodes( element );
833 final Iterator<PhylogenyNode> it = nodes.iterator();
834 while ( it.hasNext() ) {
835 final PhylogenyNode n = it.next();
836 if ( !n.isExternal() ) {
837 throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" );
839 p.deleteSubtree( n, true );
842 p.clearHashIdToNodeMap();
843 p.externalNodesHaveChanged();
846 public static void deleteExternalNodesPositiveSelection( final Set<Taxonomy> species_to_keep, final Phylogeny phy ) {
847 // final Set<Integer> to_delete = new HashSet<Integer>();
848 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
849 final PhylogenyNode n = it.next();
850 if ( n.getNodeData().isHasTaxonomy() ) {
851 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
852 //to_delete.add( n.getNodeId() );
853 phy.deleteSubtree( n, true );
857 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
860 phy.clearHashIdToNodeMap();
861 phy.externalNodesHaveChanged();
864 public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
865 final Phylogeny p ) {
866 final PhylogenyNodeIterator it = p.iteratorExternalForward();
867 final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
869 Arrays.sort( node_names_to_keep );
870 while ( it.hasNext() ) {
871 final String curent_name = it.next().getName();
872 if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
873 to_delete[ i++ ] = curent_name;
876 PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
877 final List<String> deleted = new ArrayList<String>();
878 for( final String n : to_delete ) {
879 if ( !ForesterUtil.isEmpty( n ) ) {
886 public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
887 final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
888 final Set<Integer> encountered = new HashSet<Integer>();
889 if ( !node.isExternal() ) {
890 final List<PhylogenyNode> exts = node.getAllExternalDescendants();
891 for( PhylogenyNode current : exts ) {
892 descs.add( current );
893 while ( current != node ) {
894 current = current.getParent();
895 if ( encountered.contains( current.getId() ) ) {
898 descs.add( current );
899 encountered.add( current.getId() );
913 public static Color getBranchColorValue( final PhylogenyNode node ) {
914 if ( node.getBranchData().getBranchColor() == null ) {
917 return node.getBranchData().getBranchColor().getValue();
923 public static double getBranchWidthValue( final PhylogenyNode node ) {
924 if ( !node.getBranchData().isHasBranchWidth() ) {
925 return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
927 return node.getBranchData().getBranchWidth().getValue();
933 public static double getConfidenceValue( final PhylogenyNode node ) {
934 if ( !node.getBranchData().isHasConfidences() ) {
935 return Confidence.CONFIDENCE_DEFAULT_VALUE;
937 return node.getBranchData().getConfidence( 0 ).getValue();
943 public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
944 if ( !node.getBranchData().isHasConfidences() ) {
945 return new double[ 0 ];
947 final double[] values = new double[ node.getBranchData().getConfidences().size() ];
949 for( final Confidence c : node.getBranchData().getConfidences() ) {
950 values[ i++ ] = c.getValue();
956 * Calculates the distance between PhylogenyNodes n1 and n2.
957 * PRECONDITION: n1 is a descendant of n2.
962 * @return distance between n1 and n2
964 private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
967 if ( n1.getDistanceToParent() > 0.0 ) {
968 d += n1.getDistanceToParent();
976 * Returns taxonomy t if all external descendants have
977 * the same taxonomy t, null otherwise.
980 public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
981 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
983 for( final PhylogenyNode n : descs ) {
984 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
987 else if ( tax == null ) {
988 tax = n.getNodeData().getTaxonomy();
990 else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
997 public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
998 final List<PhylogenyNode> children = node.getAllExternalDescendants();
999 PhylogenyNode farthest = null;
1000 double longest = -Double.MAX_VALUE;
1001 for( final PhylogenyNode child : children ) {
1002 if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
1004 longest = PhylogenyMethods.getDistance( child, node );
1010 public static PhylogenyMethods getInstance() {
1011 if ( PhylogenyMethods._instance == null ) {
1012 PhylogenyMethods._instance = new PhylogenyMethods();
1014 return PhylogenyMethods._instance;
1018 * Returns the largest confidence value found on phy.
1020 static public double getMaximumConfidenceValue( final Phylogeny phy ) {
1021 double max = -Double.MAX_VALUE;
1022 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1023 final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
1024 if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
1031 static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
1032 int min = Integer.MAX_VALUE;
1035 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1037 if ( n.isInternal() ) {
1038 d = n.getNumberOfDescendants();
1048 * Convenience method for display purposes.
1049 * Not intended for algorithms.
1051 public static String getSpecies( final PhylogenyNode node ) {
1052 if ( !node.getNodeData().isHasTaxonomy() ) {
1055 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
1056 return node.getNodeData().getTaxonomy().getScientificName();
1058 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1059 return node.getNodeData().getTaxonomy().getTaxonomyCode();
1062 return node.getNodeData().getTaxonomy().getCommonName();
1067 * Returns all Nodes which are connected to external PhylogenyNode n of this
1068 * Phylogeny by a path containing only speciation events. We call these
1069 * "super orthologs". Nodes are returned as Vector of references to Nodes.
1071 * PRECONDITION: This tree must be binary and rooted, and speciation -
1072 * duplication need to be assigned for each of its internal Nodes.
1074 * Returns null if this Phylogeny is empty or if n is internal.
1076 * external PhylogenyNode whose strictly speciation related Nodes
1077 * are to be returned
1078 * @return References to all strictly speciation related Nodes of
1079 * PhylogenyNode n of this Phylogeny, null if this Phylogeny is
1080 * empty or if n is internal
1082 public static List<PhylogenyNode> getSuperOrthologousNodes( final PhylogenyNode n ) {
1084 PhylogenyNode node = n;
1085 PhylogenyNode deepest = null;
1086 final List<PhylogenyNode> v = new ArrayList<PhylogenyNode>();
1087 if ( !node.isExternal() ) {
1090 while ( !node.isRoot() && !node.getParent().isDuplication() ) {
1091 node = node.getParent();
1094 deepest.setIndicatorsToZero();
1096 if ( !node.isExternal() ) {
1097 if ( node.getIndicator() == 0 ) {
1098 node.setIndicator( ( byte ) 1 );
1099 if ( !node.isDuplication() ) {
1100 node = node.getChildNode1();
1103 if ( node.getIndicator() == 1 ) {
1104 node.setIndicator( ( byte ) 2 );
1105 if ( !node.isDuplication() ) {
1106 node = node.getChildNode2();
1109 if ( ( node != deepest ) && ( node.getIndicator() == 2 ) ) {
1110 node = node.getParent();
1117 if ( node != deepest ) {
1118 node = node.getParent();
1121 node.setIndicator( ( byte ) 2 );
1124 } while ( ( node != deepest ) || ( deepest.getIndicator() != 2 ) );
1129 * Convenience method for display purposes.
1130 * Not intended for algorithms.
1132 public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
1133 if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
1136 return node.getNodeData().getTaxonomy().getIdentifier().getValue();
1140 * Returns all Nodes which are connected to external PhylogenyNode n of this
1141 * Phylogeny by a path containing, and leading to, only duplication events.
1142 * We call these "ultra paralogs". Nodes are returned as Vector of
1143 * references to Nodes.
1145 * PRECONDITION: This tree must be binary and rooted, and speciation -
1146 * duplication need to be assigned for each of its internal Nodes.
1148 * Returns null if this Phylogeny is empty or if n is internal.
1150 * (Last modified: 10/06/01)
1153 * external PhylogenyNode whose ultra paralogs are to be returned
1154 * @return Vector of references to all ultra paralogs of PhylogenyNode n of
1155 * this Phylogeny, null if this Phylogeny is empty or if n is
1158 public static List<PhylogenyNode> getUltraParalogousNodes( final PhylogenyNode n ) {
1160 PhylogenyNode node = n;
1161 if ( !node.isExternal() ) {
1162 throw new IllegalArgumentException( "attempt to get ultra-paralogous nodes of internal node" );
1164 while ( !node.isRoot() && node.getParent().isDuplication() && isAllDecendentsAreDuplications( node.getParent() ) ) {
1165 node = node.getParent();
1167 final List<PhylogenyNode> nodes = node.getAllExternalDescendants();
1172 public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
1173 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
1174 if ( node.getChildNode( i ).isExternal() ) {
1182 * This is case insensitive.
1185 public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
1186 final String[] providers ) {
1187 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
1188 final String my_tax_prov = tax.getIdentifier().getProvider();
1189 for( final String provider : providers ) {
1190 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
1201 private static boolean match( final String s,
1203 final boolean case_sensitive,
1204 final boolean partial ) {
1205 if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
1208 String my_s = s.trim();
1209 String my_query = query.trim();
1210 if ( !case_sensitive ) {
1211 my_s = my_s.toLowerCase();
1212 my_query = my_query.toLowerCase();
1215 return my_s.indexOf( my_query ) >= 0;
1218 return my_s.equals( my_query );
1222 public static void midpointRoot( final Phylogeny phylogeny ) {
1223 if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
1226 final PhylogenyMethods methods = getInstance();
1227 final double farthest_d = methods.calculateFurthestDistance( phylogeny );
1228 final PhylogenyNode f1 = methods.getFarthestNode1();
1229 final PhylogenyNode f2 = methods.getFarthestNode2();
1230 if ( farthest_d <= 0.0 ) {
1233 double x = farthest_d / 2.0;
1234 PhylogenyNode n = f1;
1235 if ( PhylogenyMethods.getDistance( f1, phylogeny.getRoot() ) < PhylogenyMethods.getDistance( f2, phylogeny
1239 while ( ( x > n.getDistanceToParent() ) && !n.isRoot() ) {
1240 x -= ( n.getDistanceToParent() > 0 ? n.getDistanceToParent() : 0 );
1243 phylogeny.reRoot( n, x );
1244 phylogeny.recalculateNumberOfExternalDescendants( true );
1245 final PhylogenyNode a = getFurthestDescendant( phylogeny.getRoot().getChildNode1() );
1246 final PhylogenyNode b = getFurthestDescendant( phylogeny.getRoot().getChildNode2() );
1247 final double da = getDistance( a, phylogeny.getRoot() );
1248 final double db = getDistance( b, phylogeny.getRoot() );
1249 if ( Math.abs( da - db ) > 0.000001 ) {
1250 throw new FailedConditionCheckException( "this should not have happened: midpoint rooting failed: da="
1251 + da + ", db=" + db + ", diff=" + Math.abs( da - db ) );
1255 public static void normalizeBootstrapValues( final Phylogeny phylogeny,
1256 final double max_bootstrap_value,
1257 final double max_normalized_value ) {
1258 for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
1259 final PhylogenyNode node = iter.next();
1260 if ( node.isInternal() ) {
1261 final double confidence = getConfidenceValue( node );
1262 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
1263 if ( confidence >= max_bootstrap_value ) {
1264 setBootstrapConfidence( node, max_normalized_value );
1267 setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
1274 public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
1275 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1276 if ( phy.isEmpty() ) {
1279 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1280 nodes.add( iter.next() );
1285 public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
1286 for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
1287 final PhylogenyNode node = iter.next();
1292 if ( node.isInternal() ) {
1293 //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
1294 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
1295 final PhylogenyNode child_node = node.getChildNode( i );
1296 final Color child_color = getBranchColorValue( child_node );
1297 if ( child_color != null ) {
1299 red += child_color.getRed();
1300 green += child_color.getGreen();
1301 blue += child_color.getBlue();
1304 setBranchColorValue( node,
1305 new Color( ForesterUtil.roundToInt( red / n ),
1306 ForesterUtil.roundToInt( green / n ),
1307 ForesterUtil.roundToInt( blue / n ) ) );
1312 public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
1313 if ( remove_me.isRoot() ) {
1314 throw new IllegalArgumentException( "ill advised attempt to remove root node" );
1316 if ( remove_me.isExternal() ) {
1317 phylogeny.deleteSubtree( remove_me, false );
1318 phylogeny.clearHashIdToNodeMap();
1319 phylogeny.externalNodesHaveChanged();
1322 final PhylogenyNode parent = remove_me.getParent();
1323 final List<PhylogenyNode> descs = remove_me.getDescendants();
1324 parent.removeChildNode( remove_me );
1325 for( final PhylogenyNode desc : descs ) {
1326 parent.addAsChild( desc );
1327 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
1328 desc.getDistanceToParent() ) );
1330 remove_me.setParent( null );
1331 phylogeny.clearHashIdToNodeMap();
1332 phylogeny.externalNodesHaveChanged();
1336 public static List<PhylogenyNode> searchData( final String query,
1337 final Phylogeny phy,
1338 final boolean case_sensitive,
1339 final boolean partial,
1340 final boolean search_domains ) {
1341 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1342 if ( phy.isEmpty() || ( query == null ) ) {
1345 if ( ForesterUtil.isEmpty( query ) ) {
1348 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1349 final PhylogenyNode node = iter.next();
1350 boolean match = false;
1351 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1354 else if ( node.getNodeData().isHasTaxonomy()
1355 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1358 else if ( node.getNodeData().isHasTaxonomy()
1359 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1362 else if ( node.getNodeData().isHasTaxonomy()
1363 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1366 else if ( node.getNodeData().isHasTaxonomy()
1367 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1368 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1374 else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1375 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1376 I: for( final String syn : syns ) {
1377 if ( match( syn, query, case_sensitive, partial ) ) {
1383 if ( !match && node.getNodeData().isHasSequence()
1384 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1387 if ( !match && node.getNodeData().isHasSequence()
1388 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1392 && node.getNodeData().isHasSequence()
1393 && ( node.getNodeData().getSequence().getAccession() != null )
1394 && match( node.getNodeData().getSequence().getAccession().getValue(),
1400 if ( search_domains && !match && node.getNodeData().isHasSequence()
1401 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1402 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1403 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1404 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1410 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1411 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1412 I: while ( it.hasNext() ) {
1413 if ( match( it.next(), query, case_sensitive, partial ) ) {
1418 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1419 I: while ( it.hasNext() ) {
1420 if ( match( it.next(), query, case_sensitive, partial ) ) {
1433 public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1434 final Phylogeny phy,
1435 final boolean case_sensitive,
1436 final boolean partial,
1437 final boolean search_domains ) {
1438 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1439 if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1442 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1443 final PhylogenyNode node = iter.next();
1444 boolean all_matched = true;
1445 for( final String query : queries ) {
1446 boolean match = false;
1447 if ( ForesterUtil.isEmpty( query ) ) {
1450 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1453 else if ( node.getNodeData().isHasTaxonomy()
1454 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1457 else if ( node.getNodeData().isHasTaxonomy()
1458 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1461 else if ( node.getNodeData().isHasTaxonomy()
1462 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1465 else if ( node.getNodeData().isHasTaxonomy()
1466 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1467 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1473 else if ( node.getNodeData().isHasTaxonomy()
1474 && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1475 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1476 I: for( final String syn : syns ) {
1477 if ( match( syn, query, case_sensitive, partial ) ) {
1483 if ( !match && node.getNodeData().isHasSequence()
1484 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1487 if ( !match && node.getNodeData().isHasSequence()
1488 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1492 && node.getNodeData().isHasSequence()
1493 && ( node.getNodeData().getSequence().getAccession() != null )
1494 && match( node.getNodeData().getSequence().getAccession().getValue(),
1500 if ( search_domains && !match && node.getNodeData().isHasSequence()
1501 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1502 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1503 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1504 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1510 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1511 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1512 I: while ( it.hasNext() ) {
1513 if ( match( it.next(), query, case_sensitive, partial ) ) {
1518 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1519 I: while ( it.hasNext() ) {
1520 if ( match( it.next(), query, case_sensitive, partial ) ) {
1527 all_matched = false;
1531 if ( all_matched ) {
1539 * Convenience method.
1540 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1542 public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1543 setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1546 public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1547 if ( node.getBranchData().getBranchColor() == null ) {
1548 node.getBranchData().setBranchColor( new BranchColor() );
1550 node.getBranchData().getBranchColor().setValue( color );
1554 * Convenience method
1556 public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1557 node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1561 * Convenience method.
1562 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1564 public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1565 setConfidence( node, confidence_value, "" );
1569 * Convenience method.
1570 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1572 public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1573 Confidence c = null;
1574 if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1575 c = node.getBranchData().getConfidence( 0 );
1578 c = new Confidence();
1579 node.getBranchData().addConfidence( c );
1582 c.setValue( confidence_value );
1585 public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1586 if ( !node.getNodeData().isHasTaxonomy() ) {
1587 node.getNodeData().setTaxonomy( new Taxonomy() );
1589 node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1593 * Convenience method to set the taxonomy code of a phylogeny node.
1597 * @param taxonomy_code
1598 * @throws PhyloXmlDataFormatException
1600 public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code )
1601 throws PhyloXmlDataFormatException {
1602 if ( !node.getNodeData().isHasTaxonomy() ) {
1603 node.getNodeData().setTaxonomy( new Taxonomy() );
1605 node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1609 * Removes from Phylogeny to_be_stripped all external Nodes which are
1610 * associated with a species NOT found in Phylogeny reference.
1613 * a reference Phylogeny
1614 * @param to_be_stripped
1615 * Phylogeny to be stripped
1616 * @return nodes removed from to_be_stripped
1618 public static List<PhylogenyNode> taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference,
1619 final Phylogeny to_be_stripped ) {
1620 final Set<String> ref_ext_taxo = new HashSet<String>();
1621 for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1622 final PhylogenyNode n = it.next();
1623 if ( !n.getNodeData().isHasTaxonomy() ) {
1624 throw new IllegalArgumentException( "no taxonomic data in node: " + n );
1626 // ref_ext_taxo.add( getSpecies( n ) );
1627 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1628 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() );
1630 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1631 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1634 final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1635 for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1636 final PhylogenyNode n = it.next();
1637 if ( !n.getNodeData().isHasTaxonomy() ) {
1638 nodes_to_delete.add( n );
1640 else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) )
1641 && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1642 nodes_to_delete.add( n );
1645 for( final PhylogenyNode phylogenyNode : nodes_to_delete ) {
1646 to_be_stripped.deleteSubtree( phylogenyNode, true );
1648 to_be_stripped.clearHashIdToNodeMap();
1649 to_be_stripped.externalNodesHaveChanged();
1650 return nodes_to_delete;
1654 * Arranges the order of childern for each node of this Phylogeny in such a
1655 * way that either the branch with more children is on top (right) or on
1656 * bottom (left), dependent on the value of boolean order.
1659 * decides in which direction to order
1662 public static void orderAppearance( final PhylogenyNode n,
1663 final boolean order,
1664 final boolean order_ext_alphabetically,
1665 final DESCENDANT_SORT_PRIORITY pri ) {
1666 if ( n.isExternal() ) {
1670 PhylogenyNode temp = null;
1671 if ( ( n.getNumberOfDescendants() == 2 )
1672 && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
1673 && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
1674 temp = n.getChildNode1();
1675 n.setChild1( n.getChildNode2() );
1676 n.setChild2( temp );
1678 else if ( order_ext_alphabetically ) {
1679 boolean all_ext = true;
1680 for( final PhylogenyNode i : n.getDescendants() ) {
1681 if ( !i.isExternal() ) {
1687 PhylogenyMethods.sortNodeDescendents( n, pri );
1690 for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
1691 orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri );
1696 public static enum PhylogenyNodeField {
1699 TAXONOMY_SCIENTIFIC_NAME,
1700 TAXONOMY_COMMON_NAME,
1703 TAXONOMY_ID_UNIPROT_1,
1704 TAXONOMY_ID_UNIPROT_2,
1708 public static enum DESCENDANT_SORT_PRIORITY {
1709 TAXONOMY, SEQUENCE, NODE_NAME;