Debian Codegraph @

src/dr/app/seqgen/SeqGen.java

raw symbols SCIP
1 /*
2 * SeqGen.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.seqgen;
27
28 import dr.evolution.io.Importer;
29 import dr.evolution.io.NewickImporter;
30 import dr.evolution.io.TreeImporter;
31 import dr.evolution.tree.NodeRef;
32 import dr.evolution.tree.Tree;
33 import dr.oldevomodel.sitemodel.GammaSiteModel;
34 import dr.oldevomodel.sitemodel.SiteModel;
35 import dr.oldevomodel.substmodel.FrequencyModel;
36 import dr.oldevomodel.substmodel.HKY;
37 import dr.oldevomodel.substmodel.SubstitutionModel;
38 import jebl.evolution.alignments.Alignment;
39 import jebl.evolution.alignments.BasicAlignment;
40 import jebl.evolution.io.FastaExporter;
41 import jebl.evolution.sequences.*;
42 import jebl.evolution.taxa.Taxon;
43 import jebl.math.Random;
44
45 import java.io.*;
46 import java.util.ArrayList;
47 import java.util.HashMap;
48 import java.util.List;
49 import java.util.Map;
50
51 /**
52 * @author Andrew Rambaut
53 * @version $Id$
54 */
55 public class SeqGen {
56
57 public SeqGen(final int length, final double substitutionRate, final FrequencyModel freqModel, final SubstitutionModel substModel, final SiteModel siteModel, final double damageRate) {
58 this.length = length;
59 this.substitutionRate = substitutionRate;
60 this.freqModel = freqModel;
61 this.substModel = substModel;
62 this.siteModel = siteModel;
63 this.damageRate = damageRate;
64 }
65
66 public Alignment simulate(Tree tree) {
67
68 int[] initialSequence = new int[length];
69
70 drawSequence(initialSequence, freqModel);
71
72 int[] siteCategories = new int[length];
73
74 drawSiteCategories(siteModel, siteCategories);
75
76 double[] rates = new double[siteModel.getCategoryCount()];
77 for (int i = 0; i < rates.length; i++) {
78 rates[i] = siteModel.getRateForCategory(i) * substitutionRate;
79 }
80
81 for (int i = 0; i < tree.getChildCount(tree.getRoot()); i++) {
82 NodeRef child = tree.getChild(tree.getRoot(), i);
83 evolveSequences(initialSequence, tree, child, substModel, siteCategories, rates);
84 }
85
86 Map<State, State[]> damageMap = new HashMap<State, State[]>();
87 damageMap.put(Nucleotides.A_STATE, new State[]{Nucleotides.G_STATE});
88 damageMap.put(Nucleotides.C_STATE, new State[]{Nucleotides.T_STATE});
89 damageMap.put(Nucleotides.G_STATE, new State[]{Nucleotides.A_STATE});
90 damageMap.put(Nucleotides.T_STATE, new State[]{Nucleotides.C_STATE});
91
92 Sequence[] sequences = new Sequence[tree.getExternalNodeCount()];
93
94 List<NucleotideState> nucs = jebl.evolution.sequences.Nucleotides.getCanonicalStates();
95 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
96 NodeRef node = tree.getExternalNode(i);
97 int[] seq = (int[]) tree.getNodeTaxon(node).getAttribute("seq");
98 State[] states = new State[seq.length];
99 for (int j = 0; j < states.length; j++) {
100 states[j] = nucs.get(seq[j]);
101 }
102
103 if (damageRate > 0) {
104 damageSequence(states, damageRate, tree.getNodeHeight(node), damageMap);
105 }
106
107 sequences[i] = new BasicSequence(SequenceType.NUCLEOTIDE,
108 Taxon.getTaxon(tree.getNodeTaxon(node).getId()),
109 states);
110 }
111
112 BasicAlignment alignment = new BasicAlignment(sequences);
113
114
115 return alignment;
116 }
117
118 void drawSiteCategories(SiteModel siteModel, int[] siteCategories) {
119 double[] categoryProportions = siteModel.getCategoryProportions();
120 double[] cumulativeProportions = new double[categoryProportions.length];
121 cumulativeProportions[0] = categoryProportions[0];
122 for (int i = 1; i < cumulativeProportions.length; i++) {
123 cumulativeProportions[i] = cumulativeProportions[i - 1] + categoryProportions[i];
124 }
125
126 for (int i = 0; i < siteCategories.length; i++) {
127 siteCategories[i] = draw(cumulativeProportions);
128 }
129 }
130
131 public void drawSequence(int[] initialSequence, FrequencyModel freqModel) {
132 double[] freqs = freqModel.getCumulativeFrequencies();
133 for (int i = 0; i < initialSequence.length; i++) {
134 initialSequence[i] = draw(freqs);
135 }
136 }
137
138 void evolveSequences(int[] sequence0,
139 Tree tree, NodeRef node,
140 SubstitutionModel substModel,
141 int[] siteCategories,
142 double[] categoryRates) {
143 int stateCount = substModel.getDataType().getStateCount();
144
145 int[] sequence1 = new int[sequence0.length];
146
147 double[][][] transitionProbabilities = new double[siteCategories.length][stateCount][stateCount];
148
149 for (int i = 0; i < categoryRates.length; i++) {
150 double branchLength = tree.getBranchLength(node) * categoryRates[i];
151 double[] tmp = new double[stateCount * stateCount];
152 substModel.getTransitionProbabilities(branchLength, tmp);
153
154 int l = 0;
155 for (int j = 0; j < stateCount; j++) {
156 transitionProbabilities[i][j][0] = tmp[l];
157 l++;
158 for (int k = 1; k < stateCount; k++) {
159 transitionProbabilities[i][j][k] = transitionProbabilities[i][j][k - 1] + tmp[l];
160 l++;
161 }
162
163 }
164 }
165
166 evolveSequence(sequence0, siteCategories, transitionProbabilities, sequence1);
167
168 if (!tree.isExternal(node)) {
169 for (int i = 0; i < tree.getChildCount(node); i++) {
170 NodeRef child = tree.getChild(node, i);
171 evolveSequences(sequence1, tree, child, substModel, siteCategories, categoryRates);
172 }
173 } else {
174 tree.getNodeTaxon(node).setAttribute("seq", sequence1);
175 }
176 }
177
178 private void evolveSequence(int[] ancestralSequence,
179 int[] siteCategories,
180 double[][][] cumulativeTransitionProbabilities,
181 int[] descendentSequence) {
182
183 for (int i = 0; i < ancestralSequence.length; i++) {
184 descendentSequence[i] = draw(cumulativeTransitionProbabilities[siteCategories[i]][ancestralSequence[i]]);
185 }
186 }
187
188 private void damageSequence(State[] sequence, double rate, double time, Map<State, State[]> damageMap) {
189 double pUndamaged = Math.exp(-rate * time);
190
191 for (int i = 0; i < sequence.length; i++) {
192 double r = Random.nextDouble();
193 if (r >= pUndamaged) {
194 State[] states = damageMap.get(sequence[i]);
195 if (states.length > 0) {
196 int index = Random.nextInt(states.length);
197 sequence[i] = states[index];
198 } else {
199 sequence[i] = states[0];
200 }
201 }
202 }
203 }
204
205 /**
206 * draws a state from using a set of cumulative frequencies (last value should be 1.0)
207 *
208 * @param cumulativeFrequencies
209 * @return
210 */
211 private int draw(double[] cumulativeFrequencies) {
212 double r = Random.nextDouble();
213
214 // defensive - make sure that it is actually set...
215 int state = -1;
216
217 for (int j = 0; j < cumulativeFrequencies.length; j++) {
218 if (r < cumulativeFrequencies[j]) {
219 state = j;
220 break;
221 }
222 }
223
224 assert (state != -1);
225
226 return state;
227 }
228
229 final int length;
230 final double substitutionRate;
231 final FrequencyModel freqModel;
232 final SubstitutionModel substModel;
233 final SiteModel siteModel;
234 final double damageRate;
235
236 public static void main(String[] argv) {
237
238 String treeFileName = argv[0];
239 String outputFileStem = argv[1];
240
241 int length = 500;
242
243 double[] frequencies = new double[]{0.25, 0.25, 0.25, 0.25};
244 double kappa = 10.0;
245 double alpha = 0.5;
246 double substitutionRate = argv.length < 3 ? 1.0E-3 : Double.parseDouble(argv[2]);
247 int categoryCount = argv.length < 4 ? 8 : Integer.parseInt(argv[3]);
248 double damageRate = argv.length < 5 ? 0 : Double.parseDouble(argv[4]); //1.56E-6;
249
250 System.out.println("substitutionRate = " + substitutionRate + "; categoryCount = " + categoryCount + "; damageRate = " + damageRate);
251
252 FrequencyModel freqModel = new FrequencyModel(dr.evolution.datatype.Nucleotides.INSTANCE, frequencies);
253
254 HKY hkyModel = new HKY(kappa, freqModel);
255 SiteModel siteModel = null;
256
257 if (categoryCount > 1) {
258 siteModel = new GammaSiteModel(hkyModel, alpha, categoryCount);
259 } else {
260 // no rate heterogeneity
261 siteModel = new GammaSiteModel(hkyModel);
262 }
263
264 List<Tree> trees = new ArrayList<Tree>();
265
266 FileReader reader = null;
267 try {
268 reader = new FileReader(treeFileName);
269 // TreeImporter importer = new NexusImporter(reader);
270 TreeImporter importer = new NewickImporter(reader);
271
272 while (importer.hasTree()) {
273 Tree tree = importer.importNextTree();
274 trees.add(tree);
275 System.out.println("tree height = " + tree.getNodeHeight(tree.getRoot()) + "; leave nodes = " + tree.getExternalNodeCount());
276 }
277
278 } catch (FileNotFoundException e) {
279 e.printStackTrace();
280 return;
281 } catch (Importer.ImportException e) {
282 e.printStackTrace();
283 return;
284 } catch (IOException e) {
285 e.printStackTrace();
286 return;
287 }
288
289 SeqGen seqGen = new SeqGen(length,
290 substitutionRate, freqModel, hkyModel, siteModel,
291 damageRate);
292 int i = 1;
293 for (Tree tree : trees) {
294 Alignment alignment = seqGen.simulate(tree);
295
296 FileWriter writer = null;
297 try {
298 // writer = new FileWriter(outputFileStem + (i < 10 ? "00" : (i < 100 ? "0" : "")) + i + ".nex");
299 // NexusExporter exporter = new NexusExporter(writer);
300 //
301 // exporter.exportAlignment(alignment);
302 //
303 // writer.close();
304 String outputFileName = outputFileStem + "-" + substitutionRate + ".fasta";
305
306 writer = new FileWriter(outputFileName);
307 BufferedWriter bf = new BufferedWriter(writer);
308 FastaExporter exporter = new FastaExporter(bf);
309
310 exporter.exportSequences(alignment.getSequenceList());
311
312 bf.close();
313 System.out.println("Write " + i + "th sequence file : " + outputFileName);
314
315 i++;
316 } catch (IOException e) {
317 e.printStackTrace();
318 return;
319 }
320 }
321
322 }
323 }