Debian Codegraph @

src/dr/inference/markovjumps/SubordinatedProcess.java

raw symbols SCIP
1 /*
2 * SubordinatedProcess.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.math.GammaFunction;
29 import dr.math.MathUtils;
30 import dr.math.matrixAlgebra.Vector;
31
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.List;
35
36
37 /**
38 * A class to represent a Poisson process and discrete-time Markov chain that subordinate
39 * a continuous-time Markov chain in the interval [0,T]. The subordinator drives the Uniformization method
40 * for simulating end-conditioned realizations
41 * <p/>
42 * This work is supported by NSF grant 0856099
43 * <p/>
44 * Hobolth A and Stone E (2009) Simulation from endpoint-conditioned, continuous-time Markov chains on a finite
45 * state space, with applications to molecular evolution. Annals of Applied Statistics, 3, 1204-1231.
46 *
47 * @author Marc A. Suchard
48 */
49
50 public class SubordinatedProcess {
51
52 public SubordinatedProcess(double[] Q, int stateCount) {
53 this.stateCount = stateCount;
54 poissonRate = getMaxRate(Q, stateCount);
55 dtmcCache = new ArrayList<double[]>();
56 dtmcCache.add(makeIndentityMatrx(stateCount));
57 dtmcCache.add(constructDtmcMatrix(Q, stateCount));
58 tmp = new double[stateCount];
59 this.Q = Q;
60 }
61
62 public double getPoissonRate() {
63 return poissonRate;
64 }
65
66 private double getCachedExp(double x) {
67 if (x != cachedXForExp) {
68 cachedXForExp = x;
69 cachedExpValue = Math.exp(x);
70 }
71 return cachedExpValue;
72 }
73
74 /**
75 * Compute the n-step discrete-time transition probabilities
76 *
77 * @param nSteps which step
78 * @return a pointer to the cached matrix
79 */
80
81 public double[] getDtmcProbabilities(int nSteps) {
82 if (nSteps > dtmcCache.size() - 1) {
83 double[] dtmcOneStep = dtmcCache.get(1);
84 for (int step = dtmcCache.size() - 1; step <= nSteps; step++) {
85 double[] lastDtmcMatrix = dtmcCache.get(step);
86 double[] nextDtmcMatrix = new double[stateCount * stateCount];
87 MarkovJumpsCore.matrixMultiply(lastDtmcMatrix, dtmcOneStep, stateCount, nextDtmcMatrix);
88 dtmcCache.add(nextDtmcMatrix);
89 }
90 }
91 return dtmcCache.get(nSteps);
92 }
93
94 /**
95 * Find max_i -Q_{ii}
96 *
97 * @param Q ctmc rate matrix
98 * @param stateCount dim
99 * @return max rate
100 */
101
102 private double getMaxRate(double[] Q, int stateCount) {
103 double max = -Q[0];
104 for (int i = 1; i < stateCount; i++) {
105 double nextRate = -Q[i * stateCount + i];
106 if (nextRate > max) {
107 max = nextRate;
108 }
109 }
110 return max;
111 }
112
113 /**
114 * R = I + 1/maxRate Q
115 *
116 * @param lambda Q
117 * @param stateCount dim
118 * @return R
119 */
120
121 private double[] constructDtmcMatrix(double[] lambda, int stateCount) {
122 double[] R = new double[stateCount * stateCount];
123 double maxRate = getMaxRate(lambda, stateCount);
124 int index = 0;
125 for (int i = 0; i < stateCount; i++) {
126 for (int j = 0; j < stateCount; j++) {
127 R[index] = lambda[index] / maxRate;
128
129 if (i == j) {
130 R[index] += 1;
131 }
132 index++;
133 }
134 }
135 return R;
136 }
137
138 /**
139 * Simulate transition times, uniformly distributed before sorting
140 *
141 * @param timeDuration T
142 * @param totalNumberOfChanges total number of changes
143 * @return the transition times of the subordinated process
144 */
145 public double[] drawTransitionTimes(double timeDuration, int totalNumberOfChanges) {
146 double[] times = new double[totalNumberOfChanges];
147 for (int i = 0; i < totalNumberOfChanges; i++) {
148 times[i] = timeDuration * MathUtils.nextDouble();
149 }
150 if (times.length > 1) {
151 Arrays.sort(times);
152 }
153 return times;
154 }
155
156 /**
157 * Simulate the next transition in the subordinated process, equation in remark 7
158 *
159 * @param currentState current state of the subordinated process
160 * @param endingState ending state of CTMC
161 * @param totalNumberOfChanges number of subordinated changes
162 * @param thisChangeNumber this transition number
163 * @return the next state of the subordinated process
164 */
165 public int drawNextChainState(int currentState, int endingState, int totalNumberOfChanges, int thisChangeNumber) {
166 computePdfNextChainState(currentState, endingState, totalNumberOfChanges, thisChangeNumber, tmp);
167 return MathUtils.randomChoicePDF(tmp);
168 }
169
170 public void computePdfNextChainState(int currentState, int endingState, int totalNumberOfChanges, int thisChangeNumber,
171 double[] pdf) {
172 double[] R = getDtmcProbabilities(1);
173 double[] RnMinusI = getDtmcProbabilities(totalNumberOfChanges - thisChangeNumber);
174
175 for (int i = 0; i < stateCount; i++) {
176 pdf[i] = R[currentState * stateCount + i] * RnMinusI[i * stateCount + endingState];
177 // / RnMinusIPlus1[currentState * stateCount + endingState] // No need to normalize
178 }
179 }
180
181 public class Exception extends java.lang.Exception {
182 // Nothing special
183 }
184
185 /**
186 * Simulate the number of transitions in the subordinated process, equation (2.9)
187 *
188 * @param startingState starting state of CTMC
189 * @param endingState ending state of CTMC
190 * @param time length of chain
191 * @param ctmcProbability the CTMC finite-time transition probability
192 * @return the number of transitions in the subordinated process
193 * @throws dr.inference.markovjumps.SubordinatedProcess.Exception exception
194 */
195 public int drawNumberOfChanges(int startingState, int endingState, double time, double ctmcProbability) throws SubordinatedProcess.Exception {
196 return drawNumberOfChanges(startingState, endingState, time, ctmcProbability, MathUtils.nextDouble());
197 }
198
199 public int drawNumberOfChanges(int startingState, int endingState, double time, double ctmcProbability,
200 double cutoff) throws SubordinatedProcess.Exception {
201 int drawnNumber = -1;
202 double cdf = 0;
203
204 double effectiveRate = getPoissonRate() * time;
205 double preFactor = getCachedExp(-effectiveRate);
206 double scale = 1.0;
207 int index = startingState * stateCount + endingState;
208
209 double[] check;
210 int maxTries = 1000;
211 if (DEBUG) {
212 check = new double[maxTries+1];
213 }
214
215 while (cutoff >= cdf) {
216 drawnNumber++;
217
218 double[] Rn = getDtmcProbabilities(drawnNumber);
219 if (drawnNumber > 0) {
220 scale *= effectiveRate;
221 }
222 if (drawnNumber > 1) {
223 scale /= (double) drawnNumber;
224 }
225
226 cdf += preFactor * scale * Rn[index] / ctmcProbability;
227
228 if (THROW_EXCEPTION) {
229 if (drawnNumber == maxTries) {
230 throw new SubordinatedProcess.Exception();
231 }
232 }
233
234 if (DEBUG) {
235 check[drawnNumber] = cdf;
236 if (drawnNumber == maxTries) {
237 System.err.println("Start state = " + startingState);
238 System.err.println("End state = " + endingState);
239 System.err.println("Time = " + time);
240 System.err.println("CDF = " + cdf);
241 System.err.println("Cutoff = " + cutoff);
242 System.err.println("CTMC prob = " + ctmcProbability);
243 System.err.println("PoissonRate = " + getPoissonRate());
244
245 double[] distr = computePDFDirectly(startingState, endingState, time, ctmcProbability, drawnNumber);
246 double[] checkCDF = new double[distr.length];
247 double total = 0;
248 for (int i = 0; i < distr.length; i++) {
249 total += distr[i];
250 checkCDF[i] = total;
251 }
252 System.err.println("Direct compute = " + new Vector(distr));
253 System.err.println("Via CDF = " + new Vector(checkCDF));
254 System.err.println("Check distr = " + new Vector(check));
255 System.err.println("Q = " + new Vector(Q));
256 System.err.println("R = " + new Vector(getDtmcProbabilities(1)));
257
258 throw new RuntimeException("Likely numerical instability in computing end-conditioned CTMC simulant.");
259 }
260 }
261 }
262 return drawnNumber;
263 }
264
265 public double[] computePDFDirectly(int startingState, int endingState, double time, double ctmcProbability,
266 int maxTerm) {
267 double[] pdf = new double[maxTerm];
268
269 final double logRateTime = Math.log(getPoissonRate())+ Math.log(time);
270 final double logCtmcProbability = Math.log(ctmcProbability);
271
272 for (int n = 0; n < maxTerm; n++) {
273 double[] Rn = getDtmcProbabilities(n);
274 // pdf[n] = Math.exp(-getPoissonRate() * time) * Math.pow(getPoissonRate() * time, n) /
275 // Math.exp(GammaFunction.lnGamma(n + 1)) * Rn[startingState * stateCount + endingState] /
276 // ctmcProbability;
277
278 pdf[n] = Math.exp(-getPoissonRate() * time + n * logRateTime - GammaFunction.lnGamma(n + 1) +
279 Math.log(Rn[startingState * stateCount + endingState]) - logCtmcProbability);
280 }
281 return pdf;
282 }
283
284 private double[] makeIndentityMatrx(int stateCount) {
285 double[] I = new double[stateCount * stateCount];
286 for (int i = 0; i < stateCount; i++) {
287 I[i * stateCount + i] = 1.0;
288 }
289 return I;
290 }
291
292 private final List<double[]> dtmcCache;
293 private final double poissonRate;
294 private final int stateCount;
295 private final double[] tmp;
296
297 private double cachedXForExp = Double.NaN;
298 private double cachedExpValue;
299
300 private static final boolean DEBUG = false;
301 private static final boolean THROW_EXCEPTION = true;
302
303 private double[] Q;
304 }