/* * CaseToCaseTreeLikelihood.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.evomodel.epidemiology.casetocase; import java.io.IOException; import java.io.PrintStream; import java.util.*; import dr.app.tools.NexusExporter; import dr.evolution.tree.FlexibleNode; import dr.evolution.tree.FlexibleTree; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.tree.TreeTrait; import dr.evolution.tree.TreeTraitProvider; import dr.evolution.util.Taxon; import dr.evolution.util.TaxonList; import dr.evomodel.epidemiology.casetocase.periodpriors.AbstractPeriodPriorDistribution; import dr.evomodel.tree.TreeModel; import dr.oldevomodel.treelikelihood.AbstractTreeLikelihood; import dr.inference.loggers.LogColumn; import dr.inference.loggers.Loggable; import dr.inference.model.Model; import dr.inference.model.Parameter; import dr.inference.model.Variable; import dr.util.Author; import dr.util.Citable; import dr.util.Citation; import org.apache.commons.math.stat.descriptive.moment.Mean; import org.apache.commons.math.stat.descriptive.moment.Variance; import org.apache.commons.math.stat.descriptive.rank.Median; /** * Handles manipulation of the tree partition, and likelihood of the infection times. * * @author Matthew Hall * @author Andrew Rambaut * @version $Id: $ */ public abstract class CaseToCaseTreeLikelihood extends AbstractTreeLikelihood implements Loggable, Citable, TreeTraitProvider { protected static final boolean DEBUG = false; protected static double tolerance = 1E-10; /* The phylogenetic tree. */ protected int noTips; protected int noCases; /* Mapping of outbreak to branches on the tree; old version is stored before operators are applied */ /* Matches outbreak to external nodes */ private double estimatedLastSampleTime; protected TreeTraitProvider.Helper treeTraits = new Helper(); /** * The set of cases */ protected AbstractOutbreak outbreak; protected double[] infectionTimes; private double[] storedInfectionTimes; protected double[] infectiousPeriods; private double[] storedInfectiousPeriods; protected double[] infectiousTimes; private double[] storedInfectiousTimes; protected double[] latentPeriods; private double[] storedLatentPeriods; protected boolean[] recalculateCaseFlags; protected HashMap elementsAsTrees; protected HashMap storedElementsAsTrees; //because of the way the former works, we need a maximum value of the time from first infection to root node. protected Parameter maxFirstInfToRoot; // latent periods protected boolean hasLatentPeriods; // PUBLIC STUFF // Name public static final String CASE_TO_CASE_TREE_LIKELIHOOD = "caseToCaseTreeLikelihood"; public static final String PARTITIONS_KEY = "partition"; // Basic constructor. public CaseToCaseTreeLikelihood(PartitionedTreeModel tree, AbstractOutbreak caseData, Parameter maxFirstInfToRoot) throws TaxonList.MissingTaxonException { this(CASE_TO_CASE_TREE_LIKELIHOOD, tree, caseData, maxFirstInfToRoot); } // Constructor for an instance with a non-default name public CaseToCaseTreeLikelihood(String name, PartitionedTreeModel tree, AbstractOutbreak caseData, Parameter maxFirstInfToRoot) { super(name, caseData, tree); if(stateCount!=treeModel.getExternalNodeCount()){ throw new RuntimeException("There are duplicate tip outbreak."); } noTips = tree.getExternalNodeCount(); //subclasses should add outbreak as a model if it contains any information that ever changes outbreak = caseData; noCases = outbreak.getCases().size(); addModel(outbreak); estimatedLastSampleTime = getLatestTaxonTime(); //map outbreak to tips addModel(tree.getBranchMap()); hasLatentPeriods = outbreak.hasLatentPeriods(); infectionTimes = new double[outbreak.size()]; infectiousPeriods = new double[outbreak.size()]; if(hasLatentPeriods){ infectiousTimes = new double[outbreak.size()]; latentPeriods = new double[outbreak.size()]; } recalculateCaseFlags = new boolean[outbreak.size()]; Arrays.fill(recalculateCaseFlags, true); this.maxFirstInfToRoot = maxFirstInfToRoot; treeTraits.addTrait(PARTITIONS_KEY, new TreeTrait.S() { public String getTraitName() { return PARTITIONS_KEY; } public Intent getIntent() { return Intent.NODE; } public String getTrait(Tree tree, NodeRef node) { return getNodePartition(tree, node); } }); if(DEBUG){ treeTraits.addTrait("NodeNumber", new TreeTrait.S() { public String getTraitName() { return "NodeNumber"; } public Intent getIntent() { return Intent.NODE; } public String getTrait(Tree tree, NodeRef node) { return Integer.toString(node.getNumber()); } }); } likelihoodKnown = false; } public AbstractOutbreak getOutbreak(){ return outbreak; } public boolean hasLatentPeriods(){ return hasLatentPeriods; } /* Get the date of the last tip */ private double getLatestTaxonTime(){ double latestTime = Double.NEGATIVE_INFINITY; for(int i=0; i latestTime){ latestTime = taxon.getDate().getTimeValue(); } } return latestTime; } private NodeRef[] getChildren(NodeRef node){ NodeRef[] children = new NodeRef[treeModel.getChildCount(node)]; for(int i=0; i< treeModel.getChildCount(node); i++){ children[i] = treeModel.getChild(node,i); } return children; } protected void explodeTree(){ for(int i=0; i descendantTipPartitions(NodeRef node, HashMap> map){ HashSet out = new HashSet(); if(treeModel.isExternal(node)){ out.add(getBranchMap().get(node.getNumber())); if(map!=null){ map.put(node.getNumber(), out); } return out; } else { for(int i=0; i< treeModel.getChildCount(node); i++){ out.addAll(descendantTipPartitions(treeModel.getChild(node, i), map)); } if(map!=null){ map.put(node.getNumber(), out); } return out; } } // change flags to indicate that something needs recalculation further down the tree protected static void flagForDescendantRecalculation(TreeModel tree, NodeRef node, boolean[] flags){ flags[node.getNumber()]=true; for(int i=0; i changedPartitions = ((PartitionedTreeModel.PartitionsChangedEvent)object).getCasesToRecalculate(); for(AbstractCase aCase : changedPartitions){ recalculateCase(aCase); } } } else if (model == getBranchMap()){ if(object instanceof ArrayList){ for(int i=0; i<((ArrayList) object).size(); i++){ BranchMapModel.BranchMapChangedEvent event = (BranchMapModel.BranchMapChangedEvent)((ArrayList) object).get(i); recalculateCase(event.getOldCase()); recalculateCase(event.getNewCase()); NodeRef node = treeModel.getNode(event.getNodeToRecalculate()); NodeRef parent = treeModel.getParent(node); if(parent!=null){ recalculateCase(getBranchMap().get(parent.getNumber())); } } } else { throw new RuntimeException("Unanticipated model changed event from BranchMapModel"); } } else if (model == outbreak){ if(object instanceof AbstractCase){ recalculateCase((AbstractCase)object); } else { for (AbstractCase aCase : outbreak.getCases()) { recalculateCase(aCase); } } } fireModelChanged(model); likelihoodKnown = false; } } protected void recalculateCase(int index){ recalculateCaseFlags[index] = true; } protected void recalculateCase(AbstractCase aCase){ if(aCase.wasEverInfected()) { recalculateCase(outbreak.getCaseIndex(aCase)); } } // ************************************************************** // VariableListener IMPLEMENTATION // ************************************************************** protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { fireModelChanged(); likelihoodKnown = false; } // ************************************************************** // Model IMPLEMENTATION // ************************************************************** /** * Stores the precalculated state (in this case the node labels and subtree likelihoods) */ protected void storeState() { super.storeState(); storedInfectionTimes = Arrays.copyOf(infectionTimes, infectionTimes.length); storedInfectiousPeriods = Arrays.copyOf(infectiousPeriods, infectiousPeriods.length); if(hasLatentPeriods){ storedInfectiousTimes = Arrays.copyOf(infectiousTimes, infectionTimes.length); storedLatentPeriods = Arrays.copyOf(latentPeriods, latentPeriods.length); } } /** * Restores the precalculated state. */ protected void restoreState() { super.restoreState(); infectionTimes = storedInfectionTimes; infectiousPeriods = storedInfectiousPeriods; if(hasLatentPeriods){ infectiousTimes = storedInfectiousTimes; latentPeriods = storedLatentPeriods; } } protected final void acceptState() { } // nothing to do // ************************************************************** // Likelihood IMPLEMENTATION // ************************************************************** public final BranchMapModel getBranchMap(){ return ((PartitionedTreeModel)treeModel).getBranchMap(); } public final PartitionedTreeModel getTreeModel(){ return (PartitionedTreeModel)treeModel; } public void makeDirty() { likelihoodKnown = false; Arrays.fill(recalculateCaseFlags, true); } protected void prepareTimings(){ infectionTimes = getInfectionTimes(true); if(hasLatentPeriods){ infectiousTimes = getInfectiousTimes(true); } infectiousPeriods = getInfectiousPeriods(true); if(hasLatentPeriods){ latentPeriods = getLatentPeriods(true); } Arrays.fill(recalculateCaseFlags, false); } /** * Calculates the log likelihood of this set of node labels given the tree. */ protected abstract double calculateLogLikelihood(); // if no infectious models, just need to check whether any infections occur after the infector was no // longer infectious protected boolean isAllowed(){ return isAllowed(treeModel.getRoot()); } private boolean isAllowed(NodeRef node){ if(!treeModel.isRoot(node)){ AbstractCase childCase = getBranchMap().get(node.getNumber()); AbstractCase parentCase = getBranchMap().get(treeModel.getParent(node).getNumber()); if(childCase!=parentCase){ double infectionTime = infectionTimes[outbreak.getCaseIndex(childCase)]; if(infectionTime>parentCase.getEndTime() || (hasLatentPeriods && infectionTime maxHeight) { throw new RuntimeException("Trying to set an infection time outside the branch on which it must occur"); } double branchPosition = (height - minHeight) / (maxHeight - minHeight); thisCase.setInfectionBranchPosition(branchPosition); } } public double getInfectiousTime(AbstractCase thisCase){ if(!hasLatentPeriods){ return getInfectionTime(thisCase); } else { if (recalculateCaseFlags[outbreak.getCaseIndex(thisCase)]) { if(thisCase.wasEverInfected()) { String latentCategory = ((CategoryOutbreak) outbreak).getLatentCategory(thisCase); Parameter latentPeriod = ((CategoryOutbreak) outbreak).getLatentPeriod(latentCategory); infectiousTimes[outbreak.getCaseIndex(thisCase)] = getInfectionTime(thisCase) + latentPeriod.getParameterValue(0); } else { infectiousTimes[outbreak.getCaseIndex(thisCase)] = Double.POSITIVE_INFINITY; } } return infectiousTimes[outbreak.getCaseIndex(thisCase)]; } } public double[] getInfectiousTimes(boolean recalculate){ if(recalculate){ for(int i=0; i out = new ArrayList(); for(int i=0; i out = new ArrayList(); for(int i=0; i out = new ArrayList(); for(int i=0; ioutTree.getNodeHeight(parent)){ try{ NexusExporter exporter = new NexusExporter(new PrintStream("fancyProblem.nex")); exporter.exportTree(outTree); } catch(IOException e){ e.printStackTrace(); } try{ ((PartitionedTreeModel)treeModel).checkPartitions(); } catch(BadPartitionException e){ System.out.print("Rewiring messed up because of partition problem."); } throw new RuntimeException("Rewiring messed up; investigate"); } } return outTree; } //************************************************************************ // Loggable implementation //************************************************************************ public LogColumn[] getColumns(){ LogColumn[] columns = new LogColumn[outbreak.infectedSize()]; int count = 0; for(int i=0; i columns = new ArrayList(); for(int i=0; i< outbreak.size(); i++){ final AbstractCase infected = outbreak.getCase(i); if(infected.wasEverInfected()) { columns.add(new LogColumn.Abstract(infected.toString() + "_infection_date") { protected String getFormattedValue() { return String.valueOf(getInfectionTime(infected)); } }); } } if(hasLatentPeriods){ for(int i=0; i< outbreak.size(); i++){ final AbstractCase infected = outbreak.getCase(i); if(infected.wasEverInfected()) { columns.add(new LogColumn.Abstract(infected.toString() + "_infectious_date") { protected String getFormattedValue() { return String.valueOf(getInfectiousTime(infected)); } }); } } for(int i=0; i< outbreak.size(); i++){ final AbstractCase infected = outbreak.getCase(i); if(infected.wasEverInfected()) { columns.add(new LogColumn.Abstract(infected.toString() + "_latent_period") { protected String getFormattedValue() { return String.valueOf(getLatentPeriod(infected)); } }); } } } for(int i=0; i< outbreak.size(); i++){ final AbstractCase infected = outbreak.getCase(i); if(infected.wasEverInfected()) { columns.add(new LogColumn.Abstract(infected.toString() + "_infectious_period") { protected String getFormattedValue() { return String.valueOf(getInfectiousPeriod(infected)); } }); } } if(hasLatentPeriods){ for(int i=0; i< outbreak.size(); i++){ final AbstractCase infected = outbreak.getCase(i); if(infected.wasEverInfected()) { columns.add(new LogColumn.Abstract(infected.toString() + "_infected_period") { protected String getFormattedValue() { return String.valueOf( getInfectiousPeriod(infected) + getLatentPeriod(infected)); } }); } } } columns.add(new LogColumn.Abstract("infectious_period.mean"){ protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroInfectiousPeriods())[0]); } }); columns.add(new LogColumn.Abstract("infectious_period.median"){ protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroInfectiousPeriods())[1]); } }); columns.add(new LogColumn.Abstract("infectious_period.var") { protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroInfectiousPeriods())[2]); } }); columns.add(new LogColumn.Abstract("infectious_period.stdev"){ protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroInfectiousPeriods())[3]); } }); if(hasLatentPeriods){ columns.add(new LogColumn.Abstract("latent_period.mean"){ protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroLatentPeriods())[0]); } }); columns.add(new LogColumn.Abstract("latent_period.median"){ protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroLatentPeriods())[1]); } }); columns.add(new LogColumn.Abstract("latent_period.var") { protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroLatentPeriods())[2]); } }); columns.add(new LogColumn.Abstract("latent_period.stdev"){ protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroLatentPeriods())[3]); } }); columns.add(new LogColumn.Abstract("infected_period.mean"){ protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroInfectedPeriods())[0]); } }); columns.add(new LogColumn.Abstract("infected_period.median"){ protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroInfectedPeriods())[1]); } }); columns.add(new LogColumn.Abstract("infected_period.var") { protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroInfectedPeriods())[2]); } }); columns.add(new LogColumn.Abstract("infected_period.stdev"){ protected String getFormattedValue() { return String.valueOf(CaseToCaseTreeLikelihood .getSummaryStatistics(getNonzeroInfectedPeriods())[3]); } }); for(int i=0; i< outbreak.size(); i++){ final AbstractCase infected = outbreak.getCase(i); if(infected.wasEverInfected()) { columns.add(new LogColumn.Abstract(infected.toString() + "_ibp") { protected String getFormattedValue() { return String.valueOf(infected.getInfectionBranchPosition().getParameterValue(0)); } }); } } } return columns.toArray(new LogColumn[columns.size()]); } @Override public Citation.Category getCategory() { return Citation.Category.TREE_PRIORS; } @Override public String getDescription() { return "Case to Case Transmission Tree model"; } public List getCitations() { return Arrays.asList(new Citation( new Author[]{new Author("M", "Hall"), new Author("M", "Woolhouse"), new Author("A", "Rambaut")}, "Epidemic Reconstruction in a Phylogenetics Framework: Transmission Trees as Partitions of the Node Set", 2016, "PLOS Comput Biol", 11, 0, 0, "10.1371/journal.pcbi.1004613", Citation.Status.PUBLISHED)); } // ************************************************************** // TreeTraitProvider IMPLEMENTATION // ************************************************************** public TreeTrait[] getTreeTraits() { return treeTraits.getTreeTraits(); } public TreeTrait getTreeTrait(String key) { return treeTraits.getTreeTrait(key); } public String getNodePartition(Tree tree, NodeRef node) { if (tree != treeModel) { // we're trying to annotate a partitioned tree, we hope try{ NodeRef oldNode = treeModel.getNode((Integer)tree.getNodeAttribute(node,"Number")); if(treeModel.getNodeHeight(oldNode)!=tree.getNodeHeight(node)){ throw new RuntimeException("Can only reconstruct states on treeModel given to constructor or a " + "partitioned tree derived from it"); } else { return getBranchMap().get(oldNode.getNumber()).toString(); } } catch(NullPointerException e){ if(tree.isRoot(node)){ return "Start"; } else { NodeRef parent = tree.getParent(node); int originalParentNumber = (Integer)tree.getNodeAttribute(parent,"Number"); return getBranchMap().get(originalParentNumber).toString(); } } } else { return getBranchMap().get(node.getNumber()).toString(); } } public Integer[] getParentsArray(){ Integer[] out = new Integer[outbreak.size()]; for(AbstractCase thisCase : outbreak.getCases()){ if(thisCase.wasEverInfected()) { out[outbreak.getCaseIndex(thisCase)] = outbreak.getCaseIndex(((PartitionedTreeModel)treeModel).getInfector(thisCase)); } else { out[outbreak.getCaseIndex(thisCase)] = null; } } return out; } public AbstractCase getInfector(int i){ return ((PartitionedTreeModel)treeModel).getInfector(getOutbreak().getCase(i)); } }