Debian Codegraph @

src/dr/inference/markovjumps/TwoStateSericolaSeriesMarkovReward.java

raw symbols SCIP
1 /*
2 * TwoStateSericolaSeriesMarkovReward.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.inference.markovjumps;
27
28 import dr.evomodel.substmodel.DefaultEigenSystem;
29 import dr.evomodel.substmodel.EigenDecomposition;
30 import dr.evomodel.substmodel.EigenSystem;
31 import dr.math.Binomial;
32 import dr.math.GammaFunction;
33 import dr.math.matrixAlgebra.Matrix;
34 import dr.math.matrixAlgebra.Vector;
35
36 /**
37 * @author Marc Suchard
38 * @author Forrest Crawford
39 */
40 public class TwoStateSericolaSeriesMarkovReward implements MarkovReward {
41
42 // Following Bladt, Meini, Neuts and Sericola (2002).
43 // Assuming each state has a distinct reward, i.e. \phi + 1 = stateCount,
44 // and states are sorted in increasing reward order
45
46 private static final boolean DEBUG = true;
47 private static final boolean DEBUG2 = false;
48
49 public TwoStateSericolaSeriesMarkovReward(double[] Q, double[] r, int dim) {
50 this(Q, r, dim, 1E-10);
51 }
52
53 public TwoStateSericolaSeriesMarkovReward(double[] Q, double[] r, int dim, double epsilon) {
54 this.Q = Q;
55 this.r = r;
56 this.maxTime = 0;
57 this.epsilon = epsilon;
58
59 this.dim = dim;
60 lambda = determineLambda();
61
62 phi = dim - 1;
63
64 if (DEBUG2) {
65 System.err.println("lambda = " + lambda);
66 }
67
68 P = initializeP(Q, lambda);
69 eigenSystem = new DefaultEigenSystem(dim);
70 }
71
72 private double[][] initializeW(int times, int dim) {
73 return new double[times][dim * dim];
74 }
75
76 private int getHfromX(double x, double time) {
77 // TODO assert x > h[0] * time;
78 int h = 1;
79 while (x >= r[h] * time) {
80 h++;
81 }
82 return h;
83 }
84
85 private void growC(double time, int extraN) {
86 int newN = getNfromC();
87 if (time > maxTime) {
88 newN = determineNumberOfSteps(time, lambda) + extraN;
89 maxTime = time;
90 }
91
92 // Grow C if necessary
93 if (newN > getNfromC()) {
94 if (DEBUG && newN > 200) {
95 System.err.println("Growing C to N = " + newN + " with " + maxTime);
96 }
97 if (newN > 500) {
98 System.err.println("Warning: > 500 recursion depth in SericolaSeriesMarkovReward");
99 }
100 initializeSpace(phi, newN);
101 computeChnk();
102 }
103 }
104
105 // START: internal structure of C
106
107 private double[][][][] internalC; // TODO Linearize for store/restore; TODO reduce to minimal storage
108
109 private void initializeSpace(int phi, int N) {
110 internalC = new double[phi + 1][N + 1][N + 1][dim * dim];
111 // indices [h][n][k][B_u][B_v]
112 }
113
114 private double[] C(int h, int n, int k) {
115 return internalC[h][n][k];
116 }
117
118 private int getNfromC() {
119 return (internalC == null) ? -1 : internalC[0].length - 1;
120 }
121
122 private int idx(int i, int j) {
123 return i * dim + j; // row-major
124 }
125
126 // END: internal structure of C, TODO Change to expandable list
127
128 private int[] getHfromX(double[] X, double time) {
129 int[] H = new int[X.length];
130 for (int i = 0; i < X.length; ++i) {
131 H[i] = getHfromX(X[0], time);
132 }
133 return H;
134 }
135
136 public double computePdf(double x, double time, int i, int j) {
137 growC(time, 1);
138
139 int uv = i * dim + j;
140
141 // double[][] W = initializeW(1, dim); // initialize with zeros
142 double w = 0.0;
143
144 final int N = getNfromC() - 1;
145 for (int n = 0; n <= N; ++n) {
146 w += accumulatePdf(x, n, time, uv);
147 }
148
149 // if (DEBUG2) {
150 // for (int i = 0; i < W.length; ++i) {
151 // System.err.println("W'[" + i + "]:\n" + new Matrix(squareMatrix(W[i])));
152 // }
153 // System.err.println("");
154 // }
155
156 return w;
157 }
158
159 public double[] computePdf(double x, double time) {
160 return computePdf(new double[]{x}, time)[0];
161 }
162
163
164 public double[][] computePdf(double[] X, double time) {
165 // int[] H = getHfromX(X, time);
166
167 growC(time, 1);
168
169 double[][] W = initializeW(X.length, dim); // initialize with zeros
170
171 final int N = getNfromC() - 1;
172 for (int n = 0; n <= N; ++n) {
173 accumulatePdf(W, X, n, time); // TODO This can be sped up when only a single entry is wanted
174 }
175
176 if (DEBUG2) {
177 for (int i = 0; i < W.length; ++i) {
178 System.err.println("W'[" + i + "]:\n" + new Matrix(squareMatrix(W[i])));
179 }
180 System.err.println("");
181 }
182
183 return W;
184 }
185
186 public double computeCdf(double x, double time, int i, int j) {
187 return computeCdf(x, time)[i * dim + j];
188 }
189
190 public double[] computeCdf(double x, double time) {
191 return computeCdf(new double[]{x}, time)[0];
192 }
193
194 public double[][] computeCdf(double[] X, double time) {
195
196 int[] H = getHfromX(X, time);
197
198 growC(time, 0);
199
200 double[][] W = initializeW(X.length, dim); // initialize with zeros
201
202 final int N = getNfromC();
203 for (int n = 0; n <= N; ++n) {
204 accumulateCdf(W, X, H, n, time);
205 }
206
207 if (DEBUG2) {
208 for (int i = 0; i < W.length; ++i) {
209 System.err.println("W[" + i + "]:\n" + new Matrix(squareMatrix(W[i])));
210 }
211 System.err.println("");
212 }
213
214 return W;
215 }
216
217 private double[] initializeP(double[] Q, double lambda) {
218 double[] P = new double[dim * dim];
219 for (int i = 0; i < dim; ++i) {
220 for (int j = 0; j < dim; ++j) {
221 double identity = (i == j) ? 1.0 : 0.0;
222 P[idx(i, j)] = identity + Q[idx(i, j)] / lambda;
223 }
224 }
225 return P;
226 }
227
228 private void accumulateCdf(double[][] W, double[] X, int[] H, int n, double time) {
229
230 final double premult = Math.exp(
231 -lambda * time + n * (Math.log(lambda) + Math.log(time)) - GammaFunction.lnGamma(n + 1.0)
232 );
233
234 // TODO Make factorial/choose static look-up tables
235
236 for (int t = 0; t < X.length; ++t) { // For each time point
237 double x = X[t];
238 int h = H[t];
239
240 double xh = (x - r[h - 1] * time) / ((r[h] - r[h - 1]) * time);
241
242 final int dim2 = dim * dim;
243 double[] inc = new double[dim2]; // W^{\epsilon}(x(i),t,n)
244 for (int k = 0; k <= n; k++) {
245 final double binomialCoef = Binomial.choose(n, k) * Math.pow(xh, k) * Math.pow(1.0 - xh, n - k);
246 for (int uv = 0; uv < dim2; ++uv) {
247 inc[uv] += binomialCoef * C(h, n, k)[uv];
248 }
249 }
250
251 for (int uv = 0; uv < dim2; ++uv) {
252 W[t][uv] += premult * inc[uv];
253 }
254 }
255 }
256
257 private double accumulatePdf(double x, int n, double time, int uv) {
258
259 double w = 0.0;
260
261 final double premult = Math.exp(
262 -lambda * time + n * (Math.log(lambda) + Math.log(time)) - GammaFunction.lnGamma(n + 1.0)
263 );
264
265 // TODO Make factorial/choose static look-up tables
266
267 // for (int t = 0; t < X.length; ++t) { // For each time point
268 int h = 1;
269
270 final double factor = lambda / (r[h] - r[h - 1]);
271
272 double xh = (x - r[h - 1] * time) / ((r[h] - r[h - 1]) * time);
273
274 // final int dim2 = dim * dim;
275 // double[] inc = new double[dim2]; // W^{\epsilon}(x(i),t,n)
276 double inc = 0.0;
277 for (int k = 0; k <= n; k++) {
278 final double binomialCoef = Binomial.choose(n, k) * Math.pow(xh, k) * Math.pow(1.0 - xh, n - k);
279 // for (int uv = 0; uv < dim2; ++uv) {
280 inc += binomialCoef * (C(h, n + 1, k + 1)[uv] - C(h, n + 1, k)[uv]);
281 // }
282 }
283
284 // for (int uv = 0; uv < dim2; ++uv) {
285 w += factor * premult * inc;
286 // }
287 // }
288 return w;
289 }
290
291 private void accumulatePdf(double[][] W, double[] X, int n, double time) {
292
293 final double premult = Math.exp(
294 -lambda * time + n * (Math.log(lambda) + Math.log(time)) - GammaFunction.lnGamma(n + 1.0)
295 );
296
297 // TODO Make factorial/choose static look-up tables
298
299 for (int t = 0; t < X.length; ++t) { // For each time point
300 double x = X[t];
301 int h = 1;
302
303 final double factor = lambda / (r[h] - r[h - 1]);
304
305 double xh = (x - r[h - 1] * time) / ((r[h] - r[h - 1]) * time);
306
307 final int dim2 = dim * dim;
308 double[] inc = new double[dim2]; // W^{\epsilon}(x(i),t,n)
309 for (int k = 0; k <= n; k++) {
310 final double binomialCoef = Binomial.choose(n, k) * Math.pow(xh, k) * Math.pow(1.0 - xh, n - k);
311 for (int uv = 0; uv < dim2; ++uv) {
312 inc[uv] += binomialCoef * (C(h, n + 1, k + 1)[uv] - C(h, n + 1, k)[uv]);
313 }
314 }
315
316 for (int uv = 0; uv < dim2; ++uv) {
317 W[t][uv] += factor * premult * inc[uv];
318 }
319 }
320 }
321
322 private double relationTwelve(int h, int n, int k, int u, int v) {
323 // TODO ratios are independent of u,v,w
324 double c = (r[u] - r[h]) / (r[u] - r[h - 1]) * C(h, n, k - 1)[idx(u, v)];
325
326 double d = 0;
327 for (int w = 0; w <= phi; ++w) {
328 d += P[idx(u, w)] * C(h, n - 1, k - 1)[idx(w, v)];
329 }
330 d *= (r[h] - r[h - 1]) / (r[u] - r[h - 1]);
331
332 return c + d;
333 }
334
335 private double relationThirteen(int h, int n, int k, int u, int v) {
336 // TODO ratios of are independent of u,v,w
337 double c = (r[h - 1] - r[u]) / (r[h] - r[u]) * C(h, n, k + 1)[idx(u, v)];
338
339 double d = 0;
340 for (int w = 0; w <= phi; ++w) {
341 d += P[idx(u, w)] * C(h, n - 1, k)[idx(w, v)];
342 }
343 d *= (r[h] - r[h - 1]) / (r[h] - r[u]);
344
345 return c + d;
346 }
347
348 private double[] product(double[] a, double[] b) {
349 double[] c = new double[dim * dim];
350 for (int i = 0; i < dim; ++i) {
351 for (int j = 0; j < dim; ++j) {
352 final int ij = idx(i, j);
353 for (int k = 0; k < dim; ++k) {
354 c[ij] += a[idx(i, k)] * b[idx(k, j)];
355 }
356 }
357 }
358 return c;
359 }
360
361 private void computeChnk() {
362
363 double[] Pn = new double[dim * dim];
364 for (int u = 0; u < dim; ++u) {
365 Pn[idx(u, u)] = 1.0;
366 }
367
368 for (int h = 1; h <= phi; ++h) {
369 // zero corner cases automatically
370 for (int u = 0; u <= h - 1; ++u) {
371 C(h, 0, 0)[idx(u, u)] = 1.0;
372 }
373 }
374
375 // accumulate(0);
376 final int N = getNfromC();
377 for (int n = 1; n <= N; ++n) {
378 // zero corner cases automatically
379 for (int h = 1; h <= phi; ++h) {
380 for (int k = 1; k <= n; ++k) {
381
382 for (int u = h; u <= phi; ++u) {
383 for (int v = 0; v <= phi; ++v) {
384 C(h, n, k)[idx(u, v)] = relationTwelve(h, n, k, u, v);
385 }
386 }
387
388 }
389 for (int u = h + 1; u <= phi; ++u) {
390 for (int v = 0; v <= phi; ++v) {
391 C(h + 1, n, 0)[idx(u, v)] = C(h, n, n)[idx(u, v)];
392 }
393 }
394 }
395
396 Pn = product(Pn, P);
397 for (int u = 0; u <= phi - 1; ++u) {
398 for (int v = 0; v <= phi; ++v) {
399 C(phi, n, n)[idx(u, v)] = Pn[idx(u, v)];
400 }
401 }
402
403 for (int h = phi; h >= 1; --h) {
404 for (int k = n - 1; k >= 0; --k) {
405
406 for (int u = 0; u <= h - 1; u++) {
407 for (int v = 0; v <= phi; ++v) {
408 C(h, n, k)[idx(u, v)] = relationThirteen(h, n, k, u, v);
409 }
410 }
411
412 for (int u = 0; u <= h - 2; ++u) {
413 for (int v = 0; v <= phi; ++v) {
414 C(h - 1, n, n)[idx(u, v)] = C(h, n, 0)[idx(u, v)];
415 }
416 }
417 }
418 }
419
420 // accumulate(n);
421 }
422 }
423
424 private double determineLambda() {
425 double lambda = Q[0]; // Q[idx(0,0)]
426 for (int i = 1; i < dim; ++i) {
427 int ii = idx(i, i);
428 if (Q[ii] < lambda) {
429 lambda = Q[ii];
430 }
431 }
432 return -lambda;
433 }
434
435 private double[][] squareMatrix(final double[] mat) {
436 double[][] rtn = new double[dim][dim];
437 for (int i = 0; i < dim; ++i) {
438 for (int j = 0; j < dim; ++j) {
439 rtn[i][j] = mat[idx(i, j)];
440 }
441 }
442 return rtn;
443 }
444
445 private int determineNumberOfSteps(double time, double lambda) {
446 // final double tolerance = (1.0 - epsilon) / Math.exp(-lambda * time);
447 // final double logTolerance = Math.log(1.0 - epsilon);
448
449 int i = -1;
450 // double sum = 0.0;
451 // int factorialI = 1;
452 //
453 // while (sum < tolerance) {
454 // i++;
455 // sum += Math.pow(lambda * time, i) / factorialI;
456 // factorialI *= (i + 1); // + 1 because used on next iterate
457 // }
458 //
459 // int firstN = i;
460 //
461 // LogTricks.logSum()
462 // i = -1;
463 final double tolerance2 =
464 // -epsilon;
465 (1.0 - epsilon);
466 double sum2 = 0.0;
467 // double sum2 = Double.NEGATIVE_INFINITY;
468 while (Math.abs(sum2 - tolerance2) > epsilon && sum2 < 1.0) {
469 // while (sum2 < tolerance2) {
470 i++;
471 double logDensity = -lambda * time + i * (Math.log(lambda) + Math.log(time)) - GammaFunction.lnGamma(i + 1);
472 sum2 += Math.exp(logDensity);
473 // sum2 = LogTricks.logSum(sum2, logDensity);
474 if (DEBUG2) {
475 System.err.println(sum2 + " " + tolerance2 + " " + Math.abs(sum2 - tolerance2) + " " + epsilon * 0.01);
476 // if (i > 500) System.exit(-1);
477 }
478 }
479
480 // System.err.println("First: " + firstN);
481 // System.err.println("Second:" + i);
482 // System.exit(-1);
483
484 return i;
485 }
486
487 public String toString() {
488 StringBuilder sb = new StringBuilder();
489 sb.append("Q: " + new Vector(Q) + "\n");
490 sb.append("r: " + new Vector(r) + "\n");
491 sb.append("lambda: " + lambda + "\n");
492 sb.append("N: " + getNfromC() + "\n");
493 sb.append("maxTime: " + maxTime + "\n");
494 sb.append("cprob at maxTime: " + new Vector(computeConditionalProbabilities(maxTime)) + "\n");
495 return sb.toString();
496 }
497
498 private EigenDecomposition getEigenDecomposition() {
499 if (eigenDecomposition == null) {
500 eigenDecomposition = eigenSystem.decomposeMatrix(squareMatrix(Q));
501 }
502 return eigenDecomposition;
503 }
504
505 private EigenDecomposition eigenDecomposition;
506
507 public double[] computeConditionalProbabilities(double distance) {
508
509 double[] matrix = new double[dim * dim];
510 eigenSystem.computeExponential(getEigenDecomposition(), distance, matrix);
511
512 return matrix;
513 }
514
515 public double computeConditionalProbability(double distance, int i, int j) {
516 return eigenSystem.computeExponential(getEigenDecomposition(), distance, i, j);
517 }
518
519 private final double[] Q;
520 private final double[] r;
521
522 private final double lambda;
523 private final double[] P;
524 private final int phi;
525 private final int dim;
526 private final double epsilon;
527
528 private final EigenSystem eigenSystem;
529
530 private double maxTime;
531 }