Debian Codegraph @

src/dr/evomodel/antigenic/MultidimensionalScalingLikelihood.java

raw symbols SCIP
1 /*
2 * MultidimensionalScalingLikelihood.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.distributions.NormalDistribution;
30 import dr.util.DataTable;
31 import dr.xml.*;
32
33 import java.io.FileReader;
34 import java.io.IOException;
35
36 /**
37 * @author Andrew Rambaut
38 * @author Marc Suchard
39 * @version $Id$
40 */
41 public class MultidimensionalScalingLikelihood extends AbstractModelLikelihood {
42
43
44 public enum ObservationType {
45 POINT,
46 UPPER_BOUND,
47 LOWER_BOUND,
48 MISSING
49 }
50
51 public final static String MULTIDIMENSIONAL_SCALING_LIKELIHOOD = "multidimensionalScalingLikelihood";
52
53 public MultidimensionalScalingLikelihood(String name) {
54
55 super(name);
56 }
57
58 /**
59 * A simple constructor for a fully specified symmetrical data matrix
60 * @param mdsDimension
61 * @param mdsPrecision
62 * @param locationsParameter
63 * @param dataTable
64 */
65 public MultidimensionalScalingLikelihood(
66 int mdsDimension,
67 boolean isLeftTruncated,
68 Parameter mdsPrecision,
69 MatrixParameter locationsParameter,
70 DataTable<double[]> dataTable) {
71
72 super(MULTIDIMENSIONAL_SCALING_LIKELIHOOD);
73
74 // construct a compact data table
75 String[] rowLabels = dataTable.getRowLabels();
76 String[] columnLabels = dataTable.getRowLabels();
77
78 int rowCount = dataTable.getRowCount();
79 int observationCount = ((rowCount - 1) * rowCount) / 2;
80 double[] observations = new double[observationCount];
81 ObservationType[] observationTypes = new ObservationType[observationCount];
82 // int[] distanceIndices = new int[observationCount];
83 int[] rowLocationIndices = new int[observationCount];
84 int[] columnLocationIndices = new int[observationCount];
85
86 int u = 0;
87 for (int i = 0; i < rowCount; i++) {
88
89 double[] dataRow = dataTable.getRow(i);
90
91 for (int j = i + 1; j < rowCount; j++) {
92 observations[u] = dataRow[j];
93 observationTypes[u] = ObservationType.POINT;
94 // distanceIndices[u] = u;
95 rowLocationIndices[u] = i;
96 columnLocationIndices[u] = j;
97 u++;
98 }
99
100 }
101
102 initialize(mdsDimension, isLeftTruncated, mdsPrecision, locationsParameter, rowLabels, observations, observationTypes, rowLocationIndices, columnLocationIndices);
103 }
104
105 protected void initialize(
106 final int mdsDimension,
107 final boolean isLeftTruncated,
108 final Parameter mdsPrecision,
109 final MatrixParameter locationsParameter,
110 final String[] locationLabels,
111 final double[] observations,
112 final ObservationType[] observationTypes,
113 // final int[] distanceIndices,
114 final int[] rowLocationIndices,
115 final int[] columnLocationIndices) {
116
117 this.mdsDimension = mdsDimension;
118
119 locationCount = locationLabels.length;
120
121 // upper triangular matrix
122 this.distanceCount = (locationCount * (locationCount - 1)) / 2;
123
124 this.locationLabels = locationLabels;
125
126 this.observations = observations;
127 this.observationTypes = observationTypes;
128 // this.distanceIndices = distanceIndices;
129 this.rowLocationIndices = rowLocationIndices;
130 this.columnLocationIndices = columnLocationIndices;
131
132 this.observationCount = observations.length;
133 this.upperThresholdCount = 0;
134 this.lowerThresholdCount = 0;
135
136 for (ObservationType type : observationTypes) {
137 upperThresholdCount += (type == ObservationType.UPPER_BOUND ? 1 : 0);
138 lowerThresholdCount += (type == ObservationType.LOWER_BOUND ? 1 : 0);
139 }
140
141 thresholdCount = upperThresholdCount + lowerThresholdCount;
142 pointObservationCount = observationCount - thresholdCount;
143
144 upperThresholdIndices = new int[upperThresholdCount];
145 lowerThresholdIndices = new int[lowerThresholdCount];
146 pointObservationIndices = new int[pointObservationCount];
147
148 int ut = 0;
149 int lt = 0;
150 int po = 0;
151 for (int i = 0; i < observationCount; i++) {
152 switch (observationTypes[i]) {
153 case POINT:
154 pointObservationIndices[po] = i;
155 po++;
156 break;
157 case UPPER_BOUND:
158 upperThresholdIndices[ut] = i;
159 ut++;
160 break;
161 case LOWER_BOUND:
162 lowerThresholdIndices[lt] = i;
163 lt++;
164 break;
165 }
166 }
167
168 this.locationsParameter = locationsParameter;
169 setupLocationsParameter(this.locationsParameter);
170 addVariable(locationsParameter);
171 locationUpdated = new boolean[locationsParameter.getParameterCount()];
172
173 // a cache of row to column distances (column indices given by array above).
174 distances = new double[distanceCount];
175 storedDistances = new double[distanceCount];
176 distanceUpdated = new boolean[distanceCount];
177
178 // a cache of individual truncations
179 truncations = new double[distanceCount];
180 storedTruncations = new double[distanceCount];
181
182 // a cache of threshold calcs
183 thresholds = new double[thresholdCount];
184 storedThresholds = new double[thresholdCount];
185
186 this.mdsPrecisionParameter = mdsPrecision;
187 addVariable(mdsPrecision);
188
189 this.isLeftTruncated = isLeftTruncated; // Re-normalize likelihood for strictly positive distances
190
191 // make sure everything is calculated on first evaluation
192 makeDirty();
193
194 addStatistic(new Distances());
195 }
196
197 protected void setupLocationsParameter(MatrixParameter locationsParameter) {
198 if (locationsParameter.getColumnDimension() > 0){
199 boolean proceed = true;
200 //TODO: allow for a generic tipTrait/location specification with mismatches: tipTraits which are not represented by the pairwise distances (tipTraits > locations) and more locations based on pairwise distances than represented by the tipTraits
201 if (locationsParameter.getColumnDimension() != locationCount){
202 System.err.println("locationsParameter column dimension ("+locationsParameter.getColumnDimension()+") is not equal to the locationCount ("+locationCount+")");
203 proceed = false;
204 }
205 if (locationsParameter.getRowDimension() != mdsDimension){
206 System.err.println("locationsParameter row dimension ("+locationsParameter.getRowDimension()+") is not equal to the mdsDimension ("+mdsDimension+")");
207 proceed = false;
208 }
209 if (!proceed) {
210 System.exit(-1);
211 }
212 } else{
213 locationsParameter.setColumnDimension(mdsDimension);
214 locationsParameter.setRowDimension(locationCount);
215 }
216 for (int i = 0; i < locationLabels.length; i++) {
217 locationsParameter.getParameter(i).setId(locationLabels[i]);
218 }
219
220 for (int i = 0; i < locationsParameter.getParameterCount(); ++i) {
221 Parameter param = locationsParameter.getParameter(i);
222 try {
223 if (param.getBounds() != null) {
224 // Do nothing
225 }
226 } catch (NullPointerException exception) {
227 param.addBounds(new Parameter.DefaultBounds(
228 Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, param.getDimension()));
229 }
230 }
231 }
232
233 @Override
234 protected void handleModelChangedEvent(Model model, Object object, int index) {
235 }
236
237 @Override
238 protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
239 // TODO Flag which cachedDistances or mdsPrecision need to be updated
240
241 if (variable == locationsParameter) {
242 int location = index / mdsDimension;
243
244 locationUpdated[location] = true;
245 distancesKnown = false;
246 residualsKnown = false;
247 thresholdsKnown = false;
248 truncationsKnown = false;
249 } else if (variable == mdsPrecisionParameter) {
250 for (int i = 0; i < distanceUpdated.length; i++) {
251 distanceUpdated[i] = true;
252 }
253 residualsKnown = false;
254 thresholdsKnown = false;
255 truncationsKnown = false;
256 } else {
257 // could be a derived class's parameter
258 // throw new IllegalArgumentException("Unknown parameter");
259 }
260 likelihoodKnown = false;
261 }
262
263 @Override
264 protected void storeState() {
265 System.arraycopy(distances, 0, storedDistances, 0, distances.length);
266 System.arraycopy(truncations, 0, storedTruncations, 0, truncations.length);
267 System.arraycopy(thresholds, 0, storedThresholds, 0, thresholds.length);
268
269 storedLogLikelihood = logLikelihood;
270 storedTruncationSum = truncationSum;
271 storedThresholdSum = thresholdSum;
272 storedSumOfSquaredResiduals = sumOfSquaredResiduals;
273 }
274
275 @Override
276 protected void restoreState() {
277 double[] tmp = storedDistances;
278 storedDistances = distances;
279 distances = tmp;
280 distancesKnown = true;
281
282 tmp = storedTruncations;
283 storedTruncations = truncations;
284 truncations = tmp;
285
286 tmp = storedThresholds;
287 storedThresholds = thresholds;
288 thresholds = tmp;
289
290 logLikelihood = storedLogLikelihood;
291 likelihoodKnown = true;
292
293 truncationSum = storedTruncationSum;
294 truncationsKnown = true;
295
296 thresholdSum = storedThresholdSum;
297 thresholdsKnown = true;
298
299 sumOfSquaredResiduals = storedSumOfSquaredResiduals;
300 residualsKnown = true;
301 }
302
303 @Override
304 protected void acceptState() {
305 // do nothing
306 }
307
308 public void makeDirty() {
309 distancesKnown = false;
310 likelihoodKnown = false;
311 residualsKnown = false;
312 truncationsKnown = false;
313 thresholdsKnown = false;
314
315 for (int i = 0; i < locationUpdated.length; i++) {
316 locationUpdated[i] = true;
317 }
318 for (int i = 0; i < distanceUpdated.length; i++) {
319 distanceUpdated[i] = true;
320 }
321 }
322
323 public Model getModel() {
324 return this;
325 }
326
327 public double getLogLikelihood() {
328 if (!likelihoodKnown) {
329 if (!distancesKnown) {
330 calculateDistances();
331 residualsKnown = false;
332 }
333
334 logLikelihood = computeLogLikelihood();
335
336 for (int i = 0; i < locationUpdated.length; i++) {
337 locationUpdated[i] = false;
338 }
339 for (int i = 0; i < distanceUpdated.length; i++) {
340 distanceUpdated[i] = false;
341 }
342 }
343
344 return logLikelihood;
345 }
346
347 // This function can be overwritten to implement other sampling densities, i.e. discrete ranks
348 protected double computeLogLikelihood() {
349
350 double precision = mdsPrecisionParameter.getParameterValue(0);
351
352 if (!residualsKnown) {
353 sumOfSquaredResiduals = calculateSumOfSquaredResiduals();
354 }
355
356 // totalNonMissingCount should be totalObservedCount (not > or < threshold)
357 double logLikelihood = (0.5 * Math.log(precision) * pointObservationCount) - (0.5 * precision * sumOfSquaredResiduals);
358
359 if (thresholdCount > 0) {
360 if (!thresholdsKnown) {
361 thresholdSum = calculateThresholdObservations(precision);
362 }
363 logLikelihood += thresholdSum;
364 }
365
366 if (isLeftTruncated) {
367 if (!truncationsKnown) {
368 calculateTruncations(precision);
369 }
370 truncationSum = calculateTruncationSum();
371 logLikelihood -= truncationSum;
372 }
373 likelihoodKnown = true;
374
375 return logLikelihood;
376 }
377
378 protected double calculateThresholdObservations(double precision) {
379 double sum = 0.0;
380 double sd = 1.0 / Math.sqrt(precision);
381 int j = 0;
382 for (int i = 0; i < upperThresholdCount; i++) {
383 int observationIndex = upperThresholdIndices[i];
384 int dist = getDistanceIndexForObservation(observationIndex);
385 if (dist != -1) {
386 if (distanceUpdated[dist]) {
387 // double cdf = NormalDistribution.cdf(observations[observationIndex], distances[dist], sd, false);
388 // double tail = 1.0 - cdf;
389 // using special tail function of NormalDistribution (see main() in NormalDistribution for test)
390 double tail = NormalDistribution.tailCDF(observations[observationIndex], distances[dist], sd);
391 thresholds[j] = Math.log(tail);
392 }
393 } else {
394 // -1 denotes a distance to self (i.e., 0)
395 double tail = NormalDistribution.tailCDF(observations[observationIndex], 0.0, sd);
396 thresholds[j] = Math.log(tail);
397 }
398
399 if (Double.isInfinite(thresholds[j])) {
400 System.out.println("Error calculation threshold probability");
401 }
402
403 sum += thresholds[j];
404 j++;
405 }
406 for (int i = 0; i < lowerThresholdCount; i++) {
407 int observationIndex = lowerThresholdIndices[i];
408 int dist = getDistanceIndexForObservation(observationIndex);
409
410 if (dist != -1) {
411 if (distanceUpdated[dist]) {
412 thresholds[j] = NormalDistribution.cdf(observations[observationIndex], distances[dist], sd, true);
413 }
414 } else {
415 // -1 denotes a distance to self (i.e., 0)
416 thresholds[j] = NormalDistribution.cdf(observations[observationIndex], 0.0, sd, true);
417 }
418
419 if (Double.isInfinite(thresholds[j])) {
420 System.out.println("Error calculation threshold probability");
421 }
422
423 sum += thresholds[j];
424 j++;
425 }
426
427 thresholdsKnown = true;
428
429 return sum;
430 }
431
432 protected void calculateTruncations(double precision) {
433 double sd = 1.0 / Math.sqrt(precision);
434 for (int i = 0; i < distanceCount; i++) {
435 if (distanceUpdated[i]) {
436 truncations[i] = NormalDistribution.cdf(distances[i], 0.0, sd, true);
437 }
438 }
439 truncationsKnown = true;
440 }
441
442 protected double calculateTruncationSum() {
443 double sum = 0.0;
444 for (int i = 0; i < observationCount; i++) {
445 int dist = getDistanceIndexForObservation(i);
446 if (dist != -1) {
447 sum += truncations[dist];
448 } else {
449 sum += Math.log(0.5);
450 }
451 }
452 return sum;
453 }
454
455 protected double calculateSumOfSquaredResiduals() {
456 double sum = 0.0;
457 for (int i = 0; i < observationCount; i++) {
458 if (observationTypes[i] == ObservationType.POINT) {
459 // Only increment sum if dataTable[i][j] is observed (not > or < threshold)
460 double residual;
461 int dist = getDistanceIndexForObservation(i);
462 if (dist == -1) {
463 // -1 denotes a distance to self (i.e., 0)
464 residual = - observations[i];
465 } else {
466 residual = distances[dist] - observations[i];
467 }
468 sum += residual * residual;
469 }
470 }
471 residualsKnown = true;
472 return sum;
473 }
474
475 protected void calculateDistances() {
476 int k = 0;
477 for (int x = 0; x < locationCount; x++) {
478 for (int y = x + 1; y < locationCount; y++) {
479 // the diagonal (x=y) is always zero so don't update it
480 if (locationUpdated[x] || locationUpdated[y]) {
481 distances[k] = calculateDistance(
482 locationsParameter.getParameter(x),
483 locationsParameter.getParameter(y));
484 distanceUpdated[k] = true;
485 }
486 k++;
487 }
488 }
489 distancesKnown = true;
490 }
491
492 private int getDistanceIndexForObservation(final int observationIndex) {
493 int row = getLocationIndex(rowLocationIndices[observationIndex]);
494 int col = getLocationIndex(columnLocationIndices[observationIndex]);
495
496 if (row == col) {
497 return -1;
498 }
499
500 // make sure row index is less than column index
501 if (row > col) {
502 int tmp = row;
503 row = col;
504 col = tmp;
505 }
506
507 // get the index of [row, col] in an unrolled upper triangular matrix
508 int index = 0;
509 for (int x = 0; x < row; x++) {
510 index += locationCount - x - 1;
511 }
512 index += col - row - 1;
513
514 return index;
515 }
516
517 /**
518 * Returns the index of the given by index
519 * Overriding this allows the clustering of locations
520 * @param index
521 * @return
522 */
523 protected int getLocationIndex(int index) {
524 return index;
525 }
526
527 public String[] getLocationLabels() {
528 return locationLabels;
529 }
530
531 protected double calculateDistance(Parameter X, Parameter Y) {
532 double sum = 0.0;
533 for (int i = 0; i < mdsDimension; i++) {
534 double difference = X.getParameterValue(i) - Y.getParameterValue(i);
535 sum += difference * difference;
536 }
537 return Math.sqrt(sum);
538 }
539
540 public int getMDSDimension() {
541 return mdsDimension;
542 }
543
544 public int getLocationCount() {
545 return locationCount;
546 }
547
548 public MatrixParameter getLocationsParameter() {
549 return locationsParameter;
550 }
551
552 public class Distances extends Statistic.Abstract {
553
554 public Distances() {
555 super("distances");
556 }
557
558 public int getDimension() {
559 return distanceCount;
560 }
561
562 public double getStatisticValue(int i) {
563 if (!distancesKnown) {
564 calculateDistances();
565 }
566 return distances[i];
567 }
568
569 }
570
571 // **************************************************************
572 // XMLObjectParser
573 // **************************************************************
574
575 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
576 public final static String FILE_NAME = "fileName";
577
578 public final static String TIP_TRAIT = "tipTrait";
579 public final static String LOCATIONS = "locations";
580 public static final String MDS_DIMENSION = "mdsDimension";
581 public static final String MDS_PRECISION = "mdsPrecision";
582
583 public String getParserName() {
584 return MULTIDIMENSIONAL_SCALING_LIKELIHOOD;
585 }
586
587 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
588
589 String fileName = xo.getStringAttribute(FILE_NAME);
590 DataTable<double[]> distanceTable;
591 try {
592 distanceTable = DataTable.Double.parse(new FileReader(fileName));
593 } catch (IOException e) {
594 throw new XMLParseException("Unable to read assay data from file: " + e.getMessage());
595 }
596
597 if (distanceTable.getRowCount() != distanceTable.getColumnCount()) {
598 throw new XMLParseException("Data table is not symmetrical.");
599 }
600
601 int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION);
602
603 MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS);
604
605 Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION);
606
607 boolean isLeftTruncated = false;
608
609 return new MultidimensionalScalingLikelihood(mdsDimension, isLeftTruncated, mdsPrecision, locationsParameter, distanceTable);
610 }
611
612 //************************************************************************
613 // AbstractXMLObjectParser implementation
614 //************************************************************************
615
616 public String getParserDescription() {
617 return "Provides the likelihood of pairwise distance given vectors of coordinates" +
618 "for points according to the multidimensional scaling scheme of XXX & Rafferty (xxxx).";
619 }
620
621 public XMLSyntaxRule[] getSyntaxRules() {
622 return rules;
623 }
624
625 private final XMLSyntaxRule[] rules = {
626 AttributeRule.newStringRule(FILE_NAME, false, "The name of the file containing the assay table"),
627 AttributeRule.newIntegerRule(MDS_DIMENSION, false, "The dimension of the space for MDS"),
628 new ElementRule(LOCATIONS, MatrixParameter.class),
629 new ElementRule(MDS_PRECISION, Parameter.class)
630 };
631
632 public Class getReturnType() {
633 return MultidimensionalScalingLikelihood.class;
634 }
635 };
636
637 private int distanceCount;
638 private int observationCount;
639 private int upperThresholdCount;
640 private int lowerThresholdCount;
641 private int pointObservationCount;
642 private int thresholdCount;
643
644
645 private String[] locationLabels;
646
647 private int locationCount;
648
649 private double[] observations;
650 private ObservationType[] observationTypes;
651 // protected int[] distanceIndices;
652 private int[] rowLocationIndices;
653 private int[] columnLocationIndices;
654 private int[] upperThresholdIndices;
655 private int[] lowerThresholdIndices;
656 private int[] pointObservationIndices;
657
658 private MatrixParameter locationsParameter;
659 private Parameter mdsPrecisionParameter;
660
661 private boolean likelihoodKnown = false;
662 private double logLikelihood;
663 private double storedLogLikelihood;
664
665 protected boolean distancesKnown = false;
666 private double sumOfSquaredResiduals;
667 private double storedSumOfSquaredResiduals;
668 private double[] distances;
669 private double[] storedDistances;
670
671 protected boolean[] locationUpdated;
672 protected boolean[] distanceUpdated;
673
674 protected boolean residualsKnown = false;
675
676 protected boolean truncationsKnown = false;
677 private double truncationSum;
678 private double storedTruncationSum;
679 private double[] truncations;
680 private double[] storedTruncations;
681
682 protected boolean thresholdsKnown = false;
683 private double thresholdSum;
684 private double storedThresholdSum;
685 private double[] thresholds;
686 private double[] storedThresholds;
687
688 private boolean isLeftTruncated;
689 private int mdsDimension;
690 }