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: https://sites.google.com/site/cmzmasek/home/software/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.ForesterUtil;
63 public class PhylogenyMethods {
65 //private static PhylogenyMethods _instance = null;
66 //private final PhylogenyNode _farthest_1 = null;
67 //private final PhylogenyNode _farthest_2 = null;
68 private PhylogenyMethods() {
69 // Hidden constructor.
72 // public double calculateFurthestDistance( final Phylogeny phylogeny ) {
73 // if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
76 // _farthest_1 = null;
77 // _farthest_2 = null;
78 // PhylogenyNode node_1 = null;
79 // PhylogenyNode node_2 = null;
80 // double farthest_d = -Double.MAX_VALUE;
81 // final PhylogenyMethods methods = PhylogenyMethods.getInstance();
82 // final List<PhylogenyNode> ext_nodes = phylogeny.getRoot().getAllExternalDescendants();
83 // for( int i = 1; i < ext_nodes.size(); ++i ) {
84 // for( int j = 0; j < i; ++j ) {
85 // final double d = methods.calculateDistance( ext_nodes.get( i ), ext_nodes.get( j ) );
87 // throw new RuntimeException( "distance cannot be negative" );
89 // if ( d > farthest_d ) {
91 // node_1 = ext_nodes.get( i );
92 // node_2 = ext_nodes.get( j );
96 // _farthest_1 = node_1;
97 // _farthest_2 = node_2;
101 public Object clone() throws CloneNotSupportedException {
102 throw new CloneNotSupportedException();
105 // public PhylogenyNode getFarthestNode1() {
106 // return _farthest_1;
108 // public PhylogenyNode getFarthestNode2() {
109 // return _farthest_2;
111 public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) {
112 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
113 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
114 final PhylogenyNode n = iter.next();
115 if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) {
116 stats.addValue( n.getDistanceToParent() );
122 public static List<DescriptiveStatistics> calculatConfidenceStatistics( final Phylogeny phy ) {
123 final List<DescriptiveStatistics> stats = new ArrayList<DescriptiveStatistics>();
124 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
125 final PhylogenyNode n = iter.next();
126 if ( !n.isExternal() && !n.isRoot() ) {
127 if ( n.getBranchData().isHasConfidences() ) {
128 for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) {
129 final Confidence c = n.getBranchData().getConfidences().get( i );
130 if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) {
131 stats.add( i, new BasicDescriptiveStatistics() );
133 if ( !ForesterUtil.isEmpty( c.getType() ) ) {
134 if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) {
135 if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) {
136 throw new IllegalArgumentException( "support values in node [" + n.toString()
137 + "] appear inconsistently ordered" );
140 stats.get( i ).setDescription( c.getType() );
142 stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 );
151 * Calculates the distance between PhylogenyNodes node1 and node2.
156 * @return distance between node1 and node2
158 public static double calculateDistance( final PhylogenyNode node1, final PhylogenyNode node2 ) {
159 final PhylogenyNode lca = calculateLCA( node1, node2 );
160 final PhylogenyNode n1 = node1;
161 final PhylogenyNode n2 = node2;
162 return ( PhylogenyMethods.getDistance( n1, lca ) + PhylogenyMethods.getDistance( n2, lca ) );
166 * Returns the LCA of PhylogenyNodes node1 and node2.
171 * @return LCA of node1 and node2
173 public final static PhylogenyNode calculateLCA( PhylogenyNode node1, PhylogenyNode node2 ) {
174 if ( node1 == null ) {
175 throw new IllegalArgumentException( "first argument (node) is null" );
177 if ( node2 == null ) {
178 throw new IllegalArgumentException( "second argument (node) is null" );
180 if ( node1 == node2 ) {
183 if ( ( node1.getParent() == node2.getParent() ) ) {
184 return node1.getParent();
186 int depth1 = node1.calculateDepth();
187 int depth2 = node2.calculateDepth();
188 while ( ( depth1 > -1 ) && ( depth2 > -1 ) ) {
189 if ( depth1 > depth2 ) {
190 node1 = node1.getParent();
193 else if ( depth2 > depth1 ) {
194 node2 = node2.getParent();
198 if ( node1 == node2 ) {
201 node1 = node1.getParent();
202 node2 = node2.getParent();
207 throw new IllegalArgumentException( "illegal attempt to calculate LCA of two nodes which do not share a common root" );
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();
237 public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) {
238 if ( node.isExternal() ) {
242 for( PhylogenyNode d : node.getAllExternalDescendants() ) {
244 while ( d != node ) {
245 if ( d.isCollapse() ) {
260 public static int calculateMaxDepth( final Phylogeny phy ) {
262 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
263 final PhylogenyNode node = iter.next();
264 final int steps = node.calculateDepth();
272 public static double calculateMaxDistanceToRoot( final Phylogeny phy ) {
274 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
275 final PhylogenyNode node = iter.next();
276 final double d = node.calculateDistanceToRoot();
284 public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) {
285 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
287 for( final PhylogenyNode n : descs ) {
288 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
295 public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) {
296 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
297 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
298 final PhylogenyNode n = iter.next();
299 if ( !n.isExternal() ) {
300 stats.addValue( n.getNumberOfDescendants() );
306 public static int countNumberOfOneDescendantNodes( final Phylogeny phy ) {
308 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
309 final PhylogenyNode n = iter.next();
310 if ( !n.isExternal() && ( n.getNumberOfDescendants() == 1 ) ) {
317 public static int countNumberOfPolytomies( final Phylogeny phy ) {
319 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
320 final PhylogenyNode n = iter.next();
321 if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) {
328 public static final HashMap<String, PhylogenyNode> createNameToExtNodeMap( final Phylogeny phy ) {
329 final HashMap<String, PhylogenyNode> nodes = new HashMap<String, PhylogenyNode>();
330 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
331 final PhylogenyNode n = iter.next();
332 nodes.put( n.getName(), n );
337 public static void deleteExternalNodesNegativeSelection( final Set<Integer> to_delete, final Phylogeny phy ) {
338 phy.clearHashIdToNodeMap();
339 for( final Integer id : to_delete ) {
340 phy.deleteSubtree( phy.getNode( id ), true );
342 phy.clearHashIdToNodeMap();
343 phy.externalNodesHaveChanged();
346 public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
347 throws IllegalArgumentException {
348 for( final String element : node_names_to_delete ) {
349 if ( ForesterUtil.isEmpty( element ) ) {
352 List<PhylogenyNode> nodes = null;
353 nodes = p.getNodes( element );
354 final Iterator<PhylogenyNode> it = nodes.iterator();
355 while ( it.hasNext() ) {
356 final PhylogenyNode n = it.next();
357 if ( !n.isExternal() ) {
358 throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" );
360 p.deleteSubtree( n, true );
363 p.clearHashIdToNodeMap();
364 p.externalNodesHaveChanged();
367 public static void deleteExternalNodesPositiveSelection( final Set<Taxonomy> species_to_keep, final Phylogeny phy ) {
368 // final Set<Integer> to_delete = new HashSet<Integer>();
369 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
370 final PhylogenyNode n = it.next();
371 if ( n.getNodeData().isHasTaxonomy() ) {
372 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
373 //to_delete.add( n.getNodeId() );
374 phy.deleteSubtree( n, true );
378 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
381 phy.clearHashIdToNodeMap();
382 phy.externalNodesHaveChanged();
385 public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
386 final Phylogeny p ) {
387 final PhylogenyNodeIterator it = p.iteratorExternalForward();
388 final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
390 Arrays.sort( node_names_to_keep );
391 while ( it.hasNext() ) {
392 final String curent_name = it.next().getName();
393 if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
394 to_delete[ i++ ] = curent_name;
397 PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
398 final List<String> deleted = new ArrayList<String>();
399 for( final String n : to_delete ) {
400 if ( !ForesterUtil.isEmpty( n ) ) {
407 final public static void deleteInternalNodesWithOnlyOneDescendent( final Phylogeny phy ) {
408 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
409 for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
410 final PhylogenyNode n = iter.next();
411 if ( ( !n.isExternal() ) && ( n.getNumberOfDescendants() == 1 ) ) {
415 for( final PhylogenyNode d : to_delete ) {
416 PhylogenyMethods.removeNode( d, phy );
418 phy.clearHashIdToNodeMap();
419 phy.externalNodesHaveChanged();
422 final public static void deleteNonOrthologousExternalNodes( final Phylogeny phy, final PhylogenyNode n ) {
423 if ( n.isInternal() ) {
424 throw new IllegalArgumentException( "node is not external" );
426 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
427 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
428 final PhylogenyNode i = it.next();
429 if ( !PhylogenyMethods.getEventAtLCA( n, i ).isSpeciation() ) {
433 for( final PhylogenyNode d : to_delete ) {
434 phy.deleteSubtree( d, true );
436 phy.clearHashIdToNodeMap();
437 phy.externalNodesHaveChanged();
440 public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
441 final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
442 final Set<Integer> encountered = new HashSet<Integer>();
443 if ( !node.isExternal() ) {
444 final List<PhylogenyNode> exts = node.getAllExternalDescendants();
445 for( PhylogenyNode current : exts ) {
446 descs.add( current );
447 while ( current != node ) {
448 current = current.getParent();
449 if ( encountered.contains( current.getId() ) ) {
452 descs.add( current );
453 encountered.add( current.getId() );
467 public static Color getBranchColorValue( final PhylogenyNode node ) {
468 if ( node.getBranchData().getBranchColor() == null ) {
471 return node.getBranchData().getBranchColor().getValue();
477 public static double getBranchWidthValue( final PhylogenyNode node ) {
478 if ( !node.getBranchData().isHasBranchWidth() ) {
479 return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
481 return node.getBranchData().getBranchWidth().getValue();
487 public static double getConfidenceValue( final PhylogenyNode node ) {
488 if ( !node.getBranchData().isHasConfidences() ) {
489 return Confidence.CONFIDENCE_DEFAULT_VALUE;
491 return node.getBranchData().getConfidence( 0 ).getValue();
497 public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
498 if ( !node.getBranchData().isHasConfidences() ) {
499 return new double[ 0 ];
501 final double[] values = new double[ node.getBranchData().getConfidences().size() ];
503 for( final Confidence c : node.getBranchData().getConfidences() ) {
504 values[ i++ ] = c.getValue();
509 final public static Event getEventAtLCA( final PhylogenyNode n1, final PhylogenyNode n2 ) {
510 return calculateLCA( n1, n2 ).getNodeData().getEvent();
514 * Returns taxonomy t if all external descendants have
515 * the same taxonomy t, null otherwise.
518 public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
519 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
521 for( final PhylogenyNode n : descs ) {
522 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
525 else if ( tax == null ) {
526 tax = n.getNodeData().getTaxonomy();
528 else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
535 public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
536 final List<PhylogenyNode> children = node.getAllExternalDescendants();
537 PhylogenyNode farthest = null;
538 double longest = -Double.MAX_VALUE;
539 for( final PhylogenyNode child : children ) {
540 if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
542 longest = PhylogenyMethods.getDistance( child, node );
548 // public static PhylogenyMethods getInstance() {
549 // if ( PhylogenyMethods._instance == null ) {
550 // PhylogenyMethods._instance = new PhylogenyMethods();
552 // return PhylogenyMethods._instance;
555 * Returns the largest confidence value found on phy.
557 static public double getMaximumConfidenceValue( final Phylogeny phy ) {
558 double max = -Double.MAX_VALUE;
559 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
560 final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
561 if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
568 static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
569 int min = Integer.MAX_VALUE;
572 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
574 if ( n.isInternal() ) {
575 d = n.getNumberOfDescendants();
585 * Convenience method for display purposes.
586 * Not intended for algorithms.
588 public static String getSpecies( final PhylogenyNode node ) {
589 if ( !node.getNodeData().isHasTaxonomy() ) {
592 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
593 return node.getNodeData().getTaxonomy().getScientificName();
595 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
596 return node.getNodeData().getTaxonomy().getTaxonomyCode();
599 return node.getNodeData().getTaxonomy().getCommonName();
604 * Convenience method for display purposes.
605 * Not intended for algorithms.
607 public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
608 if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
611 return node.getNodeData().getTaxonomy().getIdentifier().getValue();
614 public final static boolean isAllDecendentsAreDuplications( final PhylogenyNode n ) {
615 if ( n.isExternal() ) {
619 if ( n.isDuplication() ) {
620 for( final PhylogenyNode desc : n.getDescendants() ) {
621 if ( !isAllDecendentsAreDuplications( desc ) ) {
633 public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
634 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
635 if ( node.getChildNode( i ).isExternal() ) {
643 * This is case insensitive.
646 public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
647 final String[] providers ) {
648 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
649 final String my_tax_prov = tax.getIdentifier().getProvider();
650 for( final String provider : providers ) {
651 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
662 public static void midpointRoot( final Phylogeny phylogeny ) {
663 if ( ( phylogeny.getNumberOfExternalNodes() < 2 ) || ( calculateMaxDistanceToRoot( phylogeny ) <= 0 ) ) {
667 final int total_nodes = phylogeny.getNodeCount();
669 if ( ++counter > total_nodes ) {
670 throw new RuntimeException( "this should not have happened: midpoint rooting does not converge" );
672 PhylogenyNode a = null;
675 for( int i = 0; i < phylogeny.getRoot().getNumberOfDescendants(); ++i ) {
676 final PhylogenyNode f = getFurthestDescendant( phylogeny.getRoot().getChildNode( i ) );
677 final double df = getDistance( f, phylogeny.getRoot() );
684 else if ( df > db ) {
689 final double diff = da - db;
690 if ( diff < 0.000001 ) {
693 double x = da - ( diff / 2.0 );
694 while ( ( x > a.getDistanceToParent() ) && !a.isRoot() ) {
695 x -= ( a.getDistanceToParent() > 0 ? a.getDistanceToParent() : 0 );
698 phylogeny.reRoot( a, x );
700 phylogeny.recalculateNumberOfExternalDescendants( true );
703 public static void midpointRootOLD( final Phylogeny phylogeny ) {
704 // if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
707 // final PhylogenyMethods methods = getInstance();
708 //final double farthest_d = methods.calculateFurthestDistance( phylogeny );
709 // final PhylogenyNode f1 = methods.getFarthestNode1();
710 // final PhylogenyNode f2 = methods.getFarthestNode2();
711 // if ( farthest_d <= 0.0 ) {
714 // double x = farthest_d / 2.0;
715 // PhylogenyNode n = f1;
716 // if ( PhylogenyMethods.getDistance( f1, phylogeny.getRoot() ) < PhylogenyMethods.getDistance( f2, phylogeny
720 // while ( ( x > n.getDistanceToParent() ) && !n.isRoot() ) {
721 // x -= ( n.getDistanceToParent() > 0 ? n.getDistanceToParent() : 0 );
722 // n = n.getParent();
724 // phylogeny.reRoot( n, x );
725 // phylogeny.recalculateNumberOfExternalDescendants( true );
726 // final PhylogenyNode a = getFurthestDescendant( phylogeny.getRoot().getChildNode1() );
727 // final PhylogenyNode b = getFurthestDescendant( phylogeny.getRoot().getChildNode2() );
728 // final double da = getDistance( a, phylogeny.getRoot() );
729 // final double db = getDistance( b, phylogeny.getRoot() );
730 // if ( Math.abs( da - db ) > 0.000001 ) {
731 // throw new FailedConditionCheckException( "this should not have happened: midpoint rooting failed: da="
732 // + da + ", db=" + db + ", diff=" + Math.abs( da - db ) );
736 public static void normalizeBootstrapValues( final Phylogeny phylogeny,
737 final double max_bootstrap_value,
738 final double max_normalized_value ) {
739 for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
740 final PhylogenyNode node = iter.next();
741 if ( node.isInternal() ) {
742 final double confidence = getConfidenceValue( node );
743 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
744 if ( confidence >= max_bootstrap_value ) {
745 setBootstrapConfidence( node, max_normalized_value );
748 setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
755 public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
756 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
757 if ( phy.isEmpty() ) {
760 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
761 nodes.add( iter.next() );
767 * Returns the set of distinct taxonomies of
768 * all external nodes of node.
769 * If at least one the external nodes has no taxonomy,
773 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
774 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
775 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
776 for( final PhylogenyNode n : descs ) {
777 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
780 tax_set.add( n.getNodeData().getTaxonomy() );
786 * Returns a map of distinct taxonomies of
787 * all external nodes of node.
788 * If at least one of the external nodes has no taxonomy,
792 public static SortedMap<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
793 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
794 final SortedMap<Taxonomy, Integer> tax_map = new TreeMap<Taxonomy, Integer>();
795 for( final PhylogenyNode n : descs ) {
796 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
799 final Taxonomy t = n.getNodeData().getTaxonomy();
800 if ( tax_map.containsKey( t ) ) {
801 tax_map.put( t, tax_map.get( t ) + 1 );
811 * Arranges the order of childern for each node of this Phylogeny in such a
812 * way that either the branch with more children is on top (right) or on
813 * bottom (left), dependent on the value of boolean order.
816 * decides in which direction to order
819 public static void orderAppearance( final PhylogenyNode n,
821 final boolean order_ext_alphabetically,
822 final DESCENDANT_SORT_PRIORITY pri ) {
823 if ( n.isExternal() ) {
827 PhylogenyNode temp = null;
828 if ( ( n.getNumberOfDescendants() == 2 )
829 && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
830 && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
831 temp = n.getChildNode1();
832 n.setChild1( n.getChildNode2() );
835 else if ( order_ext_alphabetically ) {
836 boolean all_ext = true;
837 for( final PhylogenyNode i : n.getDescendants() ) {
838 if ( !i.isExternal() ) {
844 PhylogenyMethods.sortNodeDescendents( n, pri );
847 for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
848 orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri );
853 public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
854 for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
855 final PhylogenyNode node = iter.next();
860 if ( node.isInternal() ) {
861 //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
862 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
863 final PhylogenyNode child_node = node.getChildNode( i );
864 final Color child_color = getBranchColorValue( child_node );
865 if ( child_color != null ) {
867 red += child_color.getRed();
868 green += child_color.getGreen();
869 blue += child_color.getBlue();
872 setBranchColorValue( node,
873 new Color( ForesterUtil.roundToInt( red / n ),
874 ForesterUtil.roundToInt( green / n ),
875 ForesterUtil.roundToInt( blue / n ) ) );
880 public static final void preOrderReId( final Phylogeny phy ) {
881 if ( phy.isEmpty() ) {
884 phy.setIdToNodeMap( null );
885 int i = PhylogenyNode.getNodeCount();
886 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
887 it.next().setId( i++ );
889 PhylogenyNode.setNodeCount( i );
892 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
893 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
894 final Phylogeny[] trees = factory.create( file, parser );
895 if ( ( trees == null ) || ( trees.length == 0 ) ) {
896 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
901 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List<File> files )
903 final List<Phylogeny> tree_list = new ArrayList<Phylogeny>();
904 for( final File file : files ) {
905 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
906 final Phylogeny[] trees = factory.create( file, parser );
907 if ( ( trees == null ) || ( trees.length == 0 ) ) {
908 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
910 tree_list.addAll( Arrays.asList( trees ) );
912 return tree_list.toArray( new Phylogeny[ tree_list.size() ] );
915 public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
916 if ( remove_me.isRoot() ) {
917 if ( remove_me.getNumberOfDescendants() == 1 ) {
918 final PhylogenyNode desc = remove_me.getDescendants().get( 0 );
919 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
920 desc.getDistanceToParent() ) );
921 desc.setParent( null );
922 phylogeny.setRoot( desc );
923 phylogeny.clearHashIdToNodeMap();
926 throw new IllegalArgumentException( "attempt to remove a root node with more than one descendants" );
929 else if ( remove_me.isExternal() ) {
930 phylogeny.deleteSubtree( remove_me, false );
931 phylogeny.clearHashIdToNodeMap();
932 phylogeny.externalNodesHaveChanged();
935 final PhylogenyNode parent = remove_me.getParent();
936 final List<PhylogenyNode> descs = remove_me.getDescendants();
937 parent.removeChildNode( remove_me );
938 for( final PhylogenyNode desc : descs ) {
939 parent.addAsChild( desc );
940 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
941 desc.getDistanceToParent() ) );
943 remove_me.setParent( null );
944 phylogeny.clearHashIdToNodeMap();
945 phylogeny.externalNodesHaveChanged();
949 public static List<PhylogenyNode> searchData( final String query,
951 final boolean case_sensitive,
952 final boolean partial,
953 final boolean search_domains ) {
954 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
955 if ( phy.isEmpty() || ( query == null ) ) {
958 if ( ForesterUtil.isEmpty( query ) ) {
961 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
962 final PhylogenyNode node = iter.next();
963 boolean match = false;
964 if ( match( node.getName(), query, case_sensitive, partial ) ) {
967 else if ( node.getNodeData().isHasTaxonomy()
968 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
971 else if ( node.getNodeData().isHasTaxonomy()
972 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
975 else if ( node.getNodeData().isHasTaxonomy()
976 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
979 else if ( node.getNodeData().isHasTaxonomy()
980 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
981 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
987 else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
988 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
989 I: for( final String syn : syns ) {
990 if ( match( syn, query, case_sensitive, partial ) ) {
996 if ( !match && node.getNodeData().isHasSequence()
997 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1000 if ( !match && node.getNodeData().isHasSequence()
1001 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1005 && node.getNodeData().isHasSequence()
1006 && ( node.getNodeData().getSequence().getAccession() != null )
1007 && match( node.getNodeData().getSequence().getAccession().getValue(),
1013 if ( search_domains && !match && node.getNodeData().isHasSequence()
1014 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1015 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1016 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1017 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1023 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1024 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1025 I: while ( it.hasNext() ) {
1026 if ( match( it.next(), query, case_sensitive, partial ) ) {
1031 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1032 I: while ( it.hasNext() ) {
1033 if ( match( it.next(), query, case_sensitive, partial ) ) {
1046 public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1047 final Phylogeny phy,
1048 final boolean case_sensitive,
1049 final boolean partial,
1050 final boolean search_domains ) {
1051 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1052 if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1055 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1056 final PhylogenyNode node = iter.next();
1057 boolean all_matched = true;
1058 for( final String query : queries ) {
1059 boolean match = false;
1060 if ( ForesterUtil.isEmpty( query ) ) {
1063 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1066 else if ( node.getNodeData().isHasTaxonomy()
1067 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1070 else if ( node.getNodeData().isHasTaxonomy()
1071 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1074 else if ( node.getNodeData().isHasTaxonomy()
1075 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1078 else if ( node.getNodeData().isHasTaxonomy()
1079 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1080 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1086 else if ( node.getNodeData().isHasTaxonomy()
1087 && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1088 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1089 I: for( final String syn : syns ) {
1090 if ( match( syn, query, case_sensitive, partial ) ) {
1096 if ( !match && node.getNodeData().isHasSequence()
1097 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1100 if ( !match && node.getNodeData().isHasSequence()
1101 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1105 && node.getNodeData().isHasSequence()
1106 && ( node.getNodeData().getSequence().getAccession() != null )
1107 && match( node.getNodeData().getSequence().getAccession().getValue(),
1113 if ( search_domains && !match && node.getNodeData().isHasSequence()
1114 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1115 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1116 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1117 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1123 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1124 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1125 I: while ( it.hasNext() ) {
1126 if ( match( it.next(), query, case_sensitive, partial ) ) {
1131 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1132 I: while ( it.hasNext() ) {
1133 if ( match( it.next(), query, case_sensitive, partial ) ) {
1140 all_matched = false;
1144 if ( all_matched ) {
1152 * Convenience method.
1153 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1155 public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1156 setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1159 public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1160 if ( node.getBranchData().getBranchColor() == null ) {
1161 node.getBranchData().setBranchColor( new BranchColor() );
1163 node.getBranchData().getBranchColor().setValue( color );
1167 * Convenience method
1169 public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1170 node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1174 * Convenience method.
1175 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1177 public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1178 setConfidence( node, confidence_value, "" );
1182 * Convenience method.
1183 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1185 public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1186 Confidence c = null;
1187 if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1188 c = node.getBranchData().getConfidence( 0 );
1191 c = new Confidence();
1192 node.getBranchData().addConfidence( c );
1195 c.setValue( confidence_value );
1198 public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1199 if ( !node.getNodeData().isHasTaxonomy() ) {
1200 node.getNodeData().setTaxonomy( new Taxonomy() );
1202 node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1206 * Convenience method to set the taxonomy code of a phylogeny node.
1210 * @param taxonomy_code
1211 * @throws PhyloXmlDataFormatException
1213 public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code )
1214 throws PhyloXmlDataFormatException {
1215 if ( !node.getNodeData().isHasTaxonomy() ) {
1216 node.getNodeData().setTaxonomy( new Taxonomy() );
1218 node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1221 final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) {
1222 class PhylogenyNodeSortTaxonomyPriority implements Comparator<PhylogenyNode> {
1225 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1226 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1227 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1228 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1229 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1230 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1232 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1233 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1234 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1235 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1237 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1238 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1239 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1240 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1243 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1244 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1245 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1246 return n1.getNodeData().getSequence().getName().toLowerCase()
1247 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1249 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1250 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1251 return n1.getNodeData().getSequence().getSymbol()
1252 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1254 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1255 && ( n2.getNodeData().getSequence().getAccession() != null )
1256 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1257 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1258 return n1.getNodeData().getSequence().getAccession().getValue()
1259 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1262 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1263 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1268 class PhylogenyNodeSortSequencePriority implements Comparator<PhylogenyNode> {
1271 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1272 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1273 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1274 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1275 return n1.getNodeData().getSequence().getName().toLowerCase()
1276 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1278 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1279 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1280 return n1.getNodeData().getSequence().getSymbol()
1281 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1283 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1284 && ( n2.getNodeData().getSequence().getAccession() != null )
1285 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1286 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1287 return n1.getNodeData().getSequence().getAccession().getValue()
1288 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1291 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1292 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1293 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1294 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1295 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1297 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1298 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1299 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1300 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1302 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1303 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1304 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1305 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1308 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1309 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1314 class PhylogenyNodeSortNodeNamePriority implements Comparator<PhylogenyNode> {
1317 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1318 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1319 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1321 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1322 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1323 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1324 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1325 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1327 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1328 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1329 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1330 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1332 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1333 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1334 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1335 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1338 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1339 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1340 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1341 return n1.getNodeData().getSequence().getName().toLowerCase()
1342 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1344 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1345 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1346 return n1.getNodeData().getSequence().getSymbol()
1347 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1349 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1350 && ( n2.getNodeData().getSequence().getAccession() != null )
1351 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1352 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1353 return n1.getNodeData().getSequence().getAccession().getValue()
1354 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1360 Comparator<PhylogenyNode> c;
1363 c = new PhylogenyNodeSortSequencePriority();
1366 c = new PhylogenyNodeSortNodeNamePriority();
1369 c = new PhylogenyNodeSortTaxonomyPriority();
1371 final List<PhylogenyNode> descs = node.getDescendants();
1372 Collections.sort( descs, c );
1374 for( final PhylogenyNode desc : descs ) {
1375 node.setChildNode( i++, desc );
1380 * Removes from Phylogeny to_be_stripped all external Nodes which are
1381 * associated with a species NOT found in Phylogeny reference.
1384 * a reference Phylogeny
1385 * @param to_be_stripped
1386 * Phylogeny to be stripped
1387 * @return nodes removed from to_be_stripped
1389 public static List<PhylogenyNode> taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference,
1390 final Phylogeny to_be_stripped ) {
1391 final Set<String> ref_ext_taxo = new HashSet<String>();
1392 for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1393 final PhylogenyNode n = it.next();
1394 if ( !n.getNodeData().isHasTaxonomy() ) {
1395 throw new IllegalArgumentException( "no taxonomic data in node: " + n );
1397 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1398 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() );
1400 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1401 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1403 if ( ( n.getNodeData().getTaxonomy().getIdentifier() != null )
1404 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getIdentifier().getValue() ) ) {
1405 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() );
1408 final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1409 for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1410 final PhylogenyNode n = it.next();
1411 if ( !n.getNodeData().isHasTaxonomy() ) {
1412 nodes_to_delete.add( n );
1414 else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) )
1415 && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1416 && !( ( n.getNodeData().getTaxonomy().getIdentifier() != null ) && ref_ext_taxo.contains( n
1417 .getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() ) ) ) {
1418 nodes_to_delete.add( n );
1421 for( final PhylogenyNode n : nodes_to_delete ) {
1422 to_be_stripped.deleteSubtree( n, true );
1424 to_be_stripped.clearHashIdToNodeMap();
1425 to_be_stripped.externalNodesHaveChanged();
1426 return nodes_to_delete;
1429 final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) {
1430 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1431 while ( it.hasNext() ) {
1432 final PhylogenyNode n = it.next();
1433 if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) {
1436 value = Double.parseDouble( n.getName() );
1438 catch ( final NumberFormatException e ) {
1439 throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: "
1440 + e.getLocalizedMessage() );
1442 if ( value >= 0.0 ) {
1443 n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) );
1450 final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy ) {
1451 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1452 while ( it.hasNext() ) {
1453 final PhylogenyNode n = it.next();
1454 if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) {
1455 if ( !ForesterUtil.isEmpty( n.getName() ) ) {
1458 d = Double.parseDouble( n.getName() );
1460 catch ( final Exception e ) {
1464 n.getBranchData().addConfidence( new Confidence( d, "" ) );
1472 final static public void transferNodeNameToField( final Phylogeny phy,
1473 final PhylogenyNodeField field,
1474 final boolean external_only ) throws PhyloXmlDataFormatException {
1475 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1476 while ( it.hasNext() ) {
1477 final PhylogenyNode n = it.next();
1478 if ( external_only && n.isInternal() ) {
1481 final String name = n.getName().trim();
1482 if ( !ForesterUtil.isEmpty( name ) ) {
1486 setTaxonomyCode( n, name );
1488 case TAXONOMY_SCIENTIFIC_NAME:
1490 if ( !n.getNodeData().isHasTaxonomy() ) {
1491 n.getNodeData().setTaxonomy( new Taxonomy() );
1493 n.getNodeData().getTaxonomy().setScientificName( name );
1495 case TAXONOMY_COMMON_NAME:
1497 if ( !n.getNodeData().isHasTaxonomy() ) {
1498 n.getNodeData().setTaxonomy( new Taxonomy() );
1500 n.getNodeData().getTaxonomy().setCommonName( name );
1502 case SEQUENCE_SYMBOL:
1504 if ( !n.getNodeData().isHasSequence() ) {
1505 n.getNodeData().setSequence( new Sequence() );
1507 n.getNodeData().getSequence().setSymbol( name );
1511 if ( !n.getNodeData().isHasSequence() ) {
1512 n.getNodeData().setSequence( new Sequence() );
1514 n.getNodeData().getSequence().setName( name );
1516 case TAXONOMY_ID_UNIPROT_1: {
1517 if ( !n.getNodeData().isHasTaxonomy() ) {
1518 n.getNodeData().setTaxonomy( new Taxonomy() );
1521 final int i = name.indexOf( '_' );
1523 id = name.substring( 0, i );
1528 n.getNodeData().getTaxonomy()
1529 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1532 case TAXONOMY_ID_UNIPROT_2: {
1533 if ( !n.getNodeData().isHasTaxonomy() ) {
1534 n.getNodeData().setTaxonomy( new Taxonomy() );
1537 final int i = name.indexOf( '_' );
1539 id = name.substring( i + 1, name.length() );
1544 n.getNodeData().getTaxonomy()
1545 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1549 if ( !n.getNodeData().isHasTaxonomy() ) {
1550 n.getNodeData().setTaxonomy( new Taxonomy() );
1552 n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) );
1560 static double addPhylogenyDistances( final double a, final double b ) {
1561 if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
1564 else if ( a >= 0.0 ) {
1567 else if ( b >= 0.0 ) {
1570 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
1574 * Deep copies the phylogeny originating from this node.
1576 static PhylogenyNode copySubTree( final PhylogenyNode source ) {
1577 if ( source == null ) {
1581 final PhylogenyNode newnode = source.copyNodeData();
1582 if ( !source.isExternal() ) {
1583 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1584 newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
1592 * Shallow copies the phylogeny originating from this node.
1594 static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
1595 if ( source == null ) {
1599 final PhylogenyNode newnode = source.copyNodeDataShallow();
1600 if ( !source.isExternal() ) {
1601 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1602 newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
1610 * Calculates the distance between PhylogenyNodes n1 and n2.
1611 * PRECONDITION: n1 is a descendant of n2.
1614 * a descendant of n2
1616 * @return distance between n1 and n2
1618 private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
1620 while ( n1 != n2 ) {
1621 if ( n1.getDistanceToParent() > 0.0 ) {
1622 d += n1.getDistanceToParent();
1624 n1 = n1.getParent();
1629 private static boolean match( final String s,
1631 final boolean case_sensitive,
1632 final boolean partial ) {
1633 if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
1636 String my_s = s.trim();
1637 String my_query = query.trim();
1638 if ( !case_sensitive ) {
1639 my_s = my_s.toLowerCase();
1640 my_query = my_query.toLowerCase();
1643 return my_s.indexOf( my_query ) >= 0;
1646 return my_s.equals( my_query );
1650 public static enum DESCENDANT_SORT_PRIORITY {
1651 TAXONOMY, SEQUENCE, NODE_NAME;
1654 public static enum PhylogenyNodeField {
1657 TAXONOMY_SCIENTIFIC_NAME,
1658 TAXONOMY_COMMON_NAME,
1661 TAXONOMY_ID_UNIPROT_1,
1662 TAXONOMY_ID_UNIPROT_2,