Debian Codegraph @

src/dr/evomodel/antigenic/ContinuousAntigenicTraitLikelihood.java

raw symbols SCIP
1 /*
2 * ContinuousAntigenicTraitLikelihood.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.util.*;
31 import dr.xml.*;
32
33 import java.io.*;
34 import java.util.*;
35 import java.util.logging.Logger;
36
37 /**
38 * Antigenic evolution assuming each virus's antigenic property diffuses independently.
39 * @author Andrew Rambaut
40 * @author Marc Suchard
41 * @version $Id$
42 */
43 @Deprecated // for the moment at least
44 public class ContinuousAntigenicTraitLikelihood extends AntigenicTraitLikelihood implements Citable {
45
46 public final static String ANTIGENIC_TRAIT_LIKELIHOOD = "antigenicTraitLikelihood";
47
48 /**
49 * Constructor
50 * @param mdsDimension dimension of the mds space
51 * @param mdsPrecision parameter which gives the precision of the bmds
52 * @param tipTraitParameter a parameter of locations for the tips of the tree (mapped to virus locations)
53 * @param locationsParameter a parameter of locations of viruses/sera
54 * @param dataTable the assay table (virus in rows, serum assays in columns)
55 * @param virusAntiserumMap a map of viruses to corresponding sera
56 * @param assayAntiserumMap a map of repeated assays for a given sera
57 * @param log2Transform transform the data into log 2 space
58 */
59 public ContinuousAntigenicTraitLikelihood(
60 int mdsDimension,
61 Parameter mdsPrecision,
62 CompoundParameter tipTraitParameter,
63 MatrixParameter locationsParameter,
64 DataTable<String[]> dataTable,
65 Map<String, String> virusAntiserumMap,
66 Map<String, String> assayAntiserumMap,
67 List<String> virusLocationStatisticList,
68 final boolean log2Transform) {
69
70 super(ANTIGENIC_TRAIT_LIKELIHOOD);
71
72 String[] virusNames = dataTable.getRowLabels();
73 String[] assayNames = dataTable.getColumnLabels();
74
75 // the total number of viruses is the number of rows in the table
76 int virusCount = dataTable.getRowCount();
77 int assayCount = dataTable.getColumnCount();
78
79 int[] assayToSerumIndices = new int[assayNames.length];
80
81 double[][] observationValueTable = new double[virusCount][assayCount];
82 ObservationType[][] observationTypeTable = new ObservationType[virusCount][assayCount];
83
84 initalizeTable(dataTable, observationValueTable, observationTypeTable, log2Transform);
85
86 // This removes viruses that are not in the tree
87 List<String> tipLabels = null;
88 if (tipTraitParameter != null) {
89 tipLabels = new ArrayList<String>();
90 int tipCount = tipTraitParameter.getParameterCount();
91
92 for (int i = 0; i < tipCount; i++) {
93 String label = tipTraitParameter.getParameter(i).getParameterName();
94 if (label.endsWith(".antigenic")) {
95 label = label.substring(0, label.indexOf(".antigenic"));
96 }
97 tipLabels.add(label);
98 }
99 }
100
101 // locations are either viruses or sera (or both)
102 List<String> locationLabelsList = new ArrayList<String>();
103 int[] virusToLocationIndices = new int[virusCount];
104 int count = 0;
105 for (String virusName : virusNames) {
106 String name = null;
107
108 if (virusAntiserumMap != null) {
109 name = virusAntiserumMap.get(virusName);
110 }
111
112 if (name == null) {
113 name = virusName;
114 }
115
116 if (tipLabels == null || tipLabels.contains(name)) {
117 virusToLocationIndices[count] = locationLabelsList.size();
118 locationLabelsList.add(name);
119 } else {
120 virusToLocationIndices[count] = -1;
121 }
122 count++;
123 }
124
125 List<String> serumNamesList = new ArrayList<String>();
126 count = 0;
127 for (String assayName : assayNames) {
128 String name = null;
129
130 if (assayAntiserumMap != null) {
131 name = assayAntiserumMap.get(assayName);
132 }
133
134 if (name == null) {
135 name = assayName;
136 }
137
138 int index = serumNamesList.indexOf(name);
139 if (index == -1) {
140 index = serumNamesList.size();
141 serumNamesList.add(name);
142 }
143 assayToSerumIndices[count] = index;
144 count++;
145 }
146 String[] serumNames = new String[serumNamesList.size()];
147 serumNamesList.toArray(serumNames);
148
149 int serumCount = serumNames.length;
150 int[] serumToLocationIndices = new int[serumCount];
151 count = 0;
152 for (String serumName : serumNames) {
153 int index = locationLabelsList.indexOf(serumName);
154 if (index == -1) {
155 index = locationLabelsList.size();
156 locationLabelsList.add(serumName);
157 }
158 serumToLocationIndices[count] = index;
159 count++;
160 }
161
162 String[] locationLabels = new String[locationLabelsList.size()];
163 locationLabelsList.toArray(locationLabels);
164 int locationCount = locationLabels.length;
165
166 List<Double> observationList = new ArrayList<Double>();
167 List<ObservationType> observationTypeList = new ArrayList<ObservationType>();
168
169 int[] virusObservationCounts = new int[virusCount];
170 int[] serumObservationCounts = new int[serumCount];
171
172 List<Pair> locationPairs = new ArrayList<Pair>();
173
174 // Build a sparse matrix of non-missing assay values
175 for (int i = 0; i < virusCount; i++) {
176
177 if (virusToLocationIndices[i] != -1) {
178 // viruses with location indices of minus one have been excluded
179
180 for (int j = 0; j < assayCount; j++) {
181 int k = assayToSerumIndices[j];
182
183 Double value = observationValueTable[i][j];
184 ObservationType type = observationTypeTable[i][j];
185
186 if (type != ObservationType.MISSING) {
187 observationList.add(value);
188 observationTypeList.add(type);
189
190 locationPairs.add(new Pair(virusToLocationIndices[i], serumToLocationIndices[k]));
191
192 virusObservationCounts[i]++;
193 serumObservationCounts[k]++;
194 }
195 }
196 }
197 }
198
199 // check that all the viruses and sera have observations
200 for (int i = 0; i < virusCount; i++) {
201 if (virusToLocationIndices[i] != -1 && virusObservationCounts[i] == 0) {
202 System.err.println("WARNING: Virus " + virusNames[i] + " has 0 observations");
203 }
204 }
205 for (int j = 0; j < serumCount; j++) {
206 if (serumObservationCounts[j] == 0) {
207 System.err.println("WARNING: Antisera " + serumNames[j] + " has 0 observations");
208 }
209 }
210
211 // Convert into arrays
212 double[] observations = new double[observationList.size()];
213 for (int i = 0; i < observationList.size(); i++) {
214 observations[i] = observationList.get(i);
215 }
216
217 int[] rowLocationIndices = new int[locationPairs.size()];
218 for (int i = 0; i < rowLocationIndices.length; i++) {
219 rowLocationIndices[i] = locationPairs.get(i).location1;
220 }
221
222 int[] columnLocationIndices = new int[locationPairs.size()];
223 for (int i = 0; i < columnLocationIndices.length; i++) {
224 columnLocationIndices[i] = locationPairs.get(i).location2;
225 }
226
227 ObservationType[] observationTypes = new ObservationType[observationTypeList.size()];
228 observationTypeList.toArray(observationTypes);
229
230 int thresholdCount = 0;
231 for (int i = 0; i < observations.length; i++) {
232 thresholdCount += (observationTypes[i] != ObservationType.POINT ? 1 : 0);
233 }
234
235 if (tipTraitParameter != null) {
236 // the location -> tip map
237 tipIndices = new int[locationCount];
238 for (int i = 0; i < locationCount; i++) {
239 tipIndices[i] = tipLabels.indexOf(locationLabels[i]);
240 }
241
242 for (int i = 0; i < locationCount; i++) {
243 if (tipIndices[i] == -1) {
244 System.err.println("Location, " + locationLabels[i] + ", not found in tree");
245 }
246 }
247
248 for (String tipLabel : tipLabels) {
249 if (!locationLabelsList.contains(tipLabel)) {
250 System.err.println("Tip, " + tipLabel + ", not found in location list");
251 }
252 }
253 } else {
254 tipIndices = null;
255 }
256
257 StringBuilder sb = new StringBuilder();
258 sb.append("\tAntigenicTraitLikelihood:\n");
259 sb.append("\t\t" + virusNames.length + " viruses\n");
260 sb.append("\t\t" + assayNames.length + " assays\n");
261 sb.append("\t\t" + serumNames.length + " antisera\n");
262 sb.append("\t\t" + locationLabels.length + " locations\n");
263 sb.append("\t\t" + locationPairs.size() + " distances\n");
264 sb.append("\t\t" + observations.length + " observations\n");
265 sb.append("\t\t" + thresholdCount + " threshold observations\n");
266 Logger.getLogger("dr.evomodel").info(sb.toString());
267
268 this.tipTraitParameter = tipTraitParameter;
269
270 initialize(
271 mdsDimension,
272 false,
273 mdsPrecision,
274 locationsParameter,
275 locationLabels,
276 observations,
277 observationTypes,
278 rowLocationIndices,
279 columnLocationIndices);
280
281 // some random initial locations
282 for (int i = 0; i < locationsParameter.getParameterCount(); i++) {
283 for (int j = 0; j < mdsDimension; j++) {
284 // double r = MathUtils.nextGaussian();
285 double r = 0.0;
286 if (j == 0) {
287 r = (double) i * 0.05;
288 }
289 else {
290 r = MathUtils.nextGaussian();
291 }
292 locationsParameter.getParameter(i).setParameterValueQuietly(j, r);
293
294 if (tipTraitParameter != null) {
295 if (tipIndices[i] != -1) {
296 tipTraitParameter.setParameterValue((tipIndices[i] * mdsDimension) + j, r);
297 }
298 }
299 }
300 }
301
302 int i = 0;
303 for (String virusName : virusNames) {
304 if (virusLocationStatisticList.contains(virusName)) {
305 addStatistic(new VirusLocation(virusName + "." + "location", i));
306 }
307 i++;
308 }
309
310 }
311
312 @Override
313 protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
314 if (tipTraitParameter != null && variable == getLocationsParameter()) {
315 int mdsDimension = getMDSDimension();
316
317 int location = index / mdsDimension;
318 int dim = index % mdsDimension;
319
320 if (tipIndices[location] != -1) {
321 double value = getLocationsParameter().getParameterValue(index);
322 tipTraitParameter.setParameterValue((tipIndices[location] * mdsDimension) + dim, value);
323 }
324 }
325
326 super.handleVariableChangedEvent(variable, index, type);
327 }
328
329 public CompoundParameter getTipTraitParameter() {
330 return tipTraitParameter;
331 }
332
333 public int[] getTipIndices() {
334 return tipIndices;
335 }
336
337 private CompoundParameter tipTraitParameter;
338 private int[] tipIndices;
339
340 public class VirusLocation extends Statistic.Abstract {
341
342 public VirusLocation(String statisticName, int virusIndex) {
343 super(statisticName);
344 this.virusIndex = virusIndex;
345 }
346
347 @Override
348 public String getDimensionName(final int dim) {
349 if (getMDSDimension() == 2) {
350 return getStatisticName() + "_" + (dim == 0 ? "X" : "Y");
351 } else {
352 return getStatisticName() + "_" + (dim + 1);
353 }
354 }
355
356 public int getDimension() {
357 return getMDSDimension();
358 }
359
360 public double getStatisticValue(final int dim) {
361 Parameter loc = getLocationsParameter().getParameter(virusIndex);
362 return loc.getParameterValue(dim);
363 }
364
365 private final int virusIndex;
366 }
367
368 private class Pair {
369 Pair(final int location1, final int location2) {
370 if (location1 < location2) {
371 this.location1 = location1;
372 this.location2 = location2;
373 } else {
374 this.location1 = location2;
375 this.location2 = location1;
376 }
377 }
378
379 int location1;
380 int location2;
381
382 @Override
383 public boolean equals(final Object o) {
384 return ((Pair)o).location1 == location1 && ((Pair)o).location2 == location2;
385 }
386 };
387
388 // **************************************************************
389 // XMLObjectParser
390 // **************************************************************
391
392 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
393 public final static String FILE_NAME = "fileName";
394 public final static String VIRUS_MAP_FILE_NAME = "virusMapFile";
395 public final static String ASSAY_MAP_FILE_NAME = "assayMapFile";
396
397 public final static String TIP_TRAIT = "tipTrait";
398 public final static String LOCATIONS = "locations";
399 public static final String MDS_DIMENSION = "mdsDimension";
400 public static final String MDS_PRECISION = "mdsPrecision";
401
402 public static final String VIRUS_LOCATIONS = "virusLocations";
403
404 public static final String LOG_2_TRANSFORM = "log2Transform";
405 public static final String TITRATION_THRESHOLD = "titrationThreshold";
406
407 public String getParserName() {
408 return ANTIGENIC_TRAIT_LIKELIHOOD;
409 }
410
411 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
412
413 String fileName = xo.getStringAttribute(FILE_NAME);
414 DataTable<String[]> assayTable;
415 try {
416 assayTable = DataTable.Text.parse(new FileReader(fileName));
417 } catch (IOException e) {
418 throw new XMLParseException("Unable to read assay data from file: " + e.getMessage());
419 }
420
421 Map<String, String> virusAntiserumMap = null;
422 if (xo.hasAttribute(VIRUS_MAP_FILE_NAME)) {
423 try {
424 virusAntiserumMap = readMap(xo.getStringAttribute(VIRUS_MAP_FILE_NAME));
425 } catch (IOException e) {
426 throw new XMLParseException("Virus map file not found: " + xo.getStringAttribute(VIRUS_MAP_FILE_NAME));
427 }
428 }
429
430 Map<String, String> assayAntiserumMap = null;
431 if (xo.hasAttribute(ASSAY_MAP_FILE_NAME)) {
432 try {
433 assayAntiserumMap = readMap(xo.getStringAttribute(ASSAY_MAP_FILE_NAME));
434 } catch (IOException e) {
435 throw new XMLParseException("Assay map file not found: " + xo.getStringAttribute(ASSAY_MAP_FILE_NAME));
436 }
437 }
438
439 int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION);
440
441 boolean log2Transform = false;
442 if (xo.hasAttribute(LOG_2_TRANSFORM)) {
443 log2Transform = xo.getBooleanAttribute(LOG_2_TRANSFORM);
444 }
445
446 List<String> virusLocationStatisticList = null;
447 String[] virusLocations = xo.getStringArrayAttribute(VIRUS_LOCATIONS);
448 if (virusLocations != null) {
449 virusLocationStatisticList = Arrays.asList(virusLocations);
450 }
451
452 // This parameter needs to be linked to the one in the IntegratedMultivariateTreeLikelihood (I suggest that the parameter is created
453 // here and then a reference passed to IMTL - which optionally takes the parameter of tip trait values, in which case it listens and
454 // updates accordingly.
455 CompoundParameter tipTraitParameter = null;
456 if (xo.hasChildNamed(TIP_TRAIT)) {
457 tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT);
458 }
459
460 MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS);
461
462 Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION);
463
464 ContinuousAntigenicTraitLikelihood AGTL = new ContinuousAntigenicTraitLikelihood(mdsDimension, mdsPrecision, tipTraitParameter, locationsParameter, assayTable, virusAntiserumMap, assayAntiserumMap, virusLocationStatisticList, log2Transform);
465
466 Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGTL));
467
468 return AGTL;
469 }
470
471 private Map<String, String> readMap(String fileName) throws IOException {
472 BufferedReader reader = new BufferedReader(new FileReader(fileName));
473
474 Map<String, String> map = new HashMap<String, String>();
475
476 String line = reader.readLine();
477 while (line != null) {
478 if (line.trim().length() > 0) {
479 String[] parts = line.split("\t");
480 if (parts.length > 1) {
481 map.put(parts[0], parts[1]);
482 }
483 }
484 line = reader.readLine();
485 }
486
487 reader.close();
488
489 return map;
490 }
491
492
493
494 //************************************************************************
495 // AbstractXMLObjectParser implementation
496 //************************************************************************
497
498 public String getParserDescription() {
499 return "Provides the likelihood of immunological assay data such as Hemagglutinin inhibition (HI) given vectors of coordinates" +
500 "for viruses and sera/antisera in some multidimensional 'antigenic' space.";
501 }
502
503 public XMLSyntaxRule[] getSyntaxRules() {
504 return rules;
505 }
506
507 private final XMLSyntaxRule[] rules = {
508 AttributeRule.newStringRule(FILE_NAME, false, "The name of the file containing the assay table"),
509 AttributeRule.newStringRule(VIRUS_MAP_FILE_NAME, true, "The name of the file containing the virus to serum map"),
510 AttributeRule.newStringRule(ASSAY_MAP_FILE_NAME, true, "The name of the file containing the assay to serum map"),
511 AttributeRule.newIntegerRule(MDS_DIMENSION, false, "The dimension of the space for MDS"),
512 AttributeRule.newBooleanRule(LOG_2_TRANSFORM, true, "Whether to log2 transform the data"),
513 AttributeRule.newStringArrayRule(VIRUS_LOCATIONS, true, "A list of virus names to create location statistics for"),
514 new ElementRule(TIP_TRAIT, CompoundParameter.class, "The parameter of tip locations from the tree", true),
515 new ElementRule(LOCATIONS, MatrixParameter.class),
516 new ElementRule(MDS_PRECISION, Parameter.class)
517 };
518
519 public Class getReturnType() {
520 return ContinuousAntigenicTraitLikelihood.class;
521 }
522 };
523
524 @Override
525 public Citation.Category getCategory() {
526 return Citation.Category.TRAIT_MODELS;
527 }
528
529 @Override
530 public String getDescription() {
531 return "Bayesian Antigenic Cartography framework";
532 }
533
534 public List<Citation> getCitations() {
535 return Arrays.asList(CommonCitations.BEDFORD_2015_INTEGRATING);
536 }
537 }