Debian Codegraph @

src/dr/inference/mcmcmc/MCMCMC.java

raw symbols SCIP
1 /*
2 * MCMCMC.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.mcmcmc;
27
28 import dr.inference.loggers.LogFormatter;
29 import dr.inference.loggers.Logger;
30 import dr.inference.loggers.MCLogger;
31 import dr.inference.markovchain.MarkovChain;
32 import dr.inference.markovchain.MarkovChainListener;
33 import dr.inference.mcmc.MCMC;
34 import dr.inference.mcmc.MCMCCriterion;
35 import dr.inference.mcmc.MCMCOptions;
36 import dr.inference.model.Likelihood;
37 import dr.inference.model.Model;
38 import dr.inference.operators.AdaptableMCMCOperator;
39 import dr.inference.operators.MCMCOperator;
40 import dr.inference.operators.OperatorAnalysisPrinter;
41 import dr.inference.operators.OperatorSchedule;
42 import dr.math.MathUtils;
43 import dr.util.NumberFormatter;
44
45 import java.util.Collections;
46 import java.util.List;
47
48 /**
49 * An MCMC analysis that estimates parameters of a probabilistic model.
50 *
51 * @author Andrew Rambaut
52 * @version $Id: ParallelMCMC.java,v 1.12 2005/01/10 10:56:59 rambaut Exp $
53 */
54 public class MCMCMC implements Runnable {
55
56 public final static boolean DEBUG = false;
57
58 public MCMCMC(MCMC[] mcmcs, MCMCMCOptions mcmcmcOptions) {
59
60 this.mcmcmcOptions = mcmcmcOptions;
61
62 if (mcmcmcOptions.getChainTemperatures()[0] != 1.0) {
63 throw new RuntimeException("The first chain in the array should be cold (temperature = 1.0)");
64 }
65
66 coldChain = 0;
67
68 this.mcmcOptions = mcmcs[coldChain].getOptions();
69
70 // Get all the loggers out of all the chains. We will only use the
71 // loggers of the cold chain but we need to swap the formatters around
72 // so that which every chain is cold always writes to the same destination.
73 mcLoggers = new MCLogger[mcmcs.length][];
74 for (int i = 0; i < mcmcs.length; i++) {
75 Logger[] loggers = mcmcs[i].getLoggers();
76 mcLoggers[i] = new MCLogger[loggers.length];
77 for (int j = 0; j < loggers.length; j++) {
78 mcLoggers[i][j] = (MCLogger) loggers[j];
79 }
80 if (mcLoggers[i] == null) {
81 throw new RuntimeException("There are no loggers in the MCMC chains.");
82 }
83 }
84
85 // Get all the operator schedules. The tuning values of these must be swapped
86 // around as the temperatures are swapped.
87 schedules = new OperatorSchedule[mcmcs.length];
88 for (int i = 0; i < schedules.length; i++) {
89 schedules[i] = mcmcs[i].getOperatorSchedule();
90 }
91
92 chains = new MarkovChain[mcmcs.length];
93
94 chains[0] = mcmcs[0].getMarkovChain();
95 for (int i = 1; i < chains.length; i++) {
96 chains[i] = mcmcs[i].getMarkovChain();
97 MCMCCriterion acceptor = ((MCMCCriterion) chains[i].getAcceptor());
98 acceptor.setTemperature(mcmcmcOptions.getChainTemperatures()[i]);
99 }
100
101 }
102
103 public void run() {
104 currentState = 0;
105
106 timer.start();
107
108 // if (isPreBurninNeeded()) {
109 // long preBurnin = mcmcOptions.getAdaptationDelay();
110 // if (preBurnin > 0) {
111 // MarkovChainListener burninListener = new BurninListener(preBurnin);
112 //
113 // chains[coldChain].addMarkovChainListener(burninListener);
114 // runChains(preBurnin, true);
115 // chains[coldChain].removeMarkovChainListener(burninListener);
116 // resetChains();
117 // }
118 // }
119
120 MCLogger[] coldChainLoggers = mcLoggers[coldChain];
121 List<LogFormatter>[] logFormatters = new List[coldChainLoggers.length];
122
123 for (int i = 0; i < coldChainLoggers.length; i++) {
124 // Start the logging for the cold chain
125 coldChainLoggers[i].startLogging();
126
127 // Now get the formatters (destinations) for the cold chains coldChainLoggers
128 logFormatters[i] = coldChainLoggers[i].getFormatters();
129 }
130
131 // Set the other chains to have null log formatters...
132 for (int j = 0; j < mcLoggers.length; j++) {
133 if (j != coldChain) {
134 for (int i = 0; i < mcLoggers[j].length; i++) {
135 mcLoggers[j][i].setFormatters(Collections.EMPTY_LIST);
136 }
137 }
138 }
139
140 chains[coldChain].addMarkovChainListener(chainListener);
141
142 MCMCMCRunner[] threads = new MCMCMCRunner[chains.length];
143 for (int i = 0; i < chains.length; i++) {
144 threads[i] = new MCMCMCRunner(chains[i], mcmcmcOptions.getSwapChainsEvery(), getChainLength(), false);
145 threads[i].start();
146 }
147
148 while (chains[coldChain].getCurrentLength() < getChainLength()) {
149
150 // wait for all the threads to complete their alloted chain length
151 boolean allDone;
152 do {
153 try {
154 Thread.sleep(10);
155 } catch (InterruptedException e) {
156 //
157 }
158
159 allDone = true;
160 for (int i = 0; i < chains.length; i++) {
161 if (!threads[i].isChainDone()) {
162 allDone = false;
163 }
164 }
165 } while (!allDone);
166
167 if (chains[coldChain].getCurrentLength() < getChainLength()) {
168 int oldColdChain = coldChain;
169
170 // attempt to swap two chains' temperatures
171 coldChain = swapChainTemperatures();
172
173 // if the cold chain was involved in a swap then we need to change the
174 // listener that does the logging and the destinations for the coldChainLoggers.
175 if (coldChain != oldColdChain) {
176
177 chains[oldColdChain].removeMarkovChainListener(chainListener);
178
179 // Set the new cold chain's loggers with the formatters (destinations) of
180 // the original cold chain
181 for (int i = 0; i < mcLoggers[coldChain].length; i++) {
182 mcLoggers[coldChain][i].setFormatters(logFormatters[i]);
183 }
184
185 // Set the old cold chain to have null log formatters...
186 for (int i = 0; i < mcLoggers[oldColdChain].length; i++) {
187 mcLoggers[oldColdChain][i].setFormatters(Collections.EMPTY_LIST);
188 }
189
190 chains[coldChain].addMarkovChainListener(chainListener);
191
192 }
193
194 for (int i = 0; i < chains.length; i++) {
195 threads[i].continueChain();
196 }
197 }
198
199 }
200
201 finish();
202
203 timer.stop();
204 }
205
206 private void runChains(long length, boolean disableCoerce) {
207
208 Thread[] threads = new Thread[chains.length];
209 for (int i = 0; i < chains.length; i++) {
210 threads[i] = new MCMCMCRunner(chains[i], length, length, false);
211 threads[i].start();
212 }
213
214 // wait for all threads collected to die
215 for (int i = 0; i < chains.length; i++) {
216 // wait doggedly for thread to die
217 while (threads[i].isAlive()) {
218 try {
219 threads[i].join();
220 } catch (InterruptedException ie) {
221 // DO NOTHING
222 }
223 }
224
225 }
226 }
227
228 private int swapChainTemperatures() {
229
230 if(DEBUG){
231 System.out.print("Current scores: ");
232 for(int i=0; i<chains.length; i++){
233 System.out.print("\t");
234 if(i==coldChain){
235 System.out.print("[");
236 }
237 System.out.print(chains[i].getCurrentScore());
238 if(i==coldChain){
239 System.out.print("]");
240 }
241 }
242 System.out.println();
243 }
244
245 int newColdChain = coldChain;
246
247 int index1 = MathUtils.nextInt(chains.length);
248 int index2 = MathUtils.nextInt(chains.length);
249 while (index1 == index2) {
250 index2 = MathUtils.nextInt(chains.length);
251 }
252
253 double score1 = chains[index1].getCurrentScore();
254 MCMCCriterion acceptor1 = ((MCMCCriterion) chains[index1].getAcceptor());
255 double temperature1 = acceptor1.getTemperature();
256 double score2 = chains[index2].getCurrentScore();
257 MCMCCriterion acceptor2 = ((MCMCCriterion) chains[index2].getAcceptor());
258 double temperature2 = acceptor2.getTemperature();
259
260 double logRatio = ((score2 - score1) * temperature1) + ((score1 - score2) * temperature2);
261 boolean swap = (Math.log(MathUtils.nextDouble()) < logRatio);
262
263 if (swap) {
264 if(DEBUG){
265 System.out.println("Swapping chain "+index1+" and chain "+index2);
266 }
267
268 acceptor1.setTemperature(temperature2);
269 acceptor2.setTemperature(temperature1);
270
271 OperatorSchedule schedule1 = schedules[index1];
272 OperatorSchedule schedule2 = schedules[index2];
273
274 for (int i = 0; i < schedule1.getOperatorCount(); i++) {
275 MCMCOperator operator1 = schedule1.getOperator(i);
276 MCMCOperator operator2 = schedule2.getOperator(i);
277
278 long tmp = operator1.getAcceptCount();
279 operator1.setAcceptCount(operator2.getAcceptCount());
280 operator2.setAcceptCount(tmp);
281
282 tmp = operator1.getRejectCount();
283 operator1.setRejectCount(operator2.getRejectCount());
284 operator2.setRejectCount(tmp);
285
286 double tmp2 = operator1.getSumDeviation();
287 operator1.setSumDeviation(operator2.getSumDeviation());
288 operator2.setSumDeviation(tmp2);
289
290 if (operator1 instanceof AdaptableMCMCOperator) {
291 tmp2 = ((AdaptableMCMCOperator) operator1).getAdaptableParameter();
292 ((AdaptableMCMCOperator) operator1).setAdaptableParameter(((AdaptableMCMCOperator) operator2).getAdaptableParameter());
293 ((AdaptableMCMCOperator) operator2).setAdaptableParameter(tmp2);
294 }
295 }
296
297 if (index1 == coldChain) {
298 newColdChain = index2;
299 } else if (index2 == coldChain) {
300 newColdChain = index1;
301 }
302 }
303
304 return newColdChain;
305 }
306
307 private void resetChains() {
308
309 for (MarkovChain chain : chains) {
310 chain.reset();
311 }
312 }
313
314 /**
315 * cleans up when the chain finishes (possibly early).
316 */
317 private void finish() {
318
319 NumberFormatter formatter = new NumberFormatter(8);
320
321 MCLogger[] loggers = mcLoggers[coldChain];
322 for (MCLogger logger : loggers) {
323 logger.log(currentState);
324 logger.stopLogging();
325 }
326
327 System.out.println();
328 System.out.println("Time taken: " + timer.toString());
329
330 if (showOperatorAnalysis) {
331 System.out.println();
332 System.out.println("Operator analysis");
333 System.out.println(
334 formatter.formatToFieldWidth("Operator", 30) +
335 formatter.formatToFieldWidth("", 8) +
336 formatter.formatToFieldWidth("Pr(accept)", 11) +
337 " Performance suggestion");
338
339 OperatorAnalysisPrinter.showOperatorAnalysis(System.out, schedules[coldChain], mcmcOptions.useAdaptation());
340 System.out.println();
341 }
342 }
343
344 private final MarkovChainListener chainListener = new MarkovChainListener() {
345
346 // MarkovChainListener interface *******************************************
347 // for receiving messages from subordinate MarkovChain
348
349 /**
350 * Called to update the current model keepEvery states.
351 */
352 public synchronized void currentState(long state, MarkovChain markovChain, Model currentModel) {
353
354 currentState = state;
355
356 if (state % 1000 == 0) {
357 NumberFormatter formatter = new NumberFormatter(8);
358 formatter.setPadding(false);
359
360 //System.out.print("State " + currentState + ": ");
361 for (int i = 0; i < chains.length; i++) {
362 String score;
363 if (i == coldChain) {
364 score = "[" + formatter.format(chains[i].getCurrentScore()) + "]";
365 } else {
366 score = formatter.format(chains[i].getCurrentScore());
367 }
368 score += " ";
369 System.out.print(formatter.formatToFieldWidth(score, 12));
370 }
371 System.out.println();
372 }
373
374 MCLogger[] loggers = mcLoggers[coldChain];
375 for (MCLogger logger : loggers) {
376 logger.log(state);
377 }
378
379 }
380
381 /**
382 * Called when a new new best posterior state is found.
383 */
384 public synchronized void bestState(long state, MarkovChain markovChain, Model bestModel) {
385 currentState = state;
386 }
387
388 /**
389 * cleans up when the chain finishes (possibly early).
390 */
391 public synchronized void finished(long chainLength, MarkovChain markovChain) {
392 }
393
394 };
395
396 public int getColdChain() {
397 return coldChain;
398 }
399
400 /**
401 * @return the likelihood function.
402 */
403 public Likelihood getLikelihood() {
404 return chains[coldChain].getLikelihood();
405 }
406
407 /**
408 * @return the timer.
409 */
410 public dr.util.Timer getTimer() {
411 return timer;
412 }
413
414 /**
415 * @return the length of this analysis.
416 */
417 public final long getChainLength() {
418 return mcmcOptions.getChainLength();
419 }
420
421 // TRANSIENT PUBLIC METHODS *****************************************
422
423 /**
424 * @return the current state of the MCMC analysis.
425 */
426 public final long getCurrentState() {
427 return currentState;
428 }
429
430 /**
431 * @return the progress (0 to 1) of the MCMC analysis.
432 */
433 public final double getProgress() {
434 return (double) currentState / (double) mcmcOptions.getChainLength();
435 }
436
437 /**
438 * Requests that the MCMC chain stop prematurely.
439 */
440 public void pleaseStop() {
441 for (MarkovChain chain : chains) {
442 chain.pleaseStop();
443 }
444 }
445
446 public void setShowOperatorAnalysis(boolean soa) {
447 showOperatorAnalysis = soa;
448 }
449
450 // PRIVATE TRANSIENTS
451
452 private final MCMCOptions mcmcOptions;
453 private final MCMCMCOptions mcmcmcOptions;
454
455 private boolean showOperatorAnalysis = true;
456 private final dr.util.Timer timer = new dr.util.Timer();
457 private long currentState = 0;
458
459 private final MarkovChain[] chains;
460 private final MCLogger[][] mcLoggers;
461 private final OperatorSchedule[] schedules;
462 private int coldChain;
463 }
464