Debian Codegraph @

src/dr/evomodel/transmission/TransmissionLikelihood.java

raw symbols SCIP
1 /*
2 * TransmissionLikelihood.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.transmission;
27
28 import dr.evolution.coalescent.Coalescent;
29 import dr.evolution.coalescent.DemographicFunction;
30 import dr.evolution.coalescent.Intervals;
31 import dr.evolution.tree.NodeRef;
32 import dr.evolution.tree.Tree;
33 import dr.evolution.util.Taxon;
34 import dr.evolution.util.TaxonList;
35 import dr.evolution.util.Units;
36 import dr.evomodel.coalescent.DemographicModel;
37 import dr.evomodel.tree.TreeModel;
38 import dr.inference.model.AbstractModelLikelihood;
39 import dr.inference.model.Model;
40 import dr.inference.model.Parameter;
41 import dr.inference.model.Variable;
42 import dr.xml.*;
43
44 /**
45 * A likelihood function for a complete transmission history. Takes a viruses tree
46 * and a demographic model. The transmission history consists of a number of
47 * hosts with known history of transmission. The viruses tree should have tip
48 * attributes specifying which host they are from (host="").
49 *
50 * @author Andrew Rambaut
51 * @author Alexei Drummond
52 * @version $Id: TransmissionLikelihood.java,v 1.13 2005/06/15 17:20:54 rambaut Exp $
53 */
54 public class TransmissionLikelihood extends AbstractModelLikelihood implements Units {
55
56 // PUBLIC STUFF
57
58 public static final String TRANSMISSION_LIKELIHOOD = "transmissionLikelihood";
59 public static final String SOURCE_PATIENT = "sourcePatient";
60
61 public TransmissionLikelihood(Tree hostTree, Tree virusTree,
62 DemographicModel sourceDemographic,
63 TransmissionDemographicModel transmissionModel)
64 throws TaxonList.MissingTaxonException {
65 this(TRANSMISSION_LIKELIHOOD, hostTree, virusTree, sourceDemographic, transmissionModel);
66 }
67
68 public TransmissionLikelihood(String name, Tree hostTree, Tree virusTree,
69 DemographicModel sourceDemographic,
70 TransmissionDemographicModel transmissionModel)
71 throws TaxonList.MissingTaxonException {
72
73 super(name);
74
75 this.hostTree = hostTree;
76 if (hostTree instanceof TreeModel) {
77 addModel((TreeModel) hostTree);
78 }
79
80 this.virusTree = virusTree;
81 if (virusTree instanceof TreeModel) {
82 addModel((TreeModel) virusTree);
83 }
84
85 this.sourceDemographic = sourceDemographic;
86 addModel(sourceDemographic);
87
88 this.transmissionModel = transmissionModel;
89 addModel(transmissionModel);
90
91 for (int i = 0; i < virusTree.getExternalNodeCount(); i++) {
92 Taxon hostTaxon = (Taxon) virusTree.getTaxonAttribute(i, "host");
93 if (hostTaxon == null)
94 throw new TaxonList.MissingTaxonException("One or more of the viruses tree's taxa are missing the 'host' attribute");
95
96 int host = hostTree.getTaxonIndex(hostTaxon);
97 if (host == -1) throw new TaxonList.MissingTaxonException("One of the viruses tree's host attribute, " +
98 hostTaxon.getId() + ", was not found as a taxon in the host tree");
99 }
100
101 setupHosts();
102 }
103
104 public TransmissionLikelihood(TransmissionHistoryModel transmissionHistoryModel, Tree virusTree,
105 DemographicModel sourceDemographic,
106 TransmissionDemographicModel transmissionModel)
107 throws TaxonList.MissingTaxonException {
108 this(TRANSMISSION_LIKELIHOOD, transmissionHistoryModel, virusTree, sourceDemographic, transmissionModel);
109 }
110
111 public TransmissionLikelihood(String name, TransmissionHistoryModel transmissionHistoryModel, Tree virusTree,
112 DemographicModel sourceDemographic,
113 TransmissionDemographicModel transmissionModel)
114 throws TaxonList.MissingTaxonException {
115
116 super(name);
117
118 this.transmissionHistoryModel = transmissionHistoryModel;
119 addModel((TransmissionHistoryModel) transmissionHistoryModel);
120
121 this.virusTree = virusTree;
122 if (virusTree instanceof TreeModel) {
123 addModel((TreeModel) virusTree);
124 }
125
126 this.sourceDemographic = sourceDemographic;
127 addModel(sourceDemographic);
128
129 this.transmissionModel = transmissionModel;
130 addModel(transmissionModel);
131
132 for (int i = 0; i < virusTree.getExternalNodeCount(); i++) {
133 Taxon hostTaxon = (Taxon) virusTree.getTaxonAttribute(i, "host");
134 if (hostTaxon == null)
135 throw new TaxonList.MissingTaxonException("One or more of the viruses tree's taxa are missing the 'host' attribute");
136
137 int host = transmissionHistoryModel.getHostIndex(hostTaxon);
138 if (host == -1) throw new TaxonList.MissingTaxonException("One of the viruses tree's host attribute, " +
139 hostTaxon.getId() + ", was not found as a taxon in the transmission history");
140 }
141
142 setupHosts();
143 }
144
145 private void setupHosts() {
146
147 if (transmissionHistoryModel != null) {
148 hostCount = transmissionHistoryModel.getHostCount();
149
150 } else {
151 hostCount = hostTree.getTaxonCount();
152 }
153
154 intervals = new Intervals[hostCount];
155 for (int i = 0; i < hostCount; i++) {
156 // 3 times virusTree tip count will be enough events...
157 intervals[i] = new Intervals(virusTree.getExternalNodeCount() * 3);
158 }
159 donorHost = new int[hostCount];
160 donorHost[0] = -1;
161 transmissionTime = new double[hostCount];
162 transmissionTime[0] = Double.POSITIVE_INFINITY;
163 donorSize = new double[hostCount];
164
165 if (transmissionHistoryModel != null) {
166 for (int i = 0; i < transmissionHistoryModel.getTransmissionEventCount(); i++) {
167 TransmissionHistoryModel.TransmissionEvent event = transmissionHistoryModel.getTransmissionEvent(i);
168
169 int host1 = transmissionHistoryModel.getHostIndex(event.getDonor());
170 int host2 = transmissionHistoryModel.getHostIndex(event.getRecipient());
171
172 donorHost[host2] = host1;
173 transmissionTime[host2] = event.getTransmissionTime();
174 }
175 } else {
176 setupHostsTree(hostTree.getRoot());
177 }
178 }
179
180 private int setupHostsTree(NodeRef node) {
181
182 int host;
183
184 if (hostTree.isExternal(node)) {
185 host = node.getNumber();
186 } else {
187
188 // This traversal assumes that the first child is the donor
189 // and the second is the recipient
190
191 int host1 = setupHostsTree(hostTree.getChild(node, 0));
192 int host2 = setupHostsTree(hostTree.getChild(node, 1));
193
194 donorHost[host2] = host1;
195 transmissionTime[host2] = hostTree.getNodeHeight(node);
196
197 host = host1;
198 }
199
200 return host;
201 }
202
203 // **************************************************************
204 // ModelListener IMPLEMENTATION
205 // **************************************************************
206
207 protected final void handleModelChangedEvent(Model model, Object object, int index) {
208 if (model == virusTree) {
209 // treeModel has changed so recalculate the intervals
210 } else if (model == hostTree) {
211 // hosts treeModel has changed so recalculate the hosts and intervals
212 } else if (model == transmissionHistoryModel) {
213 // transmissionHistoryModel has changed so recalculate the hosts and intervals
214 } else {
215 // demographicModel has changed so we don't need to recalculate the intervals
216 }
217
218 likelihoodKnown = false;
219 }
220
221 // **************************************************************
222 // VariableListener IMPLEMENTATION
223 // **************************************************************
224
225 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
226 }
227
228 // **************************************************************
229 // Model IMPLEMENTATION
230 // **************************************************************
231
232 /**
233 * Stores the precalculated state: in this case the intervals
234 */
235 protected final void storeState() {
236 }
237
238 /**
239 * Restores the precalculated state: that is the intervals of the tree.
240 */
241 protected final void restoreState() {
242 likelihoodKnown = false;
243 }
244
245 protected final void acceptState() {
246 } // nothing to do
247
248 // **************************************************************
249 // Likelihood IMPLEMENTATION
250 // **************************************************************
251
252 public final Model getModel() {
253 return this;
254 }
255
256 public final double getLogLikelihood() {
257 if (!likelihoodKnown) {
258 logLikelihood = calculateLogLikelihood();
259 likelihoodKnown = true;
260 }
261 return logLikelihood;
262 }
263
264 public final void makeDirty() {
265 likelihoodKnown = false;
266 }
267
268 /**
269 * Calculates the log likelihood of this set of coalescent intervals,
270 * given a demographic model.
271 */
272 public double calculateLogLikelihood() {
273
274 makeDirty();
275 setupHosts();
276 for (int i = 0; i < hostCount; i++) {
277 intervals[i].resetEvents();
278 donorSize[i] = -1;
279 }
280 try {
281 setupIntervals(virusTree.getRoot());
282 } catch (IncompatibleException re) {
283 // register the compatibility failure
284 return Double.NEGATIVE_INFINITY;
285 }
286
287 /*
288
289 if (intervalsKnown == false) {
290
291 if (!hostsKnown) {
292 setupHosts();
293 hostsKnown = true;
294 }
295
296 for (int i = 0; i < hostCount; i++) {
297 intervals[i].resetEvents();
298 donorSize[i] = -1;
299 }
300 try {
301 setupIntervals(virusTree.getRoot());
302
303 if (isCompatible(virusTree.getRoot()) == -1) {
304 System.out.println("compatibility failed!");
305 makeDirty();
306 // register the compatibility failure
307 return Double.NEGATIVE_INFINITY;
308 }
309
310 //System.out.println("intervals set up successfully!");
311 intervalsKnown = true;
312 savedHostTree = new FlexibleTree(hostTree);
313 } catch (IncompatibleException re) {
314 System.out.println("intervals setup failed!");
315 if (savedHostTree == null) {
316 throw new RuntimeException(re.getMessage());
317 } else {
318 makeDirty();
319 // register the compatibility failure
320 return Double.NEGATIVE_INFINITY;
321 }
322 }
323 }*/
324
325 for (int i = 0; i < hostCount; i++) {
326 donorSize[i] = -1;
327 }
328
329 DemographicFunction demoFunction = sourceDemographic.getDemographicFunction();
330 double logL = Coalescent.calculateLogLikelihood(intervals[0], demoFunction);
331
332 for (int i = 1; i < hostCount; i++) {
333 double ds = getDonorSize(i);
334 demoFunction = transmissionModel.getDemographicFunction(transmissionTime[i], ds, i);
335 logL += Coalescent.calculateLogLikelihood(intervals[i], demoFunction);
336
337 }
338
339 return logL;
340 }
341
342 private double getDonorSize(int host) {
343 if (donorSize[host] > 0.0) {
344 return donorSize[host];
345 }
346
347 DemographicFunction demoFunction;
348
349 if (donorHost[host] == 0) {
350 demoFunction = sourceDemographic.getDemographicFunction();
351 } else {
352 double ds = getDonorSize(donorHost[host]);
353 demoFunction = transmissionModel.getDemographicFunction(transmissionTime[host], ds, host);
354 }
355
356 donorSize[host] = demoFunction.getDemographic(transmissionTime[host]);
357 return donorSize[host];
358 }
359
360 private int setupIntervals(NodeRef node) throws IncompatibleException {
361
362 double height = virusTree.getNodeHeight(node);
363 int host;
364
365 if (virusTree.isExternal(node)) {
366 Taxon hostTaxon = (Taxon) virusTree.getTaxonAttribute(node.getNumber(), "host");
367
368 if (transmissionHistoryModel != null) {
369 host = transmissionHistoryModel.getHostIndex(hostTaxon);
370 } else {
371 host = hostTree.getTaxonIndex(hostTaxon);
372 }
373
374 intervals[host].addSampleEvent(height);
375 } else {
376
377 // Tree should be bifurcating...
378 int host1 = setupIntervals(virusTree.getChild(node, 0));
379 int host2 = setupIntervals(virusTree.getChild(node, 1));
380
381 while (height > transmissionTime[host1]) {
382
383 double time = transmissionTime[host1];
384
385 intervals[host1].addNothingEvent(time);
386
387 host1 = donorHost[host1];
388
389 intervals[host1].addSampleEvent(time);
390 }
391
392 while (height > transmissionTime[host2]) {
393
394 double time = transmissionTime[host2];
395
396 intervals[host2].addNothingEvent(time);
397
398 host2 = donorHost[host2];
399
400 intervals[host2].addSampleEvent(time);
401 }
402
403 if (host1 != host2) {
404 throw new IncompatibleException("Virus tree is not compatible with transmission history");
405 }
406
407 host = host1;
408 intervals[host].addCoalescentEvent(height);
409
410 }
411
412 return host;
413 }
414
415 // **************************************************************
416 // Units IMPLEMENTATION
417 // **************************************************************
418
419 /**
420 * Sets the units these coalescent intervals are
421 * measured in.
422 */
423 public final void setUnits(Type u) {
424 transmissionModel.setUnits(u);
425 }
426
427 /**
428 * Returns the units these coalescent intervals are
429 * measured in.
430 */
431 public final Type getUnits() {
432 return transmissionModel.getUnits();
433 }
434
435 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
436
437 public String getParserName() {
438 return TRANSMISSION_LIKELIHOOD;
439 }
440
441 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
442
443 DemographicModel demoModel0 = (DemographicModel) xo.getElementFirstChild(SOURCE_PATIENT);
444 TransmissionDemographicModel demoModel1 = (TransmissionDemographicModel) xo.getChild(TransmissionDemographicModel.class);
445
446 Tree virusTree = (Tree) xo.getElementFirstChild("parasiteTree");
447
448 TransmissionLikelihood likelihood = null;
449
450 if (xo.getChild(TransmissionHistoryModel.class) != null) {
451 TransmissionHistoryModel history = (TransmissionHistoryModel) xo.getChild(TransmissionHistoryModel.class);
452 try {
453 likelihood = new TransmissionLikelihood(history, virusTree, demoModel0, demoModel1);
454 } catch (TaxonList.MissingTaxonException e) {
455 throw new XMLParseException(e.toString());
456 }
457 } else {
458 Tree hostTree = (Tree) xo.getElementFirstChild("hostTree");
459 try {
460 likelihood = new TransmissionLikelihood(hostTree, virusTree, demoModel0, demoModel1);
461 } catch (TaxonList.MissingTaxonException e) {
462 throw new XMLParseException(e.toString());
463 }
464 }
465
466 return likelihood;
467 }
468
469 //************************************************************************
470 // AbstractXMLObjectParser implementation
471 //************************************************************************
472
473 public String getParserDescription() {
474 return "This element represents a likelihood function for transmission.";
475 }
476
477 public Class getReturnType() {
478 return TransmissionLikelihood.class;
479 }
480
481 public XMLSyntaxRule[] getSyntaxRules() {
482 return rules;
483 }
484
485 private final XMLSyntaxRule[] rules;{
486 rules = new XMLSyntaxRule[]{
487 new ElementRule(SOURCE_PATIENT, DemographicModel.class,
488 "This describes the demographic process for the source donor patient."),
489 new ElementRule(TransmissionDemographicModel.class,
490 "This describes the demographic process for the recipient patients."),
491 new XORRule(
492 new ElementRule("hostTree",
493 new XMLSyntaxRule[]{new ElementRule(Tree.class)}),
494 new ElementRule(TransmissionHistoryModel.class,
495 "This describes the transmission history of the patients.")
496 ),
497 new ElementRule("parasiteTree",
498 new XMLSyntaxRule[]{new ElementRule(Tree.class)})
499 };
500 }
501 };
502
503 class IncompatibleException extends Exception {
504
505 /**
506 *
507 */
508 private static final long serialVersionUID = 8439923064799668934L;
509
510 public IncompatibleException(String name) {
511 super(name);
512 }
513 }
514
515
516 /**
517 * The demographic models.
518 */
519 private DemographicModel sourceDemographic = null;
520 private TransmissionDemographicModel transmissionModel = null;
521
522 /**
523 * The host tree.
524 */
525 private Tree hostTree = null;
526
527 private TransmissionHistoryModel transmissionHistoryModel = null;
528
529 /**
530 * The viruses tree.
531 */
532 private Tree virusTree = null;
533
534 /**
535 * The number of hosts.
536 */
537 private int hostCount;
538
539 /**
540 * The intervals for each host.
541 */
542 private Intervals[] intervals;
543
544 /**
545 * The donor host for each recipient host (-1 for initial host).
546 */
547 private int[] donorHost;
548
549 /**
550 * The time of transmission into this host (POSITIVE_INFINITY for initial host).
551 */
552 private double[] transmissionTime;
553
554 /**
555 * The size of the donor population at time of transmission into recipient host.
556 */
557 private double[] donorSize;
558
559 private boolean likelihoodKnown = false;
560 private double logLikelihood;
561 }