Debian Codegraph @

src/dr/evolution/coalescent/TreeIntervals.java

raw symbols SCIP
1 /*
2 * TreeIntervals.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.evolution.tree.NodeRef;
29 import dr.evolution.tree.Tree;
30 import dr.util.HeapSort;
31
32 import java.util.ArrayList;
33 import java.util.Collections;
34 import java.util.List;
35
36 /**
37 * Extracts the intervals from a tree.
38 *
39 * @author Andrew Rambaut
40 * @author Alexei Drummond
41 */
42 public class TreeIntervals implements IntervalList {
43
44 /**
45 * Parameterless constructor.
46 */
47 public TreeIntervals() {
48 }
49
50
51 public TreeIntervals(Tree tree) {
52 setTree(tree);
53 }
54
55
56 /**
57 * Sets the tree for which intervals are obtained
58 */
59 public void setTree(Tree tree) {
60 this.tree = tree;
61 intervalsKnown = false;
62 }
63
64 /**
65 * Specifies that the intervals are unknown (i.e., the tree has changed).
66 */
67 public void setIntervalsUnknown() {
68 intervalsKnown = false;
69 }
70
71 /**
72 * Sets the limit for which adjacent events are merged.
73 *
74 * @param multifurcationLimit A value of 0 means merge addition of leafs (terminal nodes) when possible but
75 * return each coalescense as a separate event.
76 */
77 public void setMultifurcationLimit(double multifurcationLimit) {
78 this.multifurcationLimit = multifurcationLimit;
79 intervalsKnown = false;
80 }
81
82 public int getSampleCount() {
83 return tree.getExternalNodeCount();
84 }
85
86 /**
87 * get number of intervals
88 */
89 public int getIntervalCount() {
90 if (!intervalsKnown) {
91 calculateIntervals();
92 }
93 return intervalCount;
94 }
95
96 /**
97 * Gets an interval.
98 */
99 public double getInterval(int i) {
100 if (!intervalsKnown) {
101 calculateIntervals();
102 }
103 if (i >= intervalCount) throw new IllegalArgumentException();
104 return intervals[i];
105 }
106
107 /**
108 * Returns the number of uncoalesced lineages within this interval.
109 * Required for s-coalescents, where new lineages are added as
110 * earlier samples are come across.
111 */
112 public int getLineageCount(int i) {
113 if (!intervalsKnown) {
114 calculateIntervals();
115 }
116 if (i >= intervalCount) throw new IllegalArgumentException();
117 return lineageCounts[i];
118 }
119
120 /**
121 * @param interval
122 * @return a list of the noderefs representing the lineages in the ith interval.
123 */
124 public final List getLineages(int interval) {
125
126 if (lineages[interval] == null) {
127
128 List<Object> lines = new ArrayList<Object>();
129 for (int i = 0; i <= interval; i++) {
130 if (lineagesAdded[i] != null) lines.addAll(lineagesAdded[i]);
131 if (lineagesRemoved[i] != null) lines.removeAll(lineagesRemoved[i]);
132 }
133 lineages[interval] = Collections.unmodifiableList(lines);
134
135 }
136 return lineages[interval];
137 }
138
139 /**
140 * Returns the number coalescent events in an interval
141 */
142 public int getCoalescentEvents(int i) {
143 if (!intervalsKnown) {
144 calculateIntervals();
145 }
146 if (i >= intervalCount) throw new IllegalArgumentException();
147 if (i < intervalCount - 1) {
148 return lineageCounts[i] - lineageCounts[i + 1];
149 } else {
150 return lineageCounts[i] - 1;
151 }
152 }
153
154 /**
155 * Returns the type of interval observed.
156 */
157 public IntervalType getIntervalType(int i) {
158 if (!intervalsKnown) {
159 calculateIntervals();
160 }
161 if (i >= intervalCount) throw new IllegalArgumentException();
162 int numEvents = getCoalescentEvents(i);
163
164 if (numEvents > 0) return IntervalType.COALESCENT;
165 else if (numEvents < 0) return IntervalType.SAMPLE;
166 else return IntervalType.NOTHING;
167 }
168
169 public NodeRef getCoalescentNode(int interval) {
170 if (getIntervalType(interval) == IntervalType.COALESCENT) {
171 if (lineagesRemoved[interval] != null) {
172 if (lineagesRemoved[interval].size() == 1) {
173 return lineagesRemoved[interval].get(0);
174 } else throw new IllegalArgumentException("multiple lineages lost over this interval!");
175 } else throw new IllegalArgumentException("Inconsistent: no intervals lost over this interval!");
176 } else throw new IllegalArgumentException("Interval " + interval + " is not a coalescent interval.");
177 }
178
179 /**
180 * get the total height of the genealogy represented by these
181 * intervals.
182 */
183 public double getTotalDuration() {
184
185 if (!intervalsKnown) {
186 calculateIntervals();
187 }
188 double height = 0.0;
189 for (int j = 0; j < intervalCount; j++) {
190 height += intervals[j];
191 }
192 return height;
193 }
194
195 /**
196 * Checks whether this set of coalescent intervals is fully resolved
197 * (i.e. whether is has exactly one coalescent event in each
198 * subsequent interval)
199 */
200 public boolean isBinaryCoalescent() {
201 if (!intervalsKnown) {
202 calculateIntervals();
203 }
204 for (int i = 0; i < intervalCount; i++) {
205 if (getCoalescentEvents(i) > 0) {
206 if (getCoalescentEvents(i) != 1) return false;
207 }
208 }
209
210 return true;
211 }
212
213 /**
214 * Checks whether this set of coalescent intervals coalescent only
215 * (i.e. whether is has exactly one or more coalescent event in each
216 * subsequent interval)
217 */
218 public boolean isCoalescentOnly() {
219 if (!intervalsKnown) {
220 calculateIntervals();
221 }
222 for (int i = 0; i < intervalCount; i++) {
223 if (getCoalescentEvents(i) < 1) return false;
224 }
225
226 return true;
227 }
228
229 /**
230 * Recalculates all the intervals for the given tree.
231 */
232 private void calculateIntervals() {
233
234 int nodeCount = tree.getNodeCount();
235
236 times = new double[nodeCount];
237 int[] childCounts = new int[nodeCount];
238
239 collectTimes(tree, times, childCounts);
240
241 indices = new int[nodeCount];
242
243 HeapSort.sort(times, indices);
244
245 if (intervals == null || intervals.length != nodeCount) {
246 intervals = new double[nodeCount];
247 lineageCounts = new int[nodeCount];
248 lineagesAdded = new List[nodeCount];
249 lineagesRemoved = new List[nodeCount];
250 lineages = new List[nodeCount];
251 }
252
253 // start is the time of the first tip
254 double start = times[indices[0]];
255 int numLines = 0;
256 int nodeNo = 0;
257 intervalCount = 0;
258 while (nodeNo < nodeCount) {
259
260 int lineagesRemoved = 0;
261 int lineagesAdded = 0;
262
263 double finish = times[indices[nodeNo]];
264 double next;
265
266 do {
267 final int childIndex = indices[nodeNo];
268 final int childCount = childCounts[childIndex];
269 // dont use nodeNo from here on in do loop
270 nodeNo += 1;
271 if (childCount == 0) {
272 addLineage(intervalCount, tree.getNode(childIndex));
273 lineagesAdded += 1;
274 } else {
275 lineagesRemoved += (childCount - 1);
276
277 // record removed lineages
278 final NodeRef parent = tree.getNode(childIndex);
279 //assert childCounts[indices[nodeNo]] == tree.getChildCount(parent);
280 //for (int j = 0; j < lineagesRemoved + 1; j++) {
281 for (int j = 0; j < childCount; j++) {
282 NodeRef child = tree.getChild(parent, j);
283 removeLineage(intervalCount, child);
284 }
285
286 // record added lineages
287 addLineage(intervalCount, parent);
288 // no mix of removed lineages when 0 th
289 if (multifurcationLimit == 0.0) {
290 break;
291 }
292 }
293
294 if (nodeNo < nodeCount) {
295 next = times[indices[nodeNo]];
296 } else break;
297 } while (Math.abs(next - finish) <= multifurcationLimit);
298
299 if (lineagesAdded > 0) {
300
301 if (intervalCount > 0 || ((finish - start) > multifurcationLimit)) {
302 intervals[intervalCount] = finish - start;
303 lineageCounts[intervalCount] = numLines;
304 intervalCount += 1;
305 }
306
307 start = finish;
308 }
309
310 // add sample event
311 numLines += lineagesAdded;
312
313 if (lineagesRemoved > 0) {
314
315 intervals[intervalCount] = finish - start;
316 lineageCounts[intervalCount] = numLines;
317 intervalCount += 1;
318 start = finish;
319 }
320 // coalescent event
321 numLines -= lineagesRemoved;
322 }
323
324 intervalsKnown = true;
325 }
326
327 /**
328 * Returns the time of the start of an interval
329 *
330 * @param i which interval
331 * @return start time
332 */
333 public double getIntervalTime(int i) {
334 if (!intervalsKnown) {
335 calculateIntervals();
336 }
337 return times[indices[i]];
338 }
339
340 private void addLineage(int interval, NodeRef node) {
341 if (lineagesAdded[interval] == null) lineagesAdded[interval] = new ArrayList<NodeRef>();
342 lineagesAdded[interval].add(node);
343 }
344
345 private void removeLineage(int interval, NodeRef node) {
346 if (lineagesRemoved[interval] == null) lineagesRemoved[interval] = new ArrayList<NodeRef>();
347 lineagesRemoved[interval].add(node);
348 }
349
350 /**
351 * @return the delta parameter of Pybus et al (Node spread statistic)
352 */
353 public double getDelta() {
354
355 return IntervalList.Utils.getDelta(this);
356 }
357
358 /**
359 * extract coalescent times and tip information into array times from tree.
360 */
361 private static void collectTimes(Tree tree, double[] times, int[] childCounts) {
362
363 for (int i = 0; i < tree.getNodeCount(); i++) {
364 NodeRef node = tree.getNode(i);
365 times[i] = tree.getNodeHeight(node);
366 childCounts[i] = tree.getChildCount(node);
367 }
368 }
369
370 /**
371 * Return the units that this tree is expressed in.
372 */
373 public final Type getUnits() {
374 return tree.getUnits();
375 }
376
377 /**
378 * Sets the units that this tree is expressed in.
379 */
380 public final void setUnits(Type units) {
381 throw new IllegalArgumentException("Can't set interval's units");
382 }
383
384 /**
385 * Extra functionality to store and restore values for caching
386 */
387 public void storeState() {
388 if (intervalsKnown) {
389
390 if (storedIntervals == null) {
391 storedIntervals = new double[intervals.length];
392 }
393 if (storedLineageCounts == null) {
394 storedLineageCounts = new int[lineageCounts.length];
395 }
396 if (superStore) {
397 if (storedIndices == null) {
398 storedIndices = new int[indices.length];
399 }
400 if (storedTimes == null) {
401 storedTimes = new double[times.length];
402 }
403 }
404 System.arraycopy(intervals, 0, storedIntervals, 0, intervals.length);
405 System.arraycopy(lineageCounts, 0, storedLineageCounts, 0, lineageCounts.length);
406 if (superStore) {
407 System.arraycopy(indices, 0, storedIndices, 0, indices.length);
408 System.arraycopy(times, 0, storedTimes, 0, times.length);
409 }
410 }
411
412 storedIntervalsKnown = intervalsKnown;
413 }
414
415 public void restoreState() {
416 intervalsKnown = storedIntervalsKnown;
417
418 if (intervalsKnown) {
419 double[] tmp1 = storedIntervals;
420 storedIntervals = intervals;
421 intervals = tmp1;
422
423 int[] tmp2 = storedLineageCounts;
424 storedLineageCounts = lineageCounts;
425 lineageCounts = tmp2;
426
427 if (superStore) {
428 tmp1 = storedTimes;
429 storedTimes = times;
430 times = tmp1;
431
432 tmp2 = storedIndices;
433 storedIndices = indices;
434 indices = tmp2;
435 }
436 }
437 }
438
439 public String toString() {
440 StringBuilder sb = new StringBuilder();
441 for (int i = 0; i < getIntervalCount(); i++) {
442 sb.append("[ ");
443 sb.append(getInterval(i));
444 sb.append(": ");
445 sb.append(getIntervalTime(i));
446 sb.append(": ");
447 sb.append(getLineageCount(i));
448 sb.append(" ]");
449 }
450 return sb.toString();
451 }
452
453 private int[] indices;
454 private int[] storedIndices;
455
456 private double[] times;
457 private double[] storedTimes;
458
459 /**
460 * The tree.
461 */
462 private Tree tree = null;
463
464 /**
465 * The widths of the intervals.
466 */
467 private double[] intervals;
468 private double[] storedIntervals;
469
470 /**
471 * The number of uncoalesced lineages within a particular interval.
472 */
473 private int[] lineageCounts;
474 private int[] storedLineageCounts;
475
476 /**
477 * The lineages in each interval (stored by node ref).
478 */
479 private List<NodeRef>[] lineagesAdded;
480 private List<NodeRef>[] lineagesRemoved;
481 private List[] lineages;
482
483 private int intervalCount = 0;
484
485 /**
486 * are the intervals known?
487 */
488 private boolean intervalsKnown = false;
489 private boolean storedIntervalsKnown;
490
491 private double multifurcationLimit = -1.0;
492
493 private static final boolean superStore = true;
494 }