Debian Codegraph @

src/dr/inference/markovjumps/StateHistory.java

raw symbols SCIP
1 /*
2 * StateHistory.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.evolution.datatype.DataType;
29 import dr.math.MathUtils;
30
31 import java.util.ArrayList;
32 import java.util.List;
33
34 /**
35 * A class to represent the complete state history of a continuous-time Markov chain in the
36 * interval [0,T].
37 * <p/>
38 * This work is supported by NSF grant 0856099
39 *
40 * @author Marc A. Suchard
41 */
42
43 public class StateHistory {
44
45 // private StateHistory(int startingState, int stateCount) {
46 // this(0.0, startingState, stateCount);
47 // }
48
49 protected StateHistory(double startingTime, int startingState, int stateCount) {
50 stateList = new ArrayList<StateChange>();
51 stateList.add(new StateChange(startingTime, startingState));
52 this.stateCount = stateCount;
53 finalized = false;
54 }
55
56 public void addChange(StateChange stateChange) {
57 checkFinalized(false);
58 stateList.add(stateChange);
59 }
60
61 public void addEndingState(StateChange stateChange) {
62 checkFinalized(false);
63 stateList.add(stateChange);
64 finalized = true;
65 }
66
67 public int[] getJumpCounts() {
68 int[] counts = new int[stateCount * stateCount];
69 accumulateSufficientStatistics(counts, null);
70 return counts;
71 }
72
73 public double[] getWaitingTimes() {
74 double[] times = new double[stateCount];
75 accumulateSufficientStatistics(null, times);
76 return times;
77 }
78
79 public double getTotalRegisteredCounts(double[] register) {
80 int[] counts = getJumpCounts();
81 // double total = 0;
82 // for (int i = 0; i < counts.length; i++) {
83 // total += counts[i] * register[i];
84 // }
85 // return total;
86 return dotProduct(counts, register);
87 }
88
89 private double dotProduct(int[] a, double[] b) {
90 double total = 0;
91 final int length = a.length;
92 for (int i = 0; i < length; i++) {
93 total += a[i] * b[i];
94 }
95 return total;
96 }
97
98 public double getTotalReward(double[] register) {
99 double[] times = getWaitingTimes();
100 double total = 0;
101 for (int i = 0; i < times.length; i++) {
102 total += times[i] * register[i]; // stateCount length vector
103 }
104 return total;
105 }
106
107 public void accumulateSufficientStatistics(int[] counts, double[] times) {
108 checkFinalized(true);
109 int nJumps = getNumberOfJumps();
110
111 StateChange initialState = stateList.get(0);
112 int currentState = initialState.getState();
113 double currentTime = initialState.getTime();
114
115 for (int i = 1; i <= nJumps; i++) {
116
117 StateChange nextStateChange = stateList.get(i);
118 int nextState = nextStateChange.getState();
119 double nextTime = nextStateChange.getTime();
120
121 if (counts != null) {
122 counts[currentState * stateCount + nextState]++;
123 }
124 if (times != null) {
125 times[currentState] += (nextTime - currentTime);
126 }
127 currentState = nextState;
128 currentTime = nextTime;
129 }
130 if (times != null) { // Add last waiting time
131 StateChange finalState = stateList.get(nJumps + 1);
132 times[currentState] += (finalState.getTime() - currentTime);
133 }
134 }
135
136 public int getNumberOfJumps() {
137 checkFinalized(true);
138 return stateList.size() - 2; // Discount starting and ending states
139 }
140
141 private void checkFinalized(boolean isTrue) {
142 if (isTrue != finalized) {
143 throw new IllegalAccessError("StateHistory " + (finalized ? "is" : "is not" + " finalized"));
144 }
145 }
146
147 public int getStartingState() {
148 return stateList.get(0).getState();
149 }
150
151 public int getEndingState() {
152 checkFinalized(true);
153 return stateList.get(stateList.size() - 1).getState();
154 }
155
156 public double getStartingTime() {
157 return stateList.get(0).getTime();
158 }
159
160 public double getEndingTime() {
161 checkFinalized(true);
162 return stateList.get(stateList.size() - 1).getTime();
163 }
164
165 public void rescaleTimesOfEvents(double inStartTime, double inEndTime) {
166
167 final double scale = (inEndTime - inStartTime) / (getEndingTime() - getStartingTime());
168
169 StateChange currentStateChange = stateList.get(0);
170 double oldCurrentTime = currentStateChange.getTime();
171 currentStateChange.setTime(inStartTime);
172 double newCurrentTime = inStartTime;
173
174 for (int i = 1; i < stateList.size(); ++i) {
175 StateChange nextStateChange = stateList.get(i);
176 double oldNextTime = nextStateChange.getTime();
177 double oldTimeDiff = oldNextTime - oldCurrentTime;
178
179 double newNextTime = oldTimeDiff * scale + newCurrentTime;
180 nextStateChange.setTime(newNextTime);
181
182 oldCurrentTime = oldNextTime;
183 newCurrentTime = newNextTime;
184
185 }
186 }
187
188 public String toString() {
189 StringBuilder sb = new StringBuilder("[");
190 for (int i = 0; i < stateList.size(); i++) {
191 if (i > 0) {
192 sb.append(",");
193 }
194 sb.append(stateList.get(i));
195 }
196 sb.append("]");
197 return sb.toString();
198 }
199
200 public static void main(String[] args) {
201 System.err.println("Testing time rescaling:");
202 StateHistory stateHistory = new StateHistory(1, 1, 4);
203 StateChange stateChange;
204 stateChange = new StateChange(2, 2);
205 stateHistory.addChange(stateChange);
206 stateChange = new StateChange(5, 2);
207 stateHistory.addEndingState(stateChange);
208
209 System.err.println("Initial history: " + stateHistory);
210
211 stateHistory.rescaleTimesOfEvents(8.0, 0.0);
212 System.err.println("Rescale history: " + stateHistory);
213
214 stateHistory.rescaleTimesOfEvents(0.0, 4.0);
215 System.err.println("Rescale history: " + stateHistory);
216 }
217
218 public StateHistory filterChanges(double[] register) {
219
220 if (getNumberOfJumps() == 0) {
221 return this;
222 }
223
224 StateChange currentState = stateList.get(0);
225 StateHistory newHistory = new StateHistory(currentState.getTime(), currentState.getState(), stateCount);
226
227 for (int i = 1; i < stateList.size() - 1; ++i) {
228 StateChange nextState = stateList.get(i);
229 if (register[currentState.getState() * stateCount + nextState.getState()] == 1) {
230 nextState = nextState.clone();
231 nextState.setPreviousState(currentState.getState());
232 newHistory.addChange(nextState);
233 }
234 currentState = nextState;
235 }
236 newHistory.addEndingState(stateList.get(stateList.size() - 1));
237 // This function can produce inconsistent histories when not all changes are reported.
238 isFiltered = true;
239 return newHistory;
240 }
241
242 public double getLogLikelihood(final double[] infinitesimalRates, final int stateCount) {
243 checkFinalized(true);
244
245 // TODO This function needs testing
246 double logLikelihood = 0.0;
247 final int totalChanges = getNumberOfJumps();
248
249 int currentState = stateList.get(0).getState();
250 double currentTime = stateList.get(0).getTime();
251 for (int i = 1; i < totalChanges; ++i) {
252 int nextState = stateList.get(i).getState();
253 double nextTime = stateList.get(i).getTime();
254
255 // Exponential pdf and destination choice
256 logLikelihood += Math.log(infinitesimalRates[currentState * stateCount + nextState])
257 + infinitesimalRates[currentState * stateCount + currentState] * (nextTime - currentTime);
258 // terms involving Math.log(\lambda_{ii}) cancel
259
260 currentState = nextState;
261 currentTime = nextTime;
262 }
263
264 final int lastState = stateList.get(stateList.size() - 1).getState();
265 final double lastTime = stateList.get(stateList.size() - 1).getTime();
266
267 assert (lastState == currentState);
268 assert (lastTime >= currentTime);
269
270 // No event in last interval
271 logLikelihood += infinitesimalRates[currentState * stateCount + currentState] * (lastTime - currentTime);
272
273 return logLikelihood;
274 }
275
276 public String toStringChanges(int site, DataType dataType) {
277 return toStringChanges(site, dataType, true);
278 }
279
280 public String toStringChanges(int site, DataType dataType, boolean wrap) {
281 StringBuilder sb = wrap ? new StringBuilder("{") : new StringBuilder();
282 // site number gets put into each and every event string
283 // sb.append(site).append(",");
284 int currentState = stateList.get(0).getState();
285 boolean firstChange = true;
286 for (int i = 1; i < stateList.size() - 1; i++) { // TODO Code review: should this really be size() - 1?
287 int nextState = stateList.get(i).getState();
288 if (isFiltered) {
289 currentState = stateList.get(i).getPreviousState();
290 }
291 if (nextState != currentState) {
292 if (!firstChange) {
293 sb.append(",");
294 }
295 double time = stateList.get(i).getTime(); // + startTime;
296 addEventToStringBuilder(sb, dataType.getCode(currentState), dataType.getCode(nextState), time, site);
297 firstChange = false;
298 currentState = nextState;
299 }
300 }
301 if (wrap) {
302 sb.append("}"); // Always returns an array of arrays
303 }
304 return sb.toString();
305 }
306
307 public static void addEventToStringBuilder(StringBuilder sb, String source, String dest, double time, int site) {
308 // AR changed this to match an attribute array:
309 sb.append("{");
310 if (site > 0) {
311 sb.append(site).append(",");
312 }
313 sb.append(time).append(",").append(source).append(",").append(dest).append("}");
314 }
315
316 public static StateHistory simulateConditionalOnEndingState(double startingTime,
317 int startingState,
318 double endingTime,
319 int endingState,
320 double[] lambda,
321 int stateCount) {
322 throw new RuntimeException("Impossible to simulate a conditioned CTMC in StateHistory");
323 }
324
325 public static StateHistory simulateUnconditionalOnEndingState(double startingTime,
326 int startingState,
327 double endingTime,
328 double[] lambda,
329 int stateCount) {
330
331 StateHistory history = new StateHistory(startingTime, startingState, stateCount);
332 double[] multinomial = new double[stateCount];
333
334 double currentTime = startingTime;
335 int currentState = startingState;
336
337 while (currentTime < endingTime) {
338
339 double currentRate = -lambda[currentState * stateCount + currentState];
340 double waitingTime = MathUtils.nextExponential(currentRate);
341
342 currentTime += waitingTime;
343 if (currentTime < endingTime) { // Simulate a jump
344 System.arraycopy(lambda, currentState * stateCount, multinomial, 0, stateCount);
345 multinomial[currentState] = 0;
346 currentState = MathUtils.randomChoicePDF(multinomial); // Does not need to be normalized
347
348 history.addChange(new StateChange(currentTime, currentState));
349 }
350 }
351
352 history.addEndingState(new StateChange(endingTime, currentState));
353
354 return history;
355 }
356
357
358 private int stateCount;
359 private List<StateChange> stateList;
360 private boolean finalized;
361 private boolean isFiltered = false;
362
363 }