Debian Codegraph @

src/dr/evomodel/epidemiology/casetocase/WithinCaseCoalescent.java

raw symbols SCIP
1 /*
2 * WithinCaseCoalescent.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.evomodel.epidemiology.casetocase;
27
28 import dr.app.tools.NexusExporter;
29 import dr.evolution.coalescent.*;
30 import dr.evolution.tree.FlexibleNode;
31 import dr.evolution.tree.FlexibleTree;
32 import dr.evolution.tree.NodeRef;
33 import dr.evolution.tree.Tree;
34 import dr.evolution.util.*;
35 import dr.evomodel.coalescent.DemographicModel;
36 import dr.evomodel.tree.TreeModel;
37 import dr.inference.loggers.LogColumn;
38 import dr.inference.model.Model;
39 import dr.inference.model.Parameter;
40 import dr.math.*;
41 import dr.xml.*;
42
43 import java.io.IOException;
44 import java.io.PrintStream;
45 import java.math.BigDecimal;
46 import java.util.*;
47
48 /**
49 * Intended to replace the tree prior; each subtree in the partition is considered a tree in its own right generated by
50 * a coalescent process
51 *
52 * @author Matthew Hall
53 */
54
55 public class WithinCaseCoalescent extends CaseToCaseTreeLikelihood {
56
57 public static final String WITHIN_CASE_COALESCENT = "withinCaseCoalescent";
58
59 private enum Mode {TRUNCATE, NORMAL}
60
61 private double[] partitionTreeLogLikelihoods;
62 private double[] storedPartitionTreeLogLikelihoods;
63 private boolean[] recalculateCoalescentFlags;
64 private DemographicModel demoModel;
65 private Mode mode;
66
67 private double coalescencesLogLikelihood;
68 private double storedCoalescencesLogLikelihood;
69
70 private boolean pleaseReExplode = true;
71
72
73 public WithinCaseCoalescent(PartitionedTreeModel virusTree, AbstractOutbreak caseData, Parameter maxFirstInfToRoot,
74 DemographicModel demoModel, Mode mode)
75 throws TaxonList.MissingTaxonException {
76
77 super(WITHIN_CASE_COALESCENT, virusTree, caseData, maxFirstInfToRoot);
78 this.mode = mode;
79 this.demoModel = demoModel;
80 addModel(demoModel);
81 addModel(outbreak);
82 partitionTreeLogLikelihoods = new double[outbreak.getCases().size()];
83 storedPartitionTreeLogLikelihoods = new double[outbreak.getCases().size()];
84 recalculateCoalescentFlags = new boolean[outbreak.getCases().size()];
85 Arrays.fill(recalculateCoalescentFlags, true);
86
87 elementsAsTrees = new HashMap<AbstractCase, Treelet>();
88 for(AbstractCase aCase: outbreak.getCases()){
89 if(aCase.wasEverInfected()){
90 elementsAsTrees.put(aCase, null);
91 }
92 }
93
94
95 storedElementsAsTrees = new HashMap<AbstractCase, Treelet>();
96
97 }
98
99 protected double calculateLogLikelihood(){
100
101 //checkPartitions();
102
103 if(pleaseReExplode){
104 explodeTree();
105 }
106
107 double logL = 0;
108
109 coalescencesLogLikelihood = 0;
110
111 for(AbstractCase aCase : outbreak.getCases()){
112
113 int number = outbreak.getCaseIndex(aCase);
114
115 if(aCase.wasEverInfected()) {
116
117 // and then the little tree calculations
118
119 if (recalculateCoalescentFlags[number]) {
120
121 Treelet treelet = elementsAsTrees.get(aCase);
122
123 if (treelet.getExternalNodeCount() > 1) {
124 SpecifiedZeroCoalescent coalescent = new SpecifiedZeroCoalescent(treelet, demoModel,
125 treelet.getZeroHeight(), mode == Mode.TRUNCATE);
126 partitionTreeLogLikelihoods[number] = coalescent.calculateLogLikelihood();
127 coalescencesLogLikelihood += partitionTreeLogLikelihoods[number];
128
129 } else {
130 partitionTreeLogLikelihoods[number] = 0.0;
131 }
132 recalculateCoalescentFlags[number] = false;
133 } else {
134 coalescencesLogLikelihood += partitionTreeLogLikelihoods[number];
135 }
136 } else {
137 recalculateCoalescentFlags[number] = false;
138 }
139 }
140
141 logL += coalescencesLogLikelihood;
142
143 likelihoodKnown = true;
144
145 return logL;
146 }
147
148 public void storeState(){
149 super.storeState();
150 storedElementsAsTrees = new HashMap<AbstractCase, Treelet>(elementsAsTrees);
151 storedPartitionTreeLogLikelihoods = Arrays.copyOf(partitionTreeLogLikelihoods,
152 partitionTreeLogLikelihoods.length);
153
154
155 storedCoalescencesLogLikelihood = coalescencesLogLikelihood;
156
157 }
158
159 public void restoreState(){
160 super.restoreState();
161 elementsAsTrees = storedElementsAsTrees;
162 partitionTreeLogLikelihoods = storedPartitionTreeLogLikelihoods;
163
164
165 coalescencesLogLikelihood = storedCoalescencesLogLikelihood;
166
167 }
168
169 protected void handleModelChangedEvent(Model model, Object object, int index) {
170
171 super.handleModelChangedEvent(model, object, index);
172
173 if(model == treeModel){
174
175 if(object instanceof PartitionedTreeModel.PartitionsChangedEvent){
176 HashSet<AbstractCase> changedPartitions =
177 ((PartitionedTreeModel.PartitionsChangedEvent)object).getCasesToRecalculate();
178 for(AbstractCase aCase : changedPartitions){
179 recalculateCaseWCC(aCase);
180 }
181 }
182 } else if(model == getBranchMap()){
183 if(object instanceof ArrayList){
184
185 for(int i=0; i<((ArrayList) object).size(); i++){
186 BranchMapModel.BranchMapChangedEvent event
187 = (BranchMapModel.BranchMapChangedEvent)((ArrayList) object).get(i);
188
189 recalculateCaseWCC(event.getOldCase());
190 recalculateCaseWCC(event.getNewCase());
191
192 NodeRef node = treeModel.getNode(event.getNodeToRecalculate());
193 NodeRef parent = treeModel.getParent(node);
194
195 if(parent!=null){
196 recalculateCaseWCC(getBranchMap().get(parent.getNumber()));
197 }
198 }
199 } else {
200 throw new RuntimeException("Unanticipated model changed event from BranchMapModel");
201 }
202 } else if(model == demoModel){
203 Arrays.fill(recalculateCoalescentFlags, true);
204 } else if(model == outbreak){
205 if(object instanceof AbstractCase){
206 AbstractCase thisCase = (AbstractCase)object;
207
208 recalculateCaseWCC(thisCase);
209
210 AbstractCase parent = ((PartitionedTreeModel)treeModel).getInfector(thisCase);
211
212 if(parent!=null){
213 recalculateCaseWCC(parent);
214 }
215 }
216 }
217 }
218
219 protected void recalculateCaseWCC(int index){
220 elementsAsTrees.put(outbreak.getCase(index), null);
221 pleaseReExplode = true;
222 recalculateCoalescentFlags[index] = true;
223 }
224
225 protected void recalculateCaseWCC(AbstractCase aCase){
226 if(aCase.wasEverInfected()) {
227 recalculateCaseWCC(outbreak.getCaseIndex(aCase));
228 }
229 }
230
231
232 public void makeDirty(){
233 super.makeDirty();
234 Arrays.fill(recalculateCoalescentFlags, true);
235 for(AbstractCase aCase : outbreak.getCases()){
236 if(aCase.wasEverInfected()) {
237 elementsAsTrees.put(aCase, null);
238 }
239 }
240 pleaseReExplode = true;
241 }
242
243 // Tears the tree into small pieces. Indexes correspond to indexes in the outbreak.
244
245 public ArrayList<AbstractCase> postOrderTransmissionTreeTraversal(){
246 return traverseTransmissionTree(getBranchMap().get(treeModel.getRoot().getNumber()));
247 }
248
249 private ArrayList<AbstractCase> traverseTransmissionTree(AbstractCase aCase){
250 ArrayList<AbstractCase> out = new ArrayList<AbstractCase>();
251 HashSet<AbstractCase> children = ((PartitionedTreeModel)treeModel).getInfectees(aCase);
252 for(int i=0; i<getOutbreak().size(); i++){
253 AbstractCase possibleChild = getOutbreak().getCase(i);
254 // easiest way to maintain the set ordering of the outbreak?
255 if(children.contains(possibleChild)){
256 out.addAll(traverseTransmissionTree(possibleChild));
257 }
258 }
259 out.add(aCase);
260 return out;
261 }
262
263
264
265 private Treelet transformTreelet(Treelet treelet){
266
267 double[] transformedNodeTimes = new double[treelet.getNodeCount()];
268
269 double totalHeight = treelet.getZeroHeight();
270
271 double willMapToZero = totalHeight - 1;
272
273 for(int i=0; i<treelet.getNodeCount(); i++){
274 NodeRef node = treelet.getNode(i);
275
276 double time = treelet.getNodeHeight(node) - totalHeight;
277
278 transformedNodeTimes[i] = -Math.log(-(time));
279 }
280
281 double first = Double.POSITIVE_INFINITY;
282 for (double transformedNodeTime : transformedNodeTimes) {
283 if (transformedNodeTime < first) {
284 first = transformedNodeTime;
285 }
286 }
287
288 double zeroHeight = -first;
289
290 Treelet copy = new Treelet(treelet, zeroHeight);
291
292 for(int i=0; i<copy.getNodeCount(); i++){
293 NodeRef node = copy.getNode(i);
294
295 copy.setNodeHeight(node, transformedNodeTimes[i] - first);
296 }
297
298 copy.resolveTree();
299
300 return copy;
301
302 }
303
304
305 private class SpecifiedZeroCoalescent extends Coalescent {
306
307 private double zeroHeight;
308 boolean truncate;
309
310 private SpecifiedZeroCoalescent(Tree tree, DemographicModel demographicModel, double zeroHeight,
311 boolean truncate){
312 super(tree, demographicModel.getDemographicFunction());
313
314 this.zeroHeight = zeroHeight;
315 this.truncate = truncate;
316
317 }
318
319 public double calculateLogLikelihood() {
320
321 return calculatePartitionTreeLogLikelihood(getIntervals(), getDemographicFunction(), 0, zeroHeight,
322 truncate);
323 }
324
325 }
326
327 public static double calculatePartitionTreeLogLikelihood(IntervalList intervals,
328 DemographicFunction demographicFunction, double threshold,
329 double zeroHeight, boolean truncate) {
330
331 double logL = 0.0;
332
333 double startTime = -zeroHeight;
334 final int n = intervals.getIntervalCount();
335
336 //TreeIntervals sets up a first zero-length interval with a lineage count of zero - skip this one
337
338 for (int i = 0; i < n; i++) {
339
340 if(truncate) {
341
342 // time zero corresponds to the date of first infection
343
344 final double duration = intervals.getInterval(i);
345 final double finishTime = startTime + duration;
346
347 // if this has happened the run is probably pretty unhappy
348
349 if (finishTime == 0) {
350 return Double.NEGATIVE_INFINITY;
351 }
352
353 final double intervalArea = demographicFunction.getIntegral(startTime, finishTime);
354 final double normalisationArea = demographicFunction.getIntegral(startTime, 0);
355
356 if (intervalArea == 0 && duration > tolerance) {
357 return Double.NEGATIVE_INFINITY;
358 }
359
360 final int lineageCount = intervals.getLineageCount(i);
361
362 if (lineageCount >= 2) {
363
364 final double kChoose2 = Binomial.choose2(lineageCount);
365
366 if (intervals.getIntervalType(i) == IntervalType.COALESCENT) {
367
368 logL += -kChoose2 * intervalArea;
369
370 final double demographicAtCoalPoint = demographicFunction.getDemographic(finishTime);
371
372 if (duration == 0.0 || demographicAtCoalPoint * (intervalArea / duration) >= threshold) {
373 logL -= Math.log(demographicAtCoalPoint);
374 } else {
375 return Double.NEGATIVE_INFINITY;
376 }
377
378 } else {
379 double numerator = Math.exp(-kChoose2 * intervalArea) - Math.exp(-kChoose2 * normalisationArea);
380 logL += Math.log(numerator);
381
382 }
383
384 // normalisation
385
386 double normExp = Math.exp(-kChoose2 * normalisationArea);
387
388 double logDenominator;
389
390 // the denominator has an irritating tendency to round to zero
391
392 if (normExp != 1) {
393 logDenominator = Math.log1p(-normExp);
394 } else {
395 logDenominator = handleDenominatorUnderflow(-kChoose2 * normalisationArea);
396 }
397
398
399 logL -= logDenominator;
400
401 }
402
403 startTime = finishTime;
404 } else {
405 if(!(demographicFunction instanceof LinearGrowth)){
406
407 throw new RuntimeException("Function must have zero population at t=0 if truncate=false");
408 }
409
410 final double duration = intervals.getInterval(i);
411 final double finishTime = startTime + duration;
412
413 final double intervalArea = demographicFunction.getIntegral(startTime, finishTime);
414 if( intervalArea == 0 && duration != 0 ) {
415 return Double.NEGATIVE_INFINITY;
416 }
417 final int lineageCount = intervals.getLineageCount(i);
418 final double kChoose2 = Binomial.choose2(lineageCount);
419 // common part
420 logL += -kChoose2 * intervalArea;
421
422 if (intervals.getIntervalType(i) == IntervalType.COALESCENT) {
423
424 final double demographicAtCoalPoint = demographicFunction.getDemographic(finishTime);
425
426 // if value at end is many orders of magnitude different than mean over interval reject the interval
427 // This is protection against cases where ridiculous infinitesimal population size at the end of a
428 // linear interval drive coalescent values to infinity.
429
430 if( duration == 0.0 || demographicAtCoalPoint * (intervalArea/duration) >= threshold ) {
431 // if( duration == 0.0 || demographicAtCoalPoint >= threshold * (duration/intervalArea) ) {
432 logL -= Math.log(demographicAtCoalPoint);
433 } else {
434 // remove this at some stage
435 // System.err.println("Warning: " + i + " " + demographicAtCoalPoint + " " + (intervalArea/duration) );
436 return Double.NEGATIVE_INFINITY;
437 }
438
439 }
440
441 startTime = finishTime;
442 }
443 }
444
445
446
447 return logL;
448 }
449
450
451 private static double handleDenominatorUnderflow(double input){
452 BigDecimal bigDec = new BigDecimal(input);
453 BigDecimal expBigDec = BigDecimalUtils.exp(bigDec, bigDec.scale());
454 BigDecimal one = new BigDecimal(1.0);
455 BigDecimal oneMinusExpBigDec = one.subtract(expBigDec);
456 BigDecimal logOneMinusExpBigDec = BigDecimalUtils.ln(oneMinusExpBigDec, oneMinusExpBigDec.scale());
457 return logOneMinusExpBigDec.doubleValue();
458 }
459
460 public void debugTreelet(Tree treelet, String fileName){
461 try{
462 FlexibleTree treeCopy = new FlexibleTree(treelet);
463 for(int j=0; j<treeCopy.getNodeCount(); j++){
464 FlexibleNode node = (FlexibleNode)treeCopy.getNode(j);
465 node.setAttribute("Number", node.getNumber());
466 }
467 NexusExporter testTreesOut = new NexusExporter(new PrintStream(fileName));
468 testTreesOut.exportTree(treeCopy);
469 } catch (IOException ignored) {System.out.println("IOException");}
470 }
471
472 public LogColumn[] passColumns(){
473 ArrayList<LogColumn> columns = new ArrayList<LogColumn>(Arrays.asList(super.passColumns()));
474
475 if(outbreak instanceof CategoryOutbreak) {
476
477 for (int i = 0; i < outbreak.size(); i++) {
478 if(outbreak.getCase(i).wasEverInfected()) {
479 final int finalI = i;
480 columns.add(new LogColumn.Abstract("coal_LL_" + i) {
481 protected String getFormattedValue() {
482 return String.valueOf(partitionTreeLogLikelihoods[finalI]);
483 }
484 });
485 }
486 }
487 columns.add(new LogColumn.Abstract("total_coal_LL") {
488 protected String getFormattedValue() {
489 return String.valueOf(coalescencesLogLikelihood);
490 }
491 });
492
493 return columns.toArray(new LogColumn[columns.size()]);
494 }
495 return null;
496
497 }
498
499
500 //************************************************************************
501 // AbstractXMLObjectParser implementation
502 //************************************************************************
503
504 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
505 public static final String STARTING_NETWORK = "startingNetwork";
506 public static final String MAX_FIRST_INF_TO_ROOT = "maxFirstInfToRoot";
507 public static final String DEMOGRAPHIC_MODEL = "demographicModel";
508 public static final String TRUNCATE = "truncate";
509
510 public String getParserName() {
511 return WITHIN_CASE_COALESCENT;
512 }
513
514 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
515
516 PartitionedTreeModel virusTree = (PartitionedTreeModel) xo.getChild(TreeModel.class);
517
518 AbstractOutbreak caseSet = (AbstractOutbreak) xo.getChild(AbstractOutbreak.class);
519
520 CaseToCaseTreeLikelihood likelihood;
521
522 Parameter earliestFirstInfection = (Parameter) xo.getElementFirstChild(MAX_FIRST_INF_TO_ROOT);
523
524 DemographicModel demoModel = (DemographicModel) xo.getElementFirstChild(DEMOGRAPHIC_MODEL);
525
526 Mode mode = xo.hasAttribute(TRUNCATE) & xo.getBooleanAttribute(TRUNCATE) ? Mode.TRUNCATE : Mode.NORMAL;
527
528 try {
529 likelihood = new WithinCaseCoalescent(virusTree, caseSet, earliestFirstInfection, demoModel, mode);
530 } catch (TaxonList.MissingTaxonException e) {
531 throw new XMLParseException(e.toString());
532 }
533
534 return likelihood;
535 }
536
537 public String getParserDescription() {
538 return "This element provides a tree prior for a partitioned tree, with each partitioned tree generated" +
539 "by a coalescent process";
540 }
541
542 public Class getReturnType() {
543 return WithinCaseCoalescent.class;
544 }
545
546 public XMLSyntaxRule[] getSyntaxRules() {
547 return rules;
548 }
549
550 private final XMLSyntaxRule[] rules = {
551 new ElementRule(PartitionedTreeModel.class, "The tree"),
552 new ElementRule(CategoryOutbreak.class, "The set of cases", 0,1),
553 new ElementRule(CategoryOutbreak.class, "The set of cases", 0,1),
554 new ElementRule("startingNetwork", String.class, "A CSV file containing a specified starting network",
555 true),
556 new ElementRule(MAX_FIRST_INF_TO_ROOT, Parameter.class, "The maximum time from the first infection to" +
557 "the root node"),
558 new ElementRule(DEMOGRAPHIC_MODEL, DemographicModel.class, "The demographic model for within-case" +
559 "evolution"),
560 AttributeRule.newBooleanRule(TRUNCATE)
561 };
562 };
563
564
565
566 }