Debian Codegraph @

src/dr/evomodel/speciation/CalibrationPoints.java

raw symbols SCIP
1 /*
2 * CalibrationPoints.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.evomodel.speciation;
27
28 import dr.evolution.tree.NodeRef;
29 import dr.evolution.tree.Tree;
30 import dr.evolution.tree.TreeUtils;
31 import dr.evolution.util.Taxa;
32 import dr.inference.model.Statistic;
33 import dr.math.distributions.Distribution;
34
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.List;
38
39 /**
40 * @author Joseph Heled
41 * Date: 8/06/2011
42 */
43 public class CalibrationPoints {
44
45 public static enum CorrectionType {
46 EXACT("exact"),
47 APPROXIMATED("approximated"),
48 PEXACT("pexact"),
49 NONE("none");
50
51 CorrectionType(String name) {
52 this.name = name;
53 }
54
55 public String toString() {
56 return name;
57 }
58
59 private final String name;
60 }
61
62 public CalibrationPoints(Tree tree, boolean isYule, List<Distribution> dists, List<Taxa> clades,
63 List<Boolean> forParent, Statistic userPDF, CorrectionType correctionType) {
64
65 this.densities = new Distribution[dists.size()];
66 this.clades = new int[clades.size()][];
67 this.forParent = new boolean[clades.size()];
68
69 for (int k = 0; k < clades.size(); ++k) {
70 final Taxa tk = clades.get(k);
71 for (int i = k + 1; i < clades.size(); ++i) {
72 final Taxa ti = clades.get(i);
73 if (ti.containsAny(tk)) {
74 if (!(ti.containsAll(tk) || tk.containsAll(ti))) {
75 throw new IllegalArgumentException("Overlapping clades??");
76 }
77 }
78 }
79 }
80
81 Taxa[] taxaInOrder = new Taxa[clades.size()];
82
83 {
84 int loc = clades.size() - 1;
85 while (loc >= 0) {
86 // place maximal clades at end one at a time
87 int k = 0;
88 for (/**/; k < clades.size(); ++k) {
89 if (isMaximal(clades, k)) {
90 break;
91 }
92 }
93 this.densities[loc] = dists.remove(k);
94 this.forParent[loc] = forParent.remove(k);
95
96 final Taxa tk = clades.get(k);
97 final int tkcount = tk.getTaxonCount();
98 this.clades[loc] = new int[tkcount];
99 for (int nt = 0; nt < tkcount; ++nt) {
100 final int taxonIndex = tree.getTaxonIndex(tk.getTaxon(nt));
101 this.clades[loc][nt] = taxonIndex;
102 if (taxonIndex < 0) {
103 throw new IllegalArgumentException("Taxon not found in tree: " + tk.getTaxon(nt));
104 }
105 }
106 taxaInOrder[loc] = tk;
107 clades.remove(k);
108
109 --loc;
110 }
111 }
112
113 List<Integer>[] tio = new List[taxaInOrder.length];
114 for (int k = 0; k < taxaInOrder.length; ++k) {
115 tio[k] = new ArrayList<Integer>();
116 }
117
118 for (int k = 0; k < taxaInOrder.length; ++k) {
119 for (int i = k + 1; i < taxaInOrder.length; ++i) {
120 if (taxaInOrder[i].containsAll(taxaInOrder[k])) {
121 tio[i].add(k);
122 break;
123 }
124 }
125 }
126
127 this.taxaPartialOrder = new int[taxaInOrder.length][];
128 for (int k = 0; k < taxaInOrder.length; ++k) {
129 List<Integer> tiok = tio[k];
130
131 this.taxaPartialOrder[k] = new int[tiok.size()];
132 for (int j = 0; j < tiok.size(); ++j) {
133 this.taxaPartialOrder[k][j] = tiok.get(j);
134 }
135 }
136 this.freeHeights = new int[this.clades.length];
137
138 for (int k = 0; k < this.clades.length; ++k) {
139 int taken = 0;
140 for (int i : this.taxaPartialOrder[k]) {
141 taken += this.clades[i].length - (this.forParent[i] ? 0 : 1);
142 }
143 this.freeHeights[k] = this.clades[k].length - (this.forParent[k] ? 1 : 2) - taken;
144 assert this.freeHeights[k] >= 0;
145 }
146
147 // true if clade is not contained in any other clade
148 boolean[] maximal = new boolean[this.clades.length];
149 for (int k = 0; k < this.clades.length; ++k) {
150 maximal[k] = true;
151 }
152
153 for (int k = 0; k < this.clades.length; ++k) {
154 for (int i : this.taxaPartialOrder[k]) {
155 maximal[i] = false;
156 }
157 }
158
159 rootCorrection = this.clades[this.clades.length - 1].length < tree.getExternalNodeCount();
160
161 this.calibrationLogPDF = userPDF;
162
163 this.correctionType = correctionType;
164
165 if (userPDF == null) {
166 if (!isYule) {
167 throw new IllegalArgumentException("Sorry, not implemented: conditional calibration prior for this non Yule models.");
168 }
169
170 if (correctionType == CorrectionType.EXACT) {
171 if (densities.length == 1) {
172 // closed form formula
173 } else {
174 boolean anyParent = false;
175 for (boolean in : this.forParent) {
176 if (in) {
177 anyParent = true;
178 }
179 }
180 if (anyParent) {
181 throw new IllegalArgumentException("Sorry, not implemented: calibration on parent for more than one clade.");
182 }
183 if (densities.length == 2 && taxaInOrder[1].containsAll(taxaInOrder[0])) {
184 // closed form formulas
185 } else {
186 setUpTables(tree);
187 linsIter = new CalibrationLineagesIterator(this.clades, this.taxaPartialOrder, maximal,
188 tree.getExternalNodeCount());
189 lastHeights = new double[this.clades.length];
190 }
191 }
192 } else if (correctionType == CorrectionType.PEXACT) {
193 setUpTables(tree);
194 }
195 }
196 }
197
198 private void setUpTables(Tree tree) {
199 final int MAX_N = tree.getExternalNodeCount() + 1;
200 double[] lints = new double[MAX_N];
201 lc2 = new double[MAX_N];
202 lfactorials = new double[MAX_N];
203 lNR = new double[MAX_N];
204
205 lints[0] = Double.NEGATIVE_INFINITY; //-infinity, should never be used
206 lints[1] = 0.0;
207 for (int i = 2; i < MAX_N; ++i) {
208 lints[i] = Math.log(i);
209 }
210
211 lc2[0] = lc2[1] = Double.NEGATIVE_INFINITY;
212 for (int i = 2; i < MAX_N; ++i) {
213 lc2[i] = lints[i] + lints[i - 1] - lg2;
214 }
215
216 lfactorials[0] = 0.0;
217 for (int i = 1; i < MAX_N; ++i) {
218 lfactorials[i] = lfactorials[i - 1] + lints[i];
219 }
220
221 lNR[0] = Double.NEGATIVE_INFINITY; //-infinity, should never be used
222 lNR[1] = 0.0;
223
224 for (int i = 2; i < MAX_N; ++i) {
225 lNR[i] = lNR[i - 1] + lc2[i];
226 }
227 }
228
229 private boolean isMaximal(List<Taxa> taxa, int k) {
230 final Taxa tk = taxa.get(k);
231 for (int i = 0; i < taxa.size(); ++i) {
232 if (i != k) {
233 final Taxa ti = taxa.get(i);
234 if (ti.containsAll(tk)) {
235 return false;
236 }
237 }
238 }
239 return true;
240 }
241
242 public double getCorrection(Tree tree, final double lam) {
243 double logL = 0.0;
244 final int nDists = densities.length;
245 double hs[] = new double[nDists];
246
247 for (int k = 0; k < nDists; ++k) {
248 NodeRef c;
249 final int[] taxk = clades[k];
250 if (taxk.length > 1) {
251 // check if monophyly and find node
252 c = TreeUtils.getCommonAncestor(tree, taxk);
253
254 if (TreeUtils.getLeafCount(tree, c) != taxk.length) {
255 return Double.NEGATIVE_INFINITY;
256 }
257 } else {
258 c = tree.getNode(taxk[0]);
259 assert forParent[k];
260 }
261
262 if (forParent[k]) {
263 c = tree.getParent(c);
264 }
265
266 final double h = tree.getNodeHeight(c);
267 logL += densities[k].logPdf(h);
268
269 hs[k] = h;
270 }
271
272 if (Double.isInfinite(logL)) {
273 return logL;
274 }
275
276 if (correctionType == CorrectionType.NONE) {
277 return logL;
278 }
279
280
281 if (calibrationLogPDF == null) {
282 switch (correctionType) {
283 case EXACT: {
284 if (nDists == 1) {
285 logL -= logMarginalDensity(lam, tree.getExternalNodeCount(), hs[0], clades[0].length, forParent[0]);
286 } else if (nDists == 2 && taxaPartialOrder[1].length == 1) {
287 assert !forParent[0] && !forParent[1];
288 logL -= logMarginalDensity(lam, tree.getExternalNodeCount(), hs[0], clades[0].length,
289 hs[1], clades[1].length);
290 } else {
291
292 if (lastLam == lam) {
293 int k = 0;
294 for (; k < hs.length; ++k) {
295 if (hs[k] != lastHeights[k]) {
296 break;
297 }
298 }
299 if (k == hs.length) {
300 return lastValue;
301 }
302 }
303
304 // the slow and painful way
305 double[] hss = new double[hs.length];
306 int[] ranks = new int[hs.length];
307 for (int k = 0; k < hs.length; ++k) {
308 int r = 0;
309 for (double h : hs) {
310 r += (h < hs[k]) ? 1 : 0;
311 }
312 ranks[k] = r + 1;
313 hss[r] = hs[k];
314 }
315 logL -= logMarginalDensity(lam, hss, ranks, linsIter);
316
317 lastLam = lam;
318 System.arraycopy(hs, 0, lastHeights, 0, lastHeights.length);
319 lastValue = logL;
320 }
321 break;
322 }
323 case APPROXIMATED: {
324
325 final double loglam = Math.log(lam);
326
327 int maxh = 0;
328 for (int k = 0; k < nDists; ++k) {
329 final double v = -lam * hs[k];
330
331 if (freeHeights[k] > 0) {
332 logL -= Math.log1p(-Math.exp(v)) * freeHeights[k];
333 }
334
335 logL -= v + loglam;
336
337 if (hs[k] > hs[maxh]) {
338 maxh = k;
339 }
340 }
341
342 if (rootCorrection || true) {
343 logL -= -(forParent[maxh] ? 0 : 1) * lam * hs[maxh];
344 }
345
346 if (Double.isNaN(logL)) {
347 logL = Double.NEGATIVE_INFINITY;
348 }
349 break;
350 }
351 case PEXACT: {
352 Arrays.sort(hs);
353 int cs[] = new int[nDists + 1];
354
355 final int internalNodeCount = tree.getInternalNodeCount();
356 for (int k = 0; k < internalNodeCount; ++k) {
357 final double nhk = tree.getNodeHeight(tree.getInternalNode(k));
358 int i = 0;
359 for (/**/; i < hs.length; ++i) {
360 if (hs[i] >= nhk) {
361 break;
362 }
363 }
364 if (i == hs.length) {
365 cs[i]++;
366 } else {
367 if (nhk < hs[i]) {
368 cs[i]++;
369 }
370 }
371 }
372
373 if (false) {
374 int l = nDists;
375 for (int i = 0; i < cs.length; ++i) {
376 l += cs[i];
377 }
378 assert l == internalNodeCount;
379 }
380 double ll = 0;
381
382 ll += cs[0] * Math.log1p(-Math.exp(-lam * hs[0])) - lam * hs[0] - lfactorials[cs[0]];
383 for (int i = 1; i < cs.length - 1; ++i) {
384 int c = cs[i];
385 ll += c * (Math.log1p(-Math.exp(-lam * (hs[i] - hs[i - 1]))) - lam * hs[i - 1]);
386 ll += -lam * hs[i] - lfactorials[c];
387 }
388 ll += -lam * (cs[nDists] + 1) * hs[nDists - 1] - lfactorials[cs[nDists] + 1];
389 ll += Math.log(lam) * nDists;
390
391 logL -= ll;
392 break;
393 }
394 }
395 } else {
396 final double value = calibrationLogPDF.getStatisticValue(0);
397 if (Double.isNaN(value) || Double.isInfinite(value)) {
398 logL = Double.NEGATIVE_INFINITY;
399 } else {
400 logL -= value;
401 }
402 }
403 return logL;
404 }
405
406 private double logMarginalDensity(final double lam, int nTaxa, final double h, int nClade, boolean forParent) {
407 double lgp;
408
409 final double lh = lam * h;
410
411 if (forParent) {
412 // n(n+1) factor left out
413
414 lgp = -2 * lh + Math.log(lam);
415 if (nClade > 1) {
416 lgp += (nClade - 1) * Math.log(1 - Math.exp(-lh));
417 }
418 } else {
419 assert nClade > 1;
420
421 lgp = -3 * lh + (nClade - 2) * Math.log(1 - Math.exp(-lh)) + Math.log(lam);
422
423 // root is a special case
424 if (nTaxa == nClade) {
425 // n(n-1) factor left out
426 lgp += lh;
427 } else {
428 // (n^3-n)/2 factor left out
429 }
430 }
431
432 return lgp;
433 }
434
435 private double logMarginalDensity(final double lam, final int nTaxa, double h2, final int n, double h1, int nm) {
436
437 assert h2 <= h1 && n < nm;
438
439 final int m = nm - n;
440
441 final double elh2 = Math.exp(-lam * h2);
442 final double elh1 = Math.exp(-lam * h1);
443
444 double lgl = 2 * Math.log(lam);
445
446 lgl += (n - 2) * Math.log(1 - elh2);
447 lgl += (m - 3) * Math.log(1 - elh1);
448
449 lgl += Math.log(1 - 2 * m * elh1 + 2 * (m - 1) * elh2
450 - m * (m - 1) * elh1 * elh2 + (m * (m + 1) / 2.) * elh1 * elh1
451 + ((m - 1) * (m - 2) / 2.) * elh2 * elh2);
452
453 if (nm < nTaxa) {
454 /* lgl += Math.log(0.5*(n*(n*n-1))*(n+1+m)) */
455 lgl -= lam * (h2 + 3 * h1);
456 } else {
457 /* lgl += Math.log(lam) /* + Math.log(n*(n*n-1)) */
458 lgl -= lam * (h2 + 2 * h1);
459 }
460
461 return lgl;
462 }
463
464 private double logMarginalDensity(final double lam, double[] hs, int[] ranks, CalibrationLineagesIterator cli) {
465
466 final int ni = cli.setup(ranks);
467
468 final int nHeights = hs.length;
469
470 double[] lehs = new double[nHeights + 1];
471 lehs[0] = 0.0;
472 for (int i = 1; i < lehs.length; ++i) {
473 lehs[i] = -lam * hs[i - 1];
474 }
475
476 // assert maxRank == len(sit)
477 boolean noRoot = ni == lehs.length;
478
479 int nLevels = nHeights + (noRoot ? 1 : 0);
480
481 double[] lebase = new double[nLevels];
482
483 for (int i = 0; i < nHeights; ++i) {
484 lebase[i] = lehs[i] + Math.log1p(-Math.exp(lehs[i + 1] - lehs[i]));
485 }
486
487 if (noRoot) {
488 lebase[nHeights] = lehs[nHeights];
489 }
490
491 int[] linsAtLevel = new int[nLevels];
492
493 int[][] joiners = cli.allJoiners();
494
495 double val = 0;
496 boolean first = true;
497
498 int[][] linsInLevels;
499 int ccc = 0;
500 while ((linsInLevels = cli.next()) != null) {
501 ccc++;
502 double v = countRankedTrees(nLevels, linsInLevels, joiners, linsAtLevel);
503 // 1 for root formula, 1 for kludge in iterator which sets root as 2 lineages
504 if (noRoot) {
505 final int ll = linsAtLevel[nLevels - 1] + 2;
506 linsAtLevel[nLevels - 1] = ll;
507
508 v -= lc2[ll] + lg2;
509 }
510
511 for (int i = 0; i < nLevels; ++i) {
512 v += linsAtLevel[i] * lebase[i];
513 }
514
515 if (first) {
516 val = v;
517 first = false;
518 } else {
519 if (val > v) {
520 val += Math.log1p(Math.exp(v - val));
521 } else {
522 val = v + Math.log1p(Math.exp(val - v));
523 }
524 }
525 }
526
527 double logc0 = 0.0;
528 int totLin = 0;
529 for (int i = 0; i < ni; ++i) {
530 final int l = cli.nStart(i);
531 if (l > 0) {
532 logc0 += lNR[l];
533 totLin += l;
534 }
535 }
536
537 final double logc1 = lfactorials[totLin];
538
539 double logc2 = nHeights * Math.log(lam);
540
541 for (int i = 1; i < nHeights + 1; ++i) {
542 logc2 += lehs[i];
543 }
544
545 if (!noRoot) {
546 // we dont have an iterator for 0 free lineages
547 logc2 += 1 * lehs[nHeights];
548 }
549
550 // Missing scale by total of all possible trees over all ranking orders.
551 // Add it outside if needed for comparison.
552
553 val += logc0 + logc1 + logc2;
554
555 return val;
556 }
557
558 private double
559 countRankedTrees(final int nLevels, final int[][] linsAtCrossings, final int[][] joiners, int[] linsAtLevel) {
560 double logCount = 0;
561
562 for (int i = 0; i < nLevels; ++i) {
563 int sumLins = 0;
564 for (int k = i; k < nLevels; ++k) {
565 int[] lack = linsAtCrossings[k];
566 int cki = lack[i];
567 if (joiners[k][i] > 0) {
568 ++cki;
569 if (cki > 1) {
570 // can be 1 if iterator without lins - for joiners only - need to check this is correct
571 logCount += lc2[cki];
572 } //assert(cki >= 2);
573 }
574 final int l = cki - lack[i + 1]; //assert(l >= 0);
575 logCount -= lfactorials[l];
576 sumLins += l;
577 }
578 linsAtLevel[i] = sumLins;
579 }
580
581 return logCount;
582 }
583
584 // Flavour of marginal computation.
585 private final CorrectionType correctionType;
586
587 // Calibrated clades, each as a list of node ids.
588 // Clades are partially ordered by inclusion - if X <= Y then X appears before Y.
589 private final int[][] clades;
590
591 // One calibration density associated with each clade
592 private final Distribution[] densities;
593
594 // true if density is for clade parent
595 private final boolean[] forParent;
596
597 // For each clade, lists the clades contained in it (using their index in clades)
598 private final int[][] taxaPartialOrder;
599
600 private final int[] freeHeights;
601
602 private final boolean rootCorrection;
603
604 // User provided function to calculate the marginal density
605 private final Statistic calibrationLogPDF;
606
607 // speedup constants
608 private final double lg2 = Math.log(2.0);
609 private double[] lc2;
610 private double[] lNR;
611 private double[] lfactorials;
612
613 private CalibrationLineagesIterator linsIter = null;
614
615 // simple cache of last result can go a long way in a big tree with a few calibration nodes, for non-global tree operators which do
616 // not change the calibration nodes heights.
617
618 double lastLam = Double.NEGATIVE_INFINITY;
619 double[] lastHeights;
620 double lastValue = Double.NEGATIVE_INFINITY;
621 }