Debian Codegraph @

src/dr/app/realtime/CheckPointModifier.java

raw symbols SCIP
1 /*
2 * CheckPointUpdater.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.realtime;
27
28 import dr.app.checkpoint.BeastCheckpointer;
29 import dr.evolution.tree.BranchRates;
30 import dr.evolution.tree.NodeRef;
31 import dr.evomodel.tree.TreeModel;
32 import dr.evomodel.tree.TreeParameterModel;
33 import dr.inference.markovchain.MarkovChain;
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
40 import java.io.BufferedReader;
41 import java.io.File;
42 import java.io.FileReader;
43 import java.io.IOException;
44 import java.util.ArrayList;
45 import java.util.HashSet;
46 import java.util.Set;
47
48 /**
49 * @author Guy Baele
50 */
51 public class CheckPointModifier extends BeastCheckpointer {
52
53 private static final boolean DEBUG = false;
54
55 private CheckPointTreeModifier modifyTree;
56 private BranchRates rateModel;
57 private ArrayList<TreeParameterModel> traitModels;
58
59 public final static String LOAD_STATE_FILE = "load.state.file";
60 public final static String SAVE_STATE_FILE = "save.state.file";
61
62 private final String loadStateFileName;
63 private final String saveStateFileName;
64
65 public CheckPointModifier() {
66 loadStateFileName = System.getProperty(LOAD_STATE_FILE, null);
67 saveStateFileName = System.getProperty(SAVE_STATE_FILE, null);
68 }
69
70 @Override
71 public long loadState(MarkovChain markovChain, double[] savedLnL) {
72 return readStateFromFile(new File(loadStateFileName), markovChain, savedLnL);
73 }
74
75 protected long readStateFromFile(File file, MarkovChain markovChain, double[] lnL) {
76
77 OperatorSchedule operatorSchedule = markovChain.getSchedule();
78 long state = -1;
79
80 this.traitModels = new ArrayList<TreeParameterModel>();
81
82 try {
83 FileReader fileIn = new FileReader(file);
84 BufferedReader in = new BufferedReader(fileIn);
85
86 int[] rngState = null;
87
88 String line = in.readLine();
89 String[] fields = line.split("\t");
90 if (fields[0].equals("rng")) {
91 // if there is a random number generator state present then load it...
92 try {
93 rngState = new int[fields.length - 1];
94 for (int i = 0; i < rngState.length; i++) {
95 rngState[i] = Integer.parseInt(fields[i + 1]);
96 }
97
98 } catch (NumberFormatException nfe) {
99 throw new RuntimeException("Unable to read state number from state file");
100 }
101
102 line = in.readLine();
103 fields = line.split("\t");
104 }
105
106 try {
107 if (!fields[0].equals("state")) {
108 throw new RuntimeException("Unable to read state number from state file");
109 }
110 state = Long.parseLong(fields[1]);
111 } catch (NumberFormatException nfe) {
112 throw new RuntimeException("Unable to read state number from state file");
113 }
114
115 line = in.readLine();
116 fields = line.split("\t");
117
118 try {
119 if (!fields[0].equals("lnL")) {
120 throw new RuntimeException("Unable to read lnL from state file");
121 }
122 if (lnL != null) {
123 lnL[0] = Double.parseDouble(fields[1]);
124 }
125 } catch (NumberFormatException nfe) {
126 throw new RuntimeException("Unable to read lnL from state file");
127 }
128
129 line = in.readLine();
130 //System.out.println(line);
131 fields = line.split("\t");
132
133 //Tree nodes have numbers as parameter ids
134 for (Parameter parameter : Parameter.CONNECTED_PARAMETER_SET) {
135
136 //first check if this is actually a tree node by checking if it's a number
137 //numbers should be positive but can include zero
138 if (isTreeNode(parameter.getId()) && isTreeNode(fields[1]) || parameter.getId().equals(fields[1])) {
139
140 int dimension = Integer.parseInt(fields[2]);
141
142 if (dimension != parameter.getDimension() && !fields[1].equals("branchRates.categories")) {
143 System.err.println("Unable to match state parameter dimension: " + dimension + ", expecting " + parameter.getDimension() + " for parameter: " + parameter.getParameterName());
144 System.err.print("Read from file: ");
145 for (int i = 0; i < fields.length; i++) {
146 System.err.print(fields[i] + "\t");
147 }
148 System.err.println();
149 }
150
151 if (fields[1].equals("branchRates.categories.rootNodeNumber")) {
152 // System.out.println("eek");
153 double value = Double.parseDouble(fields[3]);
154 parameter.setParameterValue(0, value);
155 if (DEBUG) {
156 System.out.println("restoring " + fields[1] + " with value " + value);
157 }
158 } else {
159 if (DEBUG) {
160 System.out.print("restoring " + fields[1] + " with values ");
161 }
162 if (fields[1].equals("branchRates.categories")) {
163 for (int dim = 0; dim < (fields.length-3); dim++) {
164 //System.out.println("dim " + dim);
165 parameter.setParameterValue(dim, Double.parseDouble(fields[dim + 3]));
166 if (DEBUG) {
167 System.out.print(Double.parseDouble(fields[dim + 3]) + " ");
168 }
169 }
170 } else {
171 for (int dim = 0; dim < parameter.getDimension(); dim++) {
172 parameter.setParameterValue(dim, Double.parseDouble(fields[dim + 3]));
173 if (DEBUG) {
174 System.out.print(Double.parseDouble(fields[dim + 3]) + " ");
175 }
176 }
177 }
178 if (DEBUG) {
179 System.out.println();
180 }
181 }
182
183 line = in.readLine();
184 //System.out.println(line);
185 fields = line.split("\t");
186
187 } else {
188
189 //there will be more parameters in the connected set than there are lines in the checkpoint file
190 //do nothing and just keep iterating over the parameters in the connected set
191
192 }
193
194 }
195
196 //No changes needed for loading in operators
197 for (int i = 0; i < operatorSchedule.getOperatorCount(); i++) {
198 MCMCOperator operator = operatorSchedule.getOperator(i);
199 if (!fields[1].equals(operator.getOperatorName())) {
200 throw new RuntimeException("Unable to match operator: " + fields[1]);
201 }
202 if (fields.length < 4) {
203 throw new RuntimeException("Operator missing values: " + fields[1]);
204 }
205 operator.setAcceptCount(Integer.parseInt(fields[2]));
206 operator.setRejectCount(Integer.parseInt(fields[3]));
207 if (operator instanceof AdaptableMCMCOperator) {
208 if (fields.length != 5) {
209 throw new RuntimeException("Coercable operator missing parameter: " + fields[1]);
210 }
211 ((AdaptableMCMCOperator)operator).setAdaptableParameter(Double.parseDouble(fields[4]));
212 }
213 line = in.readLine();
214 fields = line.split("\t");
215 }
216
217 // load the tree models last as we get the node heights from the tree (not the parameters which
218 // which may not be associated with the right node
219 Set<String> expectedTreeModelNames = new HashSet<String>();
220 for (Model model : Model.CONNECTED_MODEL_SET) {
221
222 if (model instanceof TreeModel) {
223 expectedTreeModelNames.add(model.getModelName());
224 }
225
226 if (model instanceof TreeParameterModel) {
227 this.traitModels.add((TreeParameterModel)model);
228 }
229
230 if (model instanceof BranchRates) {
231 this.rateModel = (BranchRates)model;
232 }
233
234 }
235
236 while (fields[0].equals("tree")) {
237
238 for (Model model : Model.CONNECTED_MODEL_SET) {
239 if (model instanceof TreeModel && fields[1].equals(model.getModelName())) {
240
241 //AR: Can we not just add them to a Flexible tree and then make a new TreeModel
242 //taking that in the constructor?
243
244 //internally, we have a tree with all the taxa
245 //externally, i.e. in the checkpoint file, we have a tree representation comprising
246 //a subset of the full taxa set
247
248 //write method that adjusts the internal representation, i.e. the one in the connected
249 //set, according to the checkpoint file and a distance-based approach to position
250 //the additional taxa
251
252 //first read in all the data from the checkpoint file
253
254 line = in.readLine();
255 line = in.readLine();
256 fields = line.split("\t");
257 //read number of nodes
258 int nodeCount = Integer.parseInt(fields[0]);
259 double[] nodeHeights = new double[nodeCount];
260 String[] taxaNames = new String[(nodeCount+1)/2];
261
262 for (int i = 0; i < nodeCount; i++) {
263 line = in.readLine();
264 fields = line.split("\t");
265 nodeHeights[i] = Double.parseDouble(fields[1]);
266 if (i < taxaNames.length) {
267 taxaNames[i] = fields[2];
268 }
269 }
270
271 //on to reading edge information
272 line = in.readLine();
273 line = in.readLine();
274 line = in.readLine();
275 fields = line.split("\t");
276
277 int edgeCount = Integer.parseInt(fields[0]);
278
279 //create data matrix of doubles to store information from list of TreeParameterModels
280 double[][] traitValues = new double[traitModels.size()][edgeCount];
281
282 //create array to store whether a node is left or right child of its parent
283 //can be important for certain tree transition kernels
284 int[] childOrder = new int[edgeCount];
285 for (int i = 0; i < childOrder.length; i++) {
286 childOrder[i] = -1;
287 }
288
289 int[] parents = new int[edgeCount];
290 for (int i = 0; i < edgeCount; i++){
291 parents[i] = -1;
292 }
293 for (int i = 0; i < edgeCount; i++) {
294 line = in.readLine();
295 if (line != null) {
296 fields = line.split("\t");
297 parents[Integer.parseInt(fields[0])] = Integer.parseInt(fields[1]);
298 childOrder[i] = Integer.parseInt(fields[2]);
299 for (int j = 0; j < traitModels.size(); j++) {
300 traitValues[j][i] = Double.parseDouble(fields[3+j]);
301 }
302 }
303 }
304
305 //perform magic with the acquired information
306 //CheckPointTreeModifier modifyTree = new CheckPointTreeModifier((TreeModel) model);
307 this.modifyTree = new CheckPointTreeModifier((TreeModel) model);
308 modifyTree.adoptTreeStructure(parents, nodeHeights, childOrder, taxaNames);
309 if (traitModels.size() > 0) {
310 modifyTree.adoptTraitData(parents, this.traitModels, traitValues);
311 }
312
313 //adopt the loaded tree structure; this does not yet copy the traits on the branches
314 //((TreeModel) model).beginTreeEdit();
315 //((TreeModel) model).adoptTreeStructure(parents, nodeHeights, childOrder);
316 //((TreeModel) model).endTreeEdit();
317
318 expectedTreeModelNames.remove(model.getModelName());
319
320 }
321 }
322
323 line = in.readLine();
324 if (line != null) {
325 fields = line.split("\t");
326 }
327
328 }
329
330 if (expectedTreeModelNames.size() > 0) {
331 StringBuilder sb = new StringBuilder();
332 for (String notFoundName : expectedTreeModelNames) {
333 sb.append("Expecting, but unable to match state parameter:" + notFoundName + "\n");
334 }
335 throw new RuntimeException(sb.toString());
336 }
337
338 in.close();
339 fileIn.close();
340
341 } catch (IOException ioe) {
342 throw new RuntimeException("Unable to read file: " + ioe.getMessage());
343 }
344
345 return state;
346 }
347
348 public void extendLoadState(CheckPointUpdaterApp.UpdateChoice choice) {
349 //add the BranchRates model here
350 if (this.rateModel == null) {
351 throw new RuntimeException("BranchRates model has not been set correctly.");
352 } else {
353 ArrayList<NodeRef> newTaxa = modifyTree.incorporateAdditionalTaxa(choice, this.rateModel);
354 modifyTree.interpolateTraitValues(this.traitModels);
355 }
356 }
357
358 @Override
359 public void checkLoadState(double savedLnL, double lnL) {
360 //do nothing
361 }
362
363 private boolean isTreeNode(String name) {
364 if (name == null) {
365 return false;
366 }
367 int length = name.length();
368 if (length == 0) {
369 return false;
370 }
371 int i = 0;
372 if (name.charAt(0) == '-') {
373 return false;
374 }
375 for (; i < length; i++) {
376 char c = name.charAt(i);
377 if (c < '0' || c > '9') {
378 return false;
379 }
380 }
381 return true;
382 }
383
384 }