Debian Codegraph @

src/dr/inference/mcmc/MCMC.java

raw symbols SCIP
1 /*
2 * MCMC.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.mcmc;
27
28 import dr.inference.state.Factory;
29 import dr.inference.state.StateLoader;
30 import dr.inference.loggers.LogColumn;
31 import dr.inference.loggers.Loggable;
32 import dr.inference.loggers.Logger;
33 import dr.inference.markovchain.MarkovChain;
34 import dr.inference.markovchain.MarkovChainListener;
35 import dr.inference.model.Likelihood;
36 import dr.inference.model.Model;
37 import dr.inference.operators.*;
38 import dr.util.Identifiable;
39 import dr.util.NumberFormatter;
40 import dr.xml.Spawnable;
41
42 import java.io.File;
43 import java.io.FileOutputStream;
44 import java.io.IOException;
45 import java.io.PrintStream;
46
47 /**
48 * An MCMC analysis that estimates parameters of a probabilistic model.
49 *
50 * @author Alexei Drummond
51 * @author Andrew Rambaut
52 * @version $Id: MCMC.java,v 1.41 2005/07/11 14:06:25 rambaut Exp $
53 */
54 public class MCMC implements Identifiable, Spawnable, Loggable {
55
56 public MCMC(String id) {
57 this.id = id;
58 }
59
60 /**
61 * Must be called before calling chain.
62 *
63 * @param options the options for this MCMC analysis
64 * @param schedule operator schedule to be used in chain.
65 * @param likelihood the likelihood for this MCMC
66 * @param loggers an array of loggers to record output of this MCMC run
67 */
68 public void init(
69 MCMCOptions options,
70 Likelihood likelihood,
71 OperatorSchedule schedule,
72 Logger[] loggers) {
73
74 MCMCCriterion criterion = new MCMCCriterion();
75 criterion.setTemperature(options.getTemperature());
76
77 mc = new MarkovChain(likelihood, schedule, criterion,
78 options.getFullEvaluationCount(), options.minOperatorCountForFullEvaluation(),
79 options.getEvaluationTestThreshold(),
80 options.useAdaptation());
81
82 this.options = options;
83 this.loggers = loggers;
84 this.schedule = schedule;
85
86 //initialize transients
87 currentState = 0;
88
89 if (Factory.INSTANCE != null) {
90 for (MarkovChainListener listener : Factory.INSTANCE.getStateSaverChainListeners()) {
91 mc.addMarkovChainListener(listener);
92 }
93 }
94
95 }
96
97 /**
98 * Must be called before calling chain.
99 *
100 * @param chainlength chain length
101 * @param likelihood the likelihood for this MCMC
102 * @param operators an array of MCMC operators
103 * @param loggers an array of loggers to record output of this MCMC run
104 */
105 public void init(long chainlength,
106 Likelihood likelihood,
107 MCMCOperator[] operators,
108 Logger[] loggers) {
109
110 MCMCOptions options = new MCMCOptions(chainlength);
111 MCMCCriterion criterion = new MCMCCriterion();
112 criterion.setTemperature(1);
113 OperatorSchedule schedule = new SimpleOperatorSchedule();
114 for (MCMCOperator operator : operators) schedule.addOperator(operator);
115
116 init(options, likelihood, schedule, loggers);
117 }
118
119 public MarkovChain getMarkovChain() {
120 return mc;
121 }
122
123 public Logger[] getLoggers() {
124 return loggers;
125 }
126
127 public MCMCOptions getOptions() {
128 return options;
129 }
130
131 public OperatorSchedule getOperatorSchedule() {
132 return schedule;
133 }
134
135 public void run() {
136 chain();
137 }
138
139 /**
140 * This method actually initiates the MCMC analysis.
141 */
142 public void chain() {
143
144 stopping = false;
145 currentState = 0;
146
147 timer.start();
148
149 if (loggers != null) {
150 for (Logger logger : loggers) {
151 logger.startLogging();
152 }
153 }
154
155 if (!stopping) {
156
157 long loadedState = 0;
158
159 if (Factory.INSTANCE != null) {
160 StateLoader initialStateLoader = Factory.INSTANCE.getInitialStateLoader();
161 if (initialStateLoader != null) {
162 double[] savedLnL = new double[1];
163
164 initialStateLoader.loadState(mc, savedLnL);
165
166 mc.setCurrentLength(loadedState);
167
168 double lnL = mc.evaluate();
169
170 initialStateLoader.checkLoadState(savedLnL[0], lnL);
171 }
172 }
173
174 mc.addMarkovChainListener(chainListener);
175
176 long chainLength = getChainLength();
177
178 //this also potentially gets the new adapationDelay of a possibly increased chain length
179 final long adapationDelay = getAdaptationDelay();
180
181 //assume that saved state has passed the adapationDelay
182 //TODO: discuss whether we want to save the adapationDelay or chainLength to file
183 if (adapationDelay > loadedState) {
184 mc.runChain(adapationDelay - loadedState, true);
185 chainLength -= adapationDelay;
186 }
187
188 //if (adapationDelay > 0) {
189 // Run the chain for adapationDelay steps with coercion disabled
190 //mc.runChain(adapationDelay, true);
191 //chainLength -= adapationDelay;
192
193 // reset operator acceptance levels
194 //GB: we are now restoring these; commenting out for now
195 /*for (int i = 0; i < schedule.getOperatorCount(); i++) {
196 schedule.getOperator(i).reset();
197 }*/
198 //}
199
200 mc.runChain(chainLength, false);
201
202 mc.terminateChain();
203
204 mc.removeMarkovChainListener(chainListener);
205
206 }
207 timer.stop();
208 }
209
210 @Override
211 public LogColumn[] getColumns() {
212 return new LogColumn[] { new LogColumn() {
213 @Override
214 public void setLabel(String label) {
215 }
216
217 @Override
218 public String getLabel() {
219 return "time";
220 }
221
222 @Override
223 public void setMinimumWidth(int minimumWidth) {
224
225 }
226
227 @Override
228 public int getMinimumWidth() {
229 return 0;
230 }
231
232 @Override
233 public String getFormatted() {
234 return Double.toString(getTimer().toSeconds());
235 }
236 } };
237 }
238
239 private final MarkovChainListener chainListener = new MarkovChainListener() {
240
241 // MarkovChainListener interface *******************************************
242 // for receiving messages from subordinate MarkovChain
243
244 /**
245 * Called to update the current model keepEvery states.
246 */
247 @Override
248 public void currentState(long state, MarkovChain markovChain, Model currentModel) {
249
250 currentState = state;
251
252 if (loggers != null) {
253 for (Logger logger : loggers) {
254 logger.log(state);
255 }
256 }
257 }
258
259 /**
260 * Called when a new new best posterior state is found.
261 */
262 @Override
263 public void bestState(long state, MarkovChain markovChain, Model bestModel) { }
264
265 /**
266 * cleans up when the chain finishes (possibly early).
267 */
268 @Override
269 public void finished(long chainLength, MarkovChain markovChain) {
270 currentState = chainLength;
271
272 if (loggers != null) {
273 for (Logger logger : loggers) {
274 logger.log(currentState);
275 logger.stopLogging();
276 }
277 }
278 // OperatorAnalysisPrinter class can do the job now
279 if (showOperatorAnalysis) {
280 OperatorAnalysisPrinter.showOperatorAnalysis(System.out, getOperatorSchedule(), options.useAdaptation());
281 }
282
283 if (operatorAnalysisFile != null) {
284 try {
285 PrintStream out = new PrintStream(new FileOutputStream(operatorAnalysisFile));
286 OperatorAnalysisPrinter.showOperatorAnalysis(out, getOperatorSchedule(), options.useAdaptation());
287 out.flush();
288 out.close();
289 } catch (IOException e) {
290 e.printStackTrace();
291 }
292 }
293
294 // How should premature finish be flagged?
295 }
296
297 };
298
299 /**
300 * @return the likelihood function.
301 */
302 public Likelihood getLikelihood() {
303 return mc.getLikelihood();
304 }
305
306 /**
307 * @return the timer.
308 */
309 public dr.util.Timer getTimer() {
310 return timer;
311 }
312
313 /**
314 * @return the length of this analysis.
315 */
316 public final long getChainLength() {
317 return options.getChainLength();
318 }
319
320 // TRANSIENT PUBLIC METHODS *****************************************
321
322 /**
323 * @return the current state of the MCMC analysis.
324 */
325 public final long getCurrentState() {
326 return currentState;
327 }
328
329 /**
330 * @return the progress (0 to 1) of the MCMC analysis.
331 */
332 public final double getProgress() {
333 return (double) currentState / (double) options.getChainLength();
334 }
335
336 /**
337 * @return true if this MCMC is currently adapting the operators.
338 */
339 public final boolean isAdapting() {
340 return isAdapting;
341 }
342
343 /**
344 * Requests that the MCMC chain stop prematurely.
345 */
346 public void pleaseStop() {
347 stopping = true;
348 mc.pleaseStop();
349 }
350
351 /**
352 * @return true if Markov chain is stopped
353 */
354 public boolean isStopped() {
355 return mc.isStopped();
356 }
357
358 public boolean getSpawnable() {
359 return spawnable;
360 }
361
362 private boolean spawnable = true;
363
364 public void setSpawnable(boolean spawnable) {
365 this.spawnable = spawnable;
366 }
367
368
369 //PRIVATE METHODS *****************************************
370 protected long getAdaptationDelay() {
371
372 long delay = options.getAdaptationDelay();
373 if (delay < 0) {
374 delay = (long)(options.getChainLength() / 100);
375 }
376 if (options.useAdaptation()) return delay;
377
378 for (int i = 0; i < schedule.getOperatorCount(); i++) {
379 MCMCOperator op = schedule.getOperator(i);
380
381 if (op instanceof AdaptableMCMCOperator) {
382 if (((AdaptableMCMCOperator) op).getMode() == AdaptationMode.ADAPTATION_ON) return delay;
383 }
384 }
385
386 return -1;
387 }
388
389 public void setShowOperatorAnalysis(boolean soa) {
390 showOperatorAnalysis = soa;
391 }
392
393
394 public void setOperatorAnalysisFile(File operatorAnalysisFile) {
395 this.operatorAnalysisFile = operatorAnalysisFile;
396 }
397
398 public String getId() {
399 return id;
400 }
401
402 public void setId(String id) {
403 this.id = id;
404 }
405
406 // PRIVATE TRANSIENTS
407
408 //private FileLogger operatorLogger = null;
409 protected final boolean isAdapting = true;
410 protected boolean stopping = false;
411 protected boolean showOperatorAnalysis = true;
412 protected File operatorAnalysisFile = null;
413 protected final dr.util.Timer timer = new dr.util.Timer();
414 protected long currentState = 0;
415 //private int stepsPerReport = 1000;
416 protected final NumberFormatter formatter = new NumberFormatter(8);
417
418 /**
419 * this markov chain does most of the work.
420 */
421 protected MarkovChain mc;
422
423 /**
424 * the options of this MCMC analysis
425 */
426 protected MCMCOptions options;
427
428 protected Logger[] loggers;
429 protected OperatorSchedule schedule;
430
431 private String id = null;
432 }