Debian Codegraph @

src/dr/app/vcs/VariableCoalescentSimulator.java

raw symbols SCIP
1 /*
2 * VariableCoalescentSimulator.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.vcs;
27
28 import dr.evolution.coalescent.CoalescentSimulator;
29 import dr.evolution.coalescent.PiecewiseLinearPopulation;
30 import dr.evolution.tree.Tree;
31 import dr.evolution.tree.TreeUtils;
32 import dr.evolution.util.Date;
33 import dr.evolution.util.Taxa;
34 import dr.evolution.util.Taxon;
35 import dr.evolution.util.Units;
36 import ml.options.Options;
37
38 import java.io.*;
39 import java.util.ArrayList;
40 import java.util.List;
41
42 /**
43 * This program simulates a set of coalescent trees from an arbitrary variable population size history expressed as
44 * a piecewise-linear function.
45 * <p/>
46 * Usage:
47 * java -jar vcs.jar [options] &lt;infile&gt; &lt;outfile&gt;
48 * <p/>
49 * Options:
50 * <ul>
51 * <li> <b> -g &lt;genTime&gt; </b> sets the generation time to the given value. This is used to scale
52 * times in the input file into units of generations.
53 * The default value is 1.0
54 * <li> <b> -n &lt;numSamples&gt; </b> sets the number of samples to generate the trees from.
55 * The default value is 50
56 * <li> <b> -p &lt;popScale&gt; </b> sets the population size scale factor to the given value. This scale
57 * factor transforms the population sizes in the input file to
58 * effective population sizes. This is useful if the population size
59 * profiles are expressed, for example, as prevalences, so then scale
60 * factor would represent the effective numbers of hosts in the
61 * population of interest.
62 * The default value is 1.0
63 * <li> <b> -se &lt;sampleEnd&gt; </b> the time at which last taxa is sampled, in the time scale provided by the input
64 * file. If this differs from the time specified be -ss option then the
65 * samples will be evenly spaced between the two times.
66 * The default value is the last time if -f is set and the first time
67 * otherwise.
68 * <li> <b> -ss &lt;sampleStart&gt; </b> the time at which first taxa is sampled, in the time scale provided by the input
69 * file. If this differs from the time specified be -se option then the
70 * samples will be evenly spaced between the two times.
71 * The default value is the last time if -f is set and the first time
72 * otherwise.
73 * <li> <b> -f </b> specifies that the population size history proceeds forward in time.
74 * Otherwise the population size history is assumed to proceed into the past. <br>
75 * <li> <b> -reps &lt;reps&gt; </b> the number of replicate simulations that will be performed.
76 * Each replicate will be separated in the output file by a comment line that labels the replicate, e.g. #rep 0.
77 * </ul>
78 * <p/>
79 * <infile> a whitespace-delimited plain text file. The first column contains the time
80 * and should be ascending from zero. Subsequent columns contain the population size
81 * histories, for which a tree will be simulated for each.
82 * <p/>
83 * <outfile> the file to which the trees will be written in newick format.
84 *
85 * @author Alexei Drummond
86 */
87 public class VariableCoalescentSimulator {
88
89 public static void main(String[] arg) throws IOException {
90
91 long startTime = System.currentTimeMillis();
92
93 Options options = new Options(arg, 0, 7);
94
95 options.getSet().addOption("g", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
96 options.getSet().addOption("n", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
97 options.getSet().addOption("p", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
98 options.getSet().addOption("se", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
99 options.getSet().addOption("ss", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
100 options.getSet().addOption("reps", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
101 options.getSet().addOption("f", Options.Multiplicity.ZERO_OR_ONE);
102
103 if (!options.check()) {
104 System.out.println(options.getCheckErrors());
105 System.out.println();
106 printUsage();
107 System.exit(1);
108 }
109
110 double generationTime = 1.0;
111 double popSizeScale = 1.0;
112 int n = 50;
113 double ss = -1;
114 double se = -1;
115 int reps = 1;
116
117 boolean timeForward = options.getSet().isSet("f");
118 if (options.getSet().isSet("g")) {
119 String g = options.getSet().getOption("g").getResultValue(0);
120 generationTime = Double.parseDouble(g);
121 System.out.println("generation time = " + g);
122 }
123 if (options.getSet().isSet("n")) {
124 String sampleSize = options.getSet().getOption("n").getResultValue(0);
125 n = Integer.parseInt(sampleSize);
126 System.out.println("sample size = " + n);
127 }
128 if (options.getSet().isSet("p")) {
129 String p = options.getSet().getOption("p").getResultValue(0);
130 popSizeScale = Double.parseDouble(p);
131 System.out.println("population size scale factor = " + p);
132 }
133 if (options.getSet().isSet("ss")) {
134 String sampleStart = options.getSet().getOption("ss").getResultValue(0);
135 ss = Double.parseDouble(sampleStart);
136 System.out.println("sample start time = " + ss);
137 }
138 if (options.getSet().isSet("se")) {
139 String sampleEnd = options.getSet().getOption("se").getResultValue(0);
140 se = Double.parseDouble(sampleEnd);
141 System.out.println("sample end time = " + se);
142 }
143 if (options.getSet().isSet("reps")) {
144 String replicates = options.getSet().getOption("reps").getResultValue(0);
145 reps = Integer.parseInt(replicates);
146 System.out.println("replicates = " + reps);
147 }
148
149 String filename = options.getSet().getData().get(0);
150 String outfile = options.getSet().getData().get(1);
151
152 // READ DEMOGRAPHIC FUNCTION
153
154 BufferedReader reader = new BufferedReader(new FileReader(filename));
155
156 List<Double> times = new ArrayList<Double>();
157
158 String line = reader.readLine();
159 String[] tokens = line.trim().split("[\t ]+");
160 if (tokens.length < 2) throw new RuntimeException();
161
162 ArrayList<ArrayList> popSizes = new ArrayList<ArrayList>();
163 while (line != null) {
164 double time = Double.parseDouble(tokens[0]) / generationTime;
165 times.add(time);
166 for (int i = 1; i < tokens.length; i++) {
167 popSizes.add(new ArrayList<Double>());
168 popSizes.get(i - 1).add(Double.parseDouble(tokens[i]));
169 }
170 line = reader.readLine();
171 if (line != null) {
172 tokens = line.trim().split("[\t ]+");
173 if (tokens.length != popSizes.size() + 1) throw new RuntimeException();
174 }
175 }
176 reader.close();
177
178 // GENERATE SAMPLE
179 double lastTime = times.get(times.size() - 1);
180
181 if (ss == -1) {
182 ss = timeForward ? lastTime : times.get(0);
183 }
184 if (se == -1) {
185 se = timeForward ? lastTime : times.get(0);
186 }
187
188 double dt = (se - ss) / ((double) n - 1.0);
189 double time = ss;
190
191 Taxa taxa = new Taxa();
192
193 for (int i = 0; i < n; i++) {
194
195 double sampleTime;
196 if (timeForward) {
197 sampleTime = (lastTime - time) / generationTime;
198 } else sampleTime = time / generationTime;
199
200 Taxon taxon = new Taxon(i + "");
201 taxon.setAttribute(dr.evolution.util.Date.DATE, new Date(sampleTime, Units.Type.GENERATIONS, true));
202 taxa.addTaxon(taxon);
203 time += dt;
204 }
205
206 double minTheta = Double.MAX_VALUE;
207 double maxTheta = 0.0;
208
209 PrintWriter out = new PrintWriter(new FileWriter(outfile));
210
211 int popHistory = 0;
212
213 PiecewiseLinearPopulation[] demography = new PiecewiseLinearPopulation[popSizes.size()];
214
215 for (List<Double> popSize : popSizes) {
216 double[] thetas = new double[popSize.size()];
217 double[] intervals = new double[times.size() - 1];
218
219 for (int i = intervals.length; i >= 0; i--) {
220
221 int j = timeForward ? intervals.length - i : i - 1;
222 int k = timeForward ? i : intervals.length - i + 1;
223
224 if (i != 0) intervals[j] = times.get(k) - times.get(k - 1);
225
226 double theta = popSize.get(k) * popSizeScale;
227 thetas[j] = theta;
228 if (theta < minTheta) {
229 minTheta = theta;
230 }
231 if (theta > maxTheta) {
232 maxTheta = theta;
233 }
234
235 //System.out.println(t + "\t" + theta);
236 }
237
238 System.out.println("N" + popHistory + "(t) range = [" + minTheta + ", " + maxTheta + "]");
239
240 demography[popHistory] = new PiecewiseLinearPopulation(intervals, thetas, Units.Type.GENERATIONS);
241
242 popHistory += 1;
243 }
244
245 CoalescentSimulator simulator = new CoalescentSimulator();
246 for (int i = 0; i < reps; i++) {
247
248 out.println("#rep " + i);
249 for (int j = 0; j < demography.length; j++) {
250 Tree tree = simulator.simulateTree(taxa, demography[j]);
251
252 out.println(TreeUtils.newick(tree));
253 //System.err.println(Tree.Utils.newick(tree));
254 }
255
256
257 }
258
259 out.flush();
260 out.close();
261
262 long stopTime = System.currentTimeMillis();
263 System.out.println("Took " + (stopTime - startTime) / 1000.0 + " seconds");
264 }
265
266 private static Taxa readSampleFile(String fileName, double generationTime) throws IOException {
267
268 BufferedReader reader = new BufferedReader(new FileReader(fileName));
269
270 String line = reader.readLine();
271 Taxa taxa = new Taxa();
272 int id = 0;
273 while (line != null) {
274
275 if (!line.startsWith("#")) {
276
277 String[] tokens = line.split("[\t ]+");
278
279 // sample times are in the same units as simulation
280 double sampleTime = Double.parseDouble(tokens[0]) / generationTime;
281 int count = Integer.parseInt(tokens[1]);
282
283 for (int i = 0; i < count; i++) {
284 Taxon taxon = new Taxon(id + "");
285 taxon.setAttribute(dr.evolution.util.Date.DATE, new Date(sampleTime, Units.Type.GENERATIONS, true));
286 taxa.addTaxon(taxon);
287 id += 1;
288 }
289 }
290 line = reader.readLine();
291 }
292
293 return taxa;
294 }
295
296 private static void printUsage() {
297
298 System.out.println(
299 "Usage: \n" +
300 " java -jar vcs.jar [options] <infile> <outfile>\n" +
301 " \n" +
302 "Options:\n" +
303 " -g <value> sets the generation time to the given value. This is used to scale\n" +
304 " times in the input file into units of generations. \n" +
305 " The default value is 1.0\n" +
306 " -n <int> sets the number of samples to generate the trees from. \n" +
307 " The default value is 50\n" +
308 " -p <value> sets the population size scale factor to the given value. This scale \n" +
309 " factor transforms the population sizes in the input file to\n" +
310 " effective population sizes. This is useful if the population size\n" +
311 " profiles are expressed, for example, as prevalences, so then scale\n" +
312 " factor would represent the effective numbers of hosts in the\n" +
313 " population of interest. \n" +
314 " The default value is 1.0\n" +
315 " -ss <value> the time at which first taxa is sampled, in the time scale provided by the input\n" +
316 " file. If this differs from the time specified be -ss option then the \n" +
317 " samples will be evenly spaced between the two times.\n" +
318 " The default value is the last time if -f is set and the first time\n" +
319 " otherwise.\n" +
320 " -se <value> the time at which last taxa is sampled, in the time scale provided by the input\n" +
321 " file. If this differs from the time specified be -se option then the \n" +
322 " samples will be evenly spaced between the two times.\n" +
323 " The default value is the last time if -f is set and the first time\n" +
324 " otherwise.\n" +
325 " -reps <reps> the number of replicate simulations that will be performed. \n" +
326 " Each replicate will be separated in the output file by a comment line that\n" +
327 " labels the replicate, e.g. #rep 0.\n" +
328 " -f specifies that the population size history proceeds forward in time.\n" +
329 " Otherwise the population size history is assumed to proceed into the past.\n" +
330 "\n" +
331 "<infile> A whitespace-delimited plain text file. The first column contains the time\n" +
332 " and should be ascending from zero. Subsequent columns contain the population size\n" +
333 " histories, for which a tree will be simulated for each.\n" +
334 "<outfile> The file to which the trees will be written in newick format.");
335
336 }
337 }