Debian Codegraph @

src/dr/inference/markovchain/MarkovChain.java

raw symbols SCIP
1 /*
2 * MarkovChain.java
3 *
4 * Copyright (c) 2002-2017 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.markovchain;
27
28 import dr.evomodel.continuous.GibbsIndependentCoalescentOperator;
29 import dr.inference.model.CompoundLikelihood;
30 import dr.inference.model.Likelihood;
31 import dr.inference.model.Model;
32 import dr.inference.model.PathLikelihood;
33 import dr.inference.operators.*;
34
35 import java.io.Serializable;
36 import java.util.ArrayList;
37 import java.util.Set;
38 import java.util.logging.Logger;
39
40 /**
41 * A concrete markov chain. This is final as the only things that should need
42 * overriding are in the delegates (prior, likelihood, schedule and acceptor).
43 * The design of this class is to be fairly immutable as far as settings goes.
44 *
45 * @author Alexei Drummond
46 * @author Andrew Rambaut
47 * @version $Id: MarkovChain.java,v 1.10 2006/06/21 13:34:42 rambaut Exp $
48 */
49 public final class MarkovChain implements Serializable {
50 private static final long serialVersionUID = 181L;
51
52 private final static boolean DEBUG = false;
53 private final static boolean PROFILE = true;
54
55 public static final double EVALUATION_TEST_THRESHOLD = 1e-1;
56
57 private final OperatorSchedule schedule;
58 private final Acceptor acceptor;
59 private final Likelihood likelihood;
60
61 private boolean pleaseStop = false;
62 private boolean isStopped = false;
63 private double bestScore, currentScore, initialScore;
64 private long currentLength;
65
66 private boolean useAdaptation = true;
67
68 private final long fullEvaluationCount;
69 private final int minOperatorCountForFullEvaluation;
70
71 private double evaluationTestThreshold = EVALUATION_TEST_THRESHOLD;
72
73
74 public MarkovChain(Likelihood likelihood,
75 OperatorSchedule schedule, Acceptor acceptor,
76 long fullEvaluationCount, int minOperatorCountForFullEvaluation, double evaluationTestThreshold,
77 boolean useAdaptation) {
78
79 currentLength = 0;
80 this.likelihood = likelihood;
81 this.schedule = schedule;
82 this.acceptor = acceptor;
83 this.useAdaptation = useAdaptation;
84
85 this.fullEvaluationCount = fullEvaluationCount;
86 this.minOperatorCountForFullEvaluation = minOperatorCountForFullEvaluation;
87 this.evaluationTestThreshold = evaluationTestThreshold;
88
89 Likelihood.CONNECTED_LIKELIHOOD_SET.add(likelihood);
90 Likelihood.CONNECTED_LIKELIHOOD_SET.addAll(likelihood.getLikelihoodSet());
91
92 for (Likelihood l : Likelihood.FULL_LIKELIHOOD_SET) {
93 if (!Likelihood.CONNECTED_LIKELIHOOD_SET.contains(l)) {
94 System.err.println("WARNING: Likelihood component, " + l.getId() + ", created but not used in the MCMC");
95 }
96 }
97
98 currentScore = evaluate(likelihood);
99 }
100
101 /**
102 * Resets the markov chain
103 */
104 public void reset() {
105 currentLength = 0;
106
107 // reset operator acceptance levels
108 for (int i = 0; i < schedule.getOperatorCount(); i++) {
109 schedule.getOperator(i).reset();
110 }
111 }
112
113 /**
114 * Run the chain for a given number of states.
115 *
116 * @param length number of states to run the chain.
117 */
118 public long runChain(long length, boolean disableAdaptation) {
119
120 likelihood.makeDirty();
121 currentScore = evaluate(likelihood);
122
123 long currentState = currentLength;
124
125 final Model currentModel = likelihood.getModel();
126
127 if (currentState == 0) {
128 initialScore = currentScore;
129 bestScore = currentScore;
130 fireBestModel(currentState, currentModel);
131 }
132
133 if (currentScore == Double.NEGATIVE_INFINITY) {
134
135 // identify which component of the score is zero...
136 String message = "The initial likelihood is zero";
137 if (likelihood instanceof CompoundLikelihood) {
138 message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis();
139 } else if (likelihood instanceof PathLikelihood) {
140 message += ": " + ((CompoundLikelihood)((PathLikelihood) likelihood).getSourceLikelihood()).getDiagnosis();
141 message += ": " + ((CompoundLikelihood)((PathLikelihood) likelihood).getDestinationLikelihood()).getDiagnosis();
142 } else {
143 message += ".";
144 }
145 throw new IllegalArgumentException(message);
146 } else if (currentScore == Double.POSITIVE_INFINITY || Double.isNaN(currentScore)) {
147 String message = "A likelihood returned with a numerical error (" + currentScore + ")";
148 if (likelihood instanceof CompoundLikelihood) {
149 message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis();
150 } else {
151 message += ".";
152 Set<Likelihood> lSet = likelihood.getLikelihoodSet();
153 for (Likelihood l : lSet) {
154 message += "\n " + l.prettyName() + " = " + l.getLogLikelihood();
155 }
156 }
157 throw new IllegalArgumentException(message);
158 }
159
160 pleaseStop = false;
161 isStopped = false;
162
163 //int otfcounter = onTheFlyOperatorWeights > 0 ? onTheFlyOperatorWeights : 0;
164
165 double[] logr = {0.0};
166
167 boolean usingFullEvaluation = true;
168 // set ops count in mcmc element instead
169 if (fullEvaluationCount == 0) // Temporary solution until full code review
170 usingFullEvaluation = false;
171 boolean fullEvaluationError = false;
172
173 while (!pleaseStop && (currentState < (currentLength + length))) {
174
175 String diagnosticStart = "";
176
177 // periodically log states
178 fireCurrentModel(currentState, currentModel);
179
180 if (pleaseStop) {
181 isStopped = true;
182 break;
183 }
184
185 // Get the operator
186 final int op = schedule.getNextOperatorIndex();
187 final MCMCOperator mcmcOperator = schedule.getOperator(op);
188
189 double oldScore = currentScore;
190 if (usingFullEvaluation) {
191 diagnosticStart = likelihood instanceof CompoundLikelihood ?
192 ((CompoundLikelihood) likelihood).getDiagnosis() : "";
193 }
194
195 // assert Profiler.startProfile("Store");
196
197 // The current model is stored here in case the proposal fails
198 if (currentModel != null) {
199 currentModel.storeModelState();
200 }
201
202 // assert Profiler.stopProfile("Store");
203
204 boolean operatorSucceeded = true;
205 double hastingsRatio = 1.0;
206 boolean accept = false;
207
208 logr[0] = -Double.MAX_VALUE;
209
210 long elaspedTime = 0;
211 if (PROFILE) {
212 elaspedTime = System.currentTimeMillis();
213 }
214
215 // The new model is proposed
216 // assert Profiler.startProfile("Operate");
217
218 if (DEBUG) {
219 System.out.println("\n>> Iteration: " + currentState);
220 System.out.println("\n&& Operator: " + mcmcOperator.getOperatorName());
221 }
222
223 if (mcmcOperator instanceof GeneralOperator) {
224 hastingsRatio = ((GeneralOperator) mcmcOperator).operate(likelihood);
225 } else {
226 hastingsRatio = mcmcOperator.operate();
227 }
228
229 // assert Profiler.stopProfile("Operate");
230 if (hastingsRatio == Double.NEGATIVE_INFINITY) {
231 // Should the evaluation be short-cutted?
232 // Previously this was set to false if OperatorFailedException was thrown.
233 // Now a -Inf HR is returned.
234 operatorSucceeded = false;
235 }
236
237 if (PROFILE) {
238 long duration = System.currentTimeMillis() - elaspedTime;
239 if (DEBUG) {
240 System.out.println("Time: " + duration);
241 }
242 mcmcOperator.addEvaluationTime(duration);
243 }
244
245 double score = Double.NaN;
246 double deviation = Double.NaN;
247
248 // System.err.print("" + currentState + ": ");
249 if (operatorSucceeded) {
250
251 // The new model is proposed
252 // assert Profiler.startProfile("Evaluate");
253
254 if (DEBUG) {
255 System.out.println("** Evaluate");
256 }
257
258 long elapsedTime = 0;
259 if (PROFILE) {
260 elapsedTime = System.currentTimeMillis();
261 }
262
263 // The new model is evaluated
264 score = evaluate(likelihood);
265
266 if (PROFILE) {
267 long duration = System.currentTimeMillis() - elapsedTime;
268 if (DEBUG) {
269 System.out.println("Time: " + duration);
270 }
271 mcmcOperator.addEvaluationTime(duration);
272 }
273
274 String diagnosticOperator = "";
275 if (usingFullEvaluation) {
276 diagnosticOperator = likelihood instanceof CompoundLikelihood ?
277 ((CompoundLikelihood) likelihood).getDiagnosis() : "";
278 }
279
280 if (score == Double.NEGATIVE_INFINITY && mcmcOperator instanceof GibbsOperator) {
281 if (!(mcmcOperator instanceof GibbsIndependentNormalDistributionOperator) && !(mcmcOperator instanceof GibbsIndependentGammaOperator) && !(mcmcOperator instanceof GibbsIndependentCoalescentOperator) && !(mcmcOperator instanceof GibbsIndependentJointNormalGammaOperator)) {
282 if (DEBUG) {
283 if (likelihood instanceof CompoundLikelihood) {
284 CompoundLikelihood cpl = (CompoundLikelihood) likelihood;
285 System.out.println("\nDEBUG CompoundLikelihood:");
286 for (Likelihood l : cpl.getLikelihoods()) {
287 if (l instanceof CompoundLikelihood) {
288 CompoundLikelihood l2 = (CompoundLikelihood)l;
289 for (Likelihood lTwo : l2.getLikelihoods()) {
290 System.out.println("\t" + lTwo.prettyName() + " = " + lTwo.getLogLikelihood());
291 }
292 }
293 System.out.println(l.prettyName() + " = " + l.getLogLikelihood());
294 }
295 System.out.println("Total likelihood = " + cpl.getLogLikelihood() + "\n");
296 }
297 }
298 Logger.getLogger("error").severe("State " + currentState + ": A Gibbs operator, " + mcmcOperator.getOperatorName() + ", returned a state with zero likelihood.");
299 }
300 }
301
302 if (score == Double.POSITIVE_INFINITY ||
303 Double.isNaN(score) ) {
304 if (likelihood instanceof CompoundLikelihood) {
305 Logger.getLogger("error").severe("State "+currentState+": A likelihood returned with a numerical error:\n" +
306 ((CompoundLikelihood)likelihood).getDiagnosis());
307 } else {
308 Logger.getLogger("error").severe("State "+currentState+": A likelihood returned with a numerical error.");
309 }
310
311 if (DEBUG) {
312 if (likelihood instanceof CompoundLikelihood) {
313 CompoundLikelihood cpl = (CompoundLikelihood) likelihood;
314 System.out.println("\nDEBUG CompoundLikelihood:");
315 for (Likelihood l : cpl.getLikelihoods()) {
316 if (l instanceof CompoundLikelihood) {
317 CompoundLikelihood l2 = (CompoundLikelihood) l;
318 for (Likelihood lTwo : l2.getLikelihoods()) {
319 System.out.println("\t" + lTwo.prettyName() + " = " + lTwo.getLogLikelihood());
320 }
321 }
322 System.out.println(l.prettyName() + " = " + l.getLogLikelihood());
323 }
324 System.out.println("Total likelihood = " + cpl.getLogLikelihood() + "\n");
325 }
326 }
327
328 // If the user has chosen to ignore this error then we transform it
329 // to a negative infinity so the state is rejected.
330 score = Double.NEGATIVE_INFINITY;
331 }
332
333 if (usingFullEvaluation) {
334
335 // This is a test that the state was correctly evaluated. The
336 // likelihood of all components of the model are flagged as
337 // needing recalculation, then the full likelihood is calculated
338 // again and compared to the first result. This checks that the
339 // BEAST is aware of all changes that the operator induced.
340
341 likelihood.makeDirty();
342 final double testScore = evaluate(likelihood);
343
344 final String d2 = likelihood instanceof CompoundLikelihood ?
345 ((CompoundLikelihood) likelihood).getDiagnosis() : "";
346
347 if (Math.abs(testScore - score) > evaluationTestThreshold) {
348 Logger.getLogger("error").severe(
349 "State "+currentState+": State was not correctly calculated after an operator move.\n"
350 + "Likelihood evaluation: " + score
351 + "\nFull Likelihood evaluation: " + testScore
352 + "\n" + "Operator: " + mcmcOperator
353 + " " + mcmcOperator.getOperatorName()
354 + (diagnosticOperator.length() > 0 ? "\n\nDetails\nBefore: " + diagnosticOperator + "\nAfter: " + d2 : "")
355 + "\n\n");
356 fullEvaluationError = true;
357 }
358 }
359
360 if (score > bestScore) {
361 bestScore = score;
362 fireBestModel(currentState, currentModel);
363 }
364
365 accept = mcmcOperator instanceof GibbsOperator || acceptor.accept(oldScore, score, hastingsRatio, logr);
366
367 deviation = score - oldScore;
368 }
369
370 // The new model is accepted or rejected
371 if (accept) {
372 if (DEBUG) {
373 System.out.println("** Move accepted: new score = " + score
374 + ", old score = " + oldScore);
375 }
376
377 mcmcOperator.accept(deviation);
378 currentModel.acceptModelState();
379 currentScore = score;
380
381 } else {
382 if (DEBUG) {
383 System.out.println("** Move rejected: new score = " + score
384 + ", old score = " + oldScore + " (logr = " + logr[0] + ")");
385 }
386
387 mcmcOperator.reject();
388
389 // assert Profiler.startProfile("Restore");
390
391 currentModel.restoreModelState();
392
393 if (usingFullEvaluation) {
394 // This is a test that the state is correctly restored. The
395 // restored state is fully evaluated and the likelihood compared with
396 // that before the operation was made.
397
398 likelihood.makeDirty();
399 final double testScore = evaluate(likelihood);
400
401 final String d2 = likelihood instanceof CompoundLikelihood ?
402 ((CompoundLikelihood) likelihood).getDiagnosis() : "";
403
404 if (Math.abs(testScore - oldScore) > evaluationTestThreshold) {
405
406
407 final Logger logger = Logger.getLogger("error");
408 logger.severe("State "+currentState+": State was not correctly restored after reject step.\n"
409 + "Likelihood before: " + oldScore
410 + " Likelihood after: " + testScore
411 + "\n" + "Operator: " + mcmcOperator
412 + " " + mcmcOperator.getOperatorName()
413 + (diagnosticStart.length() > 0 ? "\n\nDetails\nBefore: " + diagnosticStart + "\nAfter: " + d2 : "")
414 + "\n\n");
415 fullEvaluationError = true;
416 }
417 }
418 }
419 // assert Profiler.stopProfile("Restore");
420
421
422 if (useAdaptation && !disableAdaptation && mcmcOperator instanceof AdaptableMCMCOperator) {
423 adaptAcceptanceProbability((AdaptableMCMCOperator) mcmcOperator, logr[0]);
424 }
425
426 if (usingFullEvaluation) {
427 if (schedule.getMinimumAcceptAndRejectCount() >= minOperatorCountForFullEvaluation &&
428 currentState >= fullEvaluationCount) {
429 // full evaluation is only switched off when each operator has done a
430 // minimum number of operations (currently 1) and fullEvalationCount
431 // operations in total.
432
433 usingFullEvaluation = false;
434 if (fullEvaluationError) {
435 // If there has been an error then stop with an error
436 throw new RuntimeException(
437 "One or more evaluation errors occurred during the test phase of this\n" +
438 "run. These errors imply critical errors which may produce incorrect\n" +
439 "results.");
440 }
441 }
442 }
443
444 fireEndCurrentIteration(currentState);
445
446 currentState += 1;
447 }
448
449 currentLength = currentState;
450
451 return currentLength;
452 }
453
454 public void terminateChain() {
455 fireFinished(currentLength);
456
457 // Profiler.report();
458 }
459
460 public Likelihood getLikelihood() {
461 return likelihood;
462 }
463
464 public Model getModel() {
465 return likelihood.getModel();
466 }
467
468 public OperatorSchedule getSchedule() {
469 return schedule;
470 }
471
472 public Acceptor getAcceptor() {
473 return acceptor;
474 }
475
476 public double getInitialScore() {
477 return initialScore;
478 }
479
480 public double getBestScore() {
481 return bestScore;
482 }
483
484 public long getCurrentLength() {
485 return currentLength;
486 }
487
488 public void setCurrentLength(long currentLength) {
489 this.currentLength = currentLength;
490 }
491
492 public double getCurrentScore() {
493 return currentScore;
494 }
495
496 public void pleaseStop() {
497 pleaseStop = true;
498 }
499
500 public boolean isStopped() {
501 return isStopped;
502 }
503
504 public double evaluate() {
505 return evaluate(likelihood);
506 }
507
508 protected double evaluate(Likelihood likelihood) {
509
510 double logPosterior = 0.0;
511
512 final double logLikelihood = likelihood.getLogLikelihood();
513
514 if (Double.isNaN(logLikelihood)) {
515 return Double.NEGATIVE_INFINITY;
516 }
517 // System.err.println("** " + logPosterior + " + " + logLikelihood +
518 // " = " + (logPosterior + logLikelihood));
519 logPosterior += logLikelihood;
520
521 return logPosterior;
522 }
523
524 /**
525 * Updates the proposal parameter, based on the target acceptance
526 * probability This method relies on the proposal parameter being a
527 * decreasing function of acceptance probability.
528 *
529 * @param op The operator
530 * @param logr
531 */
532 private void adaptAcceptanceProbability(AdaptableMCMCOperator op, double logr) {
533
534 if (DEBUG) {
535 System.out.println("adaptAcceptanceProbability " + isAdaptable(op));
536 }
537
538 if (isAdaptable(op)) {
539 final double p = op.getAdaptableParameter();
540
541 final double i = schedule.getOptimizationTransform(MCMCOperator.Utils.getOperationCount(op));
542
543 final double target = op.getTargetAcceptanceProbability();
544
545 final double newp = p + ((1.0 / (i + 1.0)) * (Math.exp(logr) - target));
546
547 if (newp > -Double.MAX_VALUE && newp < Double.MAX_VALUE) {
548 op.setAdaptableParameter(newp);
549 if (DEBUG) {
550 System.out.println("Setting coercable parameter: " + newp + " target: " + target + " logr: " + logr);
551 }
552 }
553 }
554 }
555
556 private boolean isAdaptable(AdaptableMCMCOperator op) {
557
558 return op.getMode() == AdaptationMode.ADAPTATION_ON
559 || (op.getMode() != AdaptationMode.ADAPTATION_OFF && useAdaptation);
560 }
561
562 public void addMarkovChainListener(MarkovChainListener listener) {
563 if (listener != null) {
564 listeners.add(listener);
565 }
566 }
567
568 public void removeMarkovChainListener(MarkovChainListener listener) {
569 listeners.remove(listener);
570 }
571
572
573 private void fireBestModel(long state, Model bestModel) {
574
575 for (MarkovChainListener listener : listeners) {
576 listener.bestState(state, this, bestModel);
577 }
578 }
579
580 private void fireCurrentModel(long state, Model currentModel) {
581 for (MarkovChainListener listener : listeners) {
582 listener.currentState(state, this, currentModel);
583 }
584 }
585
586 private void fireFinished(long chainLength) {
587
588 for (MarkovChainListener listener : listeners) {
589 listener.finished(chainLength, this);
590 }
591 }
592
593 private void fireEndCurrentIteration(long state) {
594 }
595
596 private final ArrayList<MarkovChainListener> listeners = new ArrayList<MarkovChainListener>();
597 }