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 final List<PhylogenyNode> ext = phy.getExternalNodes();
331 for( final PhylogenyNode n : ext ) {
332 nodes.put( n.getName(), n );
334 // for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
335 // final PhylogenyNode n = iter.next();
336 // nodes.put( n.getName(), n );
341 public static void deleteExternalNodesNegativeSelection( final Set<Integer> to_delete, final Phylogeny phy ) {
342 phy.clearHashIdToNodeMap();
343 for( final Integer id : to_delete ) {
344 phy.deleteSubtree( phy.getNode( id ), true );
346 phy.clearHashIdToNodeMap();
347 phy.externalNodesHaveChanged();
350 public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
351 throws IllegalArgumentException {
352 for( final String element : node_names_to_delete ) {
353 if ( ForesterUtil.isEmpty( element ) ) {
356 List<PhylogenyNode> nodes = null;
357 nodes = p.getNodes( element );
358 final Iterator<PhylogenyNode> it = nodes.iterator();
359 while ( it.hasNext() ) {
360 final PhylogenyNode n = it.next();
361 if ( !n.isExternal() ) {
362 throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" );
364 p.deleteSubtree( n, true );
367 p.clearHashIdToNodeMap();
368 p.externalNodesHaveChanged();
371 public static void deleteExternalNodesPositiveSelection( final Set<Taxonomy> species_to_keep, final Phylogeny phy ) {
372 // final Set<Integer> to_delete = new HashSet<Integer>();
373 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
374 final PhylogenyNode n = it.next();
375 if ( n.getNodeData().isHasTaxonomy() ) {
376 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
377 //to_delete.add( n.getNodeId() );
378 phy.deleteSubtree( n, true );
382 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
385 phy.clearHashIdToNodeMap();
386 phy.externalNodesHaveChanged();
389 public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
390 final Phylogeny p ) {
391 final PhylogenyNodeIterator it = p.iteratorExternalForward();
392 final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
394 Arrays.sort( node_names_to_keep );
395 while ( it.hasNext() ) {
396 final String curent_name = it.next().getName();
397 if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
398 to_delete[ i++ ] = curent_name;
401 PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
402 final List<String> deleted = new ArrayList<String>();
403 for( final String n : to_delete ) {
404 if ( !ForesterUtil.isEmpty( n ) ) {
411 final public static void deleteInternalNodesWithOnlyOneDescendent( final Phylogeny phy ) {
412 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
413 for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
414 final PhylogenyNode n = iter.next();
415 if ( ( !n.isExternal() ) && ( n.getNumberOfDescendants() == 1 ) ) {
419 for( final PhylogenyNode d : to_delete ) {
420 PhylogenyMethods.removeNode( d, phy );
422 phy.clearHashIdToNodeMap();
423 phy.externalNodesHaveChanged();
426 final public static void deleteNonOrthologousExternalNodes( final Phylogeny phy, final PhylogenyNode n ) {
427 if ( n.isInternal() ) {
428 throw new IllegalArgumentException( "node is not external" );
430 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
431 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
432 final PhylogenyNode i = it.next();
433 if ( !PhylogenyMethods.getEventAtLCA( n, i ).isSpeciation() ) {
437 for( final PhylogenyNode d : to_delete ) {
438 phy.deleteSubtree( d, true );
440 phy.clearHashIdToNodeMap();
441 phy.externalNodesHaveChanged();
444 public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
445 final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
446 final Set<Long> encountered = new HashSet<Long>();
447 if ( !node.isExternal() ) {
448 final List<PhylogenyNode> exts = node.getAllExternalDescendants();
449 for( PhylogenyNode current : exts ) {
450 descs.add( current );
451 while ( current != node ) {
452 current = current.getParent();
453 if ( encountered.contains( current.getId() ) ) {
456 descs.add( current );
457 encountered.add( current.getId() );
471 public static Color getBranchColorValue( final PhylogenyNode node ) {
472 if ( node.getBranchData().getBranchColor() == null ) {
475 return node.getBranchData().getBranchColor().getValue();
481 public static double getBranchWidthValue( final PhylogenyNode node ) {
482 if ( !node.getBranchData().isHasBranchWidth() ) {
483 return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
485 return node.getBranchData().getBranchWidth().getValue();
491 public static double getConfidenceValue( final PhylogenyNode node ) {
492 if ( !node.getBranchData().isHasConfidences() ) {
493 return Confidence.CONFIDENCE_DEFAULT_VALUE;
495 return node.getBranchData().getConfidence( 0 ).getValue();
501 public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
502 if ( !node.getBranchData().isHasConfidences() ) {
503 return new double[ 0 ];
505 final double[] values = new double[ node.getBranchData().getConfidences().size() ];
507 for( final Confidence c : node.getBranchData().getConfidences() ) {
508 values[ i++ ] = c.getValue();
513 final public static Event getEventAtLCA( final PhylogenyNode n1, final PhylogenyNode n2 ) {
514 return calculateLCA( n1, n2 ).getNodeData().getEvent();
518 * Returns taxonomy t if all external descendants have
519 * the same taxonomy t, null otherwise.
522 public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
523 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
525 for( final PhylogenyNode n : descs ) {
526 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
529 else if ( tax == null ) {
530 tax = n.getNodeData().getTaxonomy();
532 else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
539 public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
540 final List<PhylogenyNode> children = node.getAllExternalDescendants();
541 PhylogenyNode farthest = null;
542 double longest = -Double.MAX_VALUE;
543 for( final PhylogenyNode child : children ) {
544 if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
546 longest = PhylogenyMethods.getDistance( child, node );
552 // public static PhylogenyMethods getInstance() {
553 // if ( PhylogenyMethods._instance == null ) {
554 // PhylogenyMethods._instance = new PhylogenyMethods();
556 // return PhylogenyMethods._instance;
559 * Returns the largest confidence value found on phy.
561 static public double getMaximumConfidenceValue( final Phylogeny phy ) {
562 double max = -Double.MAX_VALUE;
563 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
564 final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
565 if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
572 static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
573 int min = Integer.MAX_VALUE;
576 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
578 if ( n.isInternal() ) {
579 d = n.getNumberOfDescendants();
589 * Convenience method for display purposes.
590 * Not intended for algorithms.
592 public static String getSpecies( final PhylogenyNode node ) {
593 if ( !node.getNodeData().isHasTaxonomy() ) {
596 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
597 return node.getNodeData().getTaxonomy().getScientificName();
599 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
600 return node.getNodeData().getTaxonomy().getTaxonomyCode();
603 return node.getNodeData().getTaxonomy().getCommonName();
608 * Convenience method for display purposes.
609 * Not intended for algorithms.
611 public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
612 if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
615 return node.getNodeData().getTaxonomy().getIdentifier().getValue();
618 public final static boolean isAllDecendentsAreDuplications( final PhylogenyNode n ) {
619 if ( n.isExternal() ) {
623 if ( n.isDuplication() ) {
624 for( final PhylogenyNode desc : n.getDescendants() ) {
625 if ( !isAllDecendentsAreDuplications( desc ) ) {
637 public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
638 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
639 if ( node.getChildNode( i ).isExternal() ) {
647 * This is case insensitive.
650 public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
651 final String[] providers ) {
652 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
653 final String my_tax_prov = tax.getIdentifier().getProvider();
654 for( final String provider : providers ) {
655 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
666 public static void midpointRoot( final Phylogeny phylogeny ) {
667 if ( ( phylogeny.getNumberOfExternalNodes() < 2 ) || ( calculateMaxDistanceToRoot( phylogeny ) <= 0 ) ) {
671 final int total_nodes = phylogeny.getNodeCount();
673 if ( ++counter > total_nodes ) {
674 throw new RuntimeException( "this should not have happened: midpoint rooting does not converge" );
676 PhylogenyNode a = null;
679 for( int i = 0; i < phylogeny.getRoot().getNumberOfDescendants(); ++i ) {
680 final PhylogenyNode f = getFurthestDescendant( phylogeny.getRoot().getChildNode( i ) );
681 final double df = getDistance( f, phylogeny.getRoot() );
688 else if ( df > db ) {
693 final double diff = da - db;
694 if ( diff < 0.000001 ) {
697 double x = da - ( diff / 2.0 );
698 while ( ( x > a.getDistanceToParent() ) && !a.isRoot() ) {
699 x -= ( a.getDistanceToParent() > 0 ? a.getDistanceToParent() : 0 );
702 phylogeny.reRoot( a, x );
704 phylogeny.recalculateNumberOfExternalDescendants( true );
707 public static void midpointRootOLD( final Phylogeny phylogeny ) {
708 // if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
711 // final PhylogenyMethods methods = getInstance();
712 //final double farthest_d = methods.calculateFurthestDistance( phylogeny );
713 // final PhylogenyNode f1 = methods.getFarthestNode1();
714 // final PhylogenyNode f2 = methods.getFarthestNode2();
715 // if ( farthest_d <= 0.0 ) {
718 // double x = farthest_d / 2.0;
719 // PhylogenyNode n = f1;
720 // if ( PhylogenyMethods.getDistance( f1, phylogeny.getRoot() ) < PhylogenyMethods.getDistance( f2, phylogeny
724 // while ( ( x > n.getDistanceToParent() ) && !n.isRoot() ) {
725 // x -= ( n.getDistanceToParent() > 0 ? n.getDistanceToParent() : 0 );
726 // n = n.getParent();
728 // phylogeny.reRoot( n, x );
729 // phylogeny.recalculateNumberOfExternalDescendants( true );
730 // final PhylogenyNode a = getFurthestDescendant( phylogeny.getRoot().getChildNode1() );
731 // final PhylogenyNode b = getFurthestDescendant( phylogeny.getRoot().getChildNode2() );
732 // final double da = getDistance( a, phylogeny.getRoot() );
733 // final double db = getDistance( b, phylogeny.getRoot() );
734 // if ( Math.abs( da - db ) > 0.000001 ) {
735 // throw new FailedConditionCheckException( "this should not have happened: midpoint rooting failed: da="
736 // + da + ", db=" + db + ", diff=" + Math.abs( da - db ) );
740 public static void normalizeBootstrapValues( final Phylogeny phylogeny,
741 final double max_bootstrap_value,
742 final double max_normalized_value ) {
743 for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
744 final PhylogenyNode node = iter.next();
745 if ( node.isInternal() ) {
746 final double confidence = getConfidenceValue( node );
747 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
748 if ( confidence >= max_bootstrap_value ) {
749 setBootstrapConfidence( node, max_normalized_value );
752 setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
759 public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
760 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
761 if ( phy.isEmpty() ) {
764 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
765 nodes.add( iter.next() );
771 * Returns a map of distinct taxonomies of
772 * all external nodes of node.
773 * If at least one of the external nodes has no taxonomy,
777 public static SortedMap<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
778 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
779 final SortedMap<Taxonomy, Integer> tax_map = new TreeMap<Taxonomy, Integer>();
780 for( final PhylogenyNode n : descs ) {
781 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
784 final Taxonomy t = n.getNodeData().getTaxonomy();
785 if ( tax_map.containsKey( t ) ) {
786 tax_map.put( t, tax_map.get( t ) + 1 );
796 * Arranges the order of childern for each node of this Phylogeny in such a
797 * way that either the branch with more children is on top (right) or on
798 * bottom (left), dependent on the value of boolean order.
801 * decides in which direction to order
804 public static void orderAppearance( final PhylogenyNode n,
806 final boolean order_ext_alphabetically,
807 final DESCENDANT_SORT_PRIORITY pri ) {
808 if ( n.isExternal() ) {
812 PhylogenyNode temp = null;
813 if ( ( n.getNumberOfDescendants() == 2 )
814 && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
815 && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
816 temp = n.getChildNode1();
817 n.setChild1( n.getChildNode2() );
820 else if ( order_ext_alphabetically ) {
821 boolean all_ext = true;
822 for( final PhylogenyNode i : n.getDescendants() ) {
823 if ( !i.isExternal() ) {
829 PhylogenyMethods.sortNodeDescendents( n, pri );
832 for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
833 orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri );
838 public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
839 for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
840 final PhylogenyNode node = iter.next();
845 if ( node.isInternal() ) {
846 //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
847 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
848 final PhylogenyNode child_node = node.getChildNode( i );
849 final Color child_color = getBranchColorValue( child_node );
850 if ( child_color != null ) {
852 red += child_color.getRed();
853 green += child_color.getGreen();
854 blue += child_color.getBlue();
857 setBranchColorValue( node,
858 new Color( ForesterUtil.roundToInt( red / n ),
859 ForesterUtil.roundToInt( green / n ),
860 ForesterUtil.roundToInt( blue / n ) ) );
865 public static final void preOrderReId( final Phylogeny phy ) {
866 if ( phy.isEmpty() ) {
869 phy.setIdToNodeMap( null );
870 long i = PhylogenyNode.getNodeCount();
871 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
872 it.next().setId( i++ );
874 PhylogenyNode.setNodeCount( i );
877 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
878 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
879 final Phylogeny[] trees = factory.create( file, parser );
880 if ( ( trees == null ) || ( trees.length == 0 ) ) {
881 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
886 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List<File> files )
888 final List<Phylogeny> tree_list = new ArrayList<Phylogeny>();
889 for( final File file : files ) {
890 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
891 final Phylogeny[] trees = factory.create( file, parser );
892 if ( ( trees == null ) || ( trees.length == 0 ) ) {
893 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
895 tree_list.addAll( Arrays.asList( trees ) );
897 return tree_list.toArray( new Phylogeny[ tree_list.size() ] );
900 public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
901 if ( remove_me.isRoot() ) {
902 if ( remove_me.getNumberOfDescendants() == 1 ) {
903 final PhylogenyNode desc = remove_me.getDescendants().get( 0 );
904 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
905 desc.getDistanceToParent() ) );
906 desc.setParent( null );
907 phylogeny.setRoot( desc );
908 phylogeny.clearHashIdToNodeMap();
911 throw new IllegalArgumentException( "attempt to remove a root node with more than one descendants" );
914 else if ( remove_me.isExternal() ) {
915 phylogeny.deleteSubtree( remove_me, false );
916 phylogeny.clearHashIdToNodeMap();
917 phylogeny.externalNodesHaveChanged();
920 final PhylogenyNode parent = remove_me.getParent();
921 final List<PhylogenyNode> descs = remove_me.getDescendants();
922 parent.removeChildNode( remove_me );
923 for( final PhylogenyNode desc : descs ) {
924 parent.addAsChild( desc );
925 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
926 desc.getDistanceToParent() ) );
928 remove_me.setParent( null );
929 phylogeny.clearHashIdToNodeMap();
930 phylogeny.externalNodesHaveChanged();
934 public static List<PhylogenyNode> searchData( final String query,
936 final boolean case_sensitive,
937 final boolean partial,
938 final boolean search_domains ) {
939 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
940 if ( phy.isEmpty() || ( query == null ) ) {
943 if ( ForesterUtil.isEmpty( query ) ) {
946 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
947 final PhylogenyNode node = iter.next();
948 boolean match = false;
949 if ( match( node.getName(), query, case_sensitive, partial ) ) {
952 else if ( node.getNodeData().isHasTaxonomy()
953 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
956 else if ( node.getNodeData().isHasTaxonomy()
957 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
960 else if ( node.getNodeData().isHasTaxonomy()
961 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
964 else if ( node.getNodeData().isHasTaxonomy()
965 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
966 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
972 else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
973 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
974 I: for( final String syn : syns ) {
975 if ( match( syn, query, case_sensitive, partial ) ) {
981 if ( !match && node.getNodeData().isHasSequence()
982 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
985 if ( !match && node.getNodeData().isHasSequence()
986 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
990 && node.getNodeData().isHasSequence()
991 && ( node.getNodeData().getSequence().getAccession() != null )
992 && match( node.getNodeData().getSequence().getAccession().getValue(),
998 if ( search_domains && !match && node.getNodeData().isHasSequence()
999 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1000 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1001 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1002 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1008 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1009 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1010 I: while ( it.hasNext() ) {
1011 if ( match( it.next(), query, case_sensitive, partial ) ) {
1016 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1017 I: while ( it.hasNext() ) {
1018 if ( match( it.next(), query, case_sensitive, partial ) ) {
1031 public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1032 final Phylogeny phy,
1033 final boolean case_sensitive,
1034 final boolean partial,
1035 final boolean search_domains ) {
1036 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1037 if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1040 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1041 final PhylogenyNode node = iter.next();
1042 boolean all_matched = true;
1043 for( final String query : queries ) {
1044 boolean match = false;
1045 if ( ForesterUtil.isEmpty( query ) ) {
1048 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1051 else if ( node.getNodeData().isHasTaxonomy()
1052 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1055 else if ( node.getNodeData().isHasTaxonomy()
1056 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1059 else if ( node.getNodeData().isHasTaxonomy()
1060 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1063 else if ( node.getNodeData().isHasTaxonomy()
1064 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1065 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1071 else if ( node.getNodeData().isHasTaxonomy()
1072 && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1073 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1074 I: for( final String syn : syns ) {
1075 if ( match( syn, query, case_sensitive, partial ) ) {
1081 if ( !match && node.getNodeData().isHasSequence()
1082 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1085 if ( !match && node.getNodeData().isHasSequence()
1086 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1090 && node.getNodeData().isHasSequence()
1091 && ( node.getNodeData().getSequence().getAccession() != null )
1092 && match( node.getNodeData().getSequence().getAccession().getValue(),
1098 if ( search_domains && !match && node.getNodeData().isHasSequence()
1099 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1100 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1101 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1102 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1108 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1109 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1110 I: while ( it.hasNext() ) {
1111 if ( match( it.next(), query, case_sensitive, partial ) ) {
1116 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1117 I: while ( it.hasNext() ) {
1118 if ( match( it.next(), query, case_sensitive, partial ) ) {
1125 all_matched = false;
1129 if ( all_matched ) {
1137 * Convenience method.
1138 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1140 public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1141 setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1144 public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1145 if ( node.getBranchData().getBranchColor() == null ) {
1146 node.getBranchData().setBranchColor( new BranchColor() );
1148 node.getBranchData().getBranchColor().setValue( color );
1152 * Convenience method
1154 public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1155 node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1159 * Convenience method.
1160 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1162 public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1163 setConfidence( node, confidence_value, "" );
1167 * Convenience method.
1168 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1170 public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1171 Confidence c = null;
1172 if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1173 c = node.getBranchData().getConfidence( 0 );
1176 c = new Confidence();
1177 node.getBranchData().addConfidence( c );
1180 c.setValue( confidence_value );
1183 public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1184 if ( !node.getNodeData().isHasTaxonomy() ) {
1185 node.getNodeData().setTaxonomy( new Taxonomy() );
1187 node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1191 * Convenience method to set the taxonomy code of a phylogeny node.
1195 * @param taxonomy_code
1196 * @throws PhyloXmlDataFormatException
1198 public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code )
1199 throws PhyloXmlDataFormatException {
1200 if ( !node.getNodeData().isHasTaxonomy() ) {
1201 node.getNodeData().setTaxonomy( new Taxonomy() );
1203 node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1206 final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) {
1207 class PhylogenyNodeSortTaxonomyPriority implements Comparator<PhylogenyNode> {
1210 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1211 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1212 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1213 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1214 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1215 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1217 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1218 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1219 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1220 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1222 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1223 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1224 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1225 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1228 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1229 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1230 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1231 return n1.getNodeData().getSequence().getName().toLowerCase()
1232 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1234 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1235 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1236 return n1.getNodeData().getSequence().getSymbol()
1237 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1239 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1240 && ( n2.getNodeData().getSequence().getAccession() != null )
1241 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1242 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1243 return n1.getNodeData().getSequence().getAccession().getValue()
1244 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1247 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1248 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1253 class PhylogenyNodeSortSequencePriority implements Comparator<PhylogenyNode> {
1256 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1257 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1258 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1259 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1260 return n1.getNodeData().getSequence().getName().toLowerCase()
1261 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1263 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1264 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1265 return n1.getNodeData().getSequence().getSymbol()
1266 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1268 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1269 && ( n2.getNodeData().getSequence().getAccession() != null )
1270 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1271 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1272 return n1.getNodeData().getSequence().getAccession().getValue()
1273 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1276 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1277 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1278 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1279 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1280 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1282 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1283 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1284 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1285 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1287 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1288 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1289 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1290 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1293 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1294 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1299 class PhylogenyNodeSortNodeNamePriority implements Comparator<PhylogenyNode> {
1302 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1303 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1304 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1306 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1307 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1308 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1309 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1310 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1312 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1313 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1314 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1315 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1317 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1318 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1319 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1320 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1323 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1324 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1325 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1326 return n1.getNodeData().getSequence().getName().toLowerCase()
1327 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1329 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1330 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1331 return n1.getNodeData().getSequence().getSymbol()
1332 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1334 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1335 && ( n2.getNodeData().getSequence().getAccession() != null )
1336 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1337 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1338 return n1.getNodeData().getSequence().getAccession().getValue()
1339 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1345 Comparator<PhylogenyNode> c;
1348 c = new PhylogenyNodeSortSequencePriority();
1351 c = new PhylogenyNodeSortNodeNamePriority();
1354 c = new PhylogenyNodeSortTaxonomyPriority();
1356 final List<PhylogenyNode> descs = node.getDescendants();
1357 Collections.sort( descs, c );
1359 for( final PhylogenyNode desc : descs ) {
1360 node.setChildNode( i++, desc );
1365 * Removes from Phylogeny to_be_stripped all external Nodes which are
1366 * associated with a species NOT found in Phylogeny reference.
1369 * a reference Phylogeny
1370 * @param to_be_stripped
1371 * Phylogeny to be stripped
1372 * @return nodes removed from to_be_stripped
1374 public static List<PhylogenyNode> taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference,
1375 final Phylogeny to_be_stripped ) {
1376 final Set<String> ref_ext_taxo = new HashSet<String>();
1377 for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1378 final PhylogenyNode n = it.next();
1379 if ( !n.getNodeData().isHasTaxonomy() ) {
1380 throw new IllegalArgumentException( "no taxonomic data in node: " + n );
1382 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1383 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() );
1385 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1386 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1388 if ( ( n.getNodeData().getTaxonomy().getIdentifier() != null )
1389 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getIdentifier().getValue() ) ) {
1390 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() );
1393 final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1394 for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1395 final PhylogenyNode n = it.next();
1396 if ( !n.getNodeData().isHasTaxonomy() ) {
1397 nodes_to_delete.add( n );
1399 else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) )
1400 && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1401 && !( ( n.getNodeData().getTaxonomy().getIdentifier() != null ) && ref_ext_taxo.contains( n
1402 .getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() ) ) ) {
1403 nodes_to_delete.add( n );
1406 for( final PhylogenyNode n : nodes_to_delete ) {
1407 to_be_stripped.deleteSubtree( n, true );
1409 to_be_stripped.clearHashIdToNodeMap();
1410 to_be_stripped.externalNodesHaveChanged();
1411 return nodes_to_delete;
1414 final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) {
1415 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1416 while ( it.hasNext() ) {
1417 final PhylogenyNode n = it.next();
1418 if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) {
1421 value = Double.parseDouble( n.getName() );
1423 catch ( final NumberFormatException e ) {
1424 throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: "
1425 + e.getLocalizedMessage() );
1427 if ( value >= 0.0 ) {
1428 n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) );
1435 final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy ) {
1436 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1437 while ( it.hasNext() ) {
1438 final PhylogenyNode n = it.next();
1439 if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) {
1440 if ( !ForesterUtil.isEmpty( n.getName() ) ) {
1443 d = Double.parseDouble( n.getName() );
1445 catch ( final Exception e ) {
1449 n.getBranchData().addConfidence( new Confidence( d, "" ) );
1457 final static public void transferNodeNameToField( final Phylogeny phy,
1458 final PhylogenyNodeField field,
1459 final boolean external_only ) throws PhyloXmlDataFormatException {
1460 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1461 while ( it.hasNext() ) {
1462 final PhylogenyNode n = it.next();
1463 if ( external_only && n.isInternal() ) {
1466 final String name = n.getName().trim();
1467 if ( !ForesterUtil.isEmpty( name ) ) {
1471 setTaxonomyCode( n, name );
1473 case TAXONOMY_SCIENTIFIC_NAME:
1475 if ( !n.getNodeData().isHasTaxonomy() ) {
1476 n.getNodeData().setTaxonomy( new Taxonomy() );
1478 n.getNodeData().getTaxonomy().setScientificName( name );
1480 case TAXONOMY_COMMON_NAME:
1482 if ( !n.getNodeData().isHasTaxonomy() ) {
1483 n.getNodeData().setTaxonomy( new Taxonomy() );
1485 n.getNodeData().getTaxonomy().setCommonName( name );
1487 case SEQUENCE_SYMBOL:
1489 if ( !n.getNodeData().isHasSequence() ) {
1490 n.getNodeData().setSequence( new Sequence() );
1492 n.getNodeData().getSequence().setSymbol( name );
1496 if ( !n.getNodeData().isHasSequence() ) {
1497 n.getNodeData().setSequence( new Sequence() );
1499 n.getNodeData().getSequence().setName( name );
1501 case TAXONOMY_ID_UNIPROT_1: {
1502 if ( !n.getNodeData().isHasTaxonomy() ) {
1503 n.getNodeData().setTaxonomy( new Taxonomy() );
1506 final int i = name.indexOf( '_' );
1508 id = name.substring( 0, i );
1513 n.getNodeData().getTaxonomy()
1514 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1517 case TAXONOMY_ID_UNIPROT_2: {
1518 if ( !n.getNodeData().isHasTaxonomy() ) {
1519 n.getNodeData().setTaxonomy( new Taxonomy() );
1522 final int i = name.indexOf( '_' );
1524 id = name.substring( i + 1, name.length() );
1529 n.getNodeData().getTaxonomy()
1530 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1534 if ( !n.getNodeData().isHasTaxonomy() ) {
1535 n.getNodeData().setTaxonomy( new Taxonomy() );
1537 n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) );
1545 static double addPhylogenyDistances( final double a, final double b ) {
1546 if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
1549 else if ( a >= 0.0 ) {
1552 else if ( b >= 0.0 ) {
1555 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
1559 * Deep copies the phylogeny originating from this node.
1561 static PhylogenyNode copySubTree( final PhylogenyNode source ) {
1562 if ( source == null ) {
1566 final PhylogenyNode newnode = source.copyNodeData();
1567 if ( !source.isExternal() ) {
1568 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1569 newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
1577 * Shallow copies the phylogeny originating from this node.
1579 static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
1580 if ( source == null ) {
1584 final PhylogenyNode newnode = source.copyNodeDataShallow();
1585 if ( !source.isExternal() ) {
1586 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1587 newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
1595 * Calculates the distance between PhylogenyNodes n1 and n2.
1596 * PRECONDITION: n1 is a descendant of n2.
1599 * a descendant of n2
1601 * @return distance between n1 and n2
1603 private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
1605 while ( n1 != n2 ) {
1606 if ( n1.getDistanceToParent() > 0.0 ) {
1607 d += n1.getDistanceToParent();
1609 n1 = n1.getParent();
1614 private static boolean match( final String s,
1616 final boolean case_sensitive,
1617 final boolean partial ) {
1618 if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
1621 String my_s = s.trim();
1622 String my_query = query.trim();
1623 if ( !case_sensitive ) {
1624 my_s = my_s.toLowerCase();
1625 my_query = my_query.toLowerCase();
1628 return my_s.indexOf( my_query ) >= 0;
1631 return my_s.equals( my_query );
1635 public static enum DESCENDANT_SORT_PRIORITY {
1636 TAXONOMY, SEQUENCE, NODE_NAME;
1639 public static enum PhylogenyNodeField {
1642 TAXONOMY_SCIENTIFIC_NAME,
1643 TAXONOMY_COMMON_NAME,
1646 TAXONOMY_ID_UNIPROT_1,
1647 TAXONOMY_ID_UNIPROT_2,