Debian Codegraph @

src/dr/evolution/coalescent/CoalescentSimulator.java

raw symbols SCIP
1 /*
2 * CoalescentSimulator.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.evolution.coalescent;
27
28 import dr.app.tools.NexusExporter;
29 import dr.evolution.tree.*;
30 import dr.evolution.util.*;
31 import dr.evolution.util.Date;
32 import dr.math.MathUtils;
33 import dr.util.HeapSort;
34
35 import java.io.PrintStream;
36 import java.util.*;
37
38 /**
39 * This class provides the basic engine for coalescent simulation of a given demographic model over a given time period.
40 * The input is a set of nodes (some of which may be subtrees) and the output is a new (smaller) set of nodes after
41 * some coalescence over a certain time period.
42 *
43 * $Id: CoalescentSimulator.java,v 1.9 2005/05/24 20:25:55 rambaut Exp $
44 *
45 * @author Alexei Drummond
46 *
47 */
48 public class CoalescentSimulator {
49
50 public CoalescentSimulator() {}
51
52
53 /**
54 * Simulates a coalescent tree, given a taxon list.
55 * @param taxa the set of taxa to simulate a coalescent tree between
56 * @param demoFunction the demographic function to use
57 */
58 public SimpleTree simulateTree(TaxonList taxa, DemographicFunction demoFunction) {
59
60 if( taxa.getTaxonCount() == 0 ) return new SimpleTree();
61
62 SimpleNode[] nodes = new SimpleNode[taxa.getTaxonCount()];
63 for (int i = 0; i < taxa.getTaxonCount(); i++) {
64 nodes[i] = new SimpleNode();
65 nodes[i].setTaxon(taxa.getTaxon(i));
66 }
67
68 boolean usingDates = Taxon.getMostRecentDate() != null;
69
70 for (int i = 0; i < taxa.getTaxonCount(); i++) {
71 Taxon taxon = taxa.getTaxon(i);
72 if (usingDates) {
73 nodes[i].setHeight(taxon.getHeight());
74 } else {
75 // assume contemporaneous tips
76 nodes[i].setHeight(0.0);
77 }
78 }
79
80 return new SimpleTree(simulateCoalescent(nodes, demoFunction));
81 }
82
83 /**
84 * @return the root node of the given array of nodes after simulation of the coalescent under the given demographic model.
85 */
86 public SimpleNode simulateCoalescent(SimpleNode[] nodes, DemographicFunction demographic) {
87 // sanity check - disjoint trees
88
89 if( ! TreeUtils.allDisjoint(nodes) ) {
90 throw new RuntimeException("subtrees' taxa overlap");
91 }
92
93 if( nodes.length == 0 ) {
94 throw new IllegalArgumentException("empty nodes set") ;
95 }
96
97 for(int attempts = 0; attempts < 1000; ++attempts) {
98 SimpleNode[] rootNode = simulateCoalescent(nodes, demographic, 0.0, Double.POSITIVE_INFINITY);
99 if( rootNode.length == 1 ) {
100 return rootNode[0];
101 }
102 }
103
104 throw new RuntimeException("failed to merge trees after 1000 tries.");
105 }
106
107 public SimpleNode[] simulateCoalescent(SimpleNode[] nodes, DemographicFunction demographic, double currentHeight,
108 double maxHeight){
109 return simulateCoalescent(nodes, demographic, currentHeight, maxHeight, false);
110 }
111
112 // if enforceMaxHeight is true, all heights will be drawn from a normalised distribution such that maxHeight really
113 // is the maximum height
114
115 public SimpleNode[] simulateCoalescent(SimpleNode[] nodes, DemographicFunction demographic, double currentHeight,
116 double maxHeight, boolean enforceMaxHeight) {
117 // If only one node, return it
118 // continuing results in an infinite loop
119 if( nodes.length == 1 ) return nodes;
120
121 double[] heights = new double[nodes.length];
122 for (int i = 0; i < nodes.length; i++) {
123 heights[i] = nodes[i].getHeight();
124 }
125 int[] indices = new int[nodes.length];
126 HeapSort.sort(heights, indices);
127
128 // node list
129 nodeList.clear();
130 activeNodeCount = 0;
131 for (int i = 0; i < nodes.length; i++) {
132 nodeList.add(nodes[indices[i]]);
133 }
134 setCurrentHeight(currentHeight);
135
136 // get at least two tips
137 while (getActiveNodeCount() < 2) {
138 currentHeight = getMinimumInactiveHeight();
139 setCurrentHeight(currentHeight);
140 }
141
142 double nextCoalescentHeight;
143
144 // simulate coalescent events
145 if(!enforceMaxHeight){
146 nextCoalescentHeight = currentHeight + DemographicFunction.Utils.getSimulatedInterval(demographic,
147 getActiveNodeCount(), currentHeight);
148 } else {
149 nextCoalescentHeight = currentHeight + DemographicFunction.Utils.getSimulatedInterval(demographic,
150 getActiveNodeCount(), currentHeight, maxHeight);
151 }
152
153 while (nextCoalescentHeight < maxHeight && (getNodeCount() > 1)) {
154
155 if (nextCoalescentHeight >= getMinimumInactiveHeight()) {
156 currentHeight = getMinimumInactiveHeight();
157 setCurrentHeight(currentHeight);
158 } else {
159 currentHeight = nextCoalescentHeight;
160 coalesceTwoActiveNodes(currentHeight);
161 }
162
163 if (getNodeCount() > 1) {
164 // get at least two tips
165 while (getActiveNodeCount() < 2) {
166 currentHeight = getMinimumInactiveHeight();
167 setCurrentHeight(currentHeight);
168 }
169
170 if(!enforceMaxHeight){
171 // nextCoalescentHeight = currentHeight + DemographicFunction.Utils.getMedianInterval(demographic, getActiveNodeCount(), currentHeight);
172 nextCoalescentHeight = currentHeight + DemographicFunction.Utils.getSimulatedInterval(demographic,
173 getActiveNodeCount(), currentHeight);
174 } else {
175 nextCoalescentHeight = currentHeight + DemographicFunction.Utils.getSimulatedInterval(demographic,
176 getActiveNodeCount(), currentHeight, maxHeight);
177 }
178 }
179 }
180
181 SimpleNode[] nodesLeft = new SimpleNode[nodeList.size()];
182 for (int i = 0; i < nodesLeft.length; i++) {
183 nodesLeft[i] = nodeList.get(i);
184 }
185
186 return nodesLeft;
187 }
188
189 /**
190 * @return the height of youngest inactive node.
191 */
192 private double getMinimumInactiveHeight() {
193 if (activeNodeCount < nodeList.size()) {
194 return (nodeList.get(activeNodeCount)).getHeight();
195 } else return Double.POSITIVE_INFINITY;
196 }
197
198 /**
199 * Set the current height.
200 */
201 private void setCurrentHeight(double height) {
202 while (getMinimumInactiveHeight() <= height) {
203 activeNodeCount += 1;
204 }
205 }
206
207 /**
208 * @return the numver of active nodes (equate to lineages)
209 */
210 private int getActiveNodeCount() {
211 return activeNodeCount;
212 }
213
214 /**
215 * @return the total number of nodes both active and inactive
216 */
217 private int getNodeCount() {
218 return nodeList.size();
219 }
220
221 /**
222 * Coalesce two nodes in the active list. This method removes the two (randomly selected) active nodes
223 * and replaces them with the new node at the top of the active list.
224 */
225 private void coalesceTwoActiveNodes(double height) {
226 int node1 = MathUtils.nextInt(activeNodeCount);
227 int node2 = node1;
228 while (node2 == node1) {
229 node2 = MathUtils.nextInt(activeNodeCount);
230 }
231
232 SimpleNode left = nodeList.get(node1);
233 SimpleNode right = nodeList.get(node2);
234
235 SimpleNode newNode = new SimpleNode();
236 newNode.setHeight(height);
237 newNode.addChild(left);
238 newNode.addChild(right);
239
240 nodeList.remove(left);
241 nodeList.remove(right);
242
243 activeNodeCount -= 2;
244
245 nodeList.add(activeNodeCount, newNode);
246
247 activeNodeCount += 1;
248
249 if (getMinimumInactiveHeight() < height) {
250 throw new RuntimeException("This should never happen! Somehow the current active node is older than the next inactive node!");
251 }
252 }
253
254 private final ArrayList<SimpleNode> nodeList = new ArrayList<SimpleNode>();
255 private int activeNodeCount = 0;
256
257 public static void main1(String[] args) {
258
259 double[] samplingTimes = {
260 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0
261 };
262
263 ExponentialGrowth exponentialGrowth = new ExponentialGrowth(Units.Type.YEARS);
264 exponentialGrowth.setN0(10);
265 exponentialGrowth.setGrowthRate(0.5);
266
267 ConstantPopulation constantPopulation = new ConstantPopulation(Units.Type.YEARS);
268 constantPopulation.setN0(10);
269
270 Taxa taxa = new Taxa();
271 int i = 1;
272 for (double time : samplingTimes) {
273 Taxon taxon = new Taxon("tip" + i);
274 taxon.setAttribute("date", new Date(time, Units.Type.YEARS, true));
275 i++;
276 taxa.addTaxon(taxon);
277 }
278 CoalescentSimulator simulator = new CoalescentSimulator();
279 Tree tree = simulator.simulateTree(taxa, exponentialGrowth);
280
281 List<Double> heights = new ArrayList<Double>();
282 for (int j = 0; j < tree.getInternalNodeCount(); j++) {
283 heights.add(tree.getNodeHeight(tree.getInternalNode(j)));
284 }
285
286 Collections.sort(heights);
287
288 for (int j = 0; j < heights.size(); j++) {
289 System.out.println(j + "\t" + heights.get(j));
290 }
291
292 }
293
294 public static void main(String[] args) {
295
296 int N = 100000000;
297
298 double[] samplingTimes = {
299 0.0, 0.0, 0.0, 0.0, 0.0
300 };
301
302 ConstantPopulation constantPopulation = new ConstantPopulation(Units.Type.YEARS);
303 constantPopulation.setN0(1);
304
305 Taxa taxa = new Taxa();
306 int i = 1;
307 for (double time : samplingTimes) {
308 Taxon taxon = new Taxon("tip" + i);
309 taxon.setAttribute("date", new Date(time, Units.Type.YEARS, true));
310 i++;
311 taxa.addTaxon(taxon);
312 }
313 CoalescentSimulator simulator = new CoalescentSimulator();
314
315 PrintStream out = System.out;
316 // try {
317 // out = new PrintStream(new File("out.nex"));
318 // } catch (FileNotFoundException e) {
319 // e.printStackTrace();
320 // }
321 NexusExporter exporter = new NexusExporter(out);
322 Tree tree = simulator.simulateTree(taxa, constantPopulation);
323 Map<String, Integer> idMap = exporter.writeNexusHeader(tree);
324 out.println("\t\t;");
325 exporter.writeNexusTree(tree, "TREE_" + 0, true, idMap);
326
327 for (i = 1; i < N; i++) {
328 tree = simulator.simulateTree(taxa, constantPopulation);
329 exporter.writeNexusTree(tree, "TREE_" + i, true, idMap);
330 }
331 out.println("End;");
332 }
333
334
335 }