Debian Codegraph @

src/dr/app/tempest/TemporalRooting.java

raw symbols SCIP
1 /*
2 * TemporalRooting.java
3 *
4 * Copyright (c) 2002-2015 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.app.tempest;
27
28 import dr.evolution.tree.*;
29 import dr.evolution.tree.TreeUtils;
30 import dr.evolution.util.*;
31 import dr.evolution.util.Date;
32 import dr.stats.Regression;
33 import dr.stats.DiscreteStatistics;
34 import dr.math.*;
35
36 import java.util.*;
37
38 /*
39 * @author Andrew Rambaut
40 */
41
42 public class TemporalRooting {
43
44 public enum RootingFunction {
45 HEURISTIC_RESIDUAL_MEAN_SQUARED("heuristic residual mean squared"),
46 RESIDUAL_MEAN_SQUARED("residual mean squared"),
47 // SUM_RESIDUAL_SQUARED("sum squared residuals"),
48 CORRELATION("correlation"),
49 R_SQUARED("R squared");
50
51 RootingFunction(final String name) {
52 this.name = name;
53 }
54
55 @Override
56 public String toString() {
57 return name;
58 }
59
60 private final String name;
61 }
62
63 private boolean contemporaneous = false;
64 private final TaxonList taxa;
65 private final Map<String, Double> dates;
66 private final Map<String, Double> precisions;
67 private boolean useTargetRate = false;
68 private double targetRate = 0.0;
69 private double dateMin;
70 private double dateMax;
71
72 private int currentRootBranch = 0;
73 private int totalRootBranches = 0;
74
75 private boolean forcePositiveRate = false;
76
77 public TemporalRooting(TaxonList taxa) {
78 this.taxa = taxa;
79
80 dates = new HashMap<String, Double>();
81 precisions = new HashMap<String, Double>();
82
83 dateMin = Double.MAX_VALUE;
84 dateMax = -Double.MAX_VALUE;
85
86 for (int i = 0; i < taxa.getTaxonCount(); i++) {
87 Taxon taxon = taxa.getTaxon(i);
88 Date date = (Date)taxon.getAttribute("date");
89 double d = 0.0;
90 if (date != null) {
91 d = date.getAbsoluteTimeValue();
92 if (date.getUncertainty() > 0.0) {
93 d += date.getUncertainty() / 2;
94 precisions.put(taxon.getId(), date.getUncertainty());
95 }
96 }
97 if (d > dateMax) {
98 dateMax = d;
99 }
100 if (d < dateMin) {
101 dateMin = d;
102 }
103 dates.put(taxon.getId(), d);
104 }
105
106 if (Math.abs(dateMax - dateMin) < 1.0E-8) {
107 // probably contemporaneous tips
108 contemporaneous = true;
109 }
110 }
111
112 public void setForcePositiveRate(boolean forcePositiveRate) {
113 this.forcePositiveRate = forcePositiveRate;
114 }
115
116 public void setTargetRate(double targetRate) {
117 this.targetRate = targetRate;
118 }
119
120 public boolean isContemporaneous() {
121 return contemporaneous;
122 }
123
124 public double getDateRange() {
125 return dateMax - dateMin;
126 }
127
128 public Tree findRoot(Tree tree, RootingFunction rootingFunction) {
129
130 double[] dates = getTipDates(tree);
131 return findGlobalRoot(tree, dates, rootingFunction, forcePositiveRate);
132 }
133
134 public Tree findLocalRoot(Tree tree, RootingFunction rootingFunction) {
135
136 double[] dates = getTipDates(tree);
137 FlexibleTree bestTree = new FlexibleTree(tree);
138
139 findLocalRoot(bestTree, dates, rootingFunction, forcePositiveRate);
140
141 return bestTree;
142 }
143
144 public Regression getRootToTipRegression(Tree tree) {
145
146 if (contemporaneous) {
147 throw new IllegalArgumentException("Cannot do a root to tip regression on contemporaneous tips");
148 }
149
150 double[] dates = getTipDates(tree);
151 double[] distances = getRootToTipDistances(tree);
152
153 return new Regression(dates, distances);
154 }
155
156 public Regression getNodeDensityRegression(Tree tree) {
157
158 if (contemporaneous) {
159 throw new IllegalArgumentException("Cannot do a node density regression on contemporaneous tips");
160 }
161
162 double[] dates = getTipDates(tree);
163 // double[] distances = getRootToTipDistances(tree);
164 double[] density = getNodeDensity(tree);
165
166 return new Regression(dates, density);
167 }
168
169 public Regression getAncestorRootToTipRegression(Tree tree, Regression regression) {
170
171 if (contemporaneous) {
172 throw new IllegalArgumentException("Cannot do a root to tip regression on contemporaneous tips");
173 }
174
175 double[] dates = new double[tree.getExternalNodeCount()];
176 double[] distances = new double[tree.getExternalNodeCount()];
177 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
178 NodeRef tip = tree.getExternalNode(i);
179 NodeRef parent = tree.getParent(tip);
180 distances[i] = getRootToTipDistance(tree, parent);
181
182 dates[i] = regression.getXIntercept() + (distances[i] / regression.getGradient());
183 }
184
185 return new Regression(dates, distances);
186 }
187
188 public double[] getRootToTipDistances(Tree tree) {
189
190 double[] d = new double[tree.getExternalNodeCount()];
191 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
192 NodeRef tip = tree.getExternalNode(i);
193 d[i] = getRootToTipDistance(tree, tip);
194 }
195 return d;
196 }
197
198 public double[] getParentRootToTipDistances(Tree tree) {
199
200 double[] d = new double[tree.getExternalNodeCount()];
201 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
202 NodeRef tip = tree.getExternalNode(i);
203 NodeRef parent = tree.getParent(tip);
204 d[i] = getRootToTipDistance(tree, parent);
205 }
206 return d;
207 }
208
209 public double[] getRootToTipResiduals(Tree tree, Regression regression) {
210
211 double[] r = new double[tree.getExternalNodeCount()];
212 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
213 NodeRef tip = tree.getExternalNode(i);
214 Double date = dates.get(tree.getNodeTaxon(tip).getId());
215 double d = getRootToTipDistance(tree, tip);
216
217 r[i] = regression.getResidual(date, d);
218 }
219 return r;
220 }
221
222 public double[] getNodeDensity(Tree tree) {
223
224 double[] d = new double[tree.getExternalNodeCount()];
225 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
226 NodeRef tip = tree.getExternalNode(i);
227 d[i] = getNodeDensity(tree, tip);
228 }
229 return d;
230 }
231
232 public double[] getTipDates(Tree tree) {
233 double[] d = new double[tree.getExternalNodeCount()];
234 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
235 NodeRef tip = tree.getExternalNode(i);
236 Double date = dates.get(tree.getNodeTaxon(tip).getId());
237 if (date == null) {
238 throw new IllegalArgumentException("Taxon, " + tree.getNodeTaxon(tip) + ", not found in taxon list");
239 }
240 d[i] = date;
241 }
242 return d;
243 }
244
245 public double[] getTipDatePrecisions(Tree tree) {
246 double[] p = new double[tree.getExternalNodeCount()];
247 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
248 NodeRef tip = tree.getExternalNode(i);
249 Double precision = precisions.get(tree.getNodeTaxon(tip).getId());
250 if (precision == null) {
251 precision = 0.0;
252 }
253 p[i] = precision;
254 }
255 return p;
256 }
257
258 public String[] getTipLabels(Tree tree) {
259 String[] labels = new String[tree.getExternalNodeCount()];
260 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
261 NodeRef tip = tree.getExternalNode(i);
262 labels[i] = tree.getNodeTaxon(tip).getId();
263 }
264 return labels;
265 }
266
267 private Tree findGlobalRoot(final Tree source, final double[] dates, RootingFunction rootingFunction, boolean forcePositiveRate) {
268
269 FlexibleTree bestTree = new FlexibleTree(source);
270 double minF = findLocalRoot(bestTree, dates, rootingFunction, forcePositiveRate);
271 double minDiff = Double.MAX_VALUE;
272
273 totalRootBranches = source.getNodeCount();
274 for (currentRootBranch = 0; currentRootBranch < source.getNodeCount(); currentRootBranch++) {
275 FlexibleTree tmpTree = new FlexibleTree(source);
276 NodeRef node = tmpTree.getNode(currentRootBranch);
277 if (!tmpTree.isRoot(node)) {
278 double length = tmpTree.getBranchLength(node);
279 tmpTree.changeRoot(node, length * 0.5, length * 0.5);
280
281 double f = findLocalRoot(tmpTree, dates, rootingFunction, forcePositiveRate);
282 if (useTargetRate) {
283 Regression r = getRootToTipRegression(tmpTree);
284 if (Math.abs(r.getGradient() - targetRate) < minDiff) {
285 minDiff = Math.abs(r.getGradient() - targetRate);
286 bestTree = tmpTree;
287 }
288 } else {
289 if (f < minF) {
290 minF = f;
291 bestTree = tmpTree;
292 }
293 }
294 }
295 }
296
297 return bestTree;
298 }
299
300 private double findLocalRoot(final FlexibleTree tree,
301 final double[] dates,
302 final RootingFunction rootingFunction,
303 final boolean forcePositiveRate) {
304
305 if (rootingFunction == RootingFunction.RESIDUAL_MEAN_SQUARED) {
306 return findAnalyticalLocalRoot(tree, dates, rootingFunction);
307 }
308
309 NodeRef node1 = tree.getChild(tree.getRoot(), 0);
310 NodeRef node2 = tree.getChild(tree.getRoot(), 1);
311
312 final double length1 = tree.getBranchLength(node1);
313 final double length2 = tree.getBranchLength(node2);
314
315 final double sumLength = length1 + length2;
316
317 final Set<NodeRef> tipSet1 = TreeUtils.getExternalNodes(tree, node1);
318 final Set<NodeRef> tipSet2 = TreeUtils.getExternalNodes(tree, node2);
319
320 final double[] y = new double[tree.getExternalNodeCount()];
321
322 UnivariateFunction f = new UnivariateFunction() {
323 // MultivariateFunction f = new MultivariateFunction() {
324 public double evaluate(final double argument) {
325 double l1 = argument * sumLength;
326
327 for (NodeRef tip : tipSet1) {
328 y[tip.getNumber()] = getRootToTipDistance(tree, tip) - length1 + l1;
329 }
330
331 double l2 = (1.0 - argument) * sumLength;
332
333 for (NodeRef tip : tipSet2) {
334 y[tip.getNumber()] = getRootToTipDistance(tree, tip) - length2 + l2;
335 }
336
337 double score;
338
339 if (!contemporaneous) {
340 Regression r = new Regression(dates, y);
341
342 switch (rootingFunction) {
343
344 case CORRELATION:
345 score = -r.getCorrelationCoefficient();
346 break;
347 case R_SQUARED:
348 score = -r.getRSquared();
349 break;
350 case HEURISTIC_RESIDUAL_MEAN_SQUARED:
351 case RESIDUAL_MEAN_SQUARED:
352 score = r.getResidualMeanSquared();
353 break;
354 default:
355 throw new RuntimeException("Unknown enum value");
356 }
357
358 if (forcePositiveRate) {
359 score = (r.getGradient() < 0.0 ? -score : score);
360 }
361
362 } else {
363 score = DiscreteStatistics.variance(y);
364 }
365
366 return score;
367 }
368
369 public int getNumArguments() {
370 return 1;
371 }
372
373 public double getLowerBound() {
374 return 0;
375 }
376
377 public double getUpperBound() {
378 return 1.0;
379 }
380 };
381
382 // DifferentialEvolution minimum = new DifferentialEvolution(1);
383 // ConjugateDirectionSearch minimum = new ConjugateDirectionSearch();
384 // double[] minx = new double[] { 0.5 };
385 //
386 // double fminx = minimum.findMinimum(f, minx);
387 // double x = minx[0];
388
389 UnivariateMinimum minimum = new UnivariateMinimum();
390 double x = minimum.findMinimum(f);
391
392 double fminx = minimum.fminx;
393 double l1 = x * sumLength;
394 double l2 = (1.0 - x) * sumLength;
395
396 tree.setBranchLength(node1, l1);
397 tree.setBranchLength(node2, l2);
398
399 return fminx;
400 }
401
402 private double findAnalyticalLocalRoot(final FlexibleTree tree,
403 final double[] t,
404 final RootingFunction rootingFunction) {
405
406 if (rootingFunction != RootingFunction.RESIDUAL_MEAN_SQUARED) {
407 throw new UnsupportedOperationException("Analytical local root solution only for residual mean squared");
408 }
409
410 NodeRef node1 = tree.getChild(tree.getRoot(), 0);
411 NodeRef node2 = tree.getChild(tree.getRoot(), 1);
412
413 final double length1 = tree.getBranchLength(node1);
414 final double length2 = tree.getBranchLength(node2);
415
416 final double sumLength = length1 + length2;
417
418 final Set<NodeRef> tipSet1 = TreeUtils.getExternalNodes(tree, node1);
419 final Set<NodeRef> tipSet2 = TreeUtils.getExternalNodes(tree, node2);
420
421 int N = tipSet1.size() + tipSet2.size();
422 int n = tipSet2.size();
423
424 final double[] c = new double[N];
425 for (NodeRef tip : tipSet2) {
426 int i = tip.getNumber();
427 c[i] = 1;
428 }
429
430 final double[] y = getRootToTipDistances(tree);
431 for (int j = 0; j < y.length; j++) { // little fiddling with the root-to-tip divergences to get the right input vector
432 y[j] = y[j] + (1-c[j])*(sumLength-length1) - c[j]*(sumLength-length1);
433 }
434
435 double sum_tt = 0.0;
436 double sum_t = 0.0;
437 double sum_y = 0.0;
438 double sum_ty = 0.0;
439 double sum_tc = 0.0;
440 double Nd = N;
441 double nd = n; // need to set these naughty guys to doubles
442
443 for (int i = 0; i < N; i++) {
444 sum_tt += t[i] * t[i];
445 sum_t += t[i];
446 sum_y += y[i];
447 sum_ty += t[i] * y[i];
448 sum_tc += t[i] * c[i];
449 }
450 double y_bar = sum_y / Nd;
451 double t_bar = sum_t / Nd;
452
453 double C = sum_tt - (sum_t * sum_t / Nd);
454 double sumAB = 0.0;
455 double sumAA = 0.0;
456
457 for (int i = 0; i < N; i++) {
458 double Ai = 2*c[i] -
459 ((2*nd-Nd)/Nd) +
460 (2*(t_bar-t[i])/(C*Nd))*(Nd*sum_tc - nd*sum_t) - 1;
461 double Bi = (y[i] - y_bar)
462 + ((t_bar - t[i]) / (C * Nd)) * ((Nd * sum_ty) - (sum_t * sum_y));
463
464 sumAB += Ai * Bi;
465 sumAA += Ai * Ai;
466 }
467 double x = -sumAB / (sumLength * sumAA);
468 x = Math.min(Math.max(x, 0.0), 1.0);
469
470 double l1 = (1.0 - x) * sumLength;
471 double l2 = x * sumLength;
472
473
474 tree.setBranchLength(node1, l1);
475 tree.setBranchLength(node2, l2);
476
477 Regression r = new Regression(t, getRootToTipDistances(tree));
478
479 return r.getResidualMeanSquared();
480 }
481
482 public double getRootToTipDistance(Tree tree, NodeRef node) {
483 double distance = 0;
484 while (node != null) {
485 distance += tree.getBranchLength(node);
486 node = tree.getParent(node);
487 }
488 return distance;
489 }
490
491 public double getNodeDensity(Tree tree, NodeRef node) {
492 double density = 0;
493 while (node != null) {
494 density ++;
495 node = tree.getParent(node);
496 }
497 return density;
498 }
499
500 public Tree adjustTreeToConstraints(Tree source, Map<Set<String>, double[]> cladeHeights) {
501
502 FlexibleTree tree = new FlexibleTree(source);
503 setHeightsFromDates(tree);
504
505 adjustTreeToConstraints(tree, tree.getRoot(), null, cladeHeights);
506
507 return tree;
508 }
509
510 public int getCurrentRootBranch() {
511 return currentRootBranch;
512 }
513
514 public int getTotalRootBranches() {
515 return totalRootBranches;
516 }
517
518 private double adjustTreeToConstraints(FlexibleTree tree, NodeRef node,
519 Set<String> leaves,
520 Map<Set<String>, double[]> cladeHeights) {
521
522 if (!tree.isExternal(node)) {
523 Set<String> l = new HashSet<String>();
524 double maxChildHeight = 0.0;
525
526 for (int i = 0; i < tree.getChildCount(node); i++) {
527 NodeRef child = tree.getChild(node, i);
528 double h = adjustTreeToConstraints(tree, child, l, cladeHeights);
529 if (h > maxChildHeight) {
530 maxChildHeight = h;
531 }
532 }
533
534 double height = tree.getNodeHeight(node);
535
536 double lower = maxChildHeight;
537 double upper = Double.POSITIVE_INFINITY;
538
539 if (cladeHeights != null) {
540 for (Set<String> clade : cladeHeights.keySet()) {
541 if (clade.equals(l)) {
542 double[] bounds = cladeHeights.get(clade);
543 lower = Math.max(bounds[0], maxChildHeight);
544 upper = bounds[1];
545 }
546 }
547 }
548
549 if (lower > upper) {
550 throw new IllegalArgumentException("incompatible constraints");
551 }
552
553 if (height < lower) {
554 height = lower + 1E-6;
555 } else if (height > upper) {
556 height = (upper + lower) / 2;
557 }
558 tree.setNodeHeight(node, height);
559
560 if (leaves != null) {
561 leaves.addAll(l);
562 }
563 } else {
564 leaves.add(tree.getNodeTaxon(node).getId());
565 }
566 return tree.getNodeHeight(node);
567 }
568
569 private void setHeightsFromDates(FlexibleTree tree) {
570
571 Date mostRecent = null;
572 for (int i = 0; i < taxa.getTaxonCount(); i++) {
573 Date date = taxa.getTaxon(i).getDate();
574 if ((date != null) && (mostRecent == null || date.after(mostRecent))) {
575 mostRecent = date;
576 }
577 }
578
579 if (mostRecent != null) {
580 TimeScale timeScale = new TimeScale(mostRecent.getUnits(), true, mostRecent.getAbsoluteTimeValue());
581 double time0 = timeScale.convertTime(mostRecent.getTimeValue(), mostRecent);
582
583 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
584 NodeRef tip = tree.getExternalNode(i);
585
586 Date date = tree.getNodeTaxon(tip).getDate();
587 if (date != null) {
588 tree.setNodeHeight(tip, timeScale.convertTime(date.getTimeValue(), date) - time0);
589 } else {
590 tree.setNodeHeight(tip, 0.0);
591 }
592 }
593 }
594 }
595
596 }
597