Debian Codegraph @

src/dr/evolution/tree/treemetrics/KendallColijnPathDifferenceMetric.java

raw symbols SCIP
1 /*
2 * TopologyTracer.java
3 *
4 * Copyright (c) 2002-2017 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.evolution.tree.treemetrics;
27
28 import dr.evolution.io.Importer;
29 import dr.evolution.io.NewickImporter;
30 import dr.evolution.tree.NodeRef;
31 import dr.evolution.tree.Tree;
32 import dr.evolution.tree.TreeUtils;
33
34 import java.io.IOException;
35 import java.util.*;
36
37 import static dr.evolution.tree.treemetrics.TreeMetric.Utils.checkTreeTaxa;
38
39 /**
40 * @author Guy Baele
41 * Path difference metric according to Kendall & Colijn (2015)
42 */
43 public class KendallColijnPathDifferenceMetric implements TreeMetric {
44
45 public static Type TYPE = Type.KENDALL_COLIJN;
46
47 private Tree focalTree;
48 private int dim;
49 private double[] focalSmallM, focalLargeM;
50 private final boolean fixedFocalTree;
51 private final double lambda;
52
53 public KendallColijnPathDifferenceMetric(double lambda) {
54 this.lambda = lambda;
55
56 this.fixedFocalTree = false;
57 }
58
59 public KendallColijnPathDifferenceMetric(double lambda, Tree focalTree) {
60 this.lambda = lambda;
61
62 this.focalTree = focalTree;
63 this.fixedFocalTree = true;
64 //this.dim = (externalNodeCount-2)*(externalNodeCount-1)+externalNodeCount;
65 this.dim = focalTree.getExternalNodeCount() * focalTree.getExternalNodeCount();
66 this.focalSmallM = new double[dim];
67 this.focalLargeM = new double[dim];
68
69 traverse(focalTree, focalTree.getRoot(), 0.0, 0, focalLargeM, focalSmallM);
70 }
71
72 /**
73 * Compute the metric between two trees. If tree1 is not the focal tree provided to the
74 * constructor then it will store this as the new focal tree. If the focal tree is constant
75 * from call to call then a cached set of precomputation will be used, increasing efficiency.
76 * @param tree1
77 * @param tree2
78 * @return
79 */
80 @Override
81 public double getMetric(Tree tree1, Tree tree2) {
82
83 checkTreeTaxa(tree1, tree2);
84
85 if (tree1 != focalTree) {
86 if (fixedFocalTree) {
87 // If we set a focal tree in the constructor then it makes sense to check it is the same
88 // as the one set here.
89 throw new RuntimeException("Focal tree is different from that set in the constructor.");
90 }
91
92 // cache tree1 and the pre-computed path for future calls
93 focalTree = tree1;
94 if (focalSmallM == null) {
95 dim = focalTree.getExternalNodeCount() * focalTree.getExternalNodeCount();
96 focalSmallM = new double[dim];
97 focalLargeM = new double[dim];
98 }
99 traverse(focalTree, focalTree.getRoot(), 0.0, 0, focalLargeM, focalSmallM);
100 }
101
102 double[] smallMTwo = new double[dim];
103 double[] largeMTwo = new double[dim];
104
105 traverse(tree2, tree2.getRoot(), 0.0, 0, largeMTwo, smallMTwo);
106
107 List<Double> results = new ArrayList<Double>();
108
109 int n = tree1.getExternalNodeCount();
110
111 return calculateMetric(focalSmallM, focalLargeM, smallMTwo, largeMTwo, n, lambda);
112 }
113
114 private double calculateMetric(double[] smallMOne, double[] largeMOne, double[] smallMTwo, double[] largeMTwo, int n, double l) {
115 double distance = 0.0;
116 //calculate Euclidean distance for this lambda value
117 int k = 0;
118 for (int i = 0; i < n; i++) {
119 for (int j = i; j < n; j++) { // include diagonal
120 int index = (i * n) + j;
121 double vOne = (1.0 - l) * smallMOne[index] + l * largeMOne[index];
122 double vTwo = (1.0 - l) * smallMTwo[index] + l * largeMTwo[index];
123 distance += Math.pow(vOne - vTwo, 2);
124 }
125 }
126 return Math.sqrt(distance);
127 }
128
129 private Set<NodeRef> traverse(Tree tree, NodeRef node, double lengthFromRoot, int edgesFromRoot, double[] lengths, double[] edges) {
130 NodeRef left = tree.getChild(node, 0);
131 NodeRef right = tree.getChild(node, 1);
132
133
134 Set<NodeRef> leftSet = null;
135 Set<NodeRef> rightSet = null;
136
137 if (!tree.isExternal(left)) {
138 leftSet = traverse(tree, left, lengthFromRoot + tree.getBranchLength(left), edgesFromRoot + 1, lengths, edges);
139 } else {
140 leftSet = Collections.singleton(left);
141 int index = (left.getNumber() * tree.getExternalNodeCount()) + left.getNumber();
142 lengths[index] = tree.getBranchLength(left);
143 edges[index] = 1;
144 }
145 if (!tree.isExternal(right)) {
146 rightSet = traverse(tree, right, lengthFromRoot + tree.getBranchLength(right), edgesFromRoot + 1, lengths, edges);
147 } else {
148 rightSet = Collections.singleton(right);
149 int index = (right.getNumber() * tree.getExternalNodeCount()) + right.getNumber();
150 lengths[index] = tree.getBranchLength(right);
151 edges[index] = 1;
152 }
153
154 for (NodeRef tip1 : leftSet) {
155 for (NodeRef tip2 : rightSet) {
156 int index;
157 if (tip1.getNumber() < tip2.getNumber()) {
158 index = (tip1.getNumber() * tree.getExternalNodeCount()) + tip2.getNumber();
159 } else {
160 index = (tip2.getNumber() * tree.getExternalNodeCount()) + tip1.getNumber();
161 }
162 lengths[index] = lengthFromRoot;
163 edges[index] = edgesFromRoot;
164
165 }
166 }
167
168 Set<NodeRef> tips = new HashSet<NodeRef>();
169 tips.addAll(leftSet);
170 tips.addAll(rightSet);
171
172 return tips;
173 }
174
175 @Deprecated
176 public ArrayList<Double> getMetric_old(Tree tree, ArrayList<Double> lambda) {
177
178 //check if taxon lists are in the same order!!
179 if (focalTree.getExternalNodeCount() != tree.getExternalNodeCount()) {
180 throw new RuntimeException("Different number of taxa in both trees.");
181 } else {
182 for (int i = 0; i < focalTree.getExternalNodeCount(); i++) {
183 if (!focalTree.getNodeTaxon(focalTree.getExternalNode(i)).getId().equals(tree.getNodeTaxon(tree.getExternalNode(i)).getId())) {
184 throw new RuntimeException("Mismatch between taxa in both trees: " + focalTree.getNodeTaxon(focalTree.getExternalNode(i)).getId() + " vs. " + tree.getNodeTaxon(tree.getExternalNode(i)).getId());
185 }
186 }
187 }
188
189 double[] smallMTwo = new double[dim];
190 double[] largeMTwo = new double[dim];
191
192 int index = 0;
193 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
194 for (int j = i+1; j < tree.getExternalNodeCount(); j++) {
195 //get two leaf nodes
196 NodeRef nodeOne = tree.getExternalNode(i);
197 NodeRef nodeTwo = tree.getExternalNode(j);
198
199 //get common ancestor of 2 leaf nodes
200 NodeRef MRCA = TreeUtils.getCommonAncestor(tree, nodeOne, nodeTwo);
201
202 int edges = 0;
203 double branchLengths = 0.0;
204 while (MRCA != tree.getRoot()) {
205 edges++;
206 branchLengths += tree.getNodeHeight(tree.getParent(MRCA)) - tree.getNodeHeight(MRCA);
207 MRCA = tree.getParent(MRCA);
208 }
209 smallMTwo[index] = edges;
210 largeMTwo[index] = branchLengths;
211 index++;
212 }
213 }
214
215 int externalNodeCount = tree.getExternalNodeCount();
216 int d = (externalNodeCount-2)*(externalNodeCount-1)+externalNodeCount;
217
218 //fill out arrays further
219 index = 0;
220 for (int i = (externalNodeCount-1)*(externalNodeCount-2); i < d; i++) {
221 smallMTwo[i] = 1.0;
222 largeMTwo[i] = tree.getNodeHeight(tree.getParent(tree.getExternalNode(index))) - tree.getNodeHeight(tree.getExternalNode(index));
223 index++;
224 }
225
226 double[] vArrayOne = new double[dim];
227 double[] vArrayTwo = new double[dim];
228
229 ArrayList<Double> results = new ArrayList<Double>();
230
231 for (Double l : lambda) {
232 double distance = 0.0;
233 //calculate Euclidean distance for this lambda value
234 for (int i = 0; i < dim; i++) {
235 vArrayOne[i] = (1.0 - l)*focalSmallM[i] + l*focalLargeM[i];
236 vArrayTwo[i] = (1.0 - l)*smallMTwo[i] + l*largeMTwo[i];
237 distance += Math.pow(vArrayOne[i] - vArrayTwo[i],2);
238 }
239 distance = Math.sqrt(distance);
240 results.add(distance);
241 }
242
243 return results;
244
245 }
246
247 @Deprecated
248 public ArrayList<Double> getMetric_old(Tree tree1, Tree tree2, ArrayList<Double> lambda) {
249
250 int dim = (tree1.getExternalNodeCount()-2)*(tree1.getExternalNodeCount()-1)+tree1.getExternalNodeCount();
251
252 double[] smallMOne = new double[dim];
253 double[] largeMOne = new double[dim];
254 double[] smallMTwo = new double[dim];
255 double[] largeMTwo = new double[dim];
256
257 //check if taxon lists are in the same order!!
258 if (tree1.getExternalNodeCount() != tree2.getExternalNodeCount()) {
259 throw new RuntimeException("Different number of taxa in both trees.");
260 } else {
261 for (int i = 0; i < tree1.getExternalNodeCount(); i++) {
262 if (!tree1.getNodeTaxon(tree1.getExternalNode(i)).getId().equals(tree2.getNodeTaxon(tree2.getExternalNode(i)).getId())) {
263 throw new RuntimeException("Mismatch between taxa in both trees: " + tree1.getNodeTaxon(tree1.getExternalNode(i)).getId() + " vs. " + tree2.getNodeTaxon(tree2.getExternalNode(i)).getId());
264 }
265 }
266 }
267
268 int index = 0;
269 for (int i = 0; i < tree1.getExternalNodeCount(); i++) {
270 for (int j = i+1; j < tree1.getExternalNodeCount(); j++) {
271 //get two leaf nodes
272 NodeRef nodeOne = tree1.getExternalNode(i);
273 NodeRef nodeTwo = tree1.getExternalNode(j);
274
275 //get common ancestor of 2 leaf nodes
276 NodeRef MRCA = TreeUtils.getCommonAncestor(tree1, nodeOne, nodeTwo);
277
278 int edges = 0;
279 double branchLengths = 0.0;
280 while (MRCA != tree1.getRoot()) {
281 edges++;
282 branchLengths += tree1.getNodeHeight(tree1.getParent(MRCA)) - tree1.getNodeHeight(MRCA);
283 MRCA = tree1.getParent(MRCA);
284 }
285 smallMOne[index] = edges;
286 largeMOne[index] = branchLengths;
287 index++;
288 }
289 }
290
291 int externalNodeCount = tree2.getExternalNodeCount();
292 int d = (externalNodeCount-2)*(externalNodeCount-1)+externalNodeCount;
293
294 //fill out arrays further
295 index = 0;
296 for (int i = (externalNodeCount-1)*(externalNodeCount-2); i < d; i++) {
297 smallMOne[i] = 1.0;
298 largeMOne[i] = tree1.getNodeHeight(tree1.getParent(tree1.getExternalNode(index))) - tree1.getNodeHeight(tree1.getExternalNode(index));
299 index++;
300 }
301
302 /*for (int i = 0; i < smallMOne.length; i++) {
303 System.out.print(smallMOne[i] + " ");
304 }
305 System.out.println();
306 for (int i = 0; i < largeMOne.length; i++) {
307 System.out.print(largeMOne[i] + " ");
308 }
309 System.out.println("\n");*/
310
311 index = 0;
312 for (int i = 0; i < tree2.getExternalNodeCount(); i++) {
313 for (int j = i+1; j < tree2.getExternalNodeCount(); j++) {
314 //get two leaf nodes
315 NodeRef nodeOne = tree2.getExternalNode(i);
316 NodeRef nodeTwo = tree2.getExternalNode(j);
317
318 //get common ancestor of 2 leaf nodes
319 NodeRef MRCA = TreeUtils.getCommonAncestor(tree2, nodeOne, nodeTwo);
320
321 int edges = 0;
322 double branchLengths = 0.0;
323 while (MRCA != tree2.getRoot()) {
324 edges++;
325 branchLengths += tree2.getNodeHeight(tree2.getParent(MRCA)) - tree2.getNodeHeight(MRCA);
326 MRCA = tree2.getParent(MRCA);
327 }
328 smallMTwo[index] = edges;
329 largeMTwo[index] = branchLengths;
330 index++;
331 }
332 }
333
334 //fill out arrays further
335 index = 0;
336 for (int i = (externalNodeCount-1)*(externalNodeCount-2); i < d; i++) {
337 smallMTwo[i] = 1.0;
338 largeMTwo[i] = tree2.getNodeHeight(tree2.getParent(tree2.getExternalNode(index))) - tree2.getNodeHeight(tree2.getExternalNode(index));
339 index++;
340 }
341
342 /*for (int i = 0; i < smallMTwo.length; i++) {
343 System.out.print(smallMTwo[i] + " ");
344 }
345 System.out.println();
346 for (int i = 0; i < largeMTwo.length; i++) {
347 System.out.print(largeMTwo[i] + " ");
348 }
349 System.out.println("\n");*/
350
351 double[] vArrayOne = new double[dim];
352 double[] vArrayTwo = new double[dim];
353
354 ArrayList<Double> results = new ArrayList<Double>();
355
356 for (Double l : lambda) {
357 double distance = 0.0;
358 //calculate Euclidean distance for this lambda value
359 for (int i = 0; i < dim; i++) {
360 vArrayOne[i] = (1.0 - l)*smallMOne[i] + l*largeMOne[i];
361 vArrayTwo[i] = (1.0 - l)*smallMTwo[i] + l*largeMTwo[i];
362 distance += Math.pow(vArrayOne[i] - vArrayTwo[i],2);
363 }
364 distance = Math.sqrt(distance);
365 results.add(distance);
366 }
367
368 return results;
369 }
370
371
372 public static void main(String[] args) {
373 // tree 1: ((A:1.2,B:0.8):0.5,(C:0.8,D:1.0):1.1);
374 // tree 2: (((A:0.8,B:1.3999999999999997):0.30000000000000004,C:0.7000000000000002):0.8999999999999999,D:1.0);
375 //
376 // lambda (0.0) = 2.0
377 // lambda (0.5) = 1.9397164741270823
378 // lambda (1.0) = 1.962141687034858
379 // lambda (0.0) = 2.0
380 // lambda (0.5) = 1.9397164741270823
381 // lambda (1.0) = 1.962141687034858
382
383
384 try {
385
386 //4-taxa example
387 NewickImporter importer = new NewickImporter("(('A':1.2,'B':0.8):0.5,('C':0.8,'D':1.0):1.1)");
388 Tree treeOne = importer.importNextTree();
389 System.out.println("4-taxa tree 1: " + treeOne);
390
391 importer = new NewickImporter("((('A':0.8,'B':1.4):0.3,'C':0.7):0.9,'D':1.0)");
392 Tree treeTwo = importer.importNextTree();
393 System.out.println("4-taxa tree 2: " + treeTwo);
394 System.out.println();
395
396 double metrics[] = new double[] {
397 (new KendallColijnPathDifferenceMetric(0.0).getMetric(treeOne, treeTwo)),
398 (new KendallColijnPathDifferenceMetric(0.5).getMetric(treeOne, treeTwo)),
399 (new KendallColijnPathDifferenceMetric(1.0).getMetric(treeOne, treeTwo)),
400 };
401
402 System.out.println("Paired trees:");
403 System.out.println("lambda (0.0) = " + metrics[0]);
404 System.out.println("lambda (0.5) = " + metrics[1]);
405 System.out.println("lambda (1.0) = " + metrics[2]);
406 System.out.println();
407
408 //Additional test for comparing a collection of trees against a (fixed) focal tree
409 metrics = new double[] {
410 (new KendallColijnPathDifferenceMetric(0.0, treeOne).getMetric(treeOne, treeTwo)),
411 (new KendallColijnPathDifferenceMetric(0.5, treeOne).getMetric(treeOne, treeTwo)),
412 (new KendallColijnPathDifferenceMetric(1.0, treeOne).getMetric(treeOne, treeTwo)),
413 };
414
415 System.out.println("Focal trees:");
416 System.out.println("lambda (0.0) = " + metrics[0]);
417 System.out.println("lambda (0.5) = " + metrics[1]);
418 System.out.println("lambda (1.0) = " + metrics[2]);
419 System.out.println();
420 System.out.println();
421
422 //5-taxa example
423 importer = new NewickImporter("(((('A':0.6,'B':0.6):0.1,'C':0.5):0.4,'D':0.7):0.1,'E':1.3)");
424 treeOne = importer.importNextTree();
425 System.out.println("5-taxa tree 1: " + treeOne);
426
427 importer = new NewickImporter("((('A':0.8,'B':1.4):0.1,'C':0.7):0.2,('D':1.0,'E':0.9):1.3)");
428 treeTwo = importer.importNextTree();
429 System.out.println("5-taxa tree 2: " + treeTwo);
430 System.out.println();
431
432 //lambda = 0.0 should yield: sqrt(7) = 2.6457513110645907162
433 //lambda = 1.0 should yield: sqrt(2.96) = 1.7204650534085252911
434
435 metrics = new double[] {
436 (new KendallColijnPathDifferenceMetric(0.0, treeOne).getMetric(treeOne, treeTwo)),
437 (new KendallColijnPathDifferenceMetric(0.5, treeOne).getMetric(treeOne, treeTwo)),
438 (new KendallColijnPathDifferenceMetric(1.0, treeOne).getMetric(treeOne, treeTwo)),
439 };
440
441 System.out.println("Paired trees:");
442 System.out.println("lambda (0.0) = " + metrics[0]);
443 System.out.println("lambda (0.5) = " + metrics[1]);
444 System.out.println("lambda (1.0) = " + metrics[2]);
445 System.out.println();
446
447 //Additional test for comparing a collection of trees against a (fixed) focal tree
448 metrics = new double[] {
449 (new KendallColijnPathDifferenceMetric(0.0, treeOne).getMetric(treeOne, treeTwo)),
450 (new KendallColijnPathDifferenceMetric(0.5, treeOne).getMetric(treeOne, treeTwo)),
451 (new KendallColijnPathDifferenceMetric(1.0, treeOne).getMetric(treeOne, treeTwo)),
452 };
453
454 System.out.println("Focal trees:");
455 System.out.println("lambda (0.0) = " + metrics[0]);
456 System.out.println("lambda (0.5) = " + metrics[1]);
457 System.out.println("lambda (1.0) = " + metrics[2]);
458 System.out.println();
459
460
461 //timings
462 // long startTime = System.currentTimeMillis();
463 // for (int i = 0; i < 1000000; i++) {
464 // new KCPathDifferenceMetric().getMetric_old(treeOne, treeTwo, lambdaValues);
465 // }
466 // System.out.println("Old algorithm: " + (System.currentTimeMillis() - startTime) + " ms");
467
468 long startTime = System.currentTimeMillis();
469 for (int i = 0; i < 1000000; i++) {
470 new KendallColijnPathDifferenceMetric(0.5).getMetric(treeOne, treeTwo);
471 }
472 System.out.println("New algorithm, 1M reps: " + (System.currentTimeMillis() - startTime) + " ms");
473
474 } catch(Importer.ImportException ie) {
475 System.err.println(ie);
476 } catch(IOException ioe) {
477 System.err.println(ioe);
478 }
479
480 }
481
482 @Override
483 public Type getType() {
484 return TYPE;
485 }
486
487 @Override
488 public String toString() {
489 return getType().getShortName() + "(" + lambda + ")";
490 }
491
492
493 }