Debian Codegraph @

src/dr/app/seqgen/SequenceSimulator.java

raw symbols SCIP
1
2 /*
3 * SequenceSimulator.java
4 *
5 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
6 *
7 * This file is part of BEAST.
8 * See the NOTICE file distributed with this work for additional
9 * information regarding copyright ownership and licensing.
10 *
11 * BEAST is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as
13 * published by the Free Software Foundation; either version 2
14 * of the License, or (at your option) any later version.
15 *
16 * BEAST is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Lesser General Public License for more details.
20 *
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with BEAST; if not, write to the
23 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
24 * Boston, MA 02110-1301 USA
25 */
26
27 package dr.app.seqgen;
28
29 import dr.app.bss.Utils;
30 import dr.evolution.alignment.Alignment;
31 import dr.evolution.alignment.SimpleAlignment;
32 import dr.evolution.datatype.Nucleotides;
33 import dr.evolution.io.NewickImporter;
34 import dr.evolution.sequence.Sequence;
35 import dr.evolution.tree.NodeRef;
36 import dr.evolution.tree.Tree;
37 import dr.evomodel.branchratemodel.BranchRateModel;
38 import dr.evomodel.branchratemodel.DefaultBranchRateModel;
39 import dr.oldevomodel.sitemodel.GammaSiteModel;
40 import dr.oldevomodel.sitemodel.SiteModel;
41 import dr.oldevomodel.substmodel.FrequencyModel;
42 import dr.oldevomodel.substmodel.HKY;
43 import dr.oldevomodel.substmodel.SubstitutionEpochModel;
44 import dr.inference.model.Parameter;
45 import dr.math.MathUtils;
46 import dr.xml.*;
47
48 /** Class for performing random sequence generation for a given site model.
49 * Sequences for the leave nodes in the tree are returned as an alignment.
50 *
51 * @author [email protected]
52 *
53 */
54
55 public class SequenceSimulator {
56
57 private static final boolean DEBUG = false;
58
59 /** nr of samples to generate **/
60 protected int m_sequenceLength;
61 /** tree used for generating samples **/
62 protected Tree m_tree;
63 /** site model used for generating samples **/
64 protected SiteModel m_siteModel;
65 /** branch rate model used for generating samples **/
66 protected BranchRateModel m_branchRateModel;
67 /** nr of categories in site model **/
68 int m_categoryCount;
69 /** nr of states in site model **/
70 int m_stateCount;
71
72 static boolean has_ancestralSequence = false;
73 protected Sequence ancestralSequence;
74
75 /**
76 * an array used to transfer transition probabilities
77 */
78 protected double[][] m_probabilities;
79
80 /**
81 * Constructor
82 * @param tree
83 * @param siteModel
84 * @param branchRateModel
85 * @param sequenceLength: nr of sites to generate
86 */
87 SequenceSimulator(Tree tree, SiteModel siteModel, BranchRateModel branchRateModel, int sequenceLength) {
88 m_tree = tree;
89 m_siteModel = siteModel;
90 m_branchRateModel = branchRateModel;
91 m_sequenceLength = sequenceLength;
92 m_stateCount = m_siteModel.getFrequencyModel().getDataType().getStateCount();
93 m_categoryCount = m_siteModel.getCategoryCount();
94 m_probabilities = new double[m_categoryCount][m_stateCount * m_stateCount];
95 } // c'tor
96
97 /**
98 * Convert integer representation of sequence into a Sequence
99 * @param seq integer representation of the sequence
100 * @param node used to determine taxon for sequence
101 * @return Sequence
102 */
103 Sequence intArray2Sequence(int [] seq, NodeRef node) {
104 StringBuilder sSeq = new StringBuilder();
105 for (int i = 0; i < m_sequenceLength; i++) {
106 sSeq.append(m_siteModel.getFrequencyModel().getDataType().getCode(seq[i]));
107 }
108 return new Sequence(m_tree.getNodeTaxon(node), sSeq.toString());
109 } // intArray2Sequence
110
111 void setAncestralSequence(Sequence seq) {
112 ancestralSequence = seq;
113 has_ancestralSequence = true;
114 }
115
116 int[] sequence2intArray(Sequence seq) {
117
118 if(seq.getLength() != m_sequenceLength) {
119
120 throw new RuntimeException("Ancestral sequence length has "
121 + seq.getLength() + " characters " + "expecting "
122 + m_sequenceLength + " characters");
123
124 }
125
126 int array[] = new int[m_sequenceLength];
127 for (int i = 0; i < m_sequenceLength; i++) {
128 array[i] = m_siteModel.getFrequencyModel().getDataType().getState(
129 seq.getChar(i));
130 }
131 return array;
132 }//END: sequence2intArray
133
134 /**
135 * perform the actual sequence generation
136 * @return alignment containing randomly generated sequences for the nodes in the
137 * leaves of the tree
138 */
139 public Alignment simulate() {
140 NodeRef root = m_tree.getRoot();
141
142 double[] categoryProbs = m_siteModel.getCategoryProportions();
143 int[] category = new int[m_sequenceLength];
144 for (int i = 0; i < m_sequenceLength; i++) {
145 category[i] = MathUtils.randomChoicePDF(categoryProbs);
146 }
147
148 int[] seq = new int[m_sequenceLength];
149
150 if (has_ancestralSequence) {
151
152 seq = sequence2intArray(ancestralSequence);
153
154 } else {
155
156 FrequencyModel frequencyModel = m_siteModel.getFrequencyModel();
157 for (int i = 0; i < m_sequenceLength; i++) {
158 seq[i] = MathUtils.randomChoicePDF(frequencyModel
159 .getFrequencies());
160 }
161
162 }
163
164 if (DEBUG) {
165 synchronized (this) {
166 System.out.println();
167 System.out.println("root Sequence:");
168 Utils.printArray(seq);
169 }
170 }
171
172 SimpleAlignment alignment = new SimpleAlignment();
173 alignment.setReportCountStatistics(false);
174 alignment.setDataType(m_siteModel.getFrequencyModel().getDataType());
175
176 traverse(root, seq, category, alignment);
177
178 return alignment;
179 } // END: simulate
180
181 /**
182 * recursively walk through the tree top down, and add sequence to alignment whenever
183 * a leave node is reached.
184 * @param node reference to the current node, for which we visit all children
185 * @param parentSequence randomly generated sequence of the parent node
186 * @param category array of categories for each of the sites
187 * @param alignment
188 */
189 void traverse(NodeRef node, int [] parentSequence, int [] category, SimpleAlignment alignment) {
190
191 if (DEBUG) {
192 System.out.println();
193 System.out.println("I'm at: " + node.toString());
194 System.out.println();
195 }
196
197 for (int iChild = 0; iChild < m_tree.getChildCount(node); iChild++) {
198
199 NodeRef child = m_tree.getChild(node, iChild);
200
201 for (int i = 0; i < m_categoryCount; i++) {
202 getTransitionProbabilities(m_tree, child, i, m_probabilities[i]);
203 }
204
205 if (DEBUG) {
206 System.out.println("Going to child " + iChild + ": " + child.toString());
207 System.out.println("Child finite transition probs matrix:");
208 Utils.print2DArray(m_probabilities, 4);
209 System.out.println();
210 }// END: if DEBUG
211
212 int [] seq = new int[m_sequenceLength];
213 double [] cProb = new double[m_stateCount];
214
215 for (int i = 0; i < m_sequenceLength; i++) {
216
217 //System.out.println("seqChar " + parentSequence[i]);
218
219 System.arraycopy(m_probabilities[category[i]], parentSequence[i] * m_stateCount, cProb, 0, m_stateCount);
220
221 if (DEBUG) {
222 System.out.println("site:" + i);
223 System.out.println("site probs:");
224 Utils.printArray(cProb);
225 }// END: if DEBUG
226
227 seq[i] = MathUtils.randomChoicePDF(cProb);
228
229 }
230
231 if (DEBUG) {
232 // seq = new int[]{1, 3, 2, 3, 0, 1, 0, 1, 0, 2, 2, 0, 1, 3, 3, 3, 0, 1, 2, 1, 3, 1, 1, 1, 1, 3, 0, 0, 3, 2, 3, 2, 3, 2, 1, 2, 1, 3, 2, 3, 3, 0, 2, 2, 3, 2, 3, 2, 3, 1, 2, 0, 2, 1, 3, 2, 3, 1, 1, 1, 1, 0, 2, 3, 1, 0, 2, 1, 2, 1, 3, 0, 0, 0, 0, 0, 2, 0, 2, 3, 1, 0, 1, 3, 0, 2, 1, 2, 1, 3, 0, 0, 3, 2, 2, 0, 1, 0, 0, 3 };
233 System.out.println("Simulated sequence:");
234 Utils.printArray(seq);
235 }
236
237 if (m_tree.getChildCount(child) == 0) {
238
239 if (DEBUG) {
240 System.out.println("Simulated sequence (translated):");
241 System.out.println(intArray2Sequence(seq, child).getSequenceString());
242 }
243
244 alignment.addSequence(intArray2Sequence(seq, child));
245 }
246
247 traverse(m_tree.getChild(node, iChild), seq, category, alignment);
248 }//END: child nodes loop
249
250 } // traverse
251
252 void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double[] probs) {
253
254 NodeRef parent = tree.getParent(node);
255
256 final double branchRate = m_branchRateModel.getBranchRate(tree, node);
257
258 // Get the operational time of the branch
259 final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
260
261 if (branchTime < 0.0) {
262 throw new RuntimeException("Negative branch length: " + branchTime);
263 }
264
265 double branchLength = m_siteModel.getRateForCategory(rateCategory) * branchTime;
266
267 if (m_siteModel.getSubstitutionModel() instanceof SubstitutionEpochModel) {
268 ((SubstitutionEpochModel)m_siteModel.getSubstitutionModel()).getTransitionProbabilities(tree.getNodeHeight(node),
269 tree.getNodeHeight(parent),branchLength, probs);
270 return;
271 }
272 m_siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probs);
273 } // getTransitionProbabilities
274
275 /** helper method **/
276 public static void printUsageAndExit() {
277 System.err.println("Usage: java " + SequenceSimulator.class.getName() + " <nr of instantiations>");
278 System.err.println("where <nr of instantiations> is the number of instantiations to be replciated");
279 System.exit(0);
280 } // printUsageAndExit
281
282 /* standard xml parser stuff follows */
283 public static final String SEQUENCE_SIMULATOR = "sequenceSimulator";
284 public static final String SITE_MODEL = SiteModel.SITE_MODEL;
285 public static final String TREE = "tree";
286 // public static final String BRANCH_RATE_MODEL = "branchRateModel";
287 public static final String REPLICATIONS = "replications";
288
289 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
290
291 public String getParserName() {
292 return SEQUENCE_SIMULATOR;
293 }
294
295 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
296
297 int nReplications = xo.getIntegerAttribute(REPLICATIONS);
298
299 Tree tree = (Tree) xo.getChild(Tree.class);
300 SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class);
301 BranchRateModel rateModel = (BranchRateModel)xo.getChild(BranchRateModel.class);
302 Sequence ancestralSequence = (Sequence)xo.getChild(Sequence.class);
303
304 if (rateModel == null)
305 rateModel = new DefaultBranchRateModel();
306
307 SequenceSimulator s = new SequenceSimulator(tree, siteModel, rateModel, nReplications);
308
309 if(ancestralSequence != null) {
310 s.setAncestralSequence(ancestralSequence);
311 }
312
313 return s.simulate();
314 }
315
316 //************************************************************************
317 // AbstractXMLObjectParser implementation
318 //************************************************************************
319
320 public String getParserDescription() {
321 return "A SequenceSimulator that generates random sequences for a given tree, siteratemodel and branch rate model";
322 }
323
324 public Class getReturnType() {
325 return Alignment.class;
326 }
327
328 public XMLSyntaxRule[] getSyntaxRules() {
329 return rules;
330 }
331
332 private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
333 new ElementRule(Tree.class),
334 new ElementRule(SiteModel.class),
335 new ElementRule(BranchRateModel.class, true),
336 new ElementRule(Sequence.class, true),
337 AttributeRule.newIntegerRule(REPLICATIONS)
338 };
339 };
340
341 /** generate simple site model, for testing purposes **/
342 static SiteModel getDefaultSiteModel() {
343 Parameter kappa = new Parameter.Default(1, 2);
344 Parameter freqs = new Parameter.Default(new double[]{0.25, 0.25, 0.25, 0.25});
345 FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
346 HKY hky = new HKY(kappa, f);
347 return new GammaSiteModel(hky);
348 } // getDefaultSiteModel
349
350 public static void main(String [] args) {
351
352 try {
353
354 int nReplications = 10;
355
356 // create tree
357 NewickImporter importer = new NewickImporter("((A:1.0,B:1.0)AB:1.0,(C:1.0,D:1.0)CD:1.0)ABCD;");
358 Tree tree = importer.importTree(null);
359
360 // create site model
361 SiteModel siteModel = getDefaultSiteModel();
362
363 // create branch rate model
364 BranchRateModel branchRateModel = new DefaultBranchRateModel();
365
366 // feed to sequence simulator and generate leaves
367 SequenceSimulator treeSimulator = new SequenceSimulator(tree, siteModel, branchRateModel, nReplications);
368
369 Sequence ancestralSequence = new Sequence();
370 ancestralSequence.appendSequenceString("TCAGGTCAAG");
371 treeSimulator.setAncestralSequence(ancestralSequence);
372
373 System.out.println(treeSimulator.simulate().toString());
374
375 } catch (Exception e) {
376 e.printStackTrace();
377 }//END: try-catch block
378
379 } // END: main
380
381 // public static void main(String [] args) {
382 // try {
383 // if (args.length == 0) {
384 // printUsageAndExit();
385 // }
386 // int nReplications = Integer.parseInt(args[0]);
387 //
388 // // create tree
389 // NewickImporter importer = new NewickImporter("((A:1.0,B:1.0)AB:1.0,(C:1.0,D:1.0)CD:1.0)ABCD;");
390 // Tree tree = importer.importTree(null);
391 // // create site model
392 // SiteModel siteModel = getDefaultSiteModel();
393 // // create branch rate model
394 // BranchRateModel branchRateModel = new DefaultBranchRateModel();
395 //
396 // // feed to sequence simulator and generate leaves
397 // SequenceSimulator treeSimulator = new SequenceSimulator(tree, siteModel, branchRateModel, nReplications);
398 // System.err.println(treeSimulator.simulate().toString());
399 // treeSimulator.simulate();
400 // } catch (Exception e) {
401 // e.printStackTrace();
402 // }
403 // } // main
404
405 } // class SequenceSimulator