Debian Codegraph @

src/dr/app/beagle/tools/CompleteHistorySimulator.java

raw symbols SCIP
1 /*
2 * CompleteHistorySimulator.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.app.beagle.tools;
27
28 import dr.evolution.tree.*;
29 import dr.evomodel.siteratemodel.GammaSiteRateModel;
30 import dr.evomodel.substmodel.FrequencyModel;
31 import dr.evolution.alignment.SimpleAlignment;
32 import dr.evolution.datatype.Codons;
33 import dr.evolution.datatype.DataType;
34 import dr.evolution.sequence.Sequence;
35 import dr.evomodel.branchratemodel.BranchRateModel;
36 import dr.inference.markovjumps.MarkovJumpsRegisterAcceptor;
37 import dr.inference.markovjumps.MarkovJumpsType;
38 import dr.inference.markovjumps.StateHistory;
39 import dr.inference.model.Parameter;
40 import dr.math.MathUtils;
41
42 import java.text.NumberFormat;
43 import java.util.*;
44 import java.util.logging.Logger;
45
46 /**
47 * Simulates a complete transition history and alignment of sequences given a tree, substitution model and
48 * branch rate model. This code duplicates portions of dr.app.seqgen.SequenceSimulator. However, SequenceSimulator
49 * is wed to dr.evomodel.substmodel.SubstitutionModel which does not emit the infinitesimal generator.
50 *
51 * @author Marc A. Suchard
52 * @author [email protected]
53 */
54 public class CompleteHistorySimulator extends SimpleAlignment
55 implements MarkovJumpsRegisterAcceptor, TreeTraitProvider {
56
57 /**
58 * number of replications
59 */
60 protected int nReplications;
61 /**
62 * tree used for generating samples *
63 */
64 protected Tree tree;
65 /**
66 * site model used for generating samples *
67 */
68 protected GammaSiteRateModel siteModel;
69
70 /**
71 * branch rate model used for generating samples *
72 */
73 protected BranchRateModel branchRateModel;
74
75 /**
76 * nr of categories in site model *
77 */
78 int categoryCount;
79 /**
80 * nr of states in site model *
81 */
82 int stateCount;
83
84 /**
85 * an array used to hold infinitesimal generator
86 */
87 // protected double[] lambda;
88 // protected double[][] probabilities;
89
90 private boolean branchSpecificLambda = false;
91 private Parameter branchVariableParameter = null;
92 private Parameter branchPossibleValuesParameter = null;
93 private DataType dataType;
94
95 protected List<double[]> registers;
96 protected List<String> jumpTags;
97 protected List<MarkovJumpsType> jumpTypes;
98 protected List<double[][]> realizedJumps;
99 protected int nJumpProcesses = 0;
100 protected boolean sumAcrossSites;
101
102 private final Map<String, Integer> idMap = new HashMap<String, Integer>();
103
104 private boolean saveAlignment = false;
105 private Map<Integer,Sequence> alignmentTraitList;
106
107 private boolean alignmentOnly = false;
108
109 /**
110 * Constructor
111 *
112 * @param tree
113 * @param siteModel
114 * @param branchRateModel
115 * @param nReplications: nr of samples to generate
116 */
117 // public CompleteHistorySimulator(Tree tree, GammaSiteRateModel siteModel, BranchRateModel branchRateModel,
118 // int nReplications) {
119 // this(tree, siteModel, branchRateModel, nReplications, false);
120 // }
121 //
122 // public CompleteHistorySimulator(Tree tree, GammaSiteRateModel siteModel, BranchRateModel branchRateModel,
123 // int nReplications, boolean sumAcrossSites) {
124 // this(tree, siteModel, branchRateModel, nReplications, sumAcrossSites, null, null);
125 //
126 // }
127
128 public CompleteHistorySimulator(Tree tree, GammaSiteRateModel siteModel, BranchRateModel branchRateModel,
129 int nReplications, boolean sumAcrossSites,
130 Parameter branchVariableParameter, Parameter branchPossibleValuesParameter) {
131
132 this.tree = tree;
133 this.siteModel = siteModel;
134 this.branchRateModel = branchRateModel;
135 this.nReplications = nReplications;
136 stateCount = this.siteModel.getSubstitutionModel().getDataType().getStateCount();
137 categoryCount = this.siteModel.getCategoryCount();
138
139 // Codon models give exception when put inside report and when count statistics are done on them
140 dataType = siteModel.getSubstitutionModel().getDataType();
141 // if (dataType instanceof Codons && !alignmentOnly) {
142 // System.out.println("Codon models give exception when put inside report and when count statistics are done on them. "
143 // + "You can supress this by setting alignmentOnly to true.");
144 // }
145
146 this.sumAcrossSites = sumAcrossSites;
147
148 List<String> taxaIds = new ArrayList<String>();
149 for (int i = 0; i < tree.getTaxonCount(); i++) {
150 taxaIds.add(tree.getTaxon(i).getId());
151 }
152
153 int k = 1;
154 for (String taxaId : taxaIds) {
155 idMap.put(taxaId, k);
156 k += 1;
157 }
158
159 format = NumberFormat.getNumberInstance(Locale.ENGLISH);
160 format.setMaximumFractionDigits(3);
161
162 if (branchVariableParameter != null && branchPossibleValuesParameter != null) {
163 if (branchVariableParameter.getDimension() != 1) {
164 throw new RuntimeException("branchVariableParameter has the wrong dimension; should be 1");
165 }
166 if (branchPossibleValuesParameter.getDimension() != tree.getNodeCount()) {
167 throw new RuntimeException("branchPossibleValuesParameter has the wrong dimension; should be "
168 + tree.getNodeCount());
169 }
170 branchSpecificLambda = true;
171 this.branchPossibleValuesParameter = branchPossibleValuesParameter;
172 this.branchVariableParameter = branchVariableParameter;
173 StringBuilder sb = new StringBuilder();
174 sb.append("Doing a complete history simulation using branch-specific variables\n\tReplacing variable '");
175 sb.append(branchVariableParameter.getId());
176 sb.append("' with values from '");
177 sb.append(branchPossibleValuesParameter.getId());
178 sb.append("'");
179 Logger.getLogger("dr.app.beagle.tools").info(sb.toString());
180 }
181
182 alignmentTraitList = new HashMap<Integer,Sequence>(tree.getNodeCount());
183 }
184
185 /**
186 * Convert integer representation of sequence into a Sequence
187 *
188 * @param seq integer representation of the sequence
189 * @param node used to determine taxon for sequence
190 * @return Sequence
191 */
192 Sequence intArray2Sequence(int[] seq, NodeRef node) {
193 String sSeq = "";
194 // DataType dataType = siteModel.getSubstitutionModel().getDataType();
195 for (int i = 0; i < nReplications; i++) {
196 if (dataType instanceof Codons) {
197 String s = dataType.getTriplet(seq[i]);
198 sSeq += s;
199 } else {
200 String c = dataType.getCode(seq[i]);
201 sSeq += c;
202 }
203 }
204 return new Sequence(tree.getNodeTaxon(node), sSeq);
205 }
206
207 public void addAlignmentTrait() {
208
209 saveAlignment = true;
210 final String tag = "alignment";
211 treeTraits.addTrait(new TreeTrait.S() {
212 public String getTraitName() {
213 return tag;
214 }
215
216 public Intent getIntent() {
217 return Intent.NODE;
218 }
219
220 public String getTrait(Tree tree, NodeRef node) {
221 return alignmentTraitList.get(node.getNumber()).getSequenceString();
222 }
223 });
224 }
225
226 public void addRegister(Parameter addRegisterParameter, MarkovJumpsType type, boolean scaleByTime) {
227
228 if (registers == null) {
229 registers = new ArrayList<double[]>();
230 }
231
232 if (jumpTags == null) {
233 jumpTags = new ArrayList<String>();
234 }
235
236 if (jumpTypes == null) {
237 jumpTypes = new ArrayList<MarkovJumpsType>();
238 }
239
240 if (realizedJumps == null) {
241 realizedJumps = new ArrayList<double[][]>();
242 }
243
244 final String tag = addRegisterParameter.getId();
245
246 registers.add(addRegisterParameter.getParameterValues());
247 jumpTags.add(tag);
248 jumpTypes.add(type);
249 realizedJumps.add(new double[tree.getNodeCount()][nReplications]);
250
251 final int r = nJumpProcesses;
252
253 treeTraits.addTrait(new TreeTrait.S() {
254 public String getTraitName() {
255 return tag;
256 }
257
258 public Intent getIntent() {
259 return Intent.NODE;
260 }
261
262 public String getTrait(Tree tree, NodeRef node) {
263 return formattedValue(tree, node, r);
264 }
265 });
266
267 nJumpProcesses++;
268
269 // scaleByTime is currently ignored
270 }
271
272 public double[] getMarkovJumpsForNodeAndRegister(Tree tree, NodeRef node, int whichRegister) {
273 if (this.tree != tree) {
274 throw new RuntimeException("Wrong tree!");
275 }
276 return realizedJumps.get(whichRegister)[node.getNumber()];
277 }
278
279 public int getNumberOfJumpProcess() {
280 return nJumpProcesses;
281 }
282
283 // public double[][] getMarkovJumpsForNode(Tree tree, NodeRef node) {
284 // double[][] rtn = new double[nJumpProcesses][];
285 // for(int r = 0; r < nJumpProcesses; r++) {
286 // rtn[r] = getMarkovJumpsForNodeAndRegister(tree, node, r);
287 // }
288 // return rtn;
289 // }
290
291 protected Helper treeTraits = new Helper();
292
293 public TreeTrait[] getTreeTraits() {
294 return treeTraits.getTreeTraits();
295 }
296
297 public TreeTrait getTreeTrait(String key) {
298 return treeTraits.getTreeTrait(key);
299 }
300
301 private String formattedValue(Tree tree, NodeRef node, int jump) {
302 StringBuffer sb = new StringBuffer();
303 double[] values = getMarkovJumpsForNodeAndRegister(tree, node, jump);
304 if (sumAcrossSites) {
305 double total = 0;
306 for (double x : values) {
307 total += x;
308 }
309 sb.append(total);
310 } else {
311 sb.append("{");
312 for (int i = 0; i < values.length; i++) {
313 if (i > 0) {
314 sb.append(",");
315 }
316 sb.append(values[i]);
317 }
318 sb.append("}");
319 }
320 return sb.toString();
321 }
322
323 private NumberFormat format;
324
325 public String toString() {
326
327 StringBuffer sb = new StringBuffer();
328
329 if (alignmentOnly) {
330
331 this.setReportCountStatistics(false);
332 sb.append(super.toString());
333 sb.append("\n");
334
335 } else {
336
337 // alignment output
338 sb.append("alignment\n");
339 sb.append(super.toString());
340 sb.append("\n");
341 // tree output
342 sb.append("tree\n");
343 TreeUtils.newick(tree,
344 tree.getRoot(),
345 true,
346 TreeUtils.BranchLengthType.LENGTHS_AS_TIME,
347 format,
348 null,
349 (nJumpProcesses > 0 || saveAlignment ? new TreeTraitProvider[] { this }
350 : null),
351 idMap,
352 sb);
353 sb.append("\n");
354
355 }
356
357 return sb.toString();
358 }// END: toString
359
360 /**
361 * perform the actual sequence generation
362 *
363 * @return alignment containing randomly generated sequences for the nodes in the
364 * leaves of the tree
365 */
366 public void simulate() {
367
368 double[] lambda = new double[stateCount * stateCount];
369
370 if (!branchSpecificLambda) {
371 siteModel.getSubstitutionModel().getInfinitesimalMatrix(lambda); // Assumes a single generator for whole tree
372 }
373
374 NodeRef root = tree.getRoot();
375
376 double[] categoryProbs = siteModel.getCategoryProportions();
377 int[] category = new int[nReplications];
378 for (int i = 0; i < nReplications; i++) {
379 category[i] = MathUtils.randomChoicePDF(categoryProbs);
380 }
381
382 FrequencyModel frequencyModel = siteModel.getSubstitutionModel().getFrequencyModel();
383 int[] seq = new int[nReplications];
384 for (int i = 0; i < nReplications; i++) {
385 seq[i] = MathUtils.randomChoicePDF(frequencyModel.getFrequencies());
386 }
387
388 setDataType(siteModel.getSubstitutionModel().getDataType());
389
390 traverse(root, seq, category, this, lambda);
391 }
392
393 /**
394 * recursively walk through the tree top down, and add sequence to alignment whenever
395 * a leave node is reached.
396 *
397 * @param node reference to the current node, for which we visit all children
398 * @param parentSequence randomly generated sequence of the parent node
399 * @param category array of categories for each of the sites
400 * @param alignment
401 */
402 private void traverse(NodeRef node, int[] parentSequence, int[] category, SimpleAlignment alignment,
403 double[] lambda) {
404
405 if (saveAlignment) {
406 alignmentTraitList.put(node.getNumber(),intArray2Sequence(parentSequence,node));
407 }
408
409 for (int iChild = 0; iChild < tree.getChildCount(node); iChild++) {
410
411 NodeRef child = tree.getChild(node, iChild);
412 int[] seq = new int[nReplications];
413 StateHistory[] histories = new StateHistory[nReplications];
414
415 if (branchSpecificLambda) {
416 final double branchValue = branchPossibleValuesParameter.getParameterValue(child.getNumber());
417 branchVariableParameter.setParameterValue(0, branchValue);
418 // System.err.println("trying value = " + branchValue + " for " + child.getNumber());
419 siteModel.getSubstitutionModel().getInfinitesimalMatrix(lambda);
420 }
421
422 for (int i = 0; i < nReplications; i++) {
423 histories[i] = simulateAlongBranch(tree, child, category[i], parentSequence[i], lambda);
424 seq[i] = histories[i].getEndingState();
425 }
426
427 processHistory(child, histories);
428
429 if (tree.getChildCount(child) == 0) {
430 alignment.addSequence(intArray2Sequence(seq, child));
431 }
432 traverse(tree.getChild(node, iChild), seq, category, alignment, lambda);
433 }
434 }
435
436 protected void processHistory(NodeRef node, StateHistory[] histories) {
437 for (int jump = 0; jump < nJumpProcesses; jump++) {
438 double[] register = registers.get(jump);
439 MarkovJumpsType type = jumpTypes.get(jump);
440 double[] realizedJump = realizedJumps.get(jump)[node.getNumber()];
441
442 for (int i = 0; i < nReplications; i++) {
443 if (type == MarkovJumpsType.COUNTS) {
444 realizedJump[i] = histories[i].getTotalRegisteredCounts(register);
445 } else if (type == MarkovJumpsType.REWARDS) {
446 realizedJump[i] = histories[i].getTotalReward(register);
447 } else {
448 throw new IllegalAccessError("Unknown MarkovJumps type");
449 }
450 }
451 }
452 }
453
454 private StateHistory simulateAlongBranch(Tree tree, NodeRef node, int rateCategory, int startingState,
455 double[] lambda) {
456
457 NodeRef parent = tree.getParent(node);
458
459 final double branchRate = branchRateModel.getBranchRate(tree, node);
460
461 // Get the operational time of the branch
462 final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
463
464 if (branchTime < 0.0) {
465 throw new RuntimeException("Negative branch length: " + branchTime);
466 }
467
468 double branchLength = siteModel.getRateForCategory(rateCategory) * branchTime;
469
470 return StateHistory.simulateUnconditionalOnEndingState(0.0, startingState, branchLength,
471 lambda, stateCount);
472 }
473
474 public void setAlignmentOnly() {
475 alignmentOnly = true;
476 }
477
478 }//END: class