Debian Codegraph @

src/dr/evomodel/antigenic/AntigenicLikelihood.java

raw symbols SCIP
1 /*
2 * AntigenicLikelihood.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.antigenic;
27
28 import dr.inference.model.*;
29 import dr.math.MathUtils;
30 import dr.math.LogTricks;
31 import dr.math.distributions.NormalDistribution;
32 import dr.util.*;
33 import dr.xml.*;
34
35
36 import java.io.*;
37 import java.util.*;
38 import java.util.logging.Logger;
39
40 /**
41 * @author Andrew Rambaut
42 * @author Trevor Bedford
43 * @author Marc Suchard
44 * @version $Id$
45 */
46 /*
47 Both virus locations and serum locations are shifted by the parameter locationDrift.
48 A location is increased by locationDrift x offset.
49 Offset is set to 0 for the earliest virus and increasing with difference in date from earliest virus.
50 This makes the raw virusLocations and serumLocations parameters not directly interpretable.
51 */
52 public class AntigenicLikelihood extends AbstractModelLikelihood implements Citable {
53 private static final boolean CHECK_INFINITE = false;
54 private static final boolean USE_THRESHOLDS = true;
55 private static final boolean USE_INTERVALS = true;
56
57 public final static String ANTIGENIC_LIKELIHOOD = "antigenicLikelihood";
58
59 // column indices in table
60 private static final int VIRUS_ISOLATE = 0;
61 private static final int VIRUS_STRAIN = 1;
62 private static final int VIRUS_DATE = 2;
63 private static final int SERUM_ISOLATE = 3;
64 private static final int SERUM_STRAIN = 4;
65 private static final int SERUM_DATE = 5;
66 private static final int TITRE = 6;
67
68 public enum MeasurementType {
69 INTERVAL,
70 POINT,
71 THRESHOLD,
72 MISSING
73 }
74
75 public AntigenicLikelihood(
76 int mdsDimension,
77 Parameter mdsPrecisionParameter,
78 Parameter locationDriftParameter,
79 Parameter virusDriftParameter,
80 Parameter serumDriftParameter,
81 MatrixParameter virusLocationsParameter,
82 MatrixParameter serumLocationsParameter,
83 CompoundParameter tipTraitsParameter,
84 Parameter virusOffsetsParameter,
85 Parameter serumOffsetsParameter,
86 Parameter serumPotenciesParameter,
87 Parameter serumBreadthsParameter,
88 Parameter virusAviditiesParameter,
89 DataTable<String[]> dataTable,
90 boolean mergeSerumIsolates,
91 double intervalWidth,
92 double driftInitialLocations) {
93
94 super(ANTIGENIC_LIKELIHOOD);
95
96 this.intervalWidth = intervalWidth;
97 boolean useIntervals = USE_INTERVALS && intervalWidth > 0.0;
98
99 int thresholdCount = 0;
100
101
102 double earliestDate = Double.POSITIVE_INFINITY;
103 for (int i = 0; i < dataTable.getRowCount(); i++) {
104
105 String[] values = dataTable.getRow(i);
106
107 String virusName = values[VIRUS_STRAIN];
108 double virusDate = Double.parseDouble(values[VIRUS_DATE]);
109 int virus = virusNames.indexOf(virusName);
110 if (virus == -1) {
111 virusNames.add(virusName);
112 virusDates.add(virusDate);
113 virus = virusNames.size() - 1;
114 }
115
116 String serumName = "";
117 if (mergeSerumIsolates) {
118 serumName = values[SERUM_STRAIN];
119 } else {
120 serumName = values[SERUM_ISOLATE];
121 }
122 double serumDate = Double.parseDouble(values[SERUM_DATE]);
123 int serum = serumNames.indexOf(serumName);
124 if (serum == -1) {
125 serumNames.add(serumName);
126 serumDates.add(serumDate);
127 serum = serumNames.size() - 1;
128 }
129
130 boolean isThreshold = false;
131 boolean isLowerThreshold = false;
132 double rawTitre = Double.NaN;
133 if (values[TITRE].length() > 0) {
134 try {
135 rawTitre = Double.parseDouble(values[TITRE]);
136 } catch (NumberFormatException nfe) {
137 // check if threshold below
138 if (values[TITRE].contains("<")) {
139 rawTitre = Double.parseDouble(values[TITRE].replace("<",""));
140 isThreshold = true;
141 isLowerThreshold = true;
142 thresholdCount++;
143 }
144 // check if threshold above
145 if (values[TITRE].contains(">")) {
146 rawTitre = Double.parseDouble(values[TITRE].replace(">",""));
147 isThreshold = true;
148 isLowerThreshold = false;
149 thresholdCount++;
150 //throw new IllegalArgumentException("Error in measurement: unsupported greater than threshold at row " + (i+1));
151 }
152 }
153 }
154
155 if (serumDate < earliestDate) {
156 earliestDate = serumDate;
157 }
158
159 if (virusDate < earliestDate) {
160 earliestDate = virusDate;
161 }
162
163 MeasurementType type = (isThreshold ? MeasurementType.THRESHOLD : (useIntervals ? MeasurementType.INTERVAL : MeasurementType.POINT));
164 Measurement measurement = new Measurement(virus, serum, virusDate, serumDate, type, rawTitre, isLowerThreshold);
165
166 if (USE_THRESHOLDS || !isThreshold) {
167 measurements.add(measurement);
168 }
169
170 }
171
172 double[] maxColumnTitres = new double[serumNames.size()];
173 for (Measurement measurement : measurements) {
174 double titre = measurement.log2Titre;
175 if (Double.isNaN(titre)) {
176 titre = measurement.log2Titre;
177 }
178 if (titre > maxColumnTitres[measurement.serum]) {
179 maxColumnTitres[measurement.serum] = titre;
180 }
181 }
182
183 this.mdsDimension = mdsDimension;
184
185 this.mdsPrecisionParameter = mdsPrecisionParameter;
186 addVariable(mdsPrecisionParameter);
187
188 this.locationDriftParameter = locationDriftParameter;
189 if (this.locationDriftParameter != null) {
190 addVariable(locationDriftParameter);
191 }
192
193 this.virusDriftParameter = virusDriftParameter;
194 if (this.virusDriftParameter != null) {
195 addVariable(virusDriftParameter);
196 }
197
198 this.serumDriftParameter = serumDriftParameter;
199 if (this.serumDriftParameter != null) {
200 addVariable(serumDriftParameter);
201 }
202
203 this.virusLocationsParameter = virusLocationsParameter;
204 if (this.virusLocationsParameter != null) {
205 setupLocationsParameter(virusLocationsParameter, virusNames);
206 }
207
208 this.serumLocationsParameter = serumLocationsParameter;
209 if (this.serumLocationsParameter != null) {
210 setupLocationsParameter(serumLocationsParameter, serumNames);
211 }
212
213 this.tipTraitsParameter = tipTraitsParameter;
214 if (tipTraitsParameter != null) {
215 setupTipTraitsParameter(this.tipTraitsParameter, virusNames);
216 }
217
218 this.virusOffsetsParameter = virusOffsetsParameter;
219 if (virusOffsetsParameter != null) {
220 setupOffsetsParameter(virusOffsetsParameter, virusNames, virusDates, earliestDate);
221 }
222
223 this.serumOffsetsParameter = serumOffsetsParameter;
224 if (serumOffsetsParameter != null) {
225 setupOffsetsParameter(serumOffsetsParameter, serumNames, serumDates, earliestDate);
226 }
227
228 this.serumPotenciesParameter = setupSerumPotencies(serumPotenciesParameter, maxColumnTitres);
229 this.serumBreadthsParameter = setupSerumBreadths(serumBreadthsParameter);
230 this.virusAviditiesParameter = setupVirusAvidities(virusAviditiesParameter);
231
232 StringBuilder sb = new StringBuilder();
233 sb.append("\tAntigenicLikelihood:\n");
234 sb.append("\t\t" + virusNames.size() + " viruses\n");
235 sb.append("\t\t" + serumNames.size() + " sera\n");
236 sb.append("\t\t" + measurements.size() + " assay measurements\n");
237 if (USE_THRESHOLDS) {
238 sb.append("\t\t" + thresholdCount + " thresholded measurements\n");
239 }
240 if (useIntervals) {
241 sb.append("\n\t\tAssuming a log 2 measurement interval width of " + intervalWidth + "\n");
242 }
243 Logger.getLogger("dr.evomodel").info(sb.toString());
244
245 virusLocationChanged = new boolean[this.virusLocationsParameter.getParameterCount()];
246 serumLocationChanged = new boolean[this.serumLocationsParameter.getParameterCount()];
247 virusEffectChanged = new boolean[virusNames.size()];
248 serumEffectChanged = new boolean[serumNames.size()];
249 logLikelihoods = new double[measurements.size()];
250 storedLogLikelihoods = new double[measurements.size()];
251
252 setupInitialLocations(driftInitialLocations);
253
254 makeDirty();
255 }
256
257 private Parameter setupVirusAvidities(Parameter virusAviditiesParameter) {
258 // If no row parameter is given, then we will only use the serum effects
259 if (virusAviditiesParameter != null) {
260 virusAviditiesParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, Double.MIN_VALUE, 1));
261 virusAviditiesParameter.setDimension(virusNames.size());
262 addVariable(virusAviditiesParameter);
263 String[] labelArray = new String[virusNames.size()];
264 virusNames.toArray(labelArray);
265 virusAviditiesParameter.setDimensionNames(labelArray);
266 for (int i = 0; i < virusNames.size(); i++) {
267 virusAviditiesParameter.setParameterValueQuietly(i, 0.0);
268 }
269 }
270 return virusAviditiesParameter;
271 }
272
273 private Parameter setupSerumPotencies(Parameter serumPotenciesParameter, double[] maxColumnTitres) {
274 // If no serum potencies parameter is given, make one to hold maximum values for scaling titres...
275 if (serumPotenciesParameter == null) {
276 serumPotenciesParameter = new Parameter.Default("serumPotencies");
277 } else {
278 serumPotenciesParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
279 addVariable(serumPotenciesParameter);
280 }
281
282 serumPotenciesParameter.setDimension(serumNames.size());
283 String[] labelArray = new String[serumNames.size()];
284 serumNames.toArray(labelArray);
285 serumPotenciesParameter.setDimensionNames(labelArray);
286 for (int i = 0; i < maxColumnTitres.length; i++) {
287 serumPotenciesParameter.setParameterValueQuietly(i, maxColumnTitres[i]);
288 }
289
290 return serumPotenciesParameter;
291 }
292
293 private Parameter setupSerumBreadths(Parameter serumBreadthsParameter) {
294 // If no serum breadths parameter is given, then we will only use the serum potencies
295 if (serumBreadthsParameter != null) {
296 serumBreadthsParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
297 serumBreadthsParameter.setDimension(serumNames.size());
298 addVariable(serumBreadthsParameter);
299 String[] labelArray = new String[serumNames.size()];
300 serumNames.toArray(labelArray);
301 serumBreadthsParameter.setDimensionNames(labelArray);
302 for (int i = 0; i < serumNames.size(); i++) {
303 serumBreadthsParameter.setParameterValueQuietly(i, 1.0);
304 }
305 }
306 return serumBreadthsParameter;
307 }
308
309 protected void setupLocationsParameter(MatrixParameter locationsParameter, List<String> strains) {
310 locationsParameter.setColumnDimension(mdsDimension);
311 locationsParameter.setRowDimension(strains.size());
312 for (int i = 0; i < strains.size(); i++) {
313 locationsParameter.getParameter(i).setId(strains.get(i));
314 }
315 addVariable(locationsParameter);
316 }
317
318 private void setupOffsetsParameter(Parameter offsetsParameter, List<String> strainNames, List<Double> strainDates, double earliest) {
319 offsetsParameter.setDimension(strainNames.size());
320 String[] labelArray = new String[strainNames.size()];
321 strainNames.toArray(labelArray);
322 offsetsParameter.setDimensionNames(labelArray);
323 for (int i = 0; i < strainNames.size(); i++) {
324 Double offset = strainDates.get(i) - new Double(earliest);
325 if (offset == null) {
326 throw new IllegalArgumentException("Date missing for strain: " + strainNames.get(i));
327 }
328 offsetsParameter.setParameterValue(i, offset);
329 }
330 addVariable(offsetsParameter);
331 }
332
333
334 private void setupTipTraitsParameter(CompoundParameter tipTraitsParameter, List<String> strainNames) {
335 tipIndices = new int[strainNames.size()];
336
337 for (int i = 0; i < strainNames.size(); i++) {
338 tipIndices[i] = -1;
339 }
340
341 for (int i = 0; i < tipTraitsParameter.getParameterCount(); i++) {
342 Parameter tip = tipTraitsParameter.getParameter(i);
343 String label = tip.getParameterName();
344 int index = findStrain(label, strainNames);
345 if (index != -1) {
346 if (tipIndices[index] != -1) {
347 throw new IllegalArgumentException("Duplicated tip name: " + label);
348 }
349
350 tipIndices[index] = i;
351
352 // rather than setting these here, we set them when the locations are set so the changes propagate
353 // through to the diffusion model.
354 // Parameter location = locationsParameter.getParameter(index);
355 // for (int dim = 0; dim < mdsDimension; dim++) {
356 // tip.setParameterValue(dim, location.getParameterValue(dim));
357 // }
358 } else {
359 // The tree may contain viruses not present in the assay data
360 // throw new IllegalArgumentException("Unmatched tip name in assay data: " + label);
361 }
362 }
363 // we are only setting this parameter not listening to it:
364 // addVariable(this.tipTraitsParameter);
365 }
366
367 private final int findStrain(String label, List<String> strainNames) {
368 int index = 0;
369 for (String strainName : strainNames) {
370 if (label.startsWith(strainName)) {
371 return index;
372 }
373
374 index ++;
375 }
376 return -1;
377 }
378
379 private void setupInitialLocations(double drift) {
380 for (int i = 0; i < virusLocationsParameter.getParameterCount(); i++) {
381 double offset = 0.0;
382 if (virusOffsetsParameter != null) {
383 offset = drift * virusOffsetsParameter.getParameterValue(i);
384 }
385 double r = MathUtils.nextGaussian() + offset;
386 virusLocationsParameter.getParameter(i).setParameterValue(0, r);
387 if (mdsDimension > 1) {
388 for (int j = 1; j < mdsDimension; j++) {
389 r = MathUtils.nextGaussian();
390 virusLocationsParameter.getParameter(i).setParameterValue(j, r);
391 }
392 }
393 }
394 for (int i = 0; i < serumLocationsParameter.getParameterCount(); i++) {
395 double offset = 0.0;
396 if (serumOffsetsParameter != null) {
397 offset = drift * serumOffsetsParameter.getParameterValue(i);
398 }
399 double r = MathUtils.nextGaussian() + offset;
400 serumLocationsParameter.getParameter(i).setParameterValue(0, r);
401 if (mdsDimension > 1) {
402 for (int j = 1; j < mdsDimension; j++) {
403 r = MathUtils.nextGaussian();
404 serumLocationsParameter.getParameter(i).setParameterValue(j, r);
405 }
406 }
407 }
408 }
409
410 @Override
411 protected void handleModelChangedEvent(Model model, Object object, int index) {
412 }
413
414 @Override
415 protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
416 if (variable == virusLocationsParameter) {
417 if (index != -1) {
418 int loc = index / mdsDimension;
419 virusLocationChanged[loc] = true;
420 if (tipTraitsParameter != null && tipIndices[loc] != -1) {
421 Parameter location = virusLocationsParameter.getParameter(loc);
422 Parameter tip = tipTraitsParameter.getParameter(tipIndices[loc]);
423 int dim = index % mdsDimension;
424 tip.setParameterValue(dim, location.getParameterValue(dim));
425 }
426 } else {
427 if (false) { // Just for debugging purposes.
428 // for (int idx = 0; idx < virusLocationsParameter.getDimension(); ++idx) {
429 // int loc = idx / mdsDimension;
430 // virusLocationChanged[loc] = true;
431 // if (tipTraitsParameter != null && tipIndices[loc] != -1) {
432 // Parameter location = virusLocationsParameter.getParameter(loc);
433 // Parameter tip = tipTraitsParameter.getParameter(tipIndices[loc]);
434 // int dim = idx % mdsDimension;
435 // tip.setParameterValue(dim, location.getParameterValue(dim));
436 // }
437 // }
438 } else {
439 Arrays.fill(virusLocationChanged, true);
440 if (tipTraitsParameter != null) {
441 for (int pindex = 0; pindex < virusLocationsParameter.getParameterCount(); ++pindex) {
442 Parameter location = virusLocationsParameter.getParameter(pindex);
443 Parameter tip = tipTraitsParameter.getParameter(tipIndices[pindex]);
444 for (int i = 0; i < tip.getDimension(); ++i) {
445 tip.setParameterValueQuietly(i, location.getParameterValue(i));//
446 }
447 }
448 tipTraitsParameter.fireParameterChangedEvent();
449 }
450 }
451 }
452 } else if (variable == serumLocationsParameter) {
453 int loc = index / mdsDimension;
454 serumLocationChanged[loc] = true;
455 } else if (variable == mdsPrecisionParameter) {
456 setLocationChangedFlags(true);
457 } else if (variable == locationDriftParameter) {
458 setLocationChangedFlags(true);
459 } else if (variable == virusDriftParameter) {
460 setLocationChangedFlags(true);
461 } else if (variable == serumDriftParameter) {
462 setLocationChangedFlags(true);
463 } else if (variable == serumPotenciesParameter) {
464 serumEffectChanged[index] = true;
465 } else if (variable == serumBreadthsParameter) {
466 serumEffectChanged[index] = true;
467 } else if (variable == virusAviditiesParameter) {
468 virusEffectChanged[index] = true;
469 } else {
470 // could be a derived class's parameter
471 // throw new IllegalArgumentException("Unknown parameter");
472 }
473 likelihoodKnown = false;
474 }
475
476 @Override
477 protected void storeState() {
478 System.arraycopy(logLikelihoods, 0, storedLogLikelihoods, 0, logLikelihoods.length);
479 }
480
481 @Override
482 protected void restoreState() {
483 double[] tmp = logLikelihoods;
484 logLikelihoods = storedLogLikelihoods;
485 storedLogLikelihoods = tmp;
486
487 likelihoodKnown = false;
488 }
489
490 @Override
491 protected void acceptState() {
492 }
493
494 public Model getModel() {
495 return this;
496 }
497
498 public double getLogLikelihood() {
499 if (!likelihoodKnown) {
500 logLikelihood = computeLogLikelihood();
501 }
502
503 return logLikelihood;
504 }
505
506 // This function can be overwritten to implement other sampling densities, i.e. discrete ranks
507 private double computeLogLikelihood() {
508
509 double precision = mdsPrecisionParameter.getParameterValue(0);
510 double sd = 1.0 / Math.sqrt(precision);
511
512 logLikelihood = 0.0;
513 int i = 0;
514
515 for (Measurement measurement : measurements) {
516
517 if (virusLocationChanged[measurement.virus] || serumLocationChanged[measurement.serum] || virusEffectChanged[measurement.virus] || serumEffectChanged[measurement.serum]) {
518
519 double expectation = calculateBaseline(measurement.virus, measurement.serum) - computeDistance(measurement.virus, measurement.serum);
520
521 switch (measurement.type) {
522 case INTERVAL: {
523 double minTitre = measurement.log2Titre;
524 double maxTitre = measurement.log2Titre + intervalWidth;
525 logLikelihoods[i] = computeMeasurementIntervalLikelihood(minTitre, maxTitre, expectation, sd);
526 } break;
527 case POINT: {
528 logLikelihoods[i] = computeMeasurementLikelihood(measurement.log2Titre, expectation, sd);
529 } break;
530 case THRESHOLD: {
531 if(measurement.isLowerThreshold){
532 logLikelihoods[i] = computeMeasurementThresholdLikelihood(measurement.log2Titre, expectation, sd);
533 }
534 else{
535 logLikelihoods[i] = computeMeasurementUpperThresholdLikelihood(measurement.log2Titre, expectation, sd);
536 }
537 } break;
538 case MISSING:
539 break;
540 }
541 }
542 logLikelihood += logLikelihoods[i];
543 i++;
544 }
545
546 likelihoodKnown = true;
547
548 setLocationChangedFlags(false);
549 setSerumEffectChangedFlags(false);
550 setVirusEffectChangedFlags(false);
551
552 return logLikelihood;
553 }
554
555 private void setLocationChangedFlags(boolean flag) {
556 for (int i = 0; i < virusLocationChanged.length; i++) {
557 virusLocationChanged[i] = flag;
558 }
559 for (int i = 0; i < serumLocationChanged.length; i++) {
560 serumLocationChanged[i] = flag;
561 }
562 }
563
564 private void setSerumEffectChangedFlags(boolean flag) {
565 for (int i = 0; i < serumEffectChanged.length; i++) {
566 serumEffectChanged[i] = flag;
567 }
568 }
569
570 private void setVirusEffectChangedFlags(boolean flag) {
571 for (int i = 0; i < virusEffectChanged.length; i++) {
572 virusEffectChanged[i] = flag;
573 }
574 }
575
576 // offset virus and serum location when computing
577 protected double computeDistance(int virus, int serum) {
578
579 Parameter vLoc = virusLocationsParameter.getParameter(virus);
580 Parameter sLoc = serumLocationsParameter.getParameter(serum);
581 double sum = 0.0;
582
583 // first dimension is shifted
584 double vxOffset = 0.0;
585 double sxOffset = 0.0;
586 if (locationDriftParameter != null && virusOffsetsParameter != null && serumOffsetsParameter != null) {
587 vxOffset = locationDriftParameter.getParameterValue(0) * virusOffsetsParameter.getParameterValue(virus);
588 sxOffset = locationDriftParameter.getParameterValue(0) * serumOffsetsParameter.getParameterValue(serum);
589 }
590 if (virusDriftParameter != null && virusOffsetsParameter != null) {
591 vxOffset = virusDriftParameter.getParameterValue(0) * virusOffsetsParameter.getParameterValue(virus);
592 }
593 if (serumDriftParameter != null && serumOffsetsParameter != null) {
594 sxOffset = serumDriftParameter.getParameterValue(0) * serumOffsetsParameter.getParameterValue(serum);
595 }
596
597 double vxLoc = vLoc.getParameterValue(0) + vxOffset;
598 double sxLoc = sLoc.getParameterValue(0) + sxOffset;
599
600 double difference = vxLoc - sxLoc;
601 sum += difference * difference;
602
603 // other dimensions are not
604 for (int i = 1; i < mdsDimension; i++) {
605 difference = vLoc.getParameterValue(i) - sLoc.getParameterValue(i);
606 sum += difference * difference;
607 }
608
609 double dist = Math.sqrt(sum);
610
611 if (serumBreadthsParameter != null) {
612 double serumBreadth = serumBreadthsParameter.getParameterValue(serum);
613 dist /= serumBreadth;
614 }
615
616 return dist;
617 }
618
619
620 // Calculates the expected log2 titre when mapDistance = 0
621 private double calculateBaseline(int virus, int serum) {
622 double baseline = serumPotenciesParameter.getParameterValue(serum);
623 if (virusAviditiesParameter != null) {
624 baseline += virusAviditiesParameter.getParameterValue(virus);
625 }
626 return baseline;
627 }
628
629 private static double computeMeasurementLikelihood(double titre, double expectation, double sd) {
630
631 double lnL = NormalDistribution.logPdf(titre, expectation, sd);
632
633 if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
634 throw new RuntimeException("infinite point measurement");
635 }
636 return lnL;
637 }
638
639 private static double computeMeasurementThresholdLikelihood(double titre, double expectation, double sd) {
640
641 // real titre is somewhere between -infinity and measured 'titre'
642 // want the lower tail of the normal CDF
643
644 double lnL = NormalDistribution.cdf(titre, expectation, sd, true); // returns logged CDF
645
646 if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
647 throw new RuntimeException("infinite threshold measurement");
648 }
649 return lnL;
650 }
651
652
653 private static double computeMeasurementUpperThresholdLikelihood(double titre, double expectation, double sd) {
654
655 // real titre is somewhere between -infinity and measured 'titre'
656 // want the lower tail of the normal CDF
657 double L = NormalDistribution.cdf(titre, expectation, sd, false); // returns CDF
658 double lnL = Math.log(1-L); //get the upper tail probability, then log it
659
660 if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
661 throw new RuntimeException("infinite threshold measurement");
662 }
663 return lnL;
664 }
665
666
667 private static double computeMeasurementIntervalLikelihood(double minTitre, double maxTitre, double expectation, double sd) {
668
669 // real titre is somewhere between measured minTitre and maxTitre
670
671 double cdf1 = NormalDistribution.cdf(maxTitre, expectation, sd, true); // returns logged CDF
672 double cdf2 = NormalDistribution.cdf(minTitre, expectation, sd, true); // returns logged CDF
673 double lnL = LogTricks.logDiff(cdf1, cdf2);
674
675 if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
676 // this occurs when the interval is in the far tail of the distribution, cdf1 == cdf2
677 // instead return logPDF of the point
678 lnL = NormalDistribution.logPdf(minTitre, expectation, sd);
679 if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
680 throw new RuntimeException("infinite interval measurement");
681 }
682 }
683 return lnL;
684 }
685
686 public void makeDirty() {
687 likelihoodKnown = false;
688 setLocationChangedFlags(true);
689 }
690
691 private class Measurement {
692 private Measurement(final int virus, final int serum, final double virusDate, final double serumDate, final MeasurementType type, final double titre, final boolean isLowerThreshold) {
693 this.virus = virus;
694 this.serum = serum;
695 this.virusDate = virusDate;
696 this.serumDate = serumDate;
697 this.type = type;
698 this.titre = titre;
699 this.log2Titre = Math.log(titre) / Math.log(2);
700 this.isLowerThreshold = isLowerThreshold;
701 }
702
703 final int virus;
704 final int serum;
705 final double virusDate;
706 final double serumDate;
707 final MeasurementType type;
708 final double titre;
709 final double log2Titre;
710 final boolean isLowerThreshold;
711
712 };
713
714 private final List<Measurement> measurements = new ArrayList<Measurement>();
715 private final List<String> virusNames = new ArrayList<String>();
716 private final List<String> serumNames = new ArrayList<String>();
717 private final List<Double> virusDates = new ArrayList<Double>();
718 private final List<Double> serumDates = new ArrayList<Double>();
719
720 private final int mdsDimension;
721 private final double intervalWidth;
722 private final Parameter mdsPrecisionParameter;
723 private final Parameter locationDriftParameter;
724 private final Parameter virusDriftParameter;
725 private final Parameter serumDriftParameter;
726
727 private final MatrixParameter virusLocationsParameter;
728 private final MatrixParameter serumLocationsParameter;
729
730 private final Parameter virusOffsetsParameter;
731 private final Parameter serumOffsetsParameter;
732
733 private final CompoundParameter tipTraitsParameter;
734 private int[] tipIndices;
735
736 private final Parameter virusAviditiesParameter;
737 private final Parameter serumPotenciesParameter;
738 private final Parameter serumBreadthsParameter;
739
740 private double logLikelihood = 0.0;
741 private boolean likelihoodKnown = false;
742
743 private final boolean[] virusLocationChanged;
744 private final boolean[] serumLocationChanged;
745 private final boolean[] serumEffectChanged;
746 private final boolean[] virusEffectChanged;
747 private double[] logLikelihoods;
748 private double[] storedLogLikelihoods;
749
750 // **************************************************************
751 // XMLObjectParser
752 // **************************************************************
753
754 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
755
756 public final static String FILE_NAME = "fileName";
757 public final static String TIP_TRAIT = "tipTrait";
758 public final static String VIRUS_LOCATIONS = "virusLocations";
759 public final static String SERUM_LOCATIONS = "serumLocations";
760 public static final String MDS_DIMENSION = "mdsDimension";
761 public static final String MERGE_SERUM_ISOLATES = "mergeSerumIsolates";
762 public static final String DRIFT_INITIAL_LOCATIONS = "driftInitialLocations";
763 public static final String INTERVAL_WIDTH = "intervalWidth";
764 public static final String MDS_PRECISION = "mdsPrecision";
765 public static final String LOCATION_DRIFT = "locationDrift";
766 public static final String VIRUS_DRIFT = "virusDrift";
767 public static final String SERUM_DRIFT = "serumDrift";
768 public static final String VIRUS_AVIDITIES = "virusAvidities";
769 public static final String SERUM_POTENCIES = "serumPotencies";
770 public static final String SERUM_BREADTHS = "serumBreadths";
771 public final static String VIRUS_OFFSETS = "virusOffsets";
772 public final static String SERUM_OFFSETS = "serumOffsets";
773
774 public String getParserName() {
775 return ANTIGENIC_LIKELIHOOD;
776 }
777
778 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
779
780 String fileName = xo.getStringAttribute(FILE_NAME);
781 DataTable<String[]> assayTable;
782 try {
783 assayTable = DataTable.Text.parse(new FileReader(fileName), true, false);
784 } catch (IOException e) {
785 throw new XMLParseException("Unable to read assay data from file: " + e.getMessage());
786 }
787 System.out.println("Loaded HI table file: " + fileName);
788
789 boolean mergeSerumIsolates = xo.getAttribute(MERGE_SERUM_ISOLATES, false);
790
791 int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION);
792 double intervalWidth = 0.0;
793 if (xo.hasAttribute(INTERVAL_WIDTH)) {
794 intervalWidth = xo.getDoubleAttribute(INTERVAL_WIDTH);
795 }
796
797 double driftInitialLocations = 0.0;
798 if (xo.hasAttribute(DRIFT_INITIAL_LOCATIONS)) {
799 driftInitialLocations = xo.getDoubleAttribute(DRIFT_INITIAL_LOCATIONS);
800 }
801
802 CompoundParameter tipTraitParameter = null;
803 if (xo.hasChildNamed(TIP_TRAIT)) {
804 tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT);
805 }
806
807 MatrixParameter virusLocationsParameter = null;
808 if (xo.hasChildNamed(VIRUS_LOCATIONS)) {
809 virusLocationsParameter = (MatrixParameter) xo.getElementFirstChild(VIRUS_LOCATIONS);
810 }
811
812 MatrixParameter serumLocationsParameter = null;
813 if (xo.hasChildNamed(SERUM_LOCATIONS)) {
814 serumLocationsParameter = (MatrixParameter) xo.getElementFirstChild(SERUM_LOCATIONS);
815 }
816
817 Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION);
818
819 Parameter locationDrift = null;
820 if (xo.hasChildNamed(LOCATION_DRIFT)) {
821 locationDrift = (Parameter) xo.getElementFirstChild(LOCATION_DRIFT);
822 }
823
824 Parameter virusDrift = null;
825 if (xo.hasChildNamed(VIRUS_DRIFT)) {
826 virusDrift = (Parameter) xo.getElementFirstChild(VIRUS_DRIFT);
827 }
828
829 Parameter serumDrift = null;
830 if (xo.hasChildNamed(SERUM_DRIFT)) {
831 serumDrift = (Parameter) xo.getElementFirstChild(SERUM_DRIFT);
832 }
833
834 Parameter virusOffsetsParameter = null;
835 if (xo.hasChildNamed(VIRUS_OFFSETS)) {
836 virusOffsetsParameter = (Parameter) xo.getElementFirstChild(VIRUS_OFFSETS);
837 }
838
839 Parameter serumOffsetsParameter = null;
840 if (xo.hasChildNamed(SERUM_OFFSETS)) {
841 serumOffsetsParameter = (Parameter) xo.getElementFirstChild(SERUM_OFFSETS);
842 }
843
844 Parameter serumPotenciesParameter = null;
845 if (xo.hasChildNamed(SERUM_POTENCIES)) {
846 serumPotenciesParameter = (Parameter) xo.getElementFirstChild(SERUM_POTENCIES);
847 }
848
849 Parameter serumBreadthsParameter = null;
850 if (xo.hasChildNamed(SERUM_BREADTHS)) {
851 serumBreadthsParameter = (Parameter) xo.getElementFirstChild(SERUM_BREADTHS);
852 }
853
854 Parameter virusAviditiesParameter = null;
855 if (xo.hasChildNamed(VIRUS_AVIDITIES)) {
856 virusAviditiesParameter = (Parameter) xo.getElementFirstChild(VIRUS_AVIDITIES);
857 }
858
859 AntigenicLikelihood AGL = new AntigenicLikelihood(
860 mdsDimension,
861 mdsPrecision,
862 locationDrift,
863 virusDrift,
864 serumDrift,
865 virusLocationsParameter,
866 serumLocationsParameter,
867 tipTraitParameter,
868 virusOffsetsParameter,
869 serumOffsetsParameter,
870 serumPotenciesParameter,
871 serumBreadthsParameter,
872 virusAviditiesParameter,
873 assayTable,
874 mergeSerumIsolates,
875 intervalWidth,
876 driftInitialLocations);
877
878 Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGL));
879
880 return AGL;
881 }
882
883 //************************************************************************
884 // AbstractXMLObjectParser implementation
885 //************************************************************************
886
887 public String getParserDescription() {
888 return "Provides the likelihood of immunological assay data such as Hemagglutinin inhibition (HI) given vectors of coordinates" +
889 "for viruses and sera/antisera in some multidimensional 'antigenic' space.";
890 }
891
892 public XMLSyntaxRule[] getSyntaxRules() {
893 return rules;
894 }
895
896 private final XMLSyntaxRule[] rules = {
897 AttributeRule.newStringRule(FILE_NAME, false, "The name of the file containing the assay table"),
898 AttributeRule.newIntegerRule(MDS_DIMENSION, false, "The dimension of the space for MDS"),
899 AttributeRule.newBooleanRule(MERGE_SERUM_ISOLATES, true, "Should multiple serum isolates from the same strain have their locations merged (defaults to false)"),
900 AttributeRule.newDoubleRule(INTERVAL_WIDTH, true, "The width of the titre interval in log 2 space"),
901 AttributeRule.newDoubleRule(DRIFT_INITIAL_LOCATIONS, true, "The degree to drift initial virus and serum locations, defaults to 0.0"),
902 new ElementRule(TIP_TRAIT, CompoundParameter.class, "Optional parameter of tip locations from the tree", true),
903 new ElementRule(VIRUS_LOCATIONS, MatrixParameter.class, "Parameter of locations of all virus"),
904 new ElementRule(SERUM_LOCATIONS, MatrixParameter.class, "Parameter of locations of all sera"),
905 new ElementRule(VIRUS_OFFSETS, Parameter.class, "Optional parameter for virus dates to be stored", true),
906 new ElementRule(SERUM_OFFSETS, Parameter.class, "Optional parameter for serum dates to be stored", true),
907 new ElementRule(SERUM_POTENCIES, Parameter.class, "Optional parameter for serum potencies", true),
908 new ElementRule(SERUM_BREADTHS, Parameter.class, "Optional parameter for serum breadths", true),
909 new ElementRule(VIRUS_AVIDITIES, Parameter.class, "Optional parameter for virus avidities", true),
910 new ElementRule(MDS_PRECISION, Parameter.class, "Parameter for precision of MDS embedding"),
911 new ElementRule(LOCATION_DRIFT, Parameter.class, "Optional parameter for drifting locations with time", true),
912 new ElementRule(VIRUS_DRIFT, Parameter.class, "Optional parameter for drifting only virus locations, overrides locationDrift", true),
913 new ElementRule(SERUM_DRIFT, Parameter.class, "Optional parameter for drifting only serum locations, overrides locationDrift", true)
914 };
915
916 public Class getReturnType() {
917 return AntigenicLikelihood.class;
918 }
919 };
920
921 @Override
922 public Citation.Category getCategory() {
923 return Citation.Category.TRAIT_MODELS;
924 }
925
926 @Override
927 public String getDescription() {
928 return "Bayesian Antigenic Cartography framework";
929 }
930
931 public List<Citation> getCitations() {
932 return Arrays.asList(CommonCitations.BEDFORD_2015_INTEGRATING);
933 }
934
935 public static void main(String[] args) {
936 double[] titres = {0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0};
937
938 System.out.println("titre\tpoint\tinterval(tail)\tinterval(cdf)\tthreshold");
939 for (double titre : titres) {
940 double point = AntigenicLikelihood.computeMeasurementLikelihood(titre, 0.0, 1.0);
941 double interval = AntigenicLikelihood.computeMeasurementIntervalLikelihood(titre + 1.0, titre, 0.0, 1.0);
942 double threshold = AntigenicLikelihood.computeMeasurementThresholdLikelihood(titre, 0.0, 1.0);
943
944 System.out.println(titre + "\t" + point + "\t" + interval + "\t" + threshold);
945 }
946 }
947 }