Debian Codegraph @

src/dr/app/checkpoint/BeastCheckpointer.java

raw symbols SCIP
1 /*
2 * BeastCheckpointer.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.app.checkpoint;
27
28 import dr.evolution.tree.NodeRef;
29 import dr.evomodel.tree.TreeModel;
30 import dr.evomodel.tree.TreeParameterModel;
31 import dr.inference.markovchain.MarkovChain;
32 import dr.inference.markovchain.MarkovChainListener;
33 import dr.inference.model.Likelihood;
34 import dr.inference.model.Model;
35 import dr.inference.model.Parameter;
36 import dr.inference.operators.AdaptableMCMCOperator;
37 import dr.inference.operators.MCMCOperator;
38 import dr.inference.operators.OperatorSchedule;
39 import dr.inference.state.*;
40 import dr.math.MathUtils;
41
42 import java.io.*;
43 import java.text.SimpleDateFormat;
44 import java.util.*;
45
46 /**
47 * A state loader / saver
48 * @author Andrew Rambaut
49 * @author Guy Baele
50 */
51 public class BeastCheckpointer implements StateLoaderSaver {
52
53 private static final boolean DEBUG = false;
54
55 // A debugging flag to do a check that the state gives the same likelihood after loading
56 private static final boolean CHECK_LOAD_STATE = true;
57
58 public final static String LOAD_STATE_FILE = "load.state.file";
59 public final static String SAVE_STATE_FILE = "save.state.file";
60 public final static String SAVE_STATE_AT = "save.state.at";
61 public final static String SAVE_STATE_EVERY = "save.state.every";
62 public final static String SAVE_STEM = "save.state.stem";
63
64 public final static String FORCE_RESUME = "force.resume";
65
66 private final String loadStateFileName;
67 private final String saveStateFileName;
68
69 private final String stemFileName;
70
71 private boolean forceResume = false;
72
73 public BeastCheckpointer() {
74 loadStateFileName = System.getProperty(LOAD_STATE_FILE, null);
75 saveStateFileName = System.getProperty(SAVE_STATE_FILE, null);
76
77 stemFileName = System.getProperty(SAVE_STEM, null);
78
79 final List<MarkovChainListener> listeners = new ArrayList<MarkovChainListener>();
80
81 if (System.getProperty(SAVE_STATE_AT) != null) {
82 final long saveStateAt = Long.parseLong(System.getProperty(SAVE_STATE_AT));
83 listeners.add(new StateSaverChainListener(BeastCheckpointer.this, saveStateAt,false));
84 }
85 if (System.getProperty(SAVE_STATE_EVERY) != null) {
86 final long saveStateEvery = Long.parseLong(System.getProperty(SAVE_STATE_EVERY));
87 listeners.add(new StateSaverChainListener(BeastCheckpointer.this, saveStateEvery,true));
88 }
89
90 Factory.INSTANCE = new Factory() {
91 @Override
92 public StateLoader getInitialStateLoader() {
93 if (loadStateFileName == null) {
94 return null;
95 } else {
96 return getStateLoaderObject();
97 }
98 }
99
100 @Override
101 public MarkovChainListener[] getStateSaverChainListeners() {
102 return listeners.toArray(new MarkovChainListener[0]);
103 }
104
105 @Override
106 public StateLoaderSaver getStateLoaderSaver(final File loadFile, final File saveFile) {
107 return new StateLoaderSaver() {
108
109 @Override
110 public boolean saveState(MarkovChain markovChain, long state, double lnL) {
111 return BeastCheckpointer.this.writeStateToFile(saveFile, state, lnL, markovChain);
112 }
113
114 @Override
115 public long loadState(MarkovChain markovChain, double[] savedLnL) {
116 return BeastCheckpointer.this.readStateFromFile(loadFile, markovChain, savedLnL);
117 }
118
119 @Override
120 public void checkLoadState(double savedLnL, double lnL) {
121 // do nothing.
122 }
123 };
124 }
125 };
126
127 }
128
129 private BeastCheckpointer getStateLoaderObject() {
130 return this;
131 }
132
133 @Override
134 public boolean saveState(MarkovChain markovChain, long state, double lnL) {
135 String fileName = "";
136 if (stemFileName != null) {
137 fileName = stemFileName + "_" + state;
138 } else {
139 String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(Calendar.getInstance().getTime());
140 fileName = (this.saveStateFileName != null ? this.saveStateFileName : "beast_state_" + timeStamp);
141 }
142 return writeStateToFile(new File(fileName), state, lnL, markovChain);
143 }
144
145 @Override
146 public long loadState(MarkovChain markovChain, double[] savedLnL) {
147 return readStateFromFile(new File(loadStateFileName), markovChain, savedLnL);
148 }
149
150 @Override
151 public void checkLoadState(double savedLnL, double lnL) {
152
153 if (CHECK_LOAD_STATE) {
154
155 if (System.getProperty(FORCE_RESUME) != null) {
156 forceResume = Boolean.parseBoolean(System.getProperty(FORCE_RESUME));
157 //System.out.println("FORCE_RESUME? " + System.getProperty(FORCE_RESUME) + " (" + forceResume + "");
158 }
159
160 //first perform a simple check for equality of two doubles
161 //when this test fails, go over the digits
162 if (forceResume) {
163 System.out.println("Forcing analysis to resume regardless of recomputed likelihood values.");
164 } else if (lnL != savedLnL) {
165
166 System.out.println("COMPARING LIKELIHOODS: " + lnL + " vs. " + savedLnL);
167
168 //15 is the floor value for the number of decimal digits when representing a double
169 //checking for 15 identical digits below
170 String originalString = Double.toString(savedLnL);
171 String restoredString = Double.toString(lnL);
172 System.out.println(lnL + " " + originalString);
173 System.out.println(savedLnL + " " + restoredString);
174 //assume values will be nearly identical
175 int digits = 0;
176 for (int i = 0; i < Math.min(originalString.length(), restoredString.length()); i++) {
177 if (originalString.charAt(i) == restoredString.charAt(i)) {
178 if (!(originalString.charAt(i) == '-' || originalString.charAt(i) == '.')) {
179 digits++;
180 }
181 } else {
182 break;
183 }
184 }
185 //System.err.println("digits = " + digits);
186
187 //the translation table is constructed upon loading the initial tree for the analysis
188 //if that tree is user-defined or a UPGMA starting tree, the starting seed won't matter
189 //if that tree is constructed at random, we currently don't provide a way to retrieve the original translation table
190
191 if (digits < 15) {
192
193 //currently use the general BEAST -threshold argument
194 //TODO Evaluate whether a checkpoint-specific threshold option is required or useful
195 double threshold = 0.0;
196 if (System.getProperty("mcmc.evaluation.threshold") != null) {
197 threshold = Double.parseDouble(System.getProperty("mcmc.evaluation.threshold"));
198 }
199 if (Math.abs(lnL - savedLnL) > threshold) {
200 throw new RuntimeException("Saved lnL does not match recomputed value for loaded state: stored lnL: " + savedLnL +
201 ", recomputed lnL: " + lnL + " (difference " + (savedLnL - lnL) + ")." +
202 "\nYour XML may require the construction of a randomly generated starting tree. " +
203 "Try resuming the analysis by using the same starting seed as for the original BEAST run.");
204 } else {
205 System.out.println("Saved lnL does not match recomputed value for loaded state: stored lnL: " + savedLnL +
206 ", recomputed lnL: " + lnL + " (difference " + (savedLnL - lnL) + ")." +
207 "\nThreshold of " + threshold + " for restarting analysis not exceeded; continuing ...");
208 }
209 }
210
211 } else {
212 System.out.println("IDENTICAL LIKELIHOODS");
213 System.out.println("lnL" + " = " + lnL);
214 System.out.println("savedLnL[0]" + " = " + savedLnL);
215 }
216
217 }
218 }
219
220 protected boolean writeStateToFile(File file, long state, double lnL, MarkovChain markovChain) {
221 OperatorSchedule operatorSchedule = markovChain.getSchedule();
222
223 OutputStream fileOut = null;
224 try {
225 fileOut = new FileOutputStream(file);
226 PrintStream out = new PrintStream(fileOut);
227
228 ArrayList<TreeParameterModel> traitModels = new ArrayList<TreeParameterModel>();
229
230 int[] rngState = MathUtils.getRandomState();
231 out.print("rng");
232 for (int i = 0; i < rngState.length; i++) {
233 out.print("\t");
234 out.print(rngState[i]);
235 }
236 out.println();
237
238 out.print("state\t");
239 out.println(state);
240
241 out.print("lnL\t");
242 out.println(lnL);
243
244 for (Parameter parameter : Parameter.CONNECTED_PARAMETER_SET) {
245 out.print("parameter");
246 out.print("\t");
247 out.print(parameter.getParameterName());
248 out.print("\t");
249 out.print(parameter.getDimension());
250 for (int dim = 0; dim < parameter.getDimension(); dim++) {
251 out.print("\t");
252 out.print(parameter.getParameterValue(dim));
253 }
254 out.println();
255 }
256
257 for (int i = 0; i < operatorSchedule.getOperatorCount(); i++) {
258 MCMCOperator operator = operatorSchedule.getOperator(i);
259 out.print("operator");
260 out.print("\t");
261 out.print(operator.getOperatorName());
262 out.print("\t");
263 out.print(operator.getAcceptCount());
264 out.print("\t");
265 out.print(operator.getRejectCount());
266 if (operator instanceof AdaptableMCMCOperator) {
267 out.print("\t");
268 out.print(((AdaptableMCMCOperator)operator).getAdaptableParameter());
269 }
270 out.println();
271 }
272
273 //check up front if there are any TreeParameterModel objects
274 for (Model model : Model.CONNECTED_MODEL_SET) {
275 if (model instanceof TreeParameterModel) {
276 //System.out.println("\nDetected TreeParameterModel: " + ((TreeParameterModel) model).toString());
277 traitModels.add((TreeParameterModel) model);
278 }
279 }
280
281 for (Model model : Model.CONNECTED_MODEL_SET) {
282
283 if (model instanceof TreeModel) {
284 out.print("tree");
285 out.print("\t");
286 out.println(model.getModelName());
287
288 //replace Newick format by printing general graph structure
289 //out.println(((TreeModel) model).getNewick());
290
291 out.println("#node height taxon");
292 int nodeCount = ((TreeModel) model).getNodeCount();
293 out.println(nodeCount);
294 for (int i = 0; i < nodeCount; i++) {
295 out.print(((TreeModel) model).getNode(i).getNumber());
296 out.print("\t");
297 out.print(((TreeModel) model).getNodeHeight(((TreeModel) model).getNode(i)));
298 if (((TreeModel) model).isExternal(((TreeModel) model).getNode(i))) {
299 out.print("\t");
300 out.print(((TreeModel) model).getNodeTaxon(((TreeModel) model).getNode(i)).getId());
301 }
302 out.println();
303 }
304
305 out.println("#edges");
306 out.println("#child-node parent-node L/R-child traits");
307
308 out.println(nodeCount);
309 for (int i = 0; i < nodeCount; i++) {
310 NodeRef parent = ((TreeModel) model).getParent(((TreeModel) model).getNode(i));
311 if (parent != null) {
312 out.print(((TreeModel) model).getNode(i).getNumber());
313 out.print("\t");
314 out.print(((TreeModel) model).getParent(((TreeModel) model).getNode(i)).getNumber());
315 out.print("\t");
316
317 if ((((TreeModel) model).getChild(parent, 0) == ((TreeModel) model).getNode(i))) {
318 //left child
319 out.print(0);
320 } else if ((((TreeModel) model).getChild(parent, 1) == ((TreeModel) model).getNode(i))) {
321 //right child
322 out.print(1);
323 } else {
324 throw new RuntimeException("Operation currently only supported for nodes with 2 children.");
325 }
326
327 //only print the TreeParameterModel that matches the TreeModel currently being written
328 for (TreeParameterModel tpm : traitModels) {
329 if (model == tpm.getTreeModel()) {
330 out.print("\t");
331 out.print(tpm.getNodeValue((TreeModel) model, ((TreeModel) model).getNode(i)));
332 }
333 }
334 out.println();
335 } else {
336 if (DEBUG) {
337 System.out.println(((TreeModel) model).getNode(i) + " has no parent.");
338 }
339 }
340 }
341
342 }
343
344 }
345
346 out.close();
347 fileOut.close();
348 } catch (IOException ioe) {
349 System.err.println("Unable to write file: " + ioe.getMessage());
350 return false;
351 }
352
353 if (DEBUG) {
354 for (Likelihood likelihood : Likelihood.CONNECTED_LIKELIHOOD_SET) {
355 System.err.println(likelihood.getId() + ": " + likelihood.getLogLikelihood());
356 }
357 }
358
359 return true;
360 }
361
362 protected long readStateFromFile(File file, MarkovChain markovChain, double[] lnL) {
363 OperatorSchedule operatorSchedule = markovChain.getSchedule();
364
365 long state = -1;
366
367 ArrayList<TreeParameterModel> traitModels = new ArrayList<TreeParameterModel>();
368
369 try {
370 FileReader fileIn = new FileReader(file);
371 BufferedReader in = new BufferedReader(fileIn);
372
373 int[] rngState = null;
374
375 String line = in.readLine();
376 String[] fields = line.split("\t");
377 if (fields[0].equals("rng")) {
378 // if there is a random number generator state present then load it...
379 try {
380 rngState = new int[fields.length - 1];
381 for (int i = 0; i < rngState.length; i++) {
382 rngState[i] = Integer.parseInt(fields[i + 1]);
383 }
384
385 } catch (NumberFormatException nfe) {
386 throw new RuntimeException("Unable to read state number from state file");
387 }
388
389 line = in.readLine();
390 fields = line.split("\t");
391 }
392
393 try {
394 if (!fields[0].equals("state")) {
395 throw new RuntimeException("Unable to read state number from state file");
396 }
397 state = Long.parseLong(fields[1]);
398 } catch (NumberFormatException nfe) {
399 throw new RuntimeException("Unable to read state number from state file");
400 }
401
402 line = in.readLine();
403 fields = line.split("\t");
404 try {
405 if (!fields[0].equals("lnL")) {
406 throw new RuntimeException("Unable to read lnL from state file");
407 }
408 if (lnL != null) {
409 lnL[0] = Double.parseDouble(fields[1]);
410 }
411 } catch (NumberFormatException nfe) {
412 throw new RuntimeException("Unable to read lnL from state file");
413 }
414
415 for (Parameter parameter : Parameter.CONNECTED_PARAMETER_SET) {
416
417 line = in.readLine();
418 fields = line.split("\t");
419 //if (!fields[0].equals(parameter.getParameterName())) {
420 // System.err.println("Unable to match state parameter: " + fields[0] + ", expecting " + parameter.getParameterName());
421 //}
422 int dimension = Integer.parseInt(fields[2]);
423
424 if (dimension != parameter.getDimension()) {
425 System.err.println("Unable to match state parameter dimension: " + dimension + ", expecting " + parameter.getDimension() + " for parameter: " + parameter.getParameterName());
426 System.err.print("Read from file: ");
427 for (int i = 0; i < fields.length; i++) {
428 System.err.print(fields[i] + "\t");
429 }
430 System.err.println();
431 }
432
433 if (fields[1].equals("branchRates.categories.rootNodeNumber")) {
434 // System.out.println("eek");
435 double value = Double.parseDouble(fields[3]);
436 parameter.setParameterValue(0, value);
437 if (DEBUG) {
438 System.out.println("restoring " + fields[1] + " with value " + value);
439 }
440 } else {
441 if (DEBUG) {
442 System.out.print("restoring " + fields[1] + " with values ");
443 }
444 for (int dim = 0; dim < parameter.getDimension(); dim++) {
445 parameter.setParameterValue(dim, Double.parseDouble(fields[dim + 3]));
446 if (DEBUG) {
447 System.out.print(Double.parseDouble(fields[dim + 3]) + " ");
448 }
449 }
450 if (DEBUG) {
451 System.out.println();
452 }
453 }
454
455 }
456
457 for (int i = 0; i < operatorSchedule.getOperatorCount(); i++) {
458 MCMCOperator operator = operatorSchedule.getOperator(i);
459 line = in.readLine();
460 fields = line.split("\t");
461 if (!fields[1].equals(operator.getOperatorName())) {
462 throw new RuntimeException("Unable to match operator: " + fields[1]);
463 }
464 if (fields.length < 4) {
465 throw new RuntimeException("Operator missing values: " + fields[1]);
466 }
467 operator.setAcceptCount(Integer.parseInt(fields[2]));
468 operator.setRejectCount(Integer.parseInt(fields[3]));
469 if (operator instanceof AdaptableMCMCOperator) {
470 if (fields.length != 5) {
471 throw new RuntimeException("Coercable operator missing parameter: " + fields[1]);
472 }
473 ((AdaptableMCMCOperator)operator).setAdaptableParameter(Double.parseDouble(fields[4]));
474 }
475 }
476
477 // load the tree models last as we get the node heights from the tree (not the parameters which
478 // which may not be associated with the right node
479 Set<String> expectedTreeModelNames = new HashSet<String>();
480
481 //store list of TreeModels for debugging purposes
482 ArrayList<TreeModel> treeModelList = new ArrayList<TreeModel>();
483
484 for (Model model : Model.CONNECTED_MODEL_SET) {
485
486 if (model instanceof TreeModel) {
487 if (DEBUG) {
488 System.out.println("model " + model.getModelName());
489 }
490 treeModelList.add((TreeModel)model);
491 expectedTreeModelNames.add(model.getModelName());
492 if (DEBUG) {
493 System.out.println("\nexpectedTreeModelNames:");
494 for (String s : expectedTreeModelNames) {
495 System.out.println(s);
496 }
497 System.out.println();
498 }
499 }
500
501 //first add all TreeParameterModels to a list
502 if (model instanceof TreeParameterModel) {
503 traitModels.add((TreeParameterModel)model);
504 }
505
506 }
507
508 //explicitly link TreeModel (using its unique ID) to a list of TreeParameterModels
509 //this information is currently not yet used
510 HashMap<String, ArrayList<TreeParameterModel>> linkedModels = new HashMap<String, ArrayList<TreeParameterModel>>();
511 for (String name : expectedTreeModelNames) {
512 ArrayList<TreeParameterModel> tpmList = new ArrayList<TreeParameterModel>();
513 for (TreeParameterModel tpm : traitModels) {
514 if (tpm.getTreeModel().getId().equals(name)) {
515 tpmList.add(tpm);
516 if (DEBUG) {
517 System.out.println("TreeModel: " + name + " has been assigned TreeParameterModel: " + tpm.toString());
518 }
519 }
520 }
521 linkedModels.put(name, tpmList);
522 }
523
524 line = in.readLine();
525 fields = line.split("\t");
526 // Read in all (possibly more than one) trees
527 while (fields[0].equals("tree")) {
528
529 if (DEBUG) {
530 System.out.println("\ntree: " + fields[1]);
531 }
532
533 for (Model model : Model.CONNECTED_MODEL_SET) {
534 if (model instanceof TreeModel && fields[1].equals(model.getModelName())) {
535 line = in.readLine();
536 line = in.readLine();
537 fields = line.split("\t");
538 //read number of nodes
539 int nodeCount = Integer.parseInt(fields[0]);
540 double[] nodeHeights = new double[nodeCount];
541 String[] taxaNames = new String[(nodeCount+1)/2];
542
543 for (int i = 0; i < nodeCount; i++) {
544 line = in.readLine();
545 fields = line.split("\t");
546 nodeHeights[i] = Double.parseDouble(fields[1]);
547 if (i < taxaNames.length) {
548 taxaNames[i] = fields[2];
549 }
550 }
551
552 //on to reading edge information
553 line = in.readLine();
554 line = in.readLine();
555 line = in.readLine();
556 fields = line.split("\t");
557
558 int edgeCount = Integer.parseInt(fields[0]);
559 if (DEBUG) {
560 System.out.println("edge count = " + edgeCount);
561 }
562
563 //create data matrix of doubles to store information from list of TreeParameterModels
564 //size of matrix depends on the number of TreeParameterModels assigned to a TreeModel
565 double[][] traitValues = new double[linkedModels.get(model.getId()).size()][edgeCount];
566
567 //create array to store whether a node is left or right child of its parent
568 //can be important for certain tree transition kernels
569 int[] childOrder = new int[edgeCount];
570 for (int i = 0; i < childOrder.length; i++) {
571 childOrder[i] = -1;
572 }
573
574 int[] parents = new int[edgeCount];
575 for (int i = 0; i < edgeCount; i++){
576 parents[i] = -1;
577 }
578 for (int i = 0; i < edgeCount-1; i++) {
579 line = in.readLine();
580 if (line != null) {
581 if (DEBUG) {
582 System.out.println("DEBUG: " + line);
583 }
584 fields = line.split("\t");
585 parents[Integer.parseInt(fields[0])] = Integer.parseInt(fields[1]);
586 // childOrder[i] = Integer.parseInt(fields[2]);
587 childOrder[Integer.parseInt(fields[0])] = Integer.parseInt(fields[2]);
588 for (int j = 0; j < linkedModels.get(model.getId()).size(); j++) {
589 // traitValues[j][i] = Double.parseDouble(fields[3+j]);
590 traitValues[j][Integer.parseInt(fields[0])] = Double.parseDouble(fields[3+j]);
591 }
592 }
593 }
594
595 //perform magic with the acquired information
596 if (DEBUG) {
597 System.out.println("adopting tree structure");
598 }
599
600 //adopt the loaded tree structure;
601 ((TreeModel) model).beginTreeEdit();
602 ((TreeModel) model).adoptTreeStructure(parents, nodeHeights, childOrder, taxaNames);
603 if (traitModels.size() > 0) {
604 ((TreeModel) model).adoptTraitData(parents, traitModels, traitValues, taxaNames);
605 }
606 ((TreeModel) model).endTreeEdit();
607
608 expectedTreeModelNames.remove(model.getModelName());
609
610 }
611
612 }
613
614 line = in.readLine();
615 if (line != null) {
616 fields = line.split("\t");
617 }
618
619 }
620
621 if (expectedTreeModelNames.size() > 0) {
622 StringBuilder sb = new StringBuilder();
623 for (String notFoundName : expectedTreeModelNames) {
624 sb.append("Expecting, but unable to match state parameter:" + notFoundName + "\n");
625 }
626 throw new RuntimeException("\n" + sb.toString());
627 }
628
629 if (DEBUG) {
630 System.out.println("\nDouble checking:");
631 for (Parameter parameter : Parameter.CONNECTED_PARAMETER_SET) {
632 if (parameter.getParameterName().equals("branchRates.categories.rootNodeNumber")) {
633 System.out.println(parameter.getParameterName() + ": " + parameter.getParameterValue(0));
634 }
635 }
636 System.out.println("\nPrinting trees:");
637 for (TreeModel tm : treeModelList) {
638 System.out.println(tm.getId() + ": ");
639 System.out.println(tm.getNewick());
640 }
641 }
642
643 if (rngState != null) {
644 MathUtils.setRandomState(rngState);
645 }
646
647 in.close();
648 fileIn.close();
649
650 //This shouldn't be necessary and if it is then it might be hiding a bug...
651 /*for (Likelihood likelihood : Likelihood.CONNECTED_LIKELIHOOD_SET) {
652 likelihood.makeDirty();
653 }*/
654
655 } catch (IOException ioe) {
656 throw new RuntimeException("Unable to read file: " + ioe.getMessage());
657 }
658
659 return state;
660 }
661
662 }