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;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
35 import java.util.SortedMap;
36 import java.util.TreeMap;
38 import org.forester.phylogeny.data.BranchColor;
39 import org.forester.phylogeny.data.BranchWidth;
40 import org.forester.phylogeny.data.Confidence;
41 import org.forester.phylogeny.data.DomainArchitecture;
42 import org.forester.phylogeny.data.Taxonomy;
43 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
44 import org.forester.util.FailedConditionCheckException;
45 import org.forester.util.ForesterUtil;
47 public class PhylogenyMethods {
49 private static PhylogenyMethods _instance = null;
50 private final Set<Integer> _temp_hash_set = new HashSet<Integer>();
51 private PhylogenyNode _farthest_1 = null;
52 private PhylogenyNode _farthest_2 = null;
54 private PhylogenyMethods() {
55 // Hidden constructor.
59 * Calculates the distance between PhylogenyNodes node1 and node2.
64 * @return distance between node1 and node2
66 public double calculateDistance( final PhylogenyNode node1, final PhylogenyNode node2 ) {
67 final PhylogenyNode lca = obtainLCA( node1, node2 );
68 final PhylogenyNode n1 = node1;
69 final PhylogenyNode n2 = node2;
70 return ( PhylogenyMethods.getDistance( n1, lca ) + PhylogenyMethods.getDistance( n2, lca ) );
73 public double calculateFurthestDistance( final Phylogeny phylogeny ) {
74 if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
79 PhylogenyNode node_1 = null;
80 PhylogenyNode node_2 = null;
81 double farthest_d = -Double.MAX_VALUE;
82 final PhylogenyMethods methods = PhylogenyMethods.getInstance();
83 final List<PhylogenyNode> ext_nodes = phylogeny.getRoot().getAllExternalDescendants();
84 for( int i = 1; i < ext_nodes.size(); ++i ) {
85 for( int j = 0; j < i; ++j ) {
86 final double d = methods.calculateDistance( ext_nodes.get( i ), ext_nodes.get( j ) );
88 throw new RuntimeException( "distance cannot be negative" );
90 if ( d > farthest_d ) {
92 node_1 = ext_nodes.get( i );
93 node_2 = ext_nodes.get( j );
103 public Object clone() throws CloneNotSupportedException {
104 throw new CloneNotSupportedException();
107 public PhylogenyNode getFarthestNode1() {
111 public PhylogenyNode getFarthestNode2() {
116 * Returns the LCA of PhylogenyNodes node1 and node2.
121 * @return LCA of node1 and node2
123 public PhylogenyNode obtainLCA( final PhylogenyNode node1, final PhylogenyNode node2 ) {
124 _temp_hash_set.clear();
125 PhylogenyNode n1 = node1;
126 PhylogenyNode n2 = node2;
127 _temp_hash_set.add( n1.getId() );
128 while ( !n1.isRoot() ) {
130 _temp_hash_set.add( n1.getId() );
132 while ( !_temp_hash_set.contains( n2.getId() ) && !n2.isRoot() ) {
135 if ( !_temp_hash_set.contains( n2.getId() ) ) {
136 throw new IllegalArgumentException( "attempt to get LCA of two nodes which do not share a common root" );
142 * Returns all orthologs of the external PhylogenyNode n of this Phylogeny.
143 * Orthologs are returned as List of node references.
145 * PRECONDITION: This tree must be binary and rooted, and speciation -
146 * duplication need to be assigned for each of its internal Nodes.
148 * Returns null if this Phylogeny is empty or if n is internal.
150 * external PhylogenyNode whose orthologs are to be returned
151 * @return Vector of references to all orthologous Nodes of PhylogenyNode n
152 * of this Phylogeny, null if this Phylogeny is empty or if n is
155 public List<PhylogenyNode> getOrthologousNodes( final Phylogeny phy, final PhylogenyNode node ) {
156 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
157 final PhylogenyNodeIterator it = phy.iteratorExternalForward();
158 while ( it.hasNext() ) {
159 final PhylogenyNode temp_node = it.next();
160 if ( ( temp_node != node ) && isAreOrthologous( node, temp_node ) ) {
161 nodes.add( temp_node );
167 public boolean isAreOrthologous( final PhylogenyNode node1, final PhylogenyNode node2 ) {
168 return !obtainLCA( node1, node2 ).isDuplication();
171 static double addPhylogenyDistances( final double a, final double b ) {
172 if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
175 else if ( a >= 0.0 ) {
178 else if ( b >= 0.0 ) {
181 return PhylogenyNode.DISTANCE_DEFAULT;
184 // Helper for getUltraParalogousNodes( PhylogenyNode ).
185 public static boolean areAllChildrenDuplications( final PhylogenyNode n ) {
186 if ( n.isExternal() ) {
190 if ( n.isDuplication() ) {
192 for( final PhylogenyNode desc : n.getDescendants() ) {
193 if ( !areAllChildrenDuplications( desc ) ) {
205 public static int calculateDepth( final PhylogenyNode node ) {
206 PhylogenyNode n = node;
208 while ( !n.isRoot() ) {
215 public static double calculateDistanceToRoot( final PhylogenyNode node ) {
216 PhylogenyNode n = node;
218 while ( !n.isRoot() ) {
219 if ( n.getDistanceToParent() > 0.0 ) {
220 d += n.getDistanceToParent();
227 public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) {
228 if ( node.isExternal() ) {
232 for( PhylogenyNode d : node.getAllExternalDescendants() ) {
234 while ( d != node ) {
235 if ( d.isCollapse() ) {
250 public static int calculateMaxDepth( final Phylogeny phy ) {
252 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
253 final PhylogenyNode node = iter.next();
254 final int steps = calculateDepth( node );
262 public static double calculateMaxDistanceToRoot( final Phylogeny phy ) {
264 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
265 final PhylogenyNode node = iter.next();
266 final double d = calculateDistanceToRoot( node );
274 public static int calculateMaximumNumberOfDescendantsPerNode( final Phylogeny phy ) {
276 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
277 final PhylogenyNode node = iter.next();
278 if ( node.getNumberOfDescendants() > max ) {
279 max = node.getNumberOfDescendants();
286 * Returns the set of distinct taxonomies of
287 * all external nodes of node.
288 * If at least one the external nodes has no taxonomy,
292 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
293 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
294 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
295 for( final PhylogenyNode n : descs ) {
296 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
299 tax_set.add( n.getNodeData().getTaxonomy() );
305 * Returns a map of distinct taxonomies of
306 * all external nodes of node.
307 * If at least one of the external nodes has no taxonomy,
311 public static SortedMap<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
312 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
313 final SortedMap<Taxonomy, Integer> tax_map = new TreeMap<Taxonomy, Integer>();
314 for( final PhylogenyNode n : descs ) {
315 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
318 final Taxonomy t = n.getNodeData().getTaxonomy();
319 if ( tax_map.containsKey( t ) ) {
320 tax_map.put( t, tax_map.get( t ) + 1 );
329 public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) {
330 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
332 for( final PhylogenyNode n : descs ) {
333 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
341 * Deep copies the phylogeny originating from this node.
343 static PhylogenyNode copySubTree( final PhylogenyNode source ) {
344 if ( source == null ) {
348 final PhylogenyNode newnode = source.copyNodeData();
349 if ( !source.isExternal() ) {
350 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
351 newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
359 * Shallow copies the phylogeny originating from this node.
361 static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
362 if ( source == null ) {
366 final PhylogenyNode newnode = source.copyNodeDataShallow();
367 if ( !source.isExternal() ) {
368 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
369 newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
376 public static void deleteExternalNodesNegativeSelection( final Set<Integer> to_delete, final Phylogeny phy ) {
378 for( final Integer id : to_delete ) {
379 phy.deleteSubtree( phy.getNode( id ), true );
384 public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
385 throws IllegalArgumentException {
386 for( int i = 0; i < node_names_to_delete.length; ++i ) {
387 if ( ForesterUtil.isEmpty( node_names_to_delete[ i ] ) ) {
390 List<PhylogenyNode> nodes = null;
391 nodes = p.getNodes( node_names_to_delete[ i ] );
392 final Iterator<PhylogenyNode> it = nodes.iterator();
393 while ( it.hasNext() ) {
394 final PhylogenyNode n = it.next();
395 if ( !n.isExternal() ) {
396 throw new IllegalArgumentException( "attempt to delete non-external node \""
397 + node_names_to_delete[ i ] + "\"" );
399 p.deleteSubtree( n, true );
404 public static void deleteExternalNodesPositiveSelection( final Set<Taxonomy> species_to_keep, final Phylogeny phy ) {
405 // final Set<Integer> to_delete = new HashSet<Integer>();
406 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
407 final PhylogenyNode n = it.next();
408 if ( n.getNodeData().isHasTaxonomy() ) {
409 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
410 //to_delete.add( n.getNodeId() );
411 phy.deleteSubtree( n, true );
415 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
419 phy.externalNodesHaveChanged();
420 // deleteExternalNodesNegativeSelection( to_delete, phy );
423 public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
424 final Phylogeny p ) {
425 final PhylogenyNodeIterator it = p.iteratorExternalForward();
426 final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
428 Arrays.sort( node_names_to_keep );
429 while ( it.hasNext() ) {
430 final String curent_name = it.next().getName();
431 if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
432 to_delete[ i++ ] = curent_name;
435 PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
436 final List<String> deleted = new ArrayList<String>();
437 for( final String n : to_delete ) {
438 if ( !ForesterUtil.isEmpty( n ) ) {
445 public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
446 final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
447 final Set<Integer> encountered = new HashSet<Integer>();
448 if ( !node.isExternal() ) {
449 final List<PhylogenyNode> exts = node.getAllExternalDescendants();
450 for( PhylogenyNode current : exts ) {
451 descs.add( current );
452 while ( current != node ) {
453 current = current.getParent();
454 if ( encountered.contains( current.getId() ) ) {
457 descs.add( current );
458 encountered.add( current.getId() );
472 public static Color getBranchColorValue( final PhylogenyNode node ) {
473 if ( node.getBranchData().getBranchColor() == null ) {
476 return node.getBranchData().getBranchColor().getValue();
482 public static double getBranchWidthValue( final PhylogenyNode node ) {
483 if ( !node.getBranchData().isHasBranchWidth() ) {
484 return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
486 return node.getBranchData().getBranchWidth().getValue();
492 public static double getConfidenceValue( final PhylogenyNode node ) {
493 if ( !node.getBranchData().isHasConfidences() ) {
494 return Confidence.CONFIDENCE_DEFAULT_VALUE;
496 return node.getBranchData().getConfidence( 0 ).getValue();
502 public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
503 if ( !node.getBranchData().isHasConfidences() ) {
504 return new double[ 0 ];
506 final double[] values = new double[ node.getBranchData().getConfidences().size() ];
508 for( final Confidence c : node.getBranchData().getConfidences() ) {
509 values[ i++ ] = c.getValue();
515 * Calculates the distance between PhylogenyNodes n1 and n2.
516 * PRECONDITION: n1 is a descendant of n2.
521 * @return distance between n1 and n2
523 private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
526 if ( n1.getDistanceToParent() > 0.0 ) {
527 d += n1.getDistanceToParent();
535 * Returns taxonomy t if all external descendants have
536 * the same taxonomy t, null otherwise.
539 public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
540 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
542 for( final PhylogenyNode n : descs ) {
543 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
546 else if ( tax == null ) {
547 tax = n.getNodeData().getTaxonomy();
549 else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
556 public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
557 final List<PhylogenyNode> children = node.getAllExternalDescendants();
558 PhylogenyNode farthest = null;
559 double longest = -Double.MAX_VALUE;
560 for( final PhylogenyNode child : children ) {
561 if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
563 longest = PhylogenyMethods.getDistance( child, node );
569 public static PhylogenyMethods getInstance() {
570 if ( PhylogenyMethods._instance == null ) {
571 PhylogenyMethods._instance = new PhylogenyMethods();
573 return PhylogenyMethods._instance;
577 * Returns the largest confidence value found on phy.
579 static public double getMaximumConfidenceValue( final Phylogeny phy ) {
580 double max = -Double.MAX_VALUE;
581 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
582 final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
583 if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
590 static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
591 int min = Integer.MAX_VALUE;
594 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
596 if ( n.isInternal() ) {
597 d = n.getNumberOfDescendants();
607 * Convenience method for display purposes.
608 * Not intended for algorithms.
610 public static String getSpecies( final PhylogenyNode node ) {
611 if ( !node.getNodeData().isHasTaxonomy() ) {
614 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
615 return node.getNodeData().getTaxonomy().getTaxonomyCode();
617 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
618 return node.getNodeData().getTaxonomy().getScientificName();
621 return node.getNodeData().getTaxonomy().getCommonName();
626 * Returns all Nodes which are connected to external PhylogenyNode n of this
627 * Phylogeny by a path containing only speciation events. We call these
628 * "super orthologs". Nodes are returned as Vector of references to Nodes.
630 * PRECONDITION: This tree must be binary and rooted, and speciation -
631 * duplication need to be assigned for each of its internal Nodes.
633 * Returns null if this Phylogeny is empty or if n is internal.
635 * external PhylogenyNode whose strictly speciation related Nodes
637 * @return Vector of references to all strictly speciation related Nodes of
638 * PhylogenyNode n of this Phylogeny, null if this Phylogeny is
639 * empty or if n is internal
641 public static List<PhylogenyNode> getSuperOrthologousNodes( final PhylogenyNode n ) {
643 PhylogenyNode node = n, deepest = null;
644 final List<PhylogenyNode> v = new ArrayList<PhylogenyNode>();
645 if ( !node.isExternal() ) {
648 while ( !node.isRoot() && !node.getParent().isDuplication() ) {
649 node = node.getParent();
652 deepest.setIndicatorsToZero();
654 if ( !node.isExternal() ) {
655 if ( node.getIndicator() == 0 ) {
656 node.setIndicator( ( byte ) 1 );
657 if ( !node.isDuplication() ) {
658 node = node.getChildNode1();
661 if ( node.getIndicator() == 1 ) {
662 node.setIndicator( ( byte ) 2 );
663 if ( !node.isDuplication() ) {
664 node = node.getChildNode2();
667 if ( ( node != deepest ) && ( node.getIndicator() == 2 ) ) {
668 node = node.getParent();
675 if ( node != deepest ) {
676 node = node.getParent();
679 node.setIndicator( ( byte ) 2 );
682 } while ( ( node != deepest ) || ( deepest.getIndicator() != 2 ) );
687 * Convenience method for display purposes.
688 * Not intended for algorithms.
690 public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
691 if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
694 return node.getNodeData().getTaxonomy().getIdentifier().getValue();
698 * Returns all Nodes which are connected to external PhylogenyNode n of this
699 * Phylogeny by a path containing, and leading to, only duplication events.
700 * We call these "ultra paralogs". Nodes are returned as Vector of
701 * references to Nodes.
703 * PRECONDITION: This tree must be binary and rooted, and speciation -
704 * duplication need to be assigned for each of its internal Nodes.
706 * Returns null if this Phylogeny is empty or if n is internal.
708 * (Last modified: 10/06/01)
711 * external PhylogenyNode whose ultra paralogs are to be returned
712 * @return Vector of references to all ultra paralogs of PhylogenyNode n of
713 * this Phylogeny, null if this Phylogeny is empty or if n is
716 public static List<PhylogenyNode> getUltraParalogousNodes( final PhylogenyNode n ) {
718 PhylogenyNode node = n;
719 if ( !node.isExternal() ) {
722 while ( !node.isRoot() && node.getParent().isDuplication() && areAllChildrenDuplications( node.getParent() ) ) {
723 node = node.getParent();
725 final List<PhylogenyNode> nodes = node.getAllExternalDescendants();
730 public static String inferCommonPartOfScientificNameOfDescendants( final PhylogenyNode node ) {
731 final List<PhylogenyNode> descs = node.getDescendants();
733 for( final PhylogenyNode n : descs ) {
734 if ( !n.getNodeData().isHasTaxonomy()
735 || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
738 else if ( sn == null ) {
739 sn = n.getNodeData().getTaxonomy().getScientificName().trim();
742 String sn_current = n.getNodeData().getTaxonomy().getScientificName().trim();
743 if ( !sn.equals( sn_current ) ) {
744 boolean overlap = false;
745 while ( ( sn.indexOf( ' ' ) >= 0 ) || ( sn_current.indexOf( ' ' ) >= 0 ) ) {
746 if ( ForesterUtil.countChars( sn, ' ' ) > ForesterUtil.countChars( sn_current, ' ' ) ) {
747 sn = sn.substring( 0, sn.lastIndexOf( ' ' ) ).trim();
750 sn_current = sn_current.substring( 0, sn_current.lastIndexOf( ' ' ) ).trim();
752 if ( sn.equals( sn_current ) ) {
766 public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
767 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
768 if ( node.getChildNode( i ).isExternal() ) {
776 * This is case insensitive.
779 public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
780 final String[] providers ) {
781 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
782 final String my_tax_prov = tax.getIdentifier().getProvider();
783 for( final String provider : providers ) {
784 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
795 private static boolean match( final String s,
797 final boolean case_sensitive,
798 final boolean partial ) {
799 if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
802 String my_s = s.trim();
803 String my_query = query.trim();
804 if ( !case_sensitive ) {
805 my_s = my_s.toLowerCase();
806 my_query = my_query.toLowerCase();
809 return my_s.indexOf( my_query ) >= 0;
812 return my_s.equals( my_query );
816 public static void midpointRoot( final Phylogeny phylogeny ) {
817 if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
820 final PhylogenyMethods methods = getInstance();
821 final double farthest_d = methods.calculateFurthestDistance( phylogeny );
822 final PhylogenyNode f1 = methods.getFarthestNode1();
823 final PhylogenyNode f2 = methods.getFarthestNode2();
824 if ( farthest_d <= 0.0 ) {
827 double x = farthest_d / 2.0;
828 PhylogenyNode n = f1;
829 if ( PhylogenyMethods.getDistance( f1, phylogeny.getRoot() ) < PhylogenyMethods.getDistance( f2, phylogeny
833 while ( ( x > n.getDistanceToParent() ) && !n.isRoot() ) {
834 x -= ( n.getDistanceToParent() > 0 ? n.getDistanceToParent() : 0 );
837 phylogeny.reRoot( n, x );
838 phylogeny.recalculateNumberOfExternalDescendants( true );
839 final PhylogenyNode a = getFurthestDescendant( phylogeny.getRoot().getChildNode1() );
840 final PhylogenyNode b = getFurthestDescendant( phylogeny.getRoot().getChildNode2() );
841 final double da = getDistance( a, phylogeny.getRoot() );
842 final double db = getDistance( b, phylogeny.getRoot() );
843 if ( Math.abs( da - db ) > 0.000001 ) {
844 throw new FailedConditionCheckException( "this should not have happened: midpoint rooting failed: da="
845 + da + ", db=" + db + ", diff=" + Math.abs( da - db ) );
849 public static void normalizeBootstrapValues( final Phylogeny phylogeny,
850 final double max_bootstrap_value,
851 final double max_normalized_value ) {
852 for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
853 final PhylogenyNode node = iter.next();
854 if ( node.isInternal() ) {
855 final double confidence = getConfidenceValue( node );
856 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
857 if ( confidence >= max_bootstrap_value ) {
858 setBootstrapConfidence( node, max_normalized_value );
861 setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
868 public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
869 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
870 if ( phy.isEmpty() ) {
873 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
874 nodes.add( iter.next() );
879 public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
880 for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
881 final PhylogenyNode node = iter.next();
886 if ( node.isInternal() ) {
887 for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
888 final PhylogenyNode child_node = iterator.next();
889 final Color child_color = getBranchColorValue( child_node );
890 if ( child_color != null ) {
892 red += child_color.getRed();
893 green += child_color.getGreen();
894 blue += child_color.getBlue();
897 setBranchColorValue( node,
898 new Color( ForesterUtil.roundToInt( red / n ),
899 ForesterUtil.roundToInt( green / n ),
900 ForesterUtil.roundToInt( blue / n ) ) );
905 public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
906 if ( remove_me.isRoot() ) {
907 throw new IllegalArgumentException( "ill advised attempt to remove root node" );
909 if ( remove_me.isExternal() ) {
910 phylogeny.deleteSubtree( remove_me, false );
913 final PhylogenyNode parent = remove_me.getParent();
914 final List<PhylogenyNode> descs = remove_me.getDescendants();
915 parent.removeChildNode( remove_me );
916 for( final PhylogenyNode desc : descs ) {
917 parent.addAsChild( desc );
918 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
919 desc.getDistanceToParent() ) );
921 remove_me.setParent( null );
922 phylogeny.setIdHash( null );
923 phylogeny.externalNodesHaveChanged();
927 public static List<PhylogenyNode> searchData( final String query,
929 final boolean case_sensitive,
930 final boolean partial ) {
931 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
932 if ( phy.isEmpty() || ( query == null ) ) {
935 if ( ForesterUtil.isEmpty( query ) ) {
938 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
939 final PhylogenyNode node = iter.next();
940 boolean match = false;
941 if ( match( node.getName(), query, case_sensitive, partial ) ) {
944 else if ( node.getNodeData().isHasTaxonomy()
945 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
948 else if ( node.getNodeData().isHasTaxonomy()
949 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
952 else if ( node.getNodeData().isHasTaxonomy()
953 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
956 else if ( node.getNodeData().isHasTaxonomy()
957 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
958 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
964 else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
965 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
966 I: for( final String syn : syns ) {
967 if ( match( syn, query, case_sensitive, partial ) ) {
973 else if ( node.getNodeData().isHasSequence()
974 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
977 else if ( node.getNodeData().isHasSequence()
978 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
981 else if ( node.getNodeData().isHasSequence()
982 && ( node.getNodeData().getSequence().getAccession() != null )
983 && match( node.getNodeData().getSequence().getAccession().getValue(),
989 else if ( node.getNodeData().isHasSequence()
990 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
991 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
992 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
993 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1006 public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1007 final Phylogeny phy,
1008 final boolean case_sensitive,
1009 final boolean partial ) {
1010 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1011 if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1014 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1015 final PhylogenyNode node = iter.next();
1016 boolean all_matched = true;
1017 for( final String query : queries ) {
1018 boolean match = false;
1019 if ( ForesterUtil.isEmpty( query ) ) {
1022 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1025 else if ( node.getNodeData().isHasTaxonomy()
1026 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1029 else if ( node.getNodeData().isHasTaxonomy()
1030 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1033 else if ( node.getNodeData().isHasTaxonomy()
1034 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1037 else if ( node.getNodeData().isHasTaxonomy()
1038 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1039 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1045 else if ( node.getNodeData().isHasTaxonomy()
1046 && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1047 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1048 I: for( final String syn : syns ) {
1049 if ( match( syn, query, case_sensitive, partial ) ) {
1055 else if ( node.getNodeData().isHasSequence()
1056 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1059 else if ( node.getNodeData().isHasSequence()
1060 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1063 else if ( node.getNodeData().isHasSequence()
1064 && ( node.getNodeData().getSequence().getAccession() != null )
1065 && match( node.getNodeData().getSequence().getAccession().getValue(),
1071 else if ( node.getNodeData().isHasSequence()
1072 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1073 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1074 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1075 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1082 all_matched = false;
1086 if ( all_matched ) {
1094 * Convenience method.
1095 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1097 public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1098 setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1101 public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1102 if ( node.getBranchData().getBranchColor() == null ) {
1103 node.getBranchData().setBranchColor( new BranchColor() );
1105 node.getBranchData().getBranchColor().setValue( color );
1109 * Convenience method
1111 public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1112 node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1116 * Convenience method.
1117 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1119 public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1120 setConfidence( node, confidence_value, "" );
1124 * Convenience method.
1125 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1127 public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1128 Confidence c = null;
1129 if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1130 c = node.getBranchData().getConfidence( 0 );
1133 c = new Confidence();
1134 node.getBranchData().addConfidence( c );
1137 c.setValue( confidence_value );
1140 public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1141 if ( !node.getNodeData().isHasTaxonomy() ) {
1142 node.getNodeData().setTaxonomy( new Taxonomy() );
1144 node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1148 * Convenience method to set the taxonomy code of a phylogeny node.
1152 * @param taxonomy_code
1154 public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code ) {
1155 if ( !node.getNodeData().isHasTaxonomy() ) {
1156 node.getNodeData().setTaxonomy( new Taxonomy() );
1158 node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1162 * Removes from Phylogeny to_be_stripped all external Nodes which are
1163 * associated with a species NOT found in Phylogeny reference.
1166 * a reference Phylogeny
1167 * @param to_be_stripped
1168 * Phylogeny to be stripped
1169 * @return number of external nodes removed from to_be_stripped
1171 public static int taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference, final Phylogeny to_be_stripped ) {
1172 final Set<String> ref_ext_taxo = new HashSet<String>();
1173 final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1174 for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1175 ref_ext_taxo.add( getSpecies( it.next() ) );
1177 for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1178 final PhylogenyNode n = it.next();
1179 if ( !ref_ext_taxo.contains( getSpecies( n ) ) ) {
1180 nodes_to_delete.add( n );
1183 for( final PhylogenyNode phylogenyNode : nodes_to_delete ) {
1184 to_be_stripped.deleteSubtree( phylogenyNode, true );
1186 return nodes_to_delete.size();