Debian Codegraph @

src/dr/inferencexml/MCMCParser.java

raw symbols SCIP
1 /*
2 * MCMCParser.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.inferencexml;
27
28 import dr.inference.loggers.Logger;
29 import dr.inference.markovchain.MarkovChain;
30 import dr.inference.mcmc.MCMC;
31 import dr.inference.mcmc.MCMCOptions;
32 import dr.inference.model.CompoundLikelihood;
33 import dr.inference.model.Likelihood;
34 import dr.inference.model.Model;
35 import dr.inference.model.Parameter;
36 import dr.inference.operators.OperatorSchedule;
37 import dr.inference.smc.SMC;
38 import dr.inference.smc.SMCOptions;
39 import dr.inference.state.Factory;
40 import dr.inference.state.StateLoaderSaver;
41 import dr.xml.*;
42
43 import java.io.File;
44 import java.util.ArrayList;
45 import java.util.List;
46
47 public class MCMCParser extends AbstractXMLObjectParser {
48
49 public String getParserName() {
50 return MCMC;
51 }
52
53 /**
54 * @return an mcmc object based on the XML element it was passed.
55 */
56 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
57 String id = xo.getAttribute(NAME, "mcmc1");
58
59 if (System.getProperty("smc.particle_folder") != null) {
60 return parseSMC(id, xo);
61 }
62
63 return parseMCMC(id, xo);
64 }
65
66 /**
67 * Parse the MCMC object.
68 * @param xo the XML object
69 * @return the MXMX object
70 * @throws XMLParseException an exception of there is an XML parse error
71 */
72 private MCMC parseMCMC(String id, XMLObject xo) throws XMLParseException {
73 MCMC mcmc = new MCMC(id);
74
75 long chainLength = xo.getLongIntegerAttribute(CHAIN_LENGTH);
76 boolean useAdaptation =
77 xo.getAttribute(ADAPTATION, true) ||
78 xo.getAttribute(AUTO_OPTIMIZE, true);
79 if (System.getProperty("mcmc.use_adaptation") != null) {
80 useAdaptation = Boolean.parseBoolean(System.getProperty("mcmc.use_adaptation"));
81 }
82 long adaptationDelay = chainLength / 100;
83 adaptationDelay =
84 xo.getAttribute(ADAPTATION_DELAY,
85 xo.getAttribute(AUTO_OPTIMIZE_DELAY,
86 xo.getAttribute(PRE_BURNIN, adaptationDelay)));
87
88 double adaptationTarget = 0.234;
89 if (System.getProperty("mcmc.adaptation_target") != null) {
90 adaptationTarget = Double.parseDouble(System.getProperty("mcmc.adaptation_target"));
91 }
92
93 double temperature = xo.getAttribute(TEMPERATURE, 1.0);
94
95 long fullEvaluationCount = 1000;
96 fullEvaluationCount = xo.getAttribute(FULL_EVALUATION, fullEvaluationCount);
97 if (System.getProperty("mcmc.evaluation.count") != null) {
98 fullEvaluationCount = Long.parseLong(System.getProperty("mcmc.evaluation.count"));
99 }
100
101 double evaluationTestThreshold = MarkovChain.EVALUATION_TEST_THRESHOLD;
102 evaluationTestThreshold = xo.getAttribute(EVALUATION_THRESHOLD, evaluationTestThreshold);
103 if (System.getProperty("mcmc.evaluation.threshold") != null) {
104 evaluationTestThreshold = Double.parseDouble(System.getProperty("mcmc.evaluation.threshold"));
105 }
106
107 int minOperatorCountForFullEvaluation = xo.getAttribute(MIN_OPS_EVALUATIONS, 1);
108
109 MCMCOptions options = new MCMCOptions(chainLength,
110 fullEvaluationCount,
111 minOperatorCountForFullEvaluation,
112 evaluationTestThreshold,
113 useAdaptation,
114 adaptationDelay,
115 adaptationTarget,
116 temperature);
117
118 OperatorSchedule opsched = (OperatorSchedule) xo.getChild(OperatorSchedule.class);
119 Likelihood likelihood = (Likelihood) xo.getChild(Likelihood.class);
120
121 likelihood.setUsed();
122
123 if (Boolean.valueOf(System.getProperty("show_warnings", "false"))) {
124
125 // check that all models, parameters and likelihoods are being used
126 for (Likelihood l : Likelihood.FULL_LIKELIHOOD_SET) {
127 if (!l.isUsed()) {
128 java.util.logging.Logger.getLogger("dr.inference").warning("Likelihood, " + l.getId() +
129 ", of class " + l.getClass().getName() + " is not being handled by the MCMC.");
130 }
131 }
132 for (Model m : Model.FULL_MODEL_SET) {
133 if (!m.isUsed()) {
134 java.util.logging.Logger.getLogger("dr.inference").warning("Model, " + m.getId() +
135 ", of class " + m.getClass().getName() + " is not being handled by the MCMC.");
136 }
137 }
138 for (Parameter p : Parameter.FULL_PARAMETER_SET) {
139 if (!p.isUsed()) {
140 java.util.logging.Logger.getLogger("dr.inference").warning("Parameter, " + p.getId() +
141 ", of class " + p.getClass().getName() + " is not being handled by the MCMC.");
142 }
143 }
144 }
145
146 ArrayList<Logger> loggers = new ArrayList<Logger>();
147
148 for (int i = 0; i < xo.getChildCount(); i++) {
149 Object child = xo.getChild(i);
150 if (child instanceof Logger) {
151 loggers.add((Logger) child);
152 }
153 }
154
155 mcmc.setShowOperatorAnalysis(true);
156 if (xo.hasAttribute(OPERATOR_ANALYSIS)) {
157 mcmc.setOperatorAnalysisFile(XMLParser.getLogFile(xo, OPERATOR_ANALYSIS));
158 }
159
160
161 Logger[] loggerArray = new Logger[loggers.size()];
162 loggers.toArray(loggerArray);
163
164 java.util.logging.Logger.getLogger("dr.inference").info("\nCreating the MCMC chain:" +
165 "\n chain length = " + options.getChainLength() +
166 "\n operator adaption = " + options.useAdaptation() +
167 (options.useAdaptation() ? "\n adaptation delayed for " + options.getAdaptationDelay() + " steps" : "") +
168 (options.getFullEvaluationCount() == 0 ? "\n full evaluation test off" : "")
169 );
170
171 mcmc.init(options, likelihood, opsched, loggerArray);
172
173
174 MarkovChain mc = mcmc.getMarkovChain();
175 double initialScore = mc.getCurrentScore();
176
177 if (initialScore == Double.NEGATIVE_INFINITY) {
178 String message = "The initial posterior is zero";
179 if (likelihood instanceof CompoundLikelihood) {
180 message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis(2);
181 } else {
182 message += "!";
183 }
184 throw new IllegalArgumentException(message);
185 }
186
187 if (!xo.getAttribute(SPAWN, true))
188 mcmc.setSpawnable(false);
189
190 return mcmc;
191 }
192
193 /**
194 * Parse the SMC variant of MCMC.
195 * @param xo the XML object
196 * @return the SMC object
197 * @throws XMLParseException an exception of there is an XML parse error
198 */
199 private SMC parseSMC(String id, XMLObject xo) throws XMLParseException {
200
201 List<StateLoaderSaver> particleStates = new ArrayList<StateLoaderSaver>();
202
203 String particleFolder = System.getProperty("smc.particle_folder");
204 File folder = new File(particleFolder);
205 if (!folder.isDirectory()) {
206 throw new XMLParseException("Specified particle folder is not a folder");
207 }
208
209 File[] particleFiles = folder.listFiles();
210 if (particleFiles == null || particleFiles.length == 0) {
211 throw new XMLParseException("Specified particle folder is empty");
212 }
213
214 for (final File particleFile : particleFiles) {
215 // The particles are setup with a fixed loading and saving file.
216
217 if (particleFile.isFile() && particleFile.getName().endsWith(".part")) {
218 final File saveFile = new File(particleFile.getAbsolutePath() + ".out");
219
220 particleStates.add(
221 Factory.INSTANCE.getStateLoaderSaver(particleFile, saveFile)
222 );
223 }
224 }
225
226 if (particleStates.size() == 0) {
227 throw new XMLParseException("No particle files were found in the folder");
228 }
229
230 SMC smc = new SMC(id, particleStates);
231
232 long chainLength = xo.getLongIntegerAttribute(CHAIN_LENGTH);
233
234 SMCOptions options = new SMCOptions(chainLength);
235
236 OperatorSchedule opsched = (OperatorSchedule) xo.getChild(OperatorSchedule.class);
237 Likelihood likelihood = (Likelihood) xo.getChild(Likelihood.class);
238
239 likelihood.setUsed();
240
241 ArrayList<Logger> loggers = new ArrayList<Logger>();
242
243 for (int i = 0; i < xo.getChildCount(); i++) {
244 Object child = xo.getChild(i);
245 if (child instanceof Logger) {
246 loggers.add((Logger) child);
247 }
248 }
249
250 Logger[] loggerArray = new Logger[loggers.size()];
251 loggers.toArray(loggerArray);
252
253 java.util.logging.Logger.getLogger("dr.inference").info("\nCreating the SMC chain set:" +
254 "\n particles = " + particleStates.size() +
255 "\n chain length = " + options.getChainLength()
256 );
257
258 smc.init(options, likelihood, opsched, loggerArray);
259
260 return smc;
261 }
262 //************************************************************************
263 // AbstractXMLObjectParser implementation
264 //************************************************************************
265
266 public String getParserDescription() {
267 return "This element returns an MCMC chain and runs the chain as a side effect.";
268 }
269
270 public Class getReturnType() {
271 return MCMC.class;
272 }
273
274 public XMLSyntaxRule[] getSyntaxRules() {
275 return rules;
276 }
277
278 private final XMLSyntaxRule[] rules = {
279 AttributeRule.newLongIntegerRule(CHAIN_LENGTH),
280 AttributeRule.newBooleanRule(ADAPTATION, true),
281 AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true),
282 AttributeRule.newIntegerRule(ADAPTATION_DELAY, true),
283 AttributeRule.newIntegerRule(AUTO_OPTIMIZE_DELAY, true),
284 AttributeRule.newIntegerRule(PRE_BURNIN, true),
285 AttributeRule.newDoubleRule(TEMPERATURE, true),
286 AttributeRule.newIntegerRule(FULL_EVALUATION, true),
287 AttributeRule.newIntegerRule(MIN_OPS_EVALUATIONS, true),
288 AttributeRule.newDoubleRule(EVALUATION_THRESHOLD, true),
289 AttributeRule.newBooleanRule(SPAWN, true),
290 AttributeRule.newStringRule(NAME, true),
291 AttributeRule.newStringRule(OPERATOR_ANALYSIS, true),
292 new ElementRule(OperatorSchedule.class),
293 new ElementRule(Likelihood.class),
294 new ElementRule(Logger.class, 1, Integer.MAX_VALUE),
295 };
296
297 public static final String ADAPTATION = "adaptation";
298 public static final String AUTO_OPTIMIZE = "autoOptimize";
299 public static final String NAME = "name";
300 public static final String PRE_BURNIN = "preBurnin";
301 public static final String ADAPTATION_DELAY = "adaptationDelay";
302 public static final String AUTO_OPTIMIZE_DELAY = "autoOptimizeDelay";
303 public static final String MCMC = "mcmc";
304 public static final String CHAIN_LENGTH = "chainLength";
305 public static final String FULL_EVALUATION = "fullEvaluation";
306 public static final String EVALUATION_THRESHOLD = "evaluationThreshold";
307 public static final String MIN_OPS_EVALUATIONS = "minOpsFullEvaluations";
308 public static final String WEIGHT = "weight";
309 public static final String TEMPERATURE = "temperature";
310 public static final String SPAWN = "spawn";
311 public static final String OPERATOR_ANALYSIS = "operatorAnalysis";
312
313
314 }