Debian Codegraph @

src/dr/evomodel/coalescent/VDdemographicFunction.java

raw symbols SCIP
1 /*
2 * VDdemographicFunction.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.coalescent;
27
28 import dr.evolution.coalescent.DemographicFunction;
29 import dr.evolution.coalescent.IntervalType;
30 import dr.evolution.coalescent.TreeIntervals;
31 import dr.evolution.tree.Tree;
32
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.List;
36
37 /**
38 * @author Joseph Heled
39 */
40 public class VDdemographicFunction extends DemographicFunction.Abstract {
41 private double[] values;
42 private double[] times;
43 private double[] intervals;
44 private double[][] ttimes;
45 private double[] alltimes;
46 private boolean[] dirtyTrees;
47 boolean dirty;
48
49 private final VariableDemographicModel.Type type;
50
51 TreeIntervals[] ti;
52
53 public VDdemographicFunction(Tree[] trees, VariableDemographicModel.Type type,
54 double[] indicatorParameter, double[] popSizeParameter, boolean logSpace,
55 boolean mid) {
56 super(trees[0].getUnits());
57 this.type = type;
58
59 ti = new TreeIntervals[trees.length];
60 dirtyTrees = new boolean[trees.length];
61 Arrays.fill(dirtyTrees, true);
62 ttimes = new double[ti.length][];
63 int tot = 0;
64 for (int k = 0; k < ti.length; ++k) {
65 ttimes[k] = new double[trees[k].getTaxonCount() - 1];
66 tot += ttimes[k].length;
67 }
68 alltimes = new double[tot];
69
70 setDirty();
71
72 assert !(type == VariableDemographicModel.Type.EXPONENTIAL && !logSpace);
73
74 setup(trees, indicatorParameter, popSizeParameter, logSpace, mid);
75 }
76
77 /**
78 * Reduce memory footprint of object. After a call to freeze only population/intensity
79 * are allowed.
80 */
81 public void freeze() {
82 ttimes = null;
83 alltimes = null;
84 dirtyTrees = null;
85 ti = null;
86 }
87
88 public VDdemographicFunction(VDdemographicFunction demoFunction) {
89 super(demoFunction.getUnits());
90 type = demoFunction.type;
91
92 this.ti = demoFunction.ti.clone();
93 this.values = demoFunction.values.clone();
94 this.times = demoFunction.times.clone();
95 this.intervals = demoFunction.intervals.clone();
96 this.ttimes = demoFunction.ttimes.clone();
97 for (int k = 0; k < ttimes.length; ++k) {
98 ttimes[k] = ttimes[k].clone();
99 }
100
101 this.alltimes = demoFunction.alltimes.clone();
102 this.dirtyTrees = demoFunction.dirtyTrees.clone();
103 this.dirty = demoFunction.dirty;
104 }
105
106 // Hack so that VDdemo can be used as just a linear piecewise demography (the BEAST one is broken)
107 // Alexei fixed PiecewiseLinearPopulation, but did not say yet if it is tested or not.
108
109 public VDdemographicFunction(double[] t, double[] p, Type units) {
110 this(t, p, units, VariableDemographicModel.Type.LINEAR);
111 }
112
113 public VDdemographicFunction(double[] t, double[] p, Type units, VariableDemographicModel.Type type) {
114 super(units);
115 // seem safe to remove them for now
116 // assert t[0] >= 0;
117 // for(int k = 1; k < t.length; ++k) {
118 // assert t[k-1] <= t[k];
119 // }
120 // assert t.length + 1 == p.length;
121 //
122 this.type = type;
123 final int tot = p.length;
124 times = new double[tot + 1];
125 values = p;
126 intervals = new double[tot - 1];
127
128 times[0] = 0.0;
129 times[tot] = Double.POSITIVE_INFINITY;
130
131 // boolean logSpace = false;
132 // values[0] = logSpace ? Math.exp(p[0]) : p[0];
133 System.arraycopy(t, 0, times, 1, t.length);
134
135 for (int n = 0; n < intervals.length; ++n) {
136 intervals[n] = times[n + 1] - times[n];
137 }
138 dirty = false;
139 }
140
141 public int numberOfChanges() {
142 return values.length - 1;
143 }
144
145 public void treeChanged(int nt) {
146 dirtyTrees[nt] = true;
147 setDirty();
148 }
149
150 public void setDirty() {
151 dirty = true;
152 }
153
154 private boolean setTreeTimes(int nt, Tree[] trees) {
155 if (dirtyTrees[nt]) {
156 /*double[] doubles = null;
157 if( ! dirtyTrees[nt] ) {
158 doubles = ttimes[nt].clone();
159
160 }*/
161 ti[nt] = new TreeIntervals(trees[nt]);
162
163 TreeIntervals nti = ti[nt];
164 // make sure we get each coalescent event individually
165 nti.setMultifurcationLimit(0);
166 // code probably incorrect for serial samples
167 final int nLineages = nti.getIntervalCount();
168 assert nLineages >= ttimes[nt].length : nLineages + " " + ttimes[nt].length;
169
170 int iCount = 0;
171 for (int k = 0; k < ttimes[nt].length; ++k) {
172 double timeToCoal = nti.getInterval(iCount);
173 while (nti.getIntervalType(iCount) != IntervalType.COALESCENT) {
174 ++iCount;
175 timeToCoal += nti.getInterval(iCount);
176 }
177
178 int linAtStart = nti.getLineageCount(iCount);
179 ++iCount;
180
181 assert !(iCount == nLineages && linAtStart != 2);
182
183 int linAtEnd = (iCount == nLineages) ? 1 : nti.getLineageCount(iCount);
184
185 while (linAtStart <= linAtEnd) {
186 ++iCount;
187 timeToCoal += nti.getInterval(iCount);
188
189 linAtStart = linAtEnd;
190 ++iCount;
191 linAtEnd = nti.getLineageCount(iCount);
192 }
193 ttimes[nt][k] = timeToCoal + (k == 0 ? 0 : ttimes[nt][k - 1]);
194 }
195
196 /*if( doubles != null ) {
197 if( ! Arrays.equals(doubles, ttimes[nt]) ) {
198 System.out.println(Arrays.toString(doubles) + " != " + Arrays.toString(ttimes[nt])
199 + Arrays.toString(dirtyTrees) + " " + dirtyTrees);
200 }
201 }*/
202 dirtyTrees[nt] = false;
203 // System.out.print(nt + " " + Arrays.toString(dirtyTrees) + " " + dirtyTrees);
204 return true;
205 }
206 return false;
207 }
208
209 void setup(Tree[] trees, double[] indicatorParameter, double[] popSizes, boolean logSpace, boolean mid) {
210 // boolean was = dirty;
211 if (dirty) {
212 // for exponential we do the exp in the code
213 if (type == VariableDemographicModel.Type.EXPONENTIAL) logSpace = false;
214
215 boolean any = false;
216 for (int nt = 0; nt < ti.length; ++nt) {
217 if (setTreeTimes(nt, trees)) {
218 any = true;
219 }
220 }
221
222 final int nd = indicatorParameter.length;
223
224 assert nd == alltimes.length + (type == VariableDemographicModel.Type.STEPWISE ? -1 : 0) :
225 " nd=" + nd + " alltimes.length=" + alltimes.length + " type=" + type;
226
227 if (any) {
228 // now we want to merge times together
229 int[] inds = new int[ttimes.length];
230
231 for (int k = 0; k < alltimes.length; ++k) {
232 int j = 0;
233 while (inds[j] == ttimes[j].length) {
234 ++j;
235 }
236 for (int l = j + 1; l < inds.length; ++l) {
237 if (inds[l] < ttimes[l].length) {
238 if (ttimes[l][inds[l]] < ttimes[j][inds[j]]) {
239 j = l;
240 }
241 }
242 }
243 alltimes[k] = ttimes[j][inds[j]];
244 inds[j]++;
245 }
246 }
247
248 // assumes lowest node has time 0. this is probably problematic when we come
249 // to deal with multiple trees
250
251 int tot = 1;
252
253 for (int k = 0; k < nd; ++k) {
254 if (indicatorParameter[k] > 0) {
255 ++tot;
256 }
257 }
258
259 times = new double[tot + 1];
260 values = new double[tot];
261 intervals = new double[tot - 1];
262
263 times[0] = 0.0;
264 times[tot] = Double.POSITIVE_INFINITY;
265
266 final boolean xx = type == VariableDemographicModel.Type.LINEAR && !logSpace && false;
267 if (xx) {
268 double[] a = alltimes;
269 if (mid) {
270 a = new double[alltimes.length];
271 for (int k = 0; k < a.length; ++k) {
272 a[k] = ((alltimes[k] + (k > 0 ? alltimes[k - 1] : 0)) / 2);
273 }
274 }
275 bestLinearFit(a, popSizes, indicatorParameter, times, values);
276 for (int n = 0; n < intervals.length; ++n) {
277 intervals[n] = times[n + 1] - times[n];
278 }
279 for (int n = 0; n < values.length; ++n) {
280 if (values[n] <= 0) {
281 values[n] = 1e-30;
282 }
283 }
284 }
285
286
287 if (!xx) {
288
289 values[0] = logSpace ? Math.exp(popSizes[0]) : popSizes[0];
290
291 int n = 0;
292 for (int k = 0; k < nd && n + 1 < tot; ++k) {
293
294 if (indicatorParameter[k] > 0) {
295 times[n + 1] = mid ? ((alltimes[k] + (k > 0 ? alltimes[k - 1] : 0)) / 2) : alltimes[k];
296
297 values[n + 1] = logSpace ? Math.exp(popSizes[k + 1]) : popSizes[k + 1];
298 intervals[n] = times[n + 1] - times[n];
299 ++n;
300 }
301 }
302 }
303 dirty = false;
304 }
305 //
306 /*System.out.println("after setup " + (was ? "(dirty)" : "") + " , alltimes " + Arrays.toString(alltimes)
307 + " times " + Arrays.toString(times) + " values " + Arrays.toString(values) +
308 " inds " + Arrays.toString(indicatorParameter.getParameterValues())) ;*/
309 }
310
311 private int ti2f(int i, int j) {
312 return (i == 0) ? j : 2 * i + j + 1;
313 }
314
315 private void
316 bestLinearFit(double[] xs, double[] ys, double[] use, double[] ot, double[] oz) {
317
318 assert (xs.length + 1) == ys.length;
319 assert ys.length == use.length + 2 || ys.length == use.length + 1;
320
321 int N = ys.length;
322 if (N == 2) {
323 // cheaper
324 assert xs.length == ot.length;
325 assert ys.length == oz.length;
326 System.arraycopy(xs, 0, ot, 0, xs.length);
327 System.arraycopy(ys, 0, oz, 0, ys.length);
328 //return new VDdemographicFunction(xs, ys, getUnits());
329 }
330
331 List<Integer> iv = new ArrayList<Integer>(2);
332 iv.add(0);
333 for (int k = 0; k < N - 1; ++k) {
334 if (use[k] > 0) {
335 iv.add(k + 1);
336 }
337 }
338 // iv.add(N-1);
339
340 double[] ati = new double[xs.length + 1];
341 ati[0] = 0.0;
342 System.arraycopy(xs, 0, ati, 1, xs.length);
343 int n = iv.size();
344
345 double[] a = new double[3 * n];
346 double[] v = new double[n];
347
348 for (int k = 0; k < n - 1; ++k) {
349 int i0 = iv.get(k);
350 int i1 = iv.get(k + 1);
351
352 double u0 = ati[i0];
353 double u1 = ati[i1] - ati[i0];
354 // on last interval add data for last point
355 // if( i1 == N-1 ) {
356 // i1 += 1;
357 // }
358
359 final int l = ti2f(k, k);
360 final int l1 = ti2f(k + 1, k);
361
362 for (int j = i0; j < i1; ++j) {
363 double t = ati[j];
364 double y = ys[j];
365
366 double z = (t - u0) / u1;
367 v[k] += y * (1 - z);
368
369 a[l] += (1 - z) * (1 - z);
370 a[l + 1] += z * (1 - z);
371
372 a[l1] += z * (1 - z);
373 a[l1 + 1] += z * z;
374 v[k + 1] += y * z;
375 }
376 }
377
378 {
379 int k = n - 1;
380 int i0 = iv.get(k);
381 int i1 = ys.length;
382 final int l = ti2f(k, k);
383 for (int j = i0; j < i1; ++j) {
384 a[l] += 1;
385 v[k] += ys[j];
386 }
387 }
388
389 for (int k = 0; k < n - 1; ++k) {
390
391 final double r = a[ti2f(k + 1, k)] / a[ti2f(k, k)];
392 for (int j = k; j < k + 3; ++j) {
393 a[ti2f((k + 1), j)] -= a[ti2f(k, j)] * r;
394 }
395 v[k + 1] -= v[k] * r;
396 }
397 if (oz.length != n) {
398 n = 3;
399 }
400 assert oz.length == n;
401 //double[] oz = new double[n];
402 for (int k = n - 1; k > 0; --k) {
403 oz[k] = v[k] / a[ti2f(k, k)];
404 v[k - 1] -= a[ti2f((k - 1), k)] * oz[k];
405 }
406
407 oz[0] = v[0] / a[ti2f(0, 0)];
408 // first and last in ot are reserved
409 assert ot.length - 2 == iv.size() - 1;
410
411 for (int j = 1; j < ot.length - 1; ++j) {
412 ot[j] = ati[iv.get(j)];
413 }
414 }
415
416 private int getIntervalIndexStep(final double t) {
417 int j = 0;
418 // ugly hack,
419 // when doubles are added in a different order and compared later, they can be a tiny bit off. With a
420 // stepwise model this creates a "one off" situation here, which is unpleasant.
421 // use float comparison here to avoid it
422
423 final float tf = (float) t;
424 while (tf > (float) times[j + 1]) ++j;
425 return j;
426 }
427
428 private int getIntervalIndexLin(final double t) {
429 int j = 0;
430 while (t > times[j + 1]) ++j;
431 return j;
432 }
433
434 private double linPop(double t) {
435 final int j = getIntervalIndexLin(t);
436 if (j == values.length - 1) {
437 return values[j];
438 }
439
440 final double a = (t - times[j]) / (intervals[j]);
441 return a * values[j + 1] + (1 - a) * values[j];
442 }
443
444 public double getDemographic(double t) {
445
446 double p;
447 switch (type) {
448 case STEPWISE: {
449 final int j = getIntervalIndexStep(t);
450 p = values[j];
451 break;
452 }
453 case LINEAR: {
454 p = linPop(t);
455 break;
456 }
457 case EXPONENTIAL: {
458 p = Math.exp(linPop(t));
459 break;
460 }
461 default:
462 throw new IllegalArgumentException("");
463
464 }
465 return p;
466 }
467
468 public double getIntensity(double t) {
469 return getIntegral(0, t);
470 }
471
472 public double getInverseIntensity(double x) {
473 assert false;
474 return 0;
475 }
476
477 private double intensityLinInterval(double start, double end, int index) {
478 final double dx = end - start;
479 if (dx == 0) {
480 return 0;
481 }
482
483 final double popStart = values[index];
484 final double popDiff = (index < values.length - 1) ? values[index + 1] - popStart : 0.0;
485 if (popDiff == 0.0) {
486 return dx / popStart;
487 }
488 final double time0 = times[index];
489 final double interval = intervals[index];
490
491 assert (float) start <= (float) (time0 + interval) && start >= time0 && (float) end <= (float) (time0 + interval) && end >= time0;
492
493 // final double pop0 = popStart + ((start - time0) / interval) * popDiff;
494 // final double pop1 = popStart + ((end - time0) / interval) * popDiff;
495
496 // do same as above more efficiently
497 // final double r = popDiff / interval;
498 // final double x = popStart - time0 * r;
499 // final double pop0 = x + start * r;
500 // final double pop1 = x + end * r;
501 //better numerical stability but not perfect
502 final double p1minusp0 = ((end - start) / interval) * popDiff;
503
504 final double v = interval * (popStart / popDiff);
505 final double p1overp0 = (v + (end - time0)) / (v + (start - time0));
506 if (p1minusp0 == 0.0 || p1overp0 <= 0) {
507 // either dx == 0 or is very small (numerical inaccuracy)
508 final double pop0 = popStart + ((start - time0) / interval) * popDiff;
509 return dx / pop0;
510 }
511
512 return dx * Math.log(p1overp0) / p1minusp0;
513 // return dx * Math.log(pop1/pop0) / (pop1 - pop0);*/
514 }
515
516 private double intensityLinInterval(int index) {
517 final double interval = intervals[index];
518 final double pop0 = values[index];
519 final double pop1 = values[index + 1];
520 if (pop0 == pop1) {
521 return interval / pop0;
522 }
523 return interval * Math.log(pop1 / pop0) / (pop1 - pop0);
524 }
525
526 private double intensityExpInterval(double start, double end, int index) {
527 final double pop0 = values[index];
528
529 if (index == intervals.length) {
530 // on last interval
531 return (end - start) / Math.exp(pop0);
532 }
533
534 final double interval = intervals[index];
535
536 final double pop1 = values[index + 1];
537 final double time0 = times[index];
538
539 assert start >= time0 && (float) start <= (float) (time0 + interval) && (float) end <= (float) (time0 + interval) && end >= time0;
540
541 final double a = (pop0 - pop1) / interval;
542 if (a == 0) {
543 return (end - start) / Math.exp(pop0);
544 }
545 return (Math.exp((end - time0) * a - pop0) - Math.exp((start - time0) * a - pop0)) / a;
546 }
547
548 private double intensityExpInterval(int index) {
549 final double interval = intervals[index];
550 final double pop0 = values[index];
551 final double pop1 = values[index + 1];
552
553 final double a = (pop0 - pop1) / interval;
554 if (a == 0) {
555 return interval / Math.exp(pop0);
556 }
557 return Math.exp(-pop0) / a * (Math.exp(interval * a) - 1);
558 }
559
560 public double getIntegral(double start, double finish) {
561
562 double intensity = 0.0;
563
564 switch (type) {
565 case STEPWISE: {
566 final int first = getIntervalIndexStep(start);
567 final int last = getIntervalIndexStep(finish);
568
569 final double popStart = values[first];
570 if (first == last) {
571 intensity = (finish - start) / popStart;
572 } else {
573 intensity = (times[first + 1] - start) / popStart;
574
575 for (int k = first + 1; k < last; ++k) {
576 intensity += intervals[k] / values[k];
577 }
578 intensity += (finish - times[last]) / values[last];
579 }
580 break;
581 }
582 case LINEAR: {
583 final int first = getIntervalIndexLin(start);
584 final int last = getIntervalIndexLin(finish);
585
586 if (first == last) {
587 intensity += intensityLinInterval(start, finish, first);
588 } else {
589 // from first to end of interval
590 intensity += intensityLinInterval(start, times[first + 1], first);
591 // intervals until (not including) last
592 for (int k = first + 1; k < last; ++k) {
593 intensity += intensityLinInterval(k);
594 }
595 // last interval
596 intensity += intensityLinInterval(times[last], finish, last);
597 }
598 break;
599 }
600 case EXPONENTIAL: {
601 final int first = getIntervalIndexLin(start);
602 final int last = getIntervalIndexLin(finish);
603
604 if (first == last) {
605 intensity += intensityExpInterval(start, finish, first);
606 } else {
607 // from first to end of interval
608 intensity += intensityExpInterval(start, times[first + 1], first);
609 // intervals until (not including) last
610 for (int k = first + 1; k < last; ++k) {
611 intensity += intensityExpInterval(k);
612 }
613 // last interval
614 intensity += intensityExpInterval(times[last], finish, last);
615 }
616 break;
617 }
618 }
619 return intensity;
620 }
621
622 public int getNumArguments() {
623 assert false;
624 return 0;
625 }
626
627 public String getArgumentName(int n) {
628 assert false;
629 return null;
630 }
631
632 public double getArgument(int n) {
633 assert false;
634 return 0;
635 }
636
637 public void setArgument(int n, double value) {
638 assert false;
639 }
640
641 public double getLowerBound(int n) {
642 return 0.0;
643 }
644
645 public double getUpperBound(int n) {
646 return Double.POSITIVE_INFINITY;
647 }
648
649 public DemographicFunction getCopy() {
650 return null;
651 }
652
653 public double getThreshold() {
654 return 1E-12;
655 }
656
657 // not sure why we need this here
658
659 public double value(double x) {
660 return 1.0 / getDemographic(x);
661 }
662
663 public TreeIntervals getTreeIntervals(int nt) {
664 return ti[nt];
665 }
666
667 public double[] allTimePoints() {
668 return alltimes;
669 }
670
671 public double[] times() {
672 double[] valuesCopy = new double[times.length -2];
673 System.arraycopy(times, 1, valuesCopy, 0, times.length-2);
674 // defensive copy
675 return valuesCopy;
676 }
677
678 /**
679 * @return population values transformed depending on type (i.e. exp(value) for Type.EXPONENTIAL)
680 */
681 public double[] values() {
682 double[] valuesCopy = new double[values.length];
683 if (type == VariableDemographicModel.Type.EXPONENTIAL) {
684 for (int i = 0; i < values.length; i++) {
685 valuesCopy[i] = Math.exp(values[i]);
686 }
687 } else {
688 System.arraycopy(values, 0, valuesCopy, 0, values.length);
689 }
690 return valuesCopy;
691 }
692
693 // public String toString() {
694 // final StringBuilder sb = new StringBuilder(32);
695 //
696 // for (int k = 1; k < times.length - 1; ++k) {
697 // if (k > 1) {
698 // sb.append(",");
699 // }
700 // sb.append(times[k]);
701 // }
702 // sb.append("|");
703 // sb.append(type == VariableDemographicModel.Type.EXPONENTIAL ? Math.exp(values[0]) : values[0]);
704 // for (int k = 1; k < values.length; ++k) {
705 //
706 // sb.append(",");
707 // final double value = values[k];
708 // sb.append(type == VariableDemographicModel.Type.EXPONENTIAL ? Math.exp(value) : value);
709 // }
710 // return sb.toString();
711 // }
712
713 public double naturalLimit() {
714 return times[times.length - 2];
715 }
716 }
717