Debian Codegraph @

src/dr/inference/markovjumps/SericolaSeriesMarkovReward.java

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