Debian Codegraph @

src/dr/evolution/tree/TreeUtils.java

raw symbols SCIP
1 package dr.evolution.tree;
2
3 import dr.evolution.util.Taxon;
4 import dr.evolution.util.TaxonList;
5 import jebl.evolution.graphs.Node;
6 import jebl.evolution.trees.SimpleRootedTree;
7
8 import java.text.NumberFormat;
9 import java.util.*;
10
11 /**
12 * Static utility functions for trees.
13 */
14 public class TreeUtils {
15
16 /**
17 * Count number of leaves in subtree whose root is node.
18 *
19 * @param tree the tree
20 * @param node the node to get leaf count below
21 * @return the number of leaves under this node.
22 */
23 public static int getLeafCount(Tree tree, NodeRef node) {
24
25 int childCount = tree.getChildCount(node);
26 if (childCount == 0) return 1;
27
28 int leafCount = 0;
29 for (int i = 0; i < childCount; i++) {
30 leafCount += getLeafCount(tree, tree.getChild(node, i));
31 }
32 return leafCount;
33 }
34
35 public static double getTreeLength(Tree tree, NodeRef node) {
36
37 int childCount = tree.getChildCount(node);
38 if (childCount == 0) return tree.getBranchLength(node);
39
40 double length = 0;
41 for (int i = 0; i < childCount; i++) {
42 length += getTreeLength(tree, tree.getChild(node, i));
43 }
44 if (node != tree.getRoot())
45 length += tree.getBranchLength(node);
46 return length;
47
48 }
49
50 public static double getSubTreeLength(Tree tree, Set<Taxon> taxa) {
51
52 double[] treeLength = new double[] { 0.0 };
53
54 getSubTreeLength(tree, tree.getRoot(), taxa, treeLength);
55
56 return treeLength[0];
57
58 }
59
60 private static int getSubTreeLength(Tree tree, NodeRef node, Set<Taxon> taxa, double[] treeLength) {
61 int childCount = tree.getChildCount(node);
62 if (childCount == 0) {
63 if (taxa.contains(tree.getNodeTaxon(node))) {
64 treeLength[0] += tree.getBranchLength(node);
65 return 1;
66 } else {
67 return 0;
68 }
69 }
70
71 int count = 0;
72 for (int i = 0; i < childCount; i++) {
73 count += getSubTreeLength(tree, tree.getChild(node, i), taxa, treeLength);
74 }
75
76 if (count > 0 && count < taxa.size()) {
77 if (node != tree.getRoot()) {
78 treeLength[0] += tree.getBranchLength(node);
79 }
80 return count;
81 }
82
83 return 0;
84 }
85
86 /**
87 * Get the length of the path between node1 and node2.
88 * @param tree
89 * @param node1
90 * @param node2
91 * @return
92 */
93 public static double getPathLength(Tree tree, NodeRef node1, NodeRef node2) {
94
95 NodeRef mrca = getCommonAncestorNode(tree, node1, node2);
96
97 return (2 * tree.getNodeHeight(mrca)) - tree.getNodeHeight(node1) - tree.getNodeHeight(node2);
98 }
99
100 public static double getMinNodeHeight(Tree tree, NodeRef node) {
101
102 int childCount = tree.getChildCount(node);
103 if (childCount == 0) return tree.getNodeHeight(node);
104
105 double minNodeHeight = Double.MAX_VALUE;
106 for (int i = 0; i < childCount; i++) {
107 double height = getMinNodeHeight(tree, tree.getChild(node, i));
108 if (height < minNodeHeight) {
109 minNodeHeight = height;
110 }
111 }
112 return minNodeHeight;
113 }
114
115 /**
116 * @param tree the tree to test fo ultrametricity
117 * @return true only if all tips have height 0.0
118 */
119 public static boolean isUltrametric(Tree tree) {
120 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
121 if (tree.getNodeHeight(tree.getExternalNode(i)) != 0.0)
122 return false;
123 }
124 return true;
125 }
126
127 /**
128 * @param tree the tree to test if binary
129 * @return true only if internal nodes have 2 children
130 */
131 public static boolean isBinary(Tree tree) {
132 for (int i = 0; i < tree.getInternalNodeCount(); i++) {
133 if (tree.getChildCount(tree.getInternalNode(i)) > 2)
134 return false;
135 }
136 return true;
137 }
138
139 /**
140 * @param tree the tree to retrieve leaf set of
141 * @return a set of strings which are the taxa of the tree.
142 */
143 public static Set<String> getLeafSet(Tree tree) {
144
145 HashSet<String> leafSet = new HashSet<String>();
146 int m = tree.getTaxonCount();
147
148 for (int i = 0; i < m; i++) {
149
150 Taxon taxon = tree.getTaxon(i);
151 leafSet.add(taxon.getId());
152 }
153
154 return leafSet;
155 }
156
157 /**
158 * @param tree the tree
159 * @param taxa the taxa
160 * @return Set of taxon names (id's) associated with the taxa in taxa.
161 * @throws MissingTaxonException
162 * if a taxon in taxa is not contained in the tree
163 */
164 public static Set<String> getLeavesForTaxa(Tree tree, TaxonList taxa) throws MissingTaxonException {
165
166 HashSet<String> leafNodes = new HashSet<String>();
167 int m = taxa.getTaxonCount();
168 int n = tree.getExternalNodeCount();
169
170 for (int i = 0; i < m; i++) {
171
172 Taxon taxon = taxa.getTaxon(i);
173 boolean found = false;
174 for (int j = 0; j < n; j++) {
175
176 NodeRef node = tree.getExternalNode(j);
177 if (tree.getNodeTaxon(node).getId().equals(taxon.getId())) {
178
179 found = true;
180 break;
181 }
182 }
183
184 if (!found) {
185 throw new MissingTaxonException(taxon);
186 }
187
188 leafNodes.add(taxon.getId());
189 }
190
191 return leafNodes;
192 }
193
194 /**
195 * @param tree the tree
196 * @param node the node to get names of leaves below
197 * @return a set of taxa names (as strings) of the leaf nodes descended from the given node.
198 */
199 public static Set<String> getDescendantLeaves(Tree tree, NodeRef node) {
200
201 HashSet<String> set = new HashSet<String>();
202 getDescendantLeaves(tree, node, set);
203 return set;
204 }
205
206 /**
207 * @param tree the tree
208 * @param node the node to get name of leaves below
209 * @param set will be populated with taxa names (as strings) of the leaf nodes descended from the given node.
210 */
211 private static void getDescendantLeaves(Tree tree, NodeRef node, Set<String> set) {
212
213 if (tree.isExternal(node)) {
214 set.add(tree.getTaxonId(node.getNumber()));
215 } else {
216
217 for (int i = 0; i < tree.getChildCount(node); i++) {
218
219 NodeRef node1 = tree.getChild(node, i);
220
221 getDescendantLeaves(tree, node1, set);
222 }
223 }
224 }
225
226
227 /**
228 * @param tree the tree
229 * @param node the node to get external nodes below
230 * @return a set of noderefs of the leaf nodes descended from the given node.
231 */
232 public static Set<NodeRef> getExternalNodes(Tree tree, NodeRef node) {
233
234 HashSet<NodeRef> set = new HashSet<NodeRef>();
235 getExternalNodes(tree, node, set);
236 return set;
237 }
238
239 /**
240 * @param tree the tree
241 * @param node the node to get external nodes below
242 * @param set is populated with noderefs of the leaf nodes descended from the given node.
243 */
244 private static void getExternalNodes(Tree tree, NodeRef node, Set<NodeRef> set) {
245
246 if (tree.isExternal(node)) {
247 set.add(node);
248 } else {
249
250 for (int i = 0; i < tree.getChildCount(node); i++) {
251
252 NodeRef node1 = tree.getChild(node, i);
253
254 getExternalNodes(tree, node1, set);
255 }
256 }
257 }
258
259 /**
260 * Gets the most recent common ancestor (MRCA) node for a pair of nodes. One
261 * node could be the ancestor of the other.
262 *
263 * @param tree the Tree
264 * @param node1 a node
265 * @param node2 a second node
266 * @return the NodeRef of the MRCA
267 */
268 public static NodeRef getCommonAncestorNode(Tree tree, NodeRef node1, NodeRef node2) {
269
270 // get set of ancestors going back to the root for node1
271 Set<NodeRef> ancestors = new HashSet<NodeRef>();
272 NodeRef node = node1;
273 while (node != null) {
274 ancestors.add(node);
275 node = tree.getParent(node);
276 }
277
278 node = node2;
279 NodeRef mrca = null;
280
281 // walk back from node2 looking form mrca with node1
282 while (node != null && mrca == null) {
283 if (ancestors.contains(node)) {
284 mrca = node;
285 }
286
287 node = tree.getParent(node);
288 }
289
290 return mrca;
291 }
292
293
294 /**
295 * Gets the most recent common ancestor (MRCA) node of a set of leaf nodes.
296 *
297 * @param tree the Tree
298 * @param leafNodes a set of names
299 * @return the NodeRef of the MRCA
300 */
301 public static NodeRef getCommonAncestorNode(Tree tree, Set<String> leafNodes) {
302
303 int cardinality = leafNodes.size();
304
305 if (cardinality == 0) {
306 throw new IllegalArgumentException("No leaf nodes selected");
307 }
308
309 NodeRef[] mrca = {null};
310 getCommonAncestorNode(tree, tree.getRoot(), leafNodes, cardinality, mrca);
311
312 return mrca[0];
313 }
314
315 /*
316 * Private recursive function used by getCommonAncestorNode.
317 */
318 private static int getCommonAncestorNode(Tree tree, NodeRef node,
319 Set<String> leafNodes, int cardinality,
320 NodeRef[] mrca) {
321
322 if (tree.isExternal(node)) {
323
324 if (leafNodes.contains(tree.getTaxonId(node.getNumber()))) {
325 if (cardinality == 1) {
326 mrca[0] = node;
327 }
328 return 1;
329 } else {
330 return 0;
331 }
332 }
333
334 int matches = 0;
335
336 for (int i = 0; i < tree.getChildCount(node); i++) {
337
338 NodeRef node1 = tree.getChild(node, i);
339
340 matches += getCommonAncestorNode(tree, node1, leafNodes, cardinality, mrca);
341
342 if (mrca[0] != null) {
343 break;
344 }
345 }
346
347 if (mrca[0] == null) {
348 // If we haven't already found the MRCA, test this node
349 if (matches == cardinality) {
350 mrca[0] = node;
351 }
352 }
353
354 return matches;
355 }
356
357 /**
358 * @param tree the tree
359 * @param taxa the taxa
360 * @return A bitset with the node numbers set.
361 * @throws MissingTaxonException
362 * if a taxon in taxa is not contained in the tree
363 */
364 public static BitSet getTipsBitSetForTaxa(Tree tree, TaxonList taxa) throws MissingTaxonException {
365
366 BitSet tips = new BitSet();
367 for (int n: getTipsForTaxa(tree, taxa)) {
368 tips.set(n);
369 }
370 return tips;
371 }
372
373 /**
374 * @param tree the tree
375 * @param taxa the taxa
376 * @return A HashSet of node numbers.
377 * @throws MissingTaxonException
378 * if a taxon in taxa is not contained in the tree
379 */
380 public static Set<Integer> getTipsForTaxa(Tree tree, TaxonList taxa) throws MissingTaxonException {
381
382 Set<Integer> tips = new LinkedHashSet<Integer>();
383
384 for (int i = 0; i < taxa.getTaxonCount(); i++) {
385
386 Taxon taxon = taxa.getTaxon(i);
387 boolean found = false;
388 for (int j = 0; j < tree.getExternalNodeCount(); j++) {
389
390 NodeRef node = tree.getExternalNode(j);
391 if (tree.getNodeTaxon(node).getId().equals(taxon.getId())) {
392 tips.add(node.getNumber());
393 found = true;
394 break;
395 }
396 }
397
398 if (!found) {
399 throw new MissingTaxonException(taxon);
400 }
401 }
402
403 return tips;
404 }
405
406 public static boolean isMonophyletic(Tree tree, Set<String> leafNodes) {
407 return isMonophyletic(tree, leafNodes, Collections.<String>emptySet());
408 }
409
410 /**
411 * Performs a monophyly test on a set of leaf nodes. The nodes are monophyletic
412 * if there is a node in the tree which subtends all the taxa in the set (and
413 * only those taxa).
414 *
415 * @param tree a tree object to perform test on
416 * @param leafNodes a set of leaf node ids
417 * @param ignore a set of ids to ignore in monophyly assessment
418 * @return boolean is monophyletic?
419 */
420 public static boolean isMonophyletic(Tree tree, Set<String> leafNodes, Set<String> ignore) {
421
422 int cardinality = leafNodes.size();
423
424 if (cardinality == 1) {
425 // A single selected leaf is always monophyletic
426 return true;
427 }
428
429 if (cardinality == tree.getExternalNodeCount()) {
430 // All leaf nodes are selected
431 return true;
432 }
433
434 if (cardinality == 0) {
435 throw new IllegalArgumentException("No leaf nodes selected");
436 }
437
438 int[] matchCount = {0};
439 int[] leafCount = {0};
440 boolean[] isMono = {false};
441 isMonophyletic(tree, tree.getRoot(), leafNodes, ignore, cardinality, matchCount, leafCount, isMono);
442
443 return isMono[0];
444 }
445
446 /**
447 * Private recursive function used by isMonophyletic.
448 *
449 * @param tree a tree object to perform test on
450 * @param node the node that is currently being assessed in recursive procedure
451 * @param leafNodes a set of leaf node ids
452 * @param ignore a set of ids to ignore in monophyly assessment
453 * @param cardinality the size of leafNodes set
454 * @return boolean is monophyletic?
455 */
456 private static boolean isMonophyletic(Tree tree, NodeRef node,
457 Set<String> leafNodes, Set<String> ignore,
458 int cardinality,
459 int[] matchCount, int[] leafCount,
460 boolean[] isMono) {
461
462 if (tree.isExternal(node)) {
463
464 String id = tree.getNodeTaxon(node).getId();
465 if (leafNodes.contains(id)) {
466 matchCount[0] = 1;
467 } else {
468 matchCount[0] = 0;
469 }
470 if (!ignore.contains(id)) {
471 leafCount[0] = 1;
472 } else {
473 leafCount[0] = 0;
474 }
475 return false;
476 }
477
478 int mc = 0;
479 int lc = 0;
480
481 for (int i = 0; i < tree.getChildCount(node); i++) {
482
483 NodeRef node1 = tree.getChild(node, i);
484
485 boolean done = isMonophyletic(tree, node1, leafNodes, ignore, cardinality, matchCount, leafCount, isMono);
486 mc += matchCount[0];
487 lc += leafCount[0];
488
489 if (done) {
490 return true;
491 }
492 }
493
494 matchCount[0] = mc;
495 leafCount[0] = lc;
496
497 // If we haven't already found the MRCA, test this node
498 if (mc == lc && lc == cardinality) {
499 isMono[0] = true;
500 return true;
501 }
502
503 return false;
504 }
505
506 public static NodeRef getCommonAncestor(Tree tree, NodeRef n1, NodeRef n2) {
507 while( n1 != n2 ) {
508 if( tree.getNodeHeight(n1) < tree.getNodeHeight(n2) ) {
509 n1 = tree.getParent(n1);
510 } else {
511 n2 = tree.getParent(n2);
512 }
513 }
514 return n1;
515 }
516
517 public static NodeRef getCommonAncestorSafely(Tree tree, NodeRef n1, NodeRef n2) {
518 while( n1 != n2 ) {
519
520 if (tree.isRoot(n1)) return n1;
521
522 if (tree.isRoot(n2)) return n2;
523
524 if( tree.getNodeHeight(n1) < tree.getNodeHeight(n2) ) {
525 n1 = tree.getParent(n1);
526 } else {
527 n2 = tree.getParent(n2);
528 }
529 }
530 return n1;
531 }
532
533 // A lightweight version for finding the most recent common ancestor of a group of taxa.
534 // return the node-ref of the MRCA.
535
536 // would be nice to use nodeRef's, but they are not preserved :(
537 public static NodeRef getCommonAncestor(Tree tree, int[] nodes) {
538 NodeRef cur = tree.getNode(nodes[0]);
539
540 for(int k = 1; k < nodes.length; ++k) {
541 cur = getCommonAncestor(tree, cur, tree.getNode(nodes[k]));
542 }
543 return cur;
544 }
545
546
547 /**
548 * @param tree
549 * @param range
550 * @return the size of the largest clade with tips in the given range of times.
551 */
552 public static int largestClade(Tree tree, double range) {
553
554 return largestClade(tree, tree.getRoot(), range, new double[]{0.0, 0.0});
555
556 }
557
558 /**
559 * @return the size of the largest clade with tips in the given range of times.
560 */
561 private static int largestClade(Tree tree, NodeRef node, double range, double[] currentBounds) {
562
563 if (tree.isExternal(node)) {
564 currentBounds[0] = tree.getNodeHeight(node);
565 currentBounds[1] = tree.getNodeHeight(node);
566 return 1;
567 } else {
568 // get the bounds and max clade size of the left clade
569 int cladeSize1 = largestClade(tree, tree.getChild(node, 0), range, currentBounds);
570 double min = currentBounds[0];
571 double max = currentBounds[1];
572
573 // get the bounds and max clade size of the right clade
574 int cladeSize2 = largestClade(tree, tree.getChild(node, 1), range, currentBounds);
575 min = Math.min(min, currentBounds[0]);
576 max = Math.max(max, currentBounds[1]);
577
578 // update the joint bounds
579 currentBounds[0] = min;
580 currentBounds[1] = max;
581
582 // if the joint clade is valid return the joint size
583 if (max - min < range) {
584 return cladeSize1 + cladeSize2;
585 }
586 // if the joint clade is not valid return the max of the two
587 return Math.max(cladeSize1, cladeSize2);
588 }
589 }
590
591 /**
592 * Calculates the minimum number of steps for the parsimony reconstruction of a
593 * binary character defined by leafStates.
594 *
595 * @param tree a tree object to perform test on
596 * @param leafStates a set of booleans, one for each leaf node
597 * @return number of parsimony steps
598 */
599 public static int getParsimonySteps(Tree tree, Set leafStates) {
600
601 int[] score = {0};
602 getParsimonySteps(tree, tree.getRoot(), leafStates, score);
603 return score[0];
604 }
605
606 private static int getParsimonySteps(Tree tree, NodeRef node, Set leafStates, int[] score) {
607
608 if (tree.isExternal(node)) {
609 return (leafStates.contains(tree.getTaxonId(node.getNumber())) ? 1 : 2);
610
611 } else {
612
613 int uState = getParsimonySteps(tree, tree.getChild(node, 0), leafStates, score);
614 int iState = uState;
615
616 for (int i = 1; i < tree.getChildCount(node); i++) {
617
618 int state = getParsimonySteps(tree, tree.getChild(node, i), leafStates, score);
619 uState = state | uState;
620
621 iState = state & iState;
622
623 }
624
625 if (iState == 0) {
626 score[0] += 1;
627 }
628
629 return uState;
630 }
631
632 }
633
634 /**
635 * Calculates the parsimony reconstruction of a binary character defined
636 * by leafStates at a given node.
637 *
638 * @param tree a tree object to perform test on
639 * @param node a NodeRef object from tree
640 * @param leafStates a set of booleans, one for each leaf node
641 * @return number of parsimony steps
642 */
643 public static double getParsimonyState(Tree tree, NodeRef node, Set leafStates) {
644
645 int state = getParsimonyStateAtNode(tree, node, leafStates);
646 switch (state) {
647 case 1:
648 return 0.0;
649 case 2:
650 return 1.0;
651 default:
652 return 0.5;
653 }
654 }
655
656 private static int getParsimonyStateAtNode(Tree tree, NodeRef node, Set leafStates) {
657
658 if (tree.isExternal(node)) {
659 return (leafStates.contains(tree.getTaxonId(node.getNumber())) ? 1 : 2);
660
661 } else {
662
663 int uState = getParsimonyStateAtNode(tree, tree.getChild(node, 0), leafStates);
664 int iState = uState;
665
666 for (int i = 1; i < tree.getChildCount(node); i++) {
667
668 int state = getParsimonyStateAtNode(tree, tree.getChild(node, i), leafStates);
669 uState = state | uState;
670
671 iState = state & iState;
672
673 }
674
675 return uState;
676 }
677
678 }
679
680 /**
681 * determine preorder successor of this node
682 *
683 * @return next node
684 */
685 public static NodeRef preorderSuccessor(Tree tree, NodeRef node) {
686
687 NodeRef next = null;
688
689 if (tree.isExternal(node)) {
690 NodeRef cn = node, ln = null; // Current and last node
691
692 // Go up
693 do {
694 if (tree.isRoot(cn)) {
695 next = cn;
696 break;
697 }
698 ln = cn;
699 cn = tree.getParent(cn);
700 }
701 while (tree.getChild(cn, tree.getChildCount(cn) - 1) == ln);
702
703 // Determine next node
704 if (next == null) {
705 // Go down one node
706 for (int i = 0; i < tree.getChildCount(cn) - 1; i++) {
707
708 if (tree.getChild(cn, i) == ln) {
709 next = tree.getChild(cn, i + 1);
710 break;
711 }
712 }
713 }
714 } else {
715 next = tree.getChild(node, 0);
716 }
717
718 return next;
719 }
720
721 /**
722 * determine a postorder traversal list of nodes in a tree
723 *
724 */
725 public static void postOrderTraversalList(Tree tree, int[] postOrderList) {
726
727 final int nodeCount = tree.getNodeCount();
728 if (postOrderList.length != nodeCount) {
729 throw new IllegalArgumentException("Illegal list length");
730 }
731
732 int idx = nodeCount - 1;
733 int cidx = nodeCount - 1;
734
735 postOrderList[idx] = tree.getRoot().getNumber();
736
737 while (cidx > 0) {
738 NodeRef cNode = tree.getNode(postOrderList[idx]);
739 for(int i = 0; i < tree.getChildCount(cNode); ++i) {
740 cidx -= 1;
741 postOrderList[cidx] = tree.getChild(cNode, i).getNumber();
742 }
743 idx -= 1;
744 }
745 }
746
747 // populate postOrderList with node numbers in posorder: parent before children.
748 // postOrderList is pre-allocated with the right size
749 public static void preOrderTraversalList(Tree tree, int[] postOrderList) {
750
751 final int nodeCount = tree.getNodeCount();
752 if (postOrderList.length != nodeCount) {
753 throw new IllegalArgumentException("Illegal list length");
754 }
755 postOrderList[0] = tree.getRoot().getNumber();
756 preOrderTraversalList(tree, 0, postOrderList);
757 }
758
759 static int preOrderTraversalList(Tree tree, int idx, int[] postOrderList) {
760 final NodeRef node = tree.getNode(postOrderList[idx]);
761 for(int i = 0; i < tree.getChildCount(node); ++i) {
762 final NodeRef child = tree.getChild(node, i);
763 idx += 1;
764 postOrderList[idx] = child.getNumber();
765 if( ! tree.isExternal(child) ) {
766 idx = preOrderTraversalList(tree, idx, postOrderList);
767 }
768 }
769 return idx;
770 }
771
772
773 /**
774 * determine postorder successor of a node
775 *
776 * @return next node
777 */
778 public static NodeRef postorderSuccessor(Tree tree, NodeRef node) {
779
780 NodeRef cn = null;
781 NodeRef parent = tree.getParent(node);
782
783 if (tree.getRoot() == node) {
784 cn = node;
785 } else {
786
787 // Go up one node
788 if (tree.getChild(parent, tree.getChildCount(parent) - 1) == node) {
789 return parent;
790 }
791
792 // Go down one node
793 for (int i = 0; i < tree.getChildCount(parent) - 1; i++) {
794 if (tree.getChild(parent, i) == node) {
795 cn = tree.getChild(parent, i + 1);
796 break;
797 }
798 }
799 }
800
801 // Go down until leaf
802 while (tree.getChildCount(cn) > 0) {
803 cn = tree.getChild(cn, 0);
804 }
805
806 return cn;
807 }
808
809 /**
810 * Gets finds the most ancestral node with attribute set.
811 */
812 public static NodeRef findNodeWithAttribute(Tree tree, String attribute) {
813
814 NodeRef root = tree.getRoot();
815 NodeRef node = root;
816
817 do {
818
819 if (tree.getNodeAttribute(node, attribute) != null) {
820 return node;
821 }
822
823 node = TreeUtils.preorderSuccessor(tree, node);
824
825 } while (node != root);
826
827 return null;
828 }
829
830 /**
831 * Gets finds the most recent date amongst the external nodes.
832 */
833 public static dr.evolution.util.Date findMostRecentDate(Tree tree) {
834
835 dr.evolution.util.Date mostRecent = null;
836
837 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
838 Taxon taxon = tree.getNodeTaxon(tree.getExternalNode(i));
839
840 dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
841 if ((date != null) && (mostRecent == null || date.after(mostRecent))) {
842 mostRecent = date;
843 }
844 }
845
846 return mostRecent;
847 }
848
849 /**
850 * Recursive function for constructing a newick tree representation in the given buffer.
851 */
852 public static String newick(Tree tree) {
853 StringBuffer buffer = new StringBuffer();
854 newick(tree, tree.getRoot(), true, BranchLengthType.LENGTHS_AS_TIME, null, null, null, null, buffer);
855 buffer.append(";");
856 return buffer.toString();
857 }
858
859 /**
860 * @param tree tree to return in newick format
861 * @param dp the decimal places for branch lengths
862 * @return a string representation of the tree in newick format with branch lengths expressed with the given
863 * number of decimal places
864 */
865 public static String newick(Tree tree, int dp) {
866 StringBuffer buffer = new StringBuffer();
867
868 // use the English locale to ensure there are no commas in the number!
869 NumberFormat format = NumberFormat.getNumberInstance(Locale.ENGLISH);
870 format.setMaximumFractionDigits(dp);
871
872 newick(tree, tree.getRoot(), true, BranchLengthType.LENGTHS_AS_TIME, format, null, null, null, buffer);
873 buffer.append(";");
874 return buffer.toString();
875 }
876
877 public static String newick(Tree tree, BranchRates branchRates) {
878 StringBuffer buffer = new StringBuffer();
879 newick(tree, tree.getRoot(), true, BranchLengthType.LENGTHS_AS_SUBSTITUTIONS, null, branchRates, null, null, buffer);
880 buffer.append(";");
881 return buffer.toString();
882 }
883
884 public static String newick(Tree tree,
885 TreeTraitProvider[] treeTraitProviders
886 ) {
887 StringBuffer buffer = new StringBuffer();
888 newick(tree, tree.getRoot(), true, BranchLengthType.LENGTHS_AS_TIME, null, null, treeTraitProviders, null, buffer);
889 buffer.append(";");
890 return buffer.toString();
891 }
892
893 /**
894 * Recursive function for constructing a newick tree representation in the given buffer.
895 */
896 public static String newickNoLengths(Tree tree) {
897 StringBuffer buffer = new StringBuffer();
898 newick(tree, tree.getRoot(), true, BranchLengthType.NO_BRANCH_LENGTHS, null, null, null, null, buffer);
899 buffer.append(";");
900 return buffer.toString();
901 }
902
903 /**
904 * Recursive function for constructing a newick tree representation in the given buffer.
905 *
906 * @param tree The tree
907 * @param node The node [tree.getRoot()]
908 * @param labels whether labels or numbers should be used
909 * @param lengths What type of branch lengths: NO_BRANCH_LENGTHS, LENGTHS_AS_TIME, LENGTHS_AS_SUBSTITUTIONS
910 * @param branchRates An optional BranchRates (or null) used to scale branch times into substitutions
911 * @param treeTraitProviders An array of TreeTraitProvider
912 * @param format formatter for branch lengths
913 * @param idMap A map if id names to integers that is used to overide node labels when present
914 * @param buffer The StringBuffer
915 */
916 public static void newick(Tree tree, NodeRef node, boolean labels, BranchLengthType lengths, NumberFormat format,
917 BranchRates branchRates,
918 TreeTraitProvider[] treeTraitProviders,
919 Map<String, Integer> idMap, StringBuffer buffer) {
920
921 NodeRef parent = tree.getParent(node);
922
923 if (tree.isExternal(node)) {
924 if (!labels) {
925 int k = node.getNumber();
926 if (idMap != null) {
927 buffer.append(idMap.get(tree.getTaxonId(k)));
928 } else {
929 buffer.append((k + 1));
930 }
931 } else {
932 String label = tree.getTaxonId(node.getNumber());
933 if (label.contains(" ") || label.contains(":") || label.contains(";") || label.contains(",")) {
934 buffer.append("\"");
935 buffer.append(label);
936 buffer.append("\"");
937 } else {
938 buffer.append(label);
939 }
940 }
941 } else {
942 buffer.append("(");
943 newick(tree, tree.getChild(node, 0), labels, lengths, format,
944 branchRates,
945 treeTraitProviders, idMap,
946 buffer);
947 for (int i = 1; i < tree.getChildCount(node); i++) {
948 buffer.append(",");
949 newick(tree, tree.getChild(node, i), labels, lengths, format,
950 branchRates,
951 treeTraitProviders, idMap,
952 buffer);
953 }
954 buffer.append(")");
955 }
956
957 writeTreeTraits(buffer, tree, node, treeTraitProviders, TreeTrait.Intent.NODE);
958
959 if (parent != null && lengths != BranchLengthType.NO_BRANCH_LENGTHS) {
960 buffer.append(":");
961 writeTreeTraits(buffer, tree, node, treeTraitProviders, TreeTrait.Intent.BRANCH);
962
963 if (lengths != BranchLengthType.NO_BRANCH_LENGTHS) {
964 double length = tree.getNodeHeight(parent) - tree.getNodeHeight(node);
965 if (lengths == BranchLengthType.LENGTHS_AS_SUBSTITUTIONS) {
966 if (branchRates == null) {
967 throw new IllegalArgumentException("No BranchRates provided");
968 }
969 length *= branchRates.getBranchRate(tree, node);
970 }
971 String lengthString;
972 if (format != null) {
973 lengthString = format.format(length);
974 } else {
975 lengthString = String.valueOf(length);
976 }
977
978 buffer.append(lengthString);
979 }
980 }
981 }
982
983 private static void writeTreeTraits(StringBuffer buffer, Tree tree, NodeRef node, TreeTraitProvider[] treeTraitProviders, TreeTrait.Intent intent) {
984 if (treeTraitProviders != null) {
985 boolean hasAttribute = false;
986 for (TreeTraitProvider ttp : treeTraitProviders) {
987 TreeTrait[] tts = ttp.getTreeTraits();
988 for (TreeTrait treeTrait: tts) {
989 if (treeTrait.getLoggable() && treeTrait.getIntent() == intent) {
990 String value = treeTrait.getTraitString(tree, node);
991
992 if (value != null) {
993 if (!hasAttribute) {
994 buffer.append("[&");
995 hasAttribute = true;
996 } else {
997 buffer.append(",");
998 }
999 buffer.append(treeTrait.getTraitName());
1000 buffer.append("=");
1001 buffer.append(value);
1002
1003 // if (values.length > 1) {
1004 // buffer.append("{");
1005 // buffer.append(values[0]);
1006 // for (int i = 1; i < values.length; i++) {
1007 // buffer.append(",");
1008 // buffer.append(values[i]);
1009 // }
1010 // buffer.append("}");
1011 // } else {
1012 // buffer.append(values[0]);
1013 // }
1014 }
1015 }
1016
1017 }
1018 }
1019 if (hasAttribute) {
1020 buffer.append("]");
1021 }
1022 }
1023 }
1024 /**
1025 * Recursive function for constructing a newick tree representation in the given buffer.
1026 */
1027 public static String uniqueNewick(Tree tree, NodeRef node) {
1028 if (tree.isExternal(node)) {
1029 //buffer.append(tree.getNodeTaxon(node).getId());
1030 return tree.getNodeTaxon(node).getId();
1031 } else {
1032 StringBuffer buffer = new StringBuffer("(");
1033
1034 ArrayList<String> subtrees = new ArrayList<String>();
1035 for (int i = 0; i < tree.getChildCount(node); i++) {
1036 NodeRef child = tree.getChild(node, i);
1037 subtrees.add(uniqueNewick(tree, child));
1038 }
1039 Collections.sort(subtrees);
1040 for (int i = 0; i < subtrees.size(); i++) {
1041 buffer.append(subtrees.get(i));
1042 if (i < subtrees.size() - 1) {
1043 buffer.append(",");
1044 }
1045 }
1046 buffer.append(")");
1047
1048 return buffer.toString();
1049 }
1050 }
1051
1052 /**
1053 * Recursive function for constructing a newick tree representation in the given buffer.
1054 */
1055 public static Tree rotateByName(Tree tree) {
1056
1057 return new SimpleTree(rotateNodeByName(tree, tree.getRoot()));
1058 }
1059
1060 /**
1061 * Recursive function for constructing a newick tree representation in the given buffer.
1062 */
1063 private static SimpleNode rotateNodeByName(Tree tree, NodeRef node) {
1064
1065 if (tree.isExternal(node)) {
1066 return new SimpleNode(tree, node);
1067 } else {
1068
1069 SimpleNode parent = new SimpleNode(tree, node);
1070
1071 NodeRef child1 = tree.getChild(node, 0);
1072 NodeRef child2 = tree.getChild(node, 1);
1073
1074 String subtree1 = uniqueNewick(tree, child1);
1075 String subtree2 = uniqueNewick(tree, child2);
1076
1077 if (subtree1.compareTo(subtree2) > 0) {
1078 parent.addChild(rotateNodeByName(tree, child2));
1079 parent.addChild(rotateNodeByName(tree, child1));
1080 } else {
1081 parent.addChild(rotateNodeByName(tree, child1));
1082 parent.addChild(rotateNodeByName(tree, child2));
1083 }
1084 return parent;
1085 }
1086 }
1087
1088 public static MutableTree rotateTreeByComparator(Tree tree, Comparator<NodeRef> comparator) {
1089
1090 return new SimpleTree(rotateTreeByComparator(tree, tree.getRoot(), comparator));
1091 }
1092
1093 /**
1094 * Recursive function for constructing a newick tree representation in the given buffer.
1095 */
1096 private static SimpleNode rotateTreeByComparator(Tree tree, NodeRef node, Comparator<NodeRef> comparator) {
1097
1098 SimpleNode newNode = new SimpleNode();
1099 newNode.setHeight(tree.getNodeHeight(node));
1100 newNode.setRate(tree.getNodeRate(node));
1101 newNode.setId(tree.getTaxonId(node.getNumber()));
1102 newNode.setNumber(node.getNumber());
1103 newNode.setTaxon(tree.getNodeTaxon(node));
1104
1105 if (!tree.isExternal(node)) {
1106
1107 NodeRef child1 = tree.getChild(node, 0);
1108 NodeRef child2 = tree.getChild(node, 1);
1109
1110 if (comparator.compare(child1, child2) > 0) {
1111 newNode.addChild(rotateTreeByComparator(tree, child2, comparator));
1112 newNode.addChild(rotateTreeByComparator(tree, child1, comparator));
1113 } else {
1114 newNode.addChild(rotateTreeByComparator(tree, child1, comparator));
1115 newNode.addChild(rotateTreeByComparator(tree, child2, comparator));
1116 }
1117 }
1118
1119 return newNode;
1120 }
1121
1122 public static Comparator<NodeRef> createNodeDensityComparator(final Tree tree) {
1123
1124 return new Comparator<NodeRef>() {
1125
1126 public int compare(NodeRef node1, NodeRef node2) {
1127 return getLeafCount(tree, node2) - getLeafCount(tree, node1);
1128 }
1129
1130 public boolean equals(NodeRef node1, NodeRef node2) {
1131 return getLeafCount(tree, node1) == getLeafCount(tree, node2);
1132 }
1133 };
1134 }
1135
1136 public static Comparator<NodeRef> createNodeDensityMinNodeHeightComparator(final Tree tree) {
1137
1138 return new Comparator<NodeRef>() {
1139
1140 public int compare(NodeRef node1, NodeRef node2) {
1141 int larger = getLeafCount(tree, node1) - getLeafCount(tree, node2);
1142
1143 if (larger != 0) return larger;
1144
1145 double tipRecent = getMinNodeHeight(tree, node2) - getMinNodeHeight(tree, node1);
1146 if (tipRecent > 0.0) return 1;
1147 if (tipRecent < 0.0) return -1;
1148 return 0;
1149 }
1150 };
1151 }
1152
1153 public static boolean allDisjoint(SimpleNode[] nodes) {
1154
1155 // check with java 1.6
1156 Set<String>[] ids = new Set[nodes.length];
1157 for (int k = 0; k < nodes.length; ++k) {
1158 ids[k] = TreeUtils.getLeafSet(new SimpleTree(nodes[k]));
1159 for (int j = 0; j < k; ++j) {
1160 Set<String> intersection = new HashSet<String>(ids[j]);
1161 intersection.retainAll(ids[k]);
1162 if (intersection.size() > 0) {
1163 return false;
1164 }
1165 }
1166 }
1167 return true;
1168 }
1169
1170 /**
1171 * Compares 2 trees and returns true if they have the same topology (same taxon
1172 * order is assumed).
1173 */
1174 public static boolean equal(Tree tree1, Tree tree2) {
1175
1176 return uniqueNewick(tree1, tree1.getRoot()).equals(uniqueNewick(tree2, tree2.getRoot()));
1177 }
1178
1179 private static Node convertToJebl(Tree tree, NodeRef node, SimpleRootedTree jtree) {
1180 if (tree.isExternal(node)) {
1181 String taxonId = tree.getTaxonId(node.getNumber());
1182 Node externalNode = jtree.createExternalNode(jebl.evolution.taxa.Taxon.getTaxon(taxonId));
1183 jtree.setHeight(externalNode, tree.getNodeHeight(node));
1184 return externalNode;
1185 }
1186 List<Node> jchildren = new ArrayList<Node>();
1187 for (int nc = 0; nc < tree.getChildCount(node); ++nc) {
1188 NodeRef child = tree.getChild(node, nc);
1189 Node node1 = convertToJebl(tree, child, jtree);
1190 jtree.setHeight(node1, tree.getNodeHeight(child));
1191 jchildren.add(node1);
1192 }
1193
1194 return jtree.createInternalNode(jchildren);
1195 }
1196
1197 /**
1198 * Convert from beast tree to JEBL tree.
1199 * Note that currently only topology and branch lengths are preserved.
1200 * Can add attributes later if needed.
1201 *
1202 * @param tree beast
1203 * @return jebl tree
1204 */
1205 static public SimpleRootedTree asJeblTree(Tree tree) {
1206 SimpleRootedTree jtree = new SimpleRootedTree();
1207
1208 convertToJebl(tree, tree.getRoot(), jtree);
1209 jtree.setHeight(jtree.getRootNode(), tree.getNodeHeight(tree.getRoot()));
1210 return jtree;
1211 }
1212
1213 /**
1214 * Gets the set of clades in a tree
1215 *
1216 * @param tree the tree
1217 * @return the set of clades
1218 */
1219 public static Set<Set<String>> getClades(Tree tree) {
1220 Set<Set<String>> clades = new HashSet<Set<String>>();
1221 getClades(tree, tree.getRoot(), null, clades);
1222
1223 return clades;
1224 }
1225
1226 private static void getClades(Tree tree, NodeRef node, Set<String> leaves, Set<Set<String>> clades) {
1227
1228 if (tree.isExternal(node)) {
1229 leaves.add(tree.getTaxonId(node.getNumber()));
1230 } else {
1231
1232 Set<String> ls = new HashSet<String>();
1233
1234 for (int i = 0; i < tree.getChildCount(node); i++) {
1235
1236 NodeRef node1 = tree.getChild(node, i);
1237
1238 getClades(tree, node1, ls, clades);
1239 }
1240
1241 if (leaves != null) {
1242 // except for the root clade...
1243 leaves.addAll(ls);
1244 clades.add(ls);
1245 }
1246
1247 }
1248 }
1249
1250 /**
1251 * Tests whether the given tree is compatible with a set of clades
1252 *
1253 * @param tree the test tree
1254 * @param clades the set of clades
1255 * @return
1256 */
1257 public static boolean isCompatible(Tree tree, Set<Set<String>> clades) {
1258 return isCompatible(tree, tree.getRoot(), null, clades);
1259 }
1260
1261 private static boolean isCompatible(Tree tree, NodeRef node, Set<String> leaves, Set<Set<String>> clades) {
1262 if (tree.isExternal(node)) {
1263 leaves.add(tree.getTaxonId(node.getNumber()));
1264 return true;
1265 } else {
1266
1267 Set<String> ls = new HashSet<String>();
1268
1269 for (int i = 0; i < tree.getChildCount(node); i++) {
1270
1271 NodeRef node1 = tree.getChild(node, i);
1272
1273 if (!isCompatible(tree, node1, ls, clades)) {
1274 // as soon as we have an incompatibility break out...
1275 return false;
1276 }
1277 }
1278
1279 if (leaves != null) {
1280 // except for the root clade...
1281 for (Set<String> clade : clades) {
1282 Set<String> intersection = new HashSet<String>(clade);
1283 intersection.retainAll(ls);
1284
1285 if (intersection.size() != 0 &&
1286 intersection.size() != ls.size() &&
1287 intersection.size() != clade.size()) {
1288 return false;
1289 }
1290 }
1291
1292 leaves.addAll(ls);
1293 }
1294 }
1295 return true;
1296 }
1297
1298 public static void correctBranchLengthToGetUltrametricTree(Tree tree, double givenLength) {
1299
1300
1301 }
1302
1303 private void setHeight(Tree tree, NodeRef node, double givenLength) {
1304 if (tree.getChildCount(node) == 0) {
1305
1306 }
1307 for (int i = 0; i < tree.getChildCount(node); i++) {
1308
1309 }
1310 }
1311
1312 public enum BranchLengthType {
1313 NO_BRANCH_LENGTHS, LENGTHS_AS_TIME, LENGTHS_AS_SUBSTITUTIONS
1314 }
1315
1316 public static class MissingTaxonException extends Exception {
1317 /**
1318 *
1319 */
1320 private static final long serialVersionUID = 8468656622238269963L;
1321
1322 public MissingTaxonException(Taxon taxon) {
1323 super(taxon.getId());
1324 }
1325 }
1326 }