Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * CategoryOutbreak.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.evolution.util.Date;
29 import dr.evolution.util.Taxa;
30 import dr.evolution.util.Taxon;
31 import dr.evomodel.epidemiology.casetocase.periodpriors.AbstractPeriodPriorDistribution;
32 import dr.inference.model.Model;
33 import dr.inference.model.Parameter;
34 import dr.inference.model.ProductStatistic;
35 import dr.inference.model.Variable;
36 import dr.xml.*;
37
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.HashSet;
41
42 /**
43 * Outbreak class for within-case coalescent.
44 *
45 * Each case belongs to an infectious (and latent) category which corresponds to one of a list of probability
46 * distributions (most likely gamma or exponential) for the length of the infectious (latent) period. The XML rules for
47 * the outbreak class ask for at least one ParametricDistributionModel.
48 * Assignment of outbreak to distributions should be handled in whatever script or GUI writes the XML.
49 *
50 * Intended for situations where no data on infection times exists.
51 *
52 * User: Matthew Hall
53 * Date: 17/12/2013
54 */
55
56 public class CategoryOutbreak extends AbstractOutbreak {
57
58 public static final String CATEGORY_OUTBREAK = "categoryOutbreak";
59 private final HashSet<String> latentCategories;
60 private final HashSet<String> infectiousCategories;
61 private final HashMap<String, Parameter> latentMap;
62 private final HashMap<String, AbstractPeriodPriorDistribution> infectiousMap;
63 private final HashMap<AbstractCase, Double> weightMap;
64 private double[][] distances;
65
66
67 public CategoryOutbreak(String name, Taxa taxa, boolean hasGeography, boolean hasLatentPeriods,
68 HashMap<String, AbstractPeriodPriorDistribution> infectiousMap,
69 HashMap<String, Parameter> latentMap){
70 super(name, taxa, hasLatentPeriods, hasGeography);
71 cases = new ArrayList<AbstractCase>();
72 latentCategories = new HashSet<String>();
73 infectiousCategories = new HashSet<String>();
74 this.latentMap = latentMap;
75 this.infectiousMap = infectiousMap;
76 for(AbstractPeriodPriorDistribution hyperprior : infectiousMap.values()){
77 addModel(hyperprior);
78 }
79 for(Parameter hyperprior : latentMap.values()){
80 addVariable(hyperprior);
81 }
82 weightMap = new HashMap<AbstractCase, Double>();
83 }
84
85
86 private void addCase(String caseID, double endTime, Parameter coords,
87 Parameter infectionPosition, Taxa associatedTaxa, double indexPriorWeight,
88 String infectiousCategory, String latentCategory){
89 CategoryCase thisCase;
90
91 if(latentCategory==null){
92 thisCase = new CategoryCase(caseID, endTime, coords, infectionPosition, associatedTaxa,
93 indexPriorWeight, infectiousCategory);
94 } else {
95 thisCase =
96 new CategoryCase(caseID, endTime, coords, infectionPosition, associatedTaxa,
97 indexPriorWeight, infectiousCategory, latentCategory);
98 latentCategories.add(latentCategory);
99 }
100 weightMap.put(thisCase, indexPriorWeight);
101
102 infectiousCategories.add(infectiousCategory);
103 cases.add(thisCase);
104 infectedSize++;
105 addModel(thisCase);
106 }
107
108 private void addNoninfectedCase(String caseID, Parameter coords){
109 CategoryCase thisCase = new CategoryCase(caseID, Double.POSITIVE_INFINITY, coords, null, null, 0.0, null);
110 thisCase.setEverInfected(false);
111
112 cases.add(thisCase);
113 addModel(thisCase);
114 }
115
116
117 public HashMap<AbstractCase, Double> getWeightMap(){
118 return weightMap;
119 }
120
121 public HashSet<String> getLatentCategories(){
122 return latentCategories;
123 }
124
125 public HashSet<String> getInfectiousCategories(){
126 return infectiousCategories;
127 }
128
129 public int getLatentCategoryCount(){
130 return latentCategories.size();
131 }
132
133 public int getInfectiousCategoryCount(){
134 return infectiousCategories.size();
135 }
136
137 public HashMap<String, Parameter> getLatentMap(){
138 return latentMap;
139 }
140
141 public HashMap<String, AbstractPeriodPriorDistribution> getInfectiousMap(){
142 return infectiousMap;
143 }
144
145 public Parameter getLatentPeriod(String category){
146 return latentMap.get(category);
147 }
148
149 public AbstractPeriodPriorDistribution getInfectiousCategoryPrior(String category){
150 return infectiousMap.get(category);
151 }
152
153 public String getInfectiousCategory(AbstractCase aCase){
154 return ((CategoryCase)aCase).getInfectiousCategory();
155 }
156
157 public String getLatentCategory(AbstractCase aCase){
158 return ((CategoryCase)aCase).getLatentCategory();
159 }
160
161 public double getLatentPeriod(AbstractCase aCase) {
162 return latentMap.get(((CategoryCase)aCase).getLatentCategory()).getParameterValue(0);
163 }
164
165 public double getDistance(AbstractCase a, AbstractCase b) {
166 if(distances==null){
167 throw new RuntimeException("Distance matrix has not been initialised");
168 }
169 return distances[getCaseIndex(a)][getCaseIndex(b)];
170 }
171
172 private void setDistanceMatrix(double[][] distances){
173 this.distances = distances;
174 }
175
176 private void buildDistanceMatrix(){
177 distances = new double[cases.size()][cases.size()];
178
179 if(hasGeography){
180
181 for(int i=0; i<cases.size(); i++){
182 for(int j=0; j<cases.size(); j++){
183 distances[i][j]= SpatialKernel.EuclideanDistance(getCase(i).getCoords(), getCase(j).getCoords());
184 }
185 }
186 }
187 }
188
189 protected void handleModelChangedEvent(Model model, Object object, int index) {
190 if(!(model instanceof AbstractPeriodPriorDistribution)) {
191 fireModelChanged(object);
192 }
193 }
194
195 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
196 fireModelChanged();
197 }
198
199 protected void storeState() {
200 //nothing to do
201 }
202
203 protected void restoreState() {
204 //nothing to do
205 }
206
207 protected void acceptState() {
208 //nothing to do
209 }
210
211 private class CategoryCase extends AbstractCase{
212
213 public static final String CATEGORY_CASE = "categoryCase";
214 private String infectiousCategory;
215 private String latentCategory;
216 private Parameter coords;
217 private double indexPriorWeight;
218 private final ArrayList<Date> examinationTimes;
219
220 private CategoryCase(String name, String caseID, double endTime, Parameter coords,
221 Parameter infectionBranchPosition, Taxa associatedTaxa, double indexPriorWeight,
222 String infectiousCategory, String latentCategory){
223 super(name);
224
225 wasEverInfected = associatedTaxa != null;
226
227 this.caseID = caseID;
228 this.infectiousCategory = infectiousCategory;
229 this.infectionBranchPosition = infectionBranchPosition;
230 if(infectionBranchPosition!=null) {
231 addVariable(infectionBranchPosition);
232 }
233 endOfInfectiousTime = endTime;
234 this.associatedTaxa = associatedTaxa;
235 this.coords = coords;
236 this.indexPriorWeight = indexPriorWeight;
237 this.latentCategory = latentCategory;
238
239 examinationTimes = new ArrayList<Date>();
240
241 if(wasEverInfected) {
242 for (Taxon taxon : associatedTaxa) {
243 examinationTimes.add(taxon.getDate());
244 }
245 }
246
247 }
248
249 private CategoryCase(String name, String caseID, double endTime, Parameter coords,
250 Parameter infectionBranchPosition, Taxa associatedTaxa,
251 String infectiousCategory){
252 this(name, caseID, endTime, coords, infectionBranchPosition, associatedTaxa, 1.0,
253 infectiousCategory, null);
254
255 }
256
257
258
259 private CategoryCase(String caseID, double endTime, Parameter coords,
260 Parameter infectionBranchPosition, Taxa associatedTaxa, double indexPriorWeight,
261 String infectiousCategory){
262 this(CATEGORY_CASE, caseID, endTime, coords, infectionBranchPosition, associatedTaxa,
263 indexPriorWeight, infectiousCategory, null);
264 }
265
266
267 private CategoryCase(String caseID, double endTime, Parameter coords,
268 Parameter infectionBranchPosition, Taxa associatedTaxa, double indexPriorWeight,
269 String infectiousCategory, String latentCategory){
270 this(CATEGORY_CASE, caseID, endTime, coords, infectionBranchPosition, associatedTaxa,
271 indexPriorWeight, infectiousCategory, latentCategory);
272 }
273
274 //noninfected susceptible constructor
275
276 public String getLatentCategory(){
277 return latentCategory;
278 }
279
280 public String getInfectiousCategory(){
281 return infectiousCategory;
282 }
283
284 public double getIndexPriorWeight() { return indexPriorWeight;}
285
286 public boolean noninfectiousYet(double time) {
287 return time>endOfInfectiousTime;
288 }
289
290 public ArrayList<Date> getExaminationTimes(){
291 return examinationTimes;
292 }
293
294 protected void handleModelChangedEvent(Model model, Object object, int index) {
295 fireModelChanged();
296 }
297
298 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
299 fireModelChanged(this);
300 }
301
302 protected void storeState() {
303 // nothing to do?
304 }
305
306 protected void restoreState() {
307 // nothing to do?
308 }
309
310 protected void acceptState() {
311 //nothing to do?
312 }
313
314 public double[] getCoords() {
315 return new double[]{coords.getParameterValue(0), coords.getParameterValue(1)};
316 }
317 }
318
319 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
320
321 //for the outbreak
322
323 public static final String HAS_GEOGRAPHY = "hasGeography";
324 public static final String HAS_LATENT_PERIODS = "hasLatentPeriods";
325 public static final String INFECTIOUS_PERIOD_PRIOR = "infectiousPeriodPrior";
326 public static final String LATENT_PERIODS = "latentPeriods";
327 public static final String DISTANCE_MATRIX = "distanceMatrix";
328
329 //for the cases
330
331 public static final String CASE_ID = "hostID";
332 public static final String END_TIME = "endTime";
333 public static final String COORDINATES = "spatialCoordinates";
334 public static final String INFECTION_TIME_BRANCH_POSITION = "infectionTimeBranchPosition";
335 public static final String LATENT_CATEGORY = "latentCategory";
336 public static final String INFECTIOUS_CATEGORY = "infectiousCategory";
337 public static final String WAS_EVER_INFECTED = "wasEverInfected";
338 public static final String INDEX_PRIOR_WEIGHT = "indexPriorWeight";
339
340 //for the normal-gamma priors
341
342 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
343 final boolean hasGeography = xo.hasAttribute(HAS_GEOGRAPHY) && xo.getBooleanAttribute(HAS_GEOGRAPHY);
344 final boolean hasLatentPeriods = Boolean.parseBoolean((String)xo.getAttribute(HAS_LATENT_PERIODS));
345
346 final Taxa taxa = (Taxa) xo.getChild(Taxa.class);
347
348 HashMap<String, AbstractPeriodPriorDistribution> infMap
349 = new HashMap<String, AbstractPeriodPriorDistribution>();
350
351 HashMap<String, Parameter> latMap
352 = new HashMap<String, Parameter>();
353
354 for(int i=0; i<xo.getChildCount(); i++){
355 Object cxo = xo.getChild(i);
356 if(cxo instanceof XMLObject){
357 if (((XMLObject)cxo).getName().equals(INFECTIOUS_PERIOD_PRIOR)){
358 AbstractPeriodPriorDistribution hyperprior
359 = (AbstractPeriodPriorDistribution)
360 ((XMLObject)cxo).getChild(AbstractPeriodPriorDistribution.class);
361 infMap.put(hyperprior.getModelName(), hyperprior);
362 } else if ((((XMLObject)cxo).getName().equals(LATENT_PERIODS))){
363 Parameter latentPeriod
364 = (Parameter)
365 ((XMLObject)cxo).getChild(Parameter.class);
366 latMap.put(latentPeriod.getParameterName(), latentPeriod);
367 }
368 }
369 }
370
371
372 CategoryOutbreak cases = new CategoryOutbreak(null, taxa,
373 hasGeography, hasLatentPeriods, infMap, latMap);
374 for(int i=0; i<xo.getChildCount(); i++){
375 Object cxo = xo.getChild(i);
376 if(cxo instanceof XMLObject && ((XMLObject)cxo).getName()
377 .equals(CategoryCase.CATEGORY_CASE)){
378 parseCase((XMLObject)cxo, cases, hasLatentPeriods);
379 }
380 }
381
382 if(xo.hasChildNamed(DISTANCE_MATRIX)){
383 if(!hasGeography){
384 throw new XMLParseException("Told there is no geography but given a distance matrix");
385 }
386
387 Parameter matrixParameter = (Parameter)xo.getElementFirstChild(DISTANCE_MATRIX);
388
389 int size = cases.size();
390
391 if(matrixParameter.getDimension()!=size*size){
392 throw new XMLParseException("Wrong number of distance matrix entries");
393 }
394
395 double[][] distances = new double[size][size];
396 int count=0;
397
398 for(int i=0; i<size; i++){
399 for(int j=0; j<size; j++){
400 if(i==j){
401 distances[i][j]=0;
402 } else {
403 distances[i][j]=matrixParameter.getParameterValue(count);
404 }
405 count++;
406 }
407 }
408
409 cases.setDistanceMatrix(distances);
410
411 } else if(hasGeography){
412
413 for(AbstractCase aCase : cases.getCases()){
414 if(aCase.getCoords()==null){
415 throw new XMLParseException("Some cases have no geographical information");
416 }
417 }
418
419 cases.buildDistanceMatrix();
420 }
421
422
423 return cases;
424 }
425
426 public void parseCase(XMLObject xo, CategoryOutbreak outbreak, boolean expectLatentPeriods)
427 throws XMLParseException {
428
429
430 String farmID = (String) xo.getAttribute(CASE_ID);
431
432 final Parameter coords = xo.hasChildNamed(COORDINATES) ?
433 (Parameter) xo.getElementFirstChild(COORDINATES) : null;
434 boolean wasEverInfected = xo.getBooleanAttribute(WAS_EVER_INFECTED);
435 if(wasEverInfected) {
436
437 if(!xo.hasAttribute(INFECTIOUS_CATEGORY)
438 || !xo.hasAttribute(END_TIME)
439 || !xo.hasChildNamed(INFECTION_TIME_BRANCH_POSITION)){
440 throw new XMLParseException("Case " + farmID + " wasEverInfected but lacks infection-related data");
441 }
442
443
444 String infectiousCategory = (String) xo.getAttribute(INFECTIOUS_CATEGORY);
445 final double endTime = Double.parseDouble((String) xo.getAttribute(END_TIME));
446 String latentCategory = null;
447 if (xo.hasAttribute(LATENT_CATEGORY)) {
448 latentCategory = (String) xo.getAttribute(LATENT_CATEGORY);
449 } else if (expectLatentPeriods) {
450 throw new XMLParseException("Case " + farmID + " not assigned a latent periods distribution");
451 }
452
453 double indexPriorWeight = 1;
454
455 if(xo.hasAttribute(INDEX_PRIOR_WEIGHT)){
456 indexPriorWeight = Double.parseDouble((String)xo.getAttribute(INDEX_PRIOR_WEIGHT));
457 }
458
459 final Parameter ibp = (Parameter) xo.getElementFirstChild(INFECTION_TIME_BRANCH_POSITION);
460
461
462 Taxa taxa = new Taxa();
463 for (int i = 0; i < xo.getChildCount(); i++) {
464 if (xo.getChild(i) instanceof Taxon) {
465 taxa.addTaxon((Taxon) xo.getChild(i));
466 }
467 }
468 outbreak.addCase(farmID, endTime, coords, ibp, taxa, indexPriorWeight, infectiousCategory, latentCategory);
469 } else {
470 outbreak.addNoninfectedCase(farmID, coords);
471
472
473 }
474 }
475
476
477 public String getParserDescription(){
478 return "Parses a set of 'category' farm outbreak and the information that they all share";
479 }
480
481 public Class getReturnType(){
482 return CategoryOutbreak.class;
483 }
484
485 public String getParserName(){
486 return CATEGORY_OUTBREAK;
487 }
488
489 public XMLSyntaxRule[] getSyntaxRules() {
490 return rules;
491 }
492
493 private final XMLSyntaxRule[] caseRules = {
494 AttributeRule.newBooleanRule(WAS_EVER_INFECTED),
495 new StringAttributeRule(CASE_ID, "The unique identifier for this host"),
496 new StringAttributeRule(END_TIME, "The time of noninfectiousness of this host", true),
497 new ElementRule(Taxon.class, 0, Integer.MAX_VALUE),
498 new ElementRule(INFECTION_TIME_BRANCH_POSITION, Parameter.class, "The exact position on the branch" +
499 " along which the infection of this case occurs that it actually does occur", true),
500 new ElementRule(COORDINATES, Parameter.class, "The spatial coordinates of this case", true),
501 new StringAttributeRule(LATENT_CATEGORY, "The category of latent period", true),
502 new StringAttributeRule(INFECTIOUS_CATEGORY, "The category of infectious period", true),
503 new StringAttributeRule(INDEX_PRIOR_WEIGHT, "The weight of this case in the prior probabilty for the" +
504 "index case", true)
505 };
506
507
508 private final XMLSyntaxRule[] rules = {
509 new StringAttributeRule(HAS_LATENT_PERIODS, "Whether to include a latent period in the model"),
510 new ElementRule(ProductStatistic.class, 0,2),
511 new ElementRule(CategoryCase.CATEGORY_CASE, caseRules, 1, Integer.MAX_VALUE),
512 new ElementRule(Taxa.class),
513 new ElementRule(INFECTIOUS_PERIOD_PRIOR, AbstractPeriodPriorDistribution.class, "A prior " +
514 "distribution for the length of infectious periods", 1, Integer.MAX_VALUE),
515 new ElementRule(LATENT_PERIODS, Parameter.class, "A prior distribution for the length of latent" +
516 " periods", 0, Integer.MAX_VALUE),
517 AttributeRule.newBooleanRule(HAS_GEOGRAPHY, true),
518 new ElementRule(DISTANCE_MATRIX, Parameter.class, "A matrix of distances between the cases in this " +
519 "outbreak", true)
520 };
521 };
522
523 }