Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * CaseToCaseTreeLikelihood.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 import java.io.IOException;
28 import java.io.PrintStream;
29 import java.util.*;
30
31 import dr.app.tools.NexusExporter;
32 import dr.evolution.tree.FlexibleNode;
33 import dr.evolution.tree.FlexibleTree;
34 import dr.evolution.tree.NodeRef;
35 import dr.evolution.tree.Tree;
36 import dr.evolution.tree.TreeTrait;
37 import dr.evolution.tree.TreeTraitProvider;
38 import dr.evolution.util.Taxon;
39 import dr.evolution.util.TaxonList;
40 import dr.evomodel.epidemiology.casetocase.periodpriors.AbstractPeriodPriorDistribution;
41 import dr.evomodel.tree.TreeModel;
42 import dr.oldevomodel.treelikelihood.AbstractTreeLikelihood;
43 import dr.inference.loggers.LogColumn;
44 import dr.inference.loggers.Loggable;
45 import dr.inference.model.Model;
46 import dr.inference.model.Parameter;
47 import dr.inference.model.Variable;
48 import dr.util.Author;
49 import dr.util.Citable;
50 import dr.util.Citation;
51 import org.apache.commons.math.stat.descriptive.moment.Mean;
52 import org.apache.commons.math.stat.descriptive.moment.Variance;
53 import org.apache.commons.math.stat.descriptive.rank.Median;
54
55 /**
56 * Handles manipulation of the tree partition, and likelihood of the infection times.
57 *
58 * @author Matthew Hall
59 * @author Andrew Rambaut
60 * @version $Id: $
61 */
62
63 public abstract class CaseToCaseTreeLikelihood extends AbstractTreeLikelihood implements Loggable, Citable,
64 TreeTraitProvider {
65
66 protected static final boolean DEBUG = false;
67
68 protected static double tolerance = 1E-10;
69
70 /* The phylogenetic tree. */
71
72 protected int noTips;
73 protected int noCases;
74
75 /* Mapping of outbreak to branches on the tree; old version is stored before operators are applied */
76
77
78 /* Matches outbreak to external nodes */
79
80 private double estimatedLastSampleTime;
81 protected TreeTraitProvider.Helper treeTraits = new Helper();
82
83 /**
84 * The set of cases
85 */
86 protected AbstractOutbreak outbreak;
87
88 protected double[] infectionTimes;
89 private double[] storedInfectionTimes;
90 protected double[] infectiousPeriods;
91 private double[] storedInfectiousPeriods;
92 protected double[] infectiousTimes;
93 private double[] storedInfectiousTimes;
94 protected double[] latentPeriods;
95 private double[] storedLatentPeriods;
96 protected boolean[] recalculateCaseFlags;
97
98 protected HashMap<AbstractCase,Treelet> elementsAsTrees;
99 protected HashMap<AbstractCase,Treelet> storedElementsAsTrees;
100
101 //because of the way the former works, we need a maximum value of the time from first infection to root node.
102
103 protected Parameter maxFirstInfToRoot;
104
105 // latent periods
106
107 protected boolean hasLatentPeriods;
108
109
110 // PUBLIC STUFF
111
112 // Name
113
114 public static final String CASE_TO_CASE_TREE_LIKELIHOOD = "caseToCaseTreeLikelihood";
115 public static final String PARTITIONS_KEY = "partition";
116
117
118 // Basic constructor.
119
120 public CaseToCaseTreeLikelihood(PartitionedTreeModel tree, AbstractOutbreak caseData,
121 Parameter maxFirstInfToRoot)
122 throws TaxonList.MissingTaxonException {
123 this(CASE_TO_CASE_TREE_LIKELIHOOD, tree, caseData, maxFirstInfToRoot);
124 }
125
126 // Constructor for an instance with a non-default name
127
128 public CaseToCaseTreeLikelihood(String name, PartitionedTreeModel tree, AbstractOutbreak caseData,
129 Parameter maxFirstInfToRoot) {
130
131
132 super(name, caseData, tree);
133
134
135 if(stateCount!=treeModel.getExternalNodeCount()){
136 throw new RuntimeException("There are duplicate tip outbreak.");
137 }
138
139 noTips = tree.getExternalNodeCount();
140
141
142 //subclasses should add outbreak as a model if it contains any information that ever changes
143
144 outbreak = caseData;
145
146 noCases = outbreak.getCases().size();
147
148 addModel(outbreak);
149
150 estimatedLastSampleTime = getLatestTaxonTime();
151
152 //map outbreak to tips
153
154 addModel(tree.getBranchMap());
155
156 hasLatentPeriods = outbreak.hasLatentPeriods();
157
158 infectionTimes = new double[outbreak.size()];
159 infectiousPeriods = new double[outbreak.size()];
160
161 if(hasLatentPeriods){
162 infectiousTimes = new double[outbreak.size()];
163 latentPeriods = new double[outbreak.size()];
164 }
165
166
167 recalculateCaseFlags = new boolean[outbreak.size()];
168 Arrays.fill(recalculateCaseFlags, true);
169
170
171
172 this.maxFirstInfToRoot = maxFirstInfToRoot;
173
174
175 treeTraits.addTrait(PARTITIONS_KEY, new TreeTrait.S() {
176 public String getTraitName() {
177 return PARTITIONS_KEY;
178 }
179
180 public Intent getIntent() {
181 return Intent.NODE;
182 }
183
184 public String getTrait(Tree tree, NodeRef node) {
185 return getNodePartition(tree, node);
186 }
187 });
188
189 if(DEBUG){
190 treeTraits.addTrait("NodeNumber", new TreeTrait.S() {
191 public String getTraitName() {
192 return "NodeNumber";
193 }
194
195 public Intent getIntent() {
196 return Intent.NODE;
197 }
198
199 public String getTrait(Tree tree, NodeRef node) {
200 return Integer.toString(node.getNumber());
201 }
202 });
203 }
204
205 likelihoodKnown = false;
206 }
207
208
209
210 public AbstractOutbreak getOutbreak(){
211 return outbreak;
212 }
213
214 public boolean hasLatentPeriods(){
215 return hasLatentPeriods;
216 }
217
218 /* Get the date of the last tip */
219
220 private double getLatestTaxonTime(){
221 double latestTime = Double.NEGATIVE_INFINITY;
222 for(int i=0; i<treeModel.getExternalNodeCount(); i++){
223 Taxon taxon = treeModel.getNodeTaxon(treeModel.getExternalNode(i));
224 if(taxon.getDate().getTimeValue() > latestTime){
225 latestTime = taxon.getDate().getTimeValue();
226 }
227
228 }
229 return latestTime;
230 }
231
232 private NodeRef[] getChildren(NodeRef node){
233 NodeRef[] children = new NodeRef[treeModel.getChildCount(node)];
234 for(int i=0; i< treeModel.getChildCount(node); i++){
235 children[i] = treeModel.getChild(node,i);
236 }
237 return children;
238 }
239
240
241
242 protected void explodeTree(){
243
244 for(int i=0; i<outbreak.size(); i++){
245 AbstractCase aCase = outbreak.getCase(i);
246 if(aCase.wasEverInfected() && elementsAsTrees.get(aCase)==null){
247
248 NodeRef partitionRoot = ((PartitionedTreeModel)treeModel).getEarliestNodeInElement(aCase);
249
250 double extraHeight;
251
252 if(treeModel.isRoot(partitionRoot)){
253 extraHeight = maxFirstInfToRoot.getParameterValue(0)
254 * aCase.getInfectionBranchPosition().getParameterValue(0);
255 } else {
256 extraHeight = treeModel.getBranchLength(partitionRoot)
257 * aCase.getInfectionBranchPosition().getParameterValue(0);
258 }
259
260 FlexibleNode newRoot = new FlexibleNode();
261
262 FlexibleTree littleTree = new FlexibleTree(newRoot);
263 littleTree.beginTreeEdit();
264
265 if (!treeModel.isExternal(partitionRoot)) {
266 for (int j = 0; j < treeModel.getChildCount(partitionRoot); j++) {
267 copyElementToTreelet(littleTree, treeModel.getChild(partitionRoot, j), newRoot, aCase);
268 }
269 }
270
271 littleTree.endTreeEdit();
272
273 littleTree.resolveTree();
274
275 Treelet treelet = new Treelet(littleTree,
276 littleTree.getRootHeight() + extraHeight);
277
278 elementsAsTrees.put(aCase, treelet);
279 }
280 }
281 }
282
283 private void copyElementToTreelet(FlexibleTree littleTree, NodeRef oldNode, NodeRef newParent,
284 AbstractCase element){
285 if(element.wasEverInfected()) {
286 if (getBranchMap().get(oldNode.getNumber()) == element) {
287 if (treeModel.isExternal(oldNode)) {
288 NodeRef newTip = new FlexibleNode(new Taxon(treeModel.getNodeTaxon(oldNode).getId()));
289 littleTree.addChild(newParent, newTip);
290 littleTree.setBranchLength(newTip, treeModel.getBranchLength(oldNode));
291 } else {
292 NodeRef newChild = new FlexibleNode();
293 littleTree.addChild(newParent, newChild);
294 littleTree.setBranchLength(newChild, treeModel.getBranchLength(oldNode));
295 for (int i = 0; i < treeModel.getChildCount(oldNode); i++) {
296 copyElementToTreelet(littleTree, treeModel.getChild(oldNode, i), newChild, element);
297 }
298 }
299 } else {
300 // we need a new tip
301 NodeRef transmissionTip = new FlexibleNode(
302 new Taxon("Transmission_" + getBranchMap().get(oldNode.getNumber()).getName()));
303 double parentTime = getNodeTime(treeModel.getParent(oldNode));
304 double childTime = getInfectionTime(getBranchMap().get(oldNode.getNumber()));
305 littleTree.addChild(newParent, transmissionTip);
306 littleTree.setBranchLength(transmissionTip, childTime - parentTime);
307 }
308 }
309 }
310
311 protected class Treelet extends FlexibleTree {
312
313 private double zeroHeight;
314
315 protected Treelet(FlexibleTree tree, double zeroHeight){
316 super(tree);
317 this.zeroHeight = zeroHeight;
318
319 }
320
321 protected double getZeroHeight(){
322 return zeroHeight;
323 }
324
325 protected void setZeroHeight(double rootBranchLength){
326 this.zeroHeight = zeroHeight;
327 }
328 }
329
330
331
332 // find all partitions of the descendant tips of the current node. If map is specified then it makes a map of node
333 // number to possible partitions; map can be null.
334
335 public HashSet<AbstractCase> descendantTipPartitions(NodeRef node, HashMap<Integer, HashSet<AbstractCase>> map){
336 HashSet<AbstractCase> out = new HashSet<AbstractCase>();
337 if(treeModel.isExternal(node)){
338 out.add(getBranchMap().get(node.getNumber()));
339 if(map!=null){
340 map.put(node.getNumber(), out);
341 }
342 return out;
343 } else {
344 for(int i=0; i< treeModel.getChildCount(node); i++){
345 out.addAll(descendantTipPartitions(treeModel.getChild(node, i), map));
346 }
347 if(map!=null){
348 map.put(node.getNumber(), out);
349 }
350 return out;
351 }
352 }
353
354 // change flags to indicate that something needs recalculation further down the tree
355
356 protected static void flagForDescendantRecalculation(TreeModel tree, NodeRef node, boolean[] flags){
357 flags[node.getNumber()]=true;
358 for(int i=0; i<tree.getChildCount(node); i++){
359 flags[tree.getChild(node,i).getNumber()]=true;
360 }
361 NodeRef currentNode=node;
362 while(!tree.isRoot(currentNode) && !flags[currentNode.getNumber()]){
363 currentNode = tree.getParent(currentNode);
364 flags[currentNode.getNumber()]=true;
365 }
366 }
367
368 public void flagForDescendantRecalculation(TreeModel tree, NodeRef node){
369 flagForDescendantRecalculation(tree, node, updateNode);
370 }
371
372
373 // **************************************************************
374 // ModelListener IMPLEMENTATION
375 // **************************************************************
376
377
378 protected void handleModelChangedEvent(Model model, Object object, int index) {
379
380 if(!(model instanceof AbstractPeriodPriorDistribution)){
381
382 if (model == treeModel) {
383
384 if(object instanceof PartitionedTreeModel.PartitionsChangedEvent){
385 HashSet<AbstractCase> changedPartitions =
386 ((PartitionedTreeModel.PartitionsChangedEvent)object).getCasesToRecalculate();
387 for(AbstractCase aCase : changedPartitions){
388 recalculateCase(aCase);
389
390 }
391 }
392 } else if (model == getBranchMap()){
393 if(object instanceof ArrayList){
394
395 for(int i=0; i<((ArrayList) object).size(); i++){
396 BranchMapModel.BranchMapChangedEvent event
397 = (BranchMapModel.BranchMapChangedEvent)((ArrayList) object).get(i);
398
399 recalculateCase(event.getOldCase());
400 recalculateCase(event.getNewCase());
401
402 NodeRef node = treeModel.getNode(event.getNodeToRecalculate());
403 NodeRef parent = treeModel.getParent(node);
404
405 if(parent!=null){
406 recalculateCase(getBranchMap().get(parent.getNumber()));
407 }
408 }
409 } else {
410 throw new RuntimeException("Unanticipated model changed event from BranchMapModel");
411 }
412 } else if (model == outbreak){
413
414 if(object instanceof AbstractCase){
415 recalculateCase((AbstractCase)object);
416 } else {
417 for (AbstractCase aCase : outbreak.getCases()) {
418 recalculateCase(aCase);
419 }
420 }
421 }
422
423 fireModelChanged(model);
424
425 likelihoodKnown = false;
426 }
427 }
428
429 protected void recalculateCase(int index){
430 recalculateCaseFlags[index] = true;
431 }
432
433 protected void recalculateCase(AbstractCase aCase){
434 if(aCase.wasEverInfected()) {
435 recalculateCase(outbreak.getCaseIndex(aCase));
436 }
437 }
438
439
440 // **************************************************************
441 // VariableListener IMPLEMENTATION
442 // **************************************************************
443
444
445 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
446
447 fireModelChanged();
448
449 likelihoodKnown = false;
450 }
451
452 // **************************************************************
453 // Model IMPLEMENTATION
454 // **************************************************************
455
456 /**
457 * Stores the precalculated state (in this case the node labels and subtree likelihoods)
458 */
459
460 protected void storeState() {
461 super.storeState();
462 storedInfectionTimes = Arrays.copyOf(infectionTimes, infectionTimes.length);
463 storedInfectiousPeriods = Arrays.copyOf(infectiousPeriods, infectiousPeriods.length);
464 if(hasLatentPeriods){
465 storedInfectiousTimes = Arrays.copyOf(infectiousTimes, infectionTimes.length);
466 storedLatentPeriods = Arrays.copyOf(latentPeriods, latentPeriods.length);
467 }
468 }
469
470 /**
471 * Restores the precalculated state.
472 */
473
474 protected void restoreState() {
475 super.restoreState();
476 infectionTimes = storedInfectionTimes;
477 infectiousPeriods = storedInfectiousPeriods;
478 if(hasLatentPeriods){
479 infectiousTimes = storedInfectiousTimes;
480 latentPeriods = storedLatentPeriods;
481 }
482 }
483
484 protected final void acceptState() {
485 } // nothing to do
486
487 // **************************************************************
488 // Likelihood IMPLEMENTATION
489 // **************************************************************
490
491 public final BranchMapModel getBranchMap(){
492 return ((PartitionedTreeModel)treeModel).getBranchMap();
493 }
494
495 public final PartitionedTreeModel getTreeModel(){
496 return (PartitionedTreeModel)treeModel;
497 }
498
499
500 public void makeDirty() {
501 likelihoodKnown = false;
502 Arrays.fill(recalculateCaseFlags, true);
503 }
504
505
506 protected void prepareTimings(){
507
508 infectionTimes = getInfectionTimes(true);
509
510 if(hasLatentPeriods){
511 infectiousTimes = getInfectiousTimes(true);
512 }
513
514 infectiousPeriods = getInfectiousPeriods(true);
515
516 if(hasLatentPeriods){
517 latentPeriods = getLatentPeriods(true);
518 }
519
520 Arrays.fill(recalculateCaseFlags, false);
521 }
522
523 /**
524 * Calculates the log likelihood of this set of node labels given the tree.
525 */
526
527 protected abstract double calculateLogLikelihood();
528
529
530
531 // if no infectious models, just need to check whether any infections occur after the infector was no
532 // longer infectious
533
534 protected boolean isAllowed(){
535 return isAllowed(treeModel.getRoot());
536 }
537
538 private boolean isAllowed(NodeRef node){
539 if(!treeModel.isRoot(node)){
540 AbstractCase childCase = getBranchMap().get(node.getNumber());
541 AbstractCase parentCase = getBranchMap().get(treeModel.getParent(node).getNumber());
542 if(childCase!=parentCase){
543 double infectionTime = infectionTimes[outbreak.getCaseIndex(childCase)];
544 if(infectionTime>parentCase.getEndTime()
545 || (hasLatentPeriods && infectionTime<infectiousTimes[outbreak.getCaseIndex(parentCase)])){
546 return false;
547 }
548 }
549 }
550 return treeModel.isExternal(node) ||
551 (isAllowed(treeModel.getChild(node, 0)) && isAllowed(treeModel.getChild(node, 1)));
552 }
553
554 /* Return the double time at which the given node occurred */
555
556 public double getNodeTime(NodeRef node){
557 double nodeHeight = getHeight(node);
558 return estimatedLastSampleTime-nodeHeight;
559 }
560
561 public double heightToTime(double height){
562 return estimatedLastSampleTime-height;
563 }
564
565 public double timeToHeight(double time){
566 return estimatedLastSampleTime-time;
567 }
568
569 private double getHeight(NodeRef node){
570 return treeModel.getNodeHeight(node);
571 }
572
573
574
575 public double getInfectionTime(AbstractCase thisCase){
576
577 if(!recalculateCaseFlags[outbreak.getCaseIndex(thisCase)]){
578 return infectionTimes[outbreak.getCaseIndex(thisCase)];
579 } else {
580 if(thisCase.wasEverInfected()) {
581 NodeRef child = ((PartitionedTreeModel)treeModel).getEarliestNodeInElement(thisCase);
582 NodeRef parent = treeModel.getParent(child);
583
584 if (parent != null) {
585
586 double min = heightToTime(treeModel.getNodeHeight(parent));
587
588 // Let the likelihood evaluate to zero due to culling dates if it must...
589
590 double max = heightToTime(treeModel.getNodeHeight(child));
591
592
593 return getInfectionTime(min, max, thisCase);
594 } else {
595 return getRootInfectionTime(getBranchMap());
596 }
597 } else {
598 return Double.POSITIVE_INFINITY;
599 }
600 }
601 }
602
603 private double getInfectionTime(double min, double max, AbstractCase infected){
604 final double branchLength = max-min;
605 return min + branchLength*(1-infected.getInfectionBranchPosition().getParameterValue(0));
606 }
607
608
609 public double[] getInfectionTimes(boolean recalculate){
610 if(recalculate) {
611 for(int i=0; i<noCases; i++){
612 if(recalculateCaseFlags[i]){
613 infectionTimes[i] = getInfectionTime(outbreak.getCase(i));
614 }
615 }
616 }
617 return infectionTimes;
618 }
619
620 public void setInfectionTime(AbstractCase thisCase, double time){
621
622 setInfectionHeight(thisCase, timeToHeight(time));
623
624 }
625
626 public void setInfectionHeight(AbstractCase thisCase, double height){
627 if(thisCase.wasEverInfected()) {
628 NodeRef child = ((PartitionedTreeModel)treeModel).getEarliestNodeInElement(thisCase);
629 NodeRef parent = treeModel.getParent(child);
630
631 double minHeight = treeModel.getNodeHeight(child);
632 double maxHeight = parent != null ? treeModel.getNodeHeight(parent)
633 : minHeight + maxFirstInfToRoot.getParameterValue(0);
634
635 if (height < minHeight || height > maxHeight) {
636 throw new RuntimeException("Trying to set an infection time outside the branch on which it must occur");
637 }
638
639 double branchPosition = (height - minHeight) / (maxHeight - minHeight);
640
641 thisCase.setInfectionBranchPosition(branchPosition);
642
643 }
644
645 }
646
647 public double getInfectiousTime(AbstractCase thisCase){
648 if(!hasLatentPeriods){
649 return getInfectionTime(thisCase);
650 } else {
651 if (recalculateCaseFlags[outbreak.getCaseIndex(thisCase)]) {
652 if(thisCase.wasEverInfected()) {
653
654 String latentCategory = ((CategoryOutbreak) outbreak).getLatentCategory(thisCase);
655 Parameter latentPeriod = ((CategoryOutbreak) outbreak).getLatentPeriod(latentCategory);
656 infectiousTimes[outbreak.getCaseIndex(thisCase)] = getInfectionTime(thisCase)
657 + latentPeriod.getParameterValue(0);
658 } else {
659 infectiousTimes[outbreak.getCaseIndex(thisCase)] = Double.POSITIVE_INFINITY;
660 }
661 }
662 return infectiousTimes[outbreak.getCaseIndex(thisCase)];
663 }
664
665 }
666
667 public double[] getInfectiousTimes(boolean recalculate){
668 if(recalculate){
669 for(int i=0; i<noCases; i++){
670 if(recalculateCaseFlags[i]){
671 infectiousTimes[i] = getInfectiousTime(outbreak.getCase(i));
672 }
673 }
674 }
675 return infectiousTimes;
676 }
677
678
679 public double getInfectiousPeriod(AbstractCase thisCase){
680 if(recalculateCaseFlags[outbreak.getCaseIndex(thisCase)]){
681 if(thisCase.wasEverInfected()) {
682
683 if (!hasLatentPeriods) {
684 double infectionTime = getInfectionTime(thisCase);
685 double cullTime = thisCase.getEndTime();
686 infectiousPeriods[outbreak.getCaseIndex(thisCase)] = cullTime - infectionTime;
687 } else {
688 double infectiousTime = getInfectiousTime(thisCase);
689 double cullTime = thisCase.getEndTime();
690 infectiousPeriods[outbreak.getCaseIndex(thisCase)] = cullTime - infectiousTime;
691 }
692 } else {
693 infectiousPeriods[outbreak.getCaseIndex(thisCase)] = 0;
694 }
695 }
696 return infectiousPeriods[outbreak.getCaseIndex(thisCase)];
697 }
698
699 public double[] getInfectiousPeriods(boolean recalculate){
700 if(recalculate){
701 for(int i=0; i<noCases; i++){
702 if(recalculateCaseFlags[i]){
703 infectiousPeriods[i] = getInfectiousPeriod(outbreak.getCase(i));
704 }
705 }
706 }
707 return infectiousPeriods;
708 }
709
710 public Double[] getNonzeroInfectiousPeriods(){
711 ArrayList<Double> out = new ArrayList<Double>();
712
713
714 for(int i=0; i<noCases; i++){
715 AbstractCase thisCase = outbreak.getCase(i);
716
717 if(thisCase.wasEverInfected()){
718 out.add(getInfectiousPeriod(thisCase));
719 }
720 }
721
722 return out.toArray(new Double[out.size()]);
723 }
724
725
726 public double getLatentPeriod(AbstractCase thisCase){
727 if(!hasLatentPeriods || !thisCase.wasEverInfected()){
728 return 0.0;
729 }
730 if(recalculateCaseFlags[outbreak.getCaseIndex(thisCase)]){
731 latentPeriods[outbreak.getCaseIndex(thisCase)] = getInfectiousTime(thisCase) - getInfectionTime(thisCase);
732 }
733 return latentPeriods[outbreak.getCaseIndex(thisCase)];
734 }
735
736 public double[] getLatentPeriods(boolean recalculate){
737 if(recalculate){
738 for(int i=0; i<noCases; i++){
739 if(recalculateCaseFlags[i]){
740 latentPeriods[i] = getLatentPeriod(outbreak.getCase(i));
741 }
742 }
743 }
744 return latentPeriods;
745 }
746
747 public Double[] getNonzeroLatentPeriods(){
748 ArrayList<Double> out = new ArrayList<Double>();
749
750
751 for(int i=0; i<noCases; i++){
752 AbstractCase thisCase = outbreak.getCase(i);
753
754 if(thisCase.wasEverInfected()){
755 out.add(getLatentPeriod(thisCase));
756 }
757 }
758
759 return out.toArray(new Double[out.size()]);
760 }
761
762
763
764 public double[] getInfectedPeriods(boolean recalculate){
765 if(!hasLatentPeriods){
766 return getInfectiousPeriods(recalculate);
767 } else {
768 double[] out = new double[noCases];
769 for(int i=0; i<noCases; i++){
770 out[i] = getInfectedPeriod(outbreak.getCase(i));
771 }
772 return out;
773 }
774 }
775
776
777 public Double[] getNonzeroInfectedPeriods(){
778 ArrayList<Double> out = new ArrayList<Double>();
779
780
781 for(int i=0; i<noCases; i++){
782 AbstractCase thisCase = outbreak.getCase(i);
783
784 if(thisCase.wasEverInfected()){
785 out.add(getInfectedPeriod(thisCase));
786 }
787 }
788
789 return out.toArray(new Double[out.size()]);
790 }
791
792
793
794
795 public double getInfectedPeriod(AbstractCase thisCase){
796 if(thisCase.wasEverInfected) {
797 return thisCase.getEndTime() - getInfectionTime(thisCase);
798 }
799 return 0;
800 }
801
802
803 // return an array of the mean, median, variance and standard deviation of the given array
804 // @todo this is pretty wasteful since it gets called so many times per log entry
805
806 public static Double[] getSummaryStatistics(Double[] variable){
807
808 double[] primitiveVariable = new double[variable.length];
809 for(int i=0; i<variable.length; i++){
810 primitiveVariable[i] = variable[i];
811 }
812
813 Double[] out = new Double[4];
814 out[0] = (new Mean()).evaluate(primitiveVariable);
815 out[1] = (new Median()).evaluate(primitiveVariable);
816 out[2] = (new Variance()).evaluate(primitiveVariable);
817 out[3] = Math.sqrt(out[2]);
818 return out;
819 }
820
821
822
823
824 private double getRootInfectionTime(BranchMapModel branchMap){
825 NodeRef root = treeModel.getRoot();
826 AbstractCase rootCase = branchMap.get(root.getNumber());
827 final double branchLength = maxFirstInfToRoot.getParameterValue(0);
828
829 return heightToTime(treeModel.getNodeHeight(root)
830 + branchLength * rootCase.getInfectionBranchPosition().getParameterValue(0));
831
832 }
833
834 protected double getRootInfectionTime(){
835 AbstractCase rootCase = getBranchMap().get(treeModel.getRoot().getNumber());
836 return getInfectionTime(rootCase);
837 }
838
839 public void outputTreeToFile(String fileName, boolean includeTransmissionNodes){
840 outputTreeToFile(getBranchMap(), fileName, includeTransmissionNodes);
841 }
842
843
844 public void outputTreeToFile(BranchMapModel map, String fileName, boolean includeTransmissionNodes){
845 try{
846 FlexibleTree treeCopy;
847 if(!includeTransmissionNodes){
848 treeCopy = new FlexibleTree(treeModel);
849 for(int j=0; j<treeCopy.getNodeCount(); j++){
850 FlexibleNode node = (FlexibleNode)treeCopy.getNode(j);
851 node.setAttribute("Number", node.getNumber());
852 node.setAttribute("Time", heightToTime(node.getHeight()));
853 node.setAttribute(PARTITIONS_KEY, map.get(node.getNumber()));
854 }
855 } else {
856 treeCopy = addTransmissionNodes(treeModel);
857 }
858 NexusExporter testTreesOut = new NexusExporter(new PrintStream(fileName));
859 testTreesOut.exportTree(treeCopy);
860 } catch (IOException ignored) {System.out.println("IOException");}
861 }
862
863 public FlexibleTree addTransmissionNodes(Tree tree){
864 prepareTimings();
865
866 FlexibleTree outTree = new FlexibleTree(tree, true);
867
868 for(int j=0; j<outTree.getNodeCount(); j++){
869 FlexibleNode node = (FlexibleNode)outTree.getNode(j);
870 node.setAttribute("Number", node.getNumber());
871 node.setAttribute("Time", heightToTime(node.getHeight()));
872 node.setAttribute(PARTITIONS_KEY, getBranchMap().get(node.getNumber()));
873 }
874
875 for(AbstractCase aCase : outbreak.getCases()){
876 if(aCase.wasEverInfected()) {
877 NodeRef originalNode = ((PartitionedTreeModel)treeModel).getEarliestNodeInElement(aCase);
878
879 int infectionNodeNo = originalNode.getNumber();
880 if (!treeModel.isRoot(originalNode)) {
881 NodeRef originalParent = treeModel.getParent(originalNode);
882 double nodeTime = getNodeTime(originalNode);
883 double infectionTime = getInfectionTime(aCase);
884 double heightToBreakBranch = getHeight(originalNode) + (nodeTime - infectionTime);
885 FlexibleNode newNode = (FlexibleNode) outTree.getNode(infectionNodeNo);
886 FlexibleNode oldParent = (FlexibleNode) outTree.getParent(newNode);
887
888 outTree.beginTreeEdit();
889 outTree.removeChild(oldParent, newNode);
890 FlexibleNode infectionNode = new FlexibleNode();
891 infectionNode.setHeight(heightToBreakBranch);
892 infectionNode.setLength(oldParent.getHeight() - heightToBreakBranch);
893 infectionNode.setAttribute(PARTITIONS_KEY, getNodePartition(treeModel, originalParent));
894 infectionNode.setAttribute("Time", heightToTime(heightToBreakBranch));
895 newNode.setLength(nodeTime - infectionTime);
896
897 outTree.addChild(oldParent, infectionNode);
898 outTree.addChild(infectionNode, newNode);
899 outTree.endTreeEdit();
900 } else {
901 double nodeTime = getNodeTime(originalNode);
902 double infectionTime = getInfectionTime(aCase);
903 double heightToInstallRoot = getHeight(originalNode) + (nodeTime - infectionTime);
904 FlexibleNode newNode = (FlexibleNode) outTree.getNode(infectionNodeNo);
905 outTree.beginTreeEdit();
906 FlexibleNode infectionNode = new FlexibleNode();
907 infectionNode.setHeight(heightToInstallRoot);
908 infectionNode.setAttribute("Time", heightToTime(heightToInstallRoot));
909 infectionNode.setAttribute(PARTITIONS_KEY, "Origin");
910 outTree.addChild(infectionNode, newNode);
911 newNode.setLength(heightToInstallRoot - getHeight(originalNode));
912 outTree.setRoot(infectionNode);
913 outTree.endTreeEdit();
914 }
915 }
916 }
917
918 outTree = new FlexibleTree((FlexibleNode)outTree.getRoot());
919
920
921 for(int i=0; i<outTree.getNodeCount(); i++){
922 NodeRef node = outTree.getNode(i);
923 NodeRef parent = outTree.getParent(node);
924 if(parent!=null && outTree.getNodeHeight(node)>outTree.getNodeHeight(parent)){
925 try{
926 NexusExporter exporter = new NexusExporter(new PrintStream("fancyProblem.nex"));
927 exporter.exportTree(outTree);
928 } catch(IOException e){
929 e.printStackTrace();
930 }
931 try{
932 ((PartitionedTreeModel)treeModel).checkPartitions();
933 } catch(BadPartitionException e){
934 System.out.print("Rewiring messed up because of partition problem.");
935 }
936
937
938 throw new RuntimeException("Rewiring messed up; investigate");
939 }
940
941 }
942
943
944 return outTree;
945 }
946
947 //************************************************************************
948 // Loggable implementation
949 //************************************************************************
950
951
952 public LogColumn[] getColumns(){
953 LogColumn[] columns = new LogColumn[outbreak.infectedSize()];
954 int count = 0;
955 for(int i=0; i<outbreak.size(); i++){
956 final AbstractCase infected = outbreak.getCase(i);
957 if(infected.wasEverInfected()) {
958 columns[count] = new LogColumn.Abstract(infected.toString() + "_infector") {
959 protected String getFormattedValue() {
960 if (((PartitionedTreeModel)treeModel).getInfector(infected) == null) {
961 return "Start";
962 } else {
963 return ((PartitionedTreeModel)treeModel).getInfector(infected).toString();
964 }
965 }
966 };
967 count++;
968 }
969 }
970 return columns;
971 }
972
973 public LogColumn[] passColumns(){
974 ArrayList<LogColumn> columns = new ArrayList<LogColumn>();
975 for(int i=0; i< outbreak.size(); i++){
976 final AbstractCase infected = outbreak.getCase(i);
977 if(infected.wasEverInfected()) {
978 columns.add(new LogColumn.Abstract(infected.toString() + "_infection_date") {
979 protected String getFormattedValue() {
980 return String.valueOf(getInfectionTime(infected));
981 }
982 });
983 }
984 }
985 if(hasLatentPeriods){
986 for(int i=0; i< outbreak.size(); i++){
987 final AbstractCase infected = outbreak.getCase(i);
988 if(infected.wasEverInfected()) {
989 columns.add(new LogColumn.Abstract(infected.toString() + "_infectious_date") {
990 protected String getFormattedValue() {
991 return String.valueOf(getInfectiousTime(infected));
992 }
993 });
994 }
995 }
996 for(int i=0; i< outbreak.size(); i++){
997 final AbstractCase infected = outbreak.getCase(i);
998 if(infected.wasEverInfected()) {
999 columns.add(new LogColumn.Abstract(infected.toString() + "_latent_period") {
1000 protected String getFormattedValue() {
1001 return String.valueOf(getLatentPeriod(infected));
1002 }
1003 });
1004 }
1005 }
1006 }
1007 for(int i=0; i< outbreak.size(); i++){
1008 final AbstractCase infected = outbreak.getCase(i);
1009 if(infected.wasEverInfected()) {
1010 columns.add(new LogColumn.Abstract(infected.toString() + "_infectious_period") {
1011 protected String getFormattedValue() {
1012 return String.valueOf(getInfectiousPeriod(infected));
1013 }
1014 });
1015 }
1016 }
1017 if(hasLatentPeriods){
1018 for(int i=0; i< outbreak.size(); i++){
1019 final AbstractCase infected = outbreak.getCase(i);
1020 if(infected.wasEverInfected()) {
1021 columns.add(new LogColumn.Abstract(infected.toString() + "_infected_period") {
1022 protected String getFormattedValue() {
1023 return String.valueOf(
1024 getInfectiousPeriod(infected) + getLatentPeriod(infected));
1025 }
1026 });
1027 }
1028 }
1029 }
1030
1031 columns.add(new LogColumn.Abstract("infectious_period.mean"){
1032 protected String getFormattedValue() {
1033 return String.valueOf(CaseToCaseTreeLikelihood
1034 .getSummaryStatistics(getNonzeroInfectiousPeriods())[0]);
1035 }
1036 });
1037 columns.add(new LogColumn.Abstract("infectious_period.median"){
1038 protected String getFormattedValue() {
1039 return String.valueOf(CaseToCaseTreeLikelihood
1040 .getSummaryStatistics(getNonzeroInfectiousPeriods())[1]);
1041 }
1042 });
1043 columns.add(new LogColumn.Abstract("infectious_period.var") {
1044 protected String getFormattedValue() {
1045 return String.valueOf(CaseToCaseTreeLikelihood
1046 .getSummaryStatistics(getNonzeroInfectiousPeriods())[2]);
1047 }
1048 });
1049 columns.add(new LogColumn.Abstract("infectious_period.stdev"){
1050 protected String getFormattedValue() {
1051 return String.valueOf(CaseToCaseTreeLikelihood
1052 .getSummaryStatistics(getNonzeroInfectiousPeriods())[3]);
1053 }
1054 });
1055 if(hasLatentPeriods){
1056 columns.add(new LogColumn.Abstract("latent_period.mean"){
1057 protected String getFormattedValue() {
1058 return String.valueOf(CaseToCaseTreeLikelihood
1059 .getSummaryStatistics(getNonzeroLatentPeriods())[0]);
1060 }
1061 });
1062 columns.add(new LogColumn.Abstract("latent_period.median"){
1063 protected String getFormattedValue() {
1064 return String.valueOf(CaseToCaseTreeLikelihood
1065 .getSummaryStatistics(getNonzeroLatentPeriods())[1]);
1066 }
1067 });
1068 columns.add(new LogColumn.Abstract("latent_period.var") {
1069 protected String getFormattedValue() {
1070 return String.valueOf(CaseToCaseTreeLikelihood
1071 .getSummaryStatistics(getNonzeroLatentPeriods())[2]);
1072 }
1073 });
1074 columns.add(new LogColumn.Abstract("latent_period.stdev"){
1075 protected String getFormattedValue() {
1076 return String.valueOf(CaseToCaseTreeLikelihood
1077 .getSummaryStatistics(getNonzeroLatentPeriods())[3]);
1078 }
1079 });
1080 columns.add(new LogColumn.Abstract("infected_period.mean"){
1081 protected String getFormattedValue() {
1082 return String.valueOf(CaseToCaseTreeLikelihood
1083 .getSummaryStatistics(getNonzeroInfectedPeriods())[0]);
1084 }
1085 });
1086 columns.add(new LogColumn.Abstract("infected_period.median"){
1087 protected String getFormattedValue() {
1088 return String.valueOf(CaseToCaseTreeLikelihood
1089 .getSummaryStatistics(getNonzeroInfectedPeriods())[1]);
1090 }
1091 });
1092 columns.add(new LogColumn.Abstract("infected_period.var") {
1093 protected String getFormattedValue() {
1094 return String.valueOf(CaseToCaseTreeLikelihood
1095 .getSummaryStatistics(getNonzeroInfectedPeriods())[2]);
1096 }
1097 });
1098 columns.add(new LogColumn.Abstract("infected_period.stdev"){
1099 protected String getFormattedValue() {
1100 return String.valueOf(CaseToCaseTreeLikelihood
1101 .getSummaryStatistics(getNonzeroInfectedPeriods())[3]);
1102 }
1103 });
1104 for(int i=0; i< outbreak.size(); i++){
1105 final AbstractCase infected = outbreak.getCase(i);
1106 if(infected.wasEverInfected()) {
1107 columns.add(new LogColumn.Abstract(infected.toString() + "_ibp") {
1108 protected String getFormattedValue() {
1109 return String.valueOf(infected.getInfectionBranchPosition().getParameterValue(0));
1110 }
1111 });
1112 }
1113 }
1114 }
1115
1116 return columns.toArray(new LogColumn[columns.size()]);
1117
1118
1119 }
1120
1121 @Override
1122 public Citation.Category getCategory() {
1123 return Citation.Category.TREE_PRIORS;
1124 }
1125
1126 @Override
1127 public String getDescription() {
1128 return "Case to Case Transmission Tree model";
1129 }
1130
1131 public List<Citation> getCitations() {
1132 return Arrays.asList(new Citation(
1133 new Author[]{new Author("M", "Hall"), new Author("M", "Woolhouse"), new Author("A", "Rambaut")},
1134 "Epidemic Reconstruction in a Phylogenetics Framework: Transmission Trees as Partitions of the Node Set",
1135 2016, "PLOS Comput Biol",
1136 11,
1137 0, 0, "10.1371/journal.pcbi.1004613",
1138 Citation.Status.PUBLISHED));
1139 }
1140
1141 // **************************************************************
1142 // TreeTraitProvider IMPLEMENTATION
1143 // **************************************************************
1144
1145 public TreeTrait[] getTreeTraits() {
1146 return treeTraits.getTreeTraits();
1147 }
1148
1149 public TreeTrait getTreeTrait(String key) {
1150 return treeTraits.getTreeTrait(key);
1151 }
1152
1153 public String getNodePartition(Tree tree, NodeRef node) {
1154 if (tree != treeModel) {
1155 // we're trying to annotate a partitioned tree, we hope
1156 try{
1157 NodeRef oldNode = treeModel.getNode((Integer)tree.getNodeAttribute(node,"Number"));
1158 if(treeModel.getNodeHeight(oldNode)!=tree.getNodeHeight(node)){
1159 throw new RuntimeException("Can only reconstruct states on treeModel given to constructor or a " +
1160 "partitioned tree derived from it");
1161 } else {
1162 return getBranchMap().get(oldNode.getNumber()).toString();
1163 }
1164 } catch(NullPointerException e){
1165 if(tree.isRoot(node)){
1166 return "Start";
1167 } else {
1168 NodeRef parent = tree.getParent(node);
1169 int originalParentNumber = (Integer)tree.getNodeAttribute(parent,"Number");
1170 return getBranchMap().get(originalParentNumber).toString();
1171 }
1172 }
1173 } else {
1174 return getBranchMap().get(node.getNumber()).toString();
1175 }
1176 }
1177
1178 public Integer[] getParentsArray(){
1179 Integer[] out = new Integer[outbreak.size()];
1180 for(AbstractCase thisCase : outbreak.getCases()){
1181 if(thisCase.wasEverInfected()) {
1182 out[outbreak.getCaseIndex(thisCase)] = outbreak.getCaseIndex(((PartitionedTreeModel)treeModel).getInfector(thisCase));
1183 } else {
1184 out[outbreak.getCaseIndex(thisCase)] = null;
1185 }
1186 }
1187 return out;
1188 }
1189
1190 public AbstractCase getInfector(int i){
1191 return ((PartitionedTreeModel)treeModel).getInfector(getOutbreak().getCase(i));
1192 }
1193
1194 }
1195
1196
1197
1198
1199
1200
1201
1202