Debian Codegraph @

src/dr/evomodel/coalescent/GMRFSkyrideLikelihood.java

raw symbols SCIP
1 /*
2 * GMRFSkyrideLikelihood.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.coalescent;
27
28 import dr.evolution.coalescent.IntervalType;
29 import dr.evolution.tree.NodeRef;
30 import dr.evolution.tree.Tree;
31 import dr.evomodel.tree.TreeModel;
32 import dr.evomodelxml.coalescent.GMRFSkyrideLikelihoodParser;
33 import dr.inference.model.MatrixParameter;
34 import dr.inference.model.Parameter;
35 import dr.inference.model.Variable;
36 import dr.math.MathUtils;
37 import dr.util.Author;
38 import dr.util.Citable;
39 import dr.util.Citation;
40 import no.uib.cipr.matrix.DenseVector;
41 import no.uib.cipr.matrix.NotConvergedException;
42 import no.uib.cipr.matrix.SymmTridiagEVD;
43 import no.uib.cipr.matrix.SymmTridiagMatrix;
44
45 import java.util.ArrayList;
46 import java.util.Collections;
47 import java.util.List;
48
49 /**
50 * A likelihood function for a Gaussian Markov random field on a log population size trajectory.
51 *
52 * @author Jen Tom
53 * @author Erik Bloomquist
54 * @author Vladimir Minin
55 * @author Marc Suchard
56 * @version $Id: GMRFSkylineLikelihood.java,v 1.3 2007/03/20 22:40:04 msuchard Exp $
57 */
58 public class GMRFSkyrideLikelihood extends OldAbstractCoalescentLikelihood implements CoalescentIntervalProvider, Citable {
59
60 // PUBLIC STUFF
61
62 public static final double LOG_TWO_TIMES_PI = 1.837877;
63 public static final boolean TIME_AWARE_IS_ON_BY_DEFAULT = true;
64
65 // PRIVATE STUFF
66
67 protected Parameter popSizeParameter;
68 protected Parameter groupSizeParameter;
69 protected Parameter precisionParameter;
70 protected Parameter lambdaParameter;
71 protected Parameter betaParameter;
72 // protected double[] gmrfWeights;
73 protected int fieldLength;
74 protected double[] coalescentIntervals;
75 protected double[] storedCoalescentIntervals;
76 protected double[] sufficientStatistics;
77 protected double[] storedSufficientStatistics;
78
79
80 //changed from private to protected
81 protected double logFieldLikelihood;
82 protected double storedLogFieldLikelihood;
83
84 protected SymmTridiagMatrix weightMatrix;
85 protected SymmTridiagMatrix storedWeightMatrix;
86 protected MatrixParameter dMatrix;
87 protected boolean timeAwareSmoothing = TIME_AWARE_IS_ON_BY_DEFAULT;
88 protected boolean rescaleByRootHeight;
89
90 public GMRFSkyrideLikelihood() {
91 super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD);
92 }
93
94 public GMRFSkyrideLikelihood(String name) {
95 super(name);
96 }
97
98 public GMRFSkyrideLikelihood(Tree tree, Parameter popParameter, Parameter groupParameter, Parameter precParameter,
99 Parameter lambda, Parameter beta, MatrixParameter dMatrix,
100 boolean timeAwareSmoothing, boolean rescaleByRootHeight) {
101 this(wrapTree(tree), popParameter, groupParameter, precParameter, lambda, beta, dMatrix, timeAwareSmoothing,
102 rescaleByRootHeight);
103 }
104
105 private static List<Tree> wrapTree(Tree tree) {
106 List<Tree> treeList = new ArrayList<Tree>();
107 treeList.add(tree);
108 return treeList;
109 }
110
111 public GMRFSkyrideLikelihood(List<Tree> treeList, Parameter popParameter, Parameter groupParameter, Parameter precParameter,
112 Parameter lambda, Parameter beta, MatrixParameter dMatrix,
113 boolean timeAwareSmoothing, boolean rescaleByRootHeight) {
114
115 super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD);
116
117 // adding the key word to the the model means the keyword will be logged in the
118 // header of the logfile.
119 this.addKeyword("skyride");
120
121 this.popSizeParameter = popParameter;
122 this.groupSizeParameter = groupParameter;
123 this.precisionParameter = precParameter;
124 this.lambdaParameter = lambda;
125 this.betaParameter = beta;
126 this.dMatrix = dMatrix;
127 this.timeAwareSmoothing = timeAwareSmoothing;
128 this.rescaleByRootHeight = rescaleByRootHeight;
129
130 addVariable(popSizeParameter);
131 addVariable(precisionParameter);
132 addVariable(lambdaParameter);
133 if (betaParameter != null) {
134 addVariable(betaParameter);
135 }
136
137 setTree(treeList);
138
139 int correctFieldLength = getCorrectFieldLength();
140
141 if (popSizeParameter.getDimension() <= 1) {
142 // popSize dimension hasn't been set yet, set it here:
143 popSizeParameter.setDimension(correctFieldLength);
144 }
145
146 fieldLength = popSizeParameter.getDimension();
147 if (correctFieldLength != fieldLength) {
148 throw new IllegalArgumentException("Population size parameter should have length " + correctFieldLength);
149 }
150
151 // Field length must be set by this point
152 wrapSetupIntervals();
153 coalescentIntervals = new double[fieldLength];
154 storedCoalescentIntervals = new double[fieldLength];
155 sufficientStatistics = new double[fieldLength];
156 storedSufficientStatistics = new double[fieldLength];
157
158 setupGMRFWeights();
159
160 addStatistic(new DeltaStatistic());
161
162 initializationReport();
163
164 /* Force all entries in groupSizeParameter = 1 for compatibility with Tracer */
165 if (groupSizeParameter != null) {
166 for (int i = 0; i < groupSizeParameter.getDimension(); i++)
167 groupSizeParameter.setParameterValue(i, 1.0);
168 }
169 }
170
171 protected int getCorrectFieldLength() {
172 return tree.getExternalNodeCount() - 1;
173 }
174
175 protected void wrapSetupIntervals() {
176 setupIntervals();
177 }
178
179 protected void setTree(List<Tree> treeList) {
180 if (treeList.size() != 1) {
181 throw new RuntimeException("GMRFSkyrideLikelihood only implemented for one tree");
182 }
183 this.tree = treeList.get(0);
184 this.treesSet = null;
185 if (tree instanceof TreeModel) {
186 addModel((TreeModel) tree);
187 }
188 }
189
190 // public double[] getCopyOfCoalescentIntervals() {
191 // return coalescentIntervals.clone();
192 // }
193 //
194 // public double[] getCoalescentIntervals() {
195 // return coalescentIntervals;
196 // }
197
198 public void initializationReport() {
199 System.out.println("Creating a GMRF smoothed skyride model:");
200 System.out.println("\tPopulation sizes: " + popSizeParameter.getDimension());
201 System.out.println("\tIf you publish results using this model, please reference: Minin, Bloomquist and Suchard (2008) Molecular Biology and Evolution, 25, 1459-1471.");
202 }
203
204 public static void checkTree(TreeModel treeModel) {
205
206 // todo Should only be run if there exists a zero-length interval
207
208 // TreeModel treeModel = (TreeModel) tree;
209 for (int i = 0; i < treeModel.getInternalNodeCount(); i++) {
210 NodeRef node = treeModel.getInternalNode(i);
211 if (node != treeModel.getRoot()) {
212 double parentHeight = treeModel.getNodeHeight(treeModel.getParent(node));
213 double childHeight0 = treeModel.getNodeHeight(treeModel.getChild(node, 0));
214 double childHeight1 = treeModel.getNodeHeight(treeModel.getChild(node, 1));
215 double maxChild = childHeight0;
216 if (childHeight1 > maxChild)
217 maxChild = childHeight1;
218 double newHeight = maxChild + MathUtils.nextDouble() * (parentHeight - maxChild);
219 treeModel.setNodeHeight(node, newHeight);
220 }
221 }
222 treeModel.pushTreeChangedEvent();
223
224 }
225
226 // **************************************************************
227 // Likelihood IMPLEMENTATION
228 // **************************************************************
229
230 public double getLogLikelihood() {
231 if (!likelihoodKnown) {
232 logLikelihood = calculateLogCoalescentLikelihood();
233 logFieldLikelihood = calculateLogFieldLikelihood();
234 likelihoodKnown = true;
235 }
236 return logLikelihood + logFieldLikelihood;
237 }
238
239 protected double peakLogCoalescentLikelihood() {
240 return logLikelihood;
241 }
242
243 protected double peakLogFieldLikelihood() {
244 return logFieldLikelihood;
245 }
246
247 public double[] getSufficientStatistics() {
248 return sufficientStatistics;
249 }
250
251 public String toString() {
252 return getId() + "(" + Double.toString(getLogLikelihood()) + ")";
253 }
254
255 protected void setupSufficientStatistics() {
256 int index = 0;
257
258 double length = 0;
259 double weight = 0;
260 for (int i = 0; i < getIntervalCount(); i++) {
261 length += getInterval(i);
262 weight += getInterval(i) * getLineageCount(i) * (getLineageCount(i) - 1);
263 if (getIntervalType(i) == CoalescentEventType.COALESCENT) {
264 coalescentIntervals[index] = length;
265 sufficientStatistics[index] = weight / 2.0;
266 index++;
267 length = 0;
268 weight = 0;
269 }
270 }
271 }
272
273 protected double getFieldScalar() {
274 final double rootHeight;
275 if (rescaleByRootHeight) {
276 rootHeight = tree.getNodeHeight(tree.getRoot());
277 } else {
278 rootHeight = 1.0;
279 }
280 return rootHeight;
281 }
282
283 protected void setupGMRFWeights() {
284
285 setupSufficientStatistics();
286
287 //Set up the weight Matrix
288 double[] offdiag = new double[fieldLength - 1];
289 double[] diag = new double[fieldLength];
290
291 //First set up the offdiagonal entries;
292
293 if (!timeAwareSmoothing) {
294 for (int i = 0; i < fieldLength - 1; i++) {
295 offdiag[i] = -1.0;
296 }
297
298
299 } else {
300 for (int i = 0; i < fieldLength - 1; i++) {
301 offdiag[i] = -2.0 / (coalescentIntervals[i] + coalescentIntervals[i + 1]) * getFieldScalar();
302 }
303 }
304
305 //Then set up the diagonal entries;
306 for (int i = 1; i < fieldLength - 1; i++)
307 diag[i] = -(offdiag[i] + offdiag[i - 1]);
308
309 //Take care of the endpoints
310 diag[0] = -offdiag[0];
311 diag[fieldLength - 1] = -offdiag[fieldLength - 2];
312
313 weightMatrix = new SymmTridiagMatrix(diag, offdiag);
314 }
315
316
317 public SymmTridiagMatrix getScaledWeightMatrix(double precision) {
318 SymmTridiagMatrix a = weightMatrix.copy();
319 for (int i = 0; i < a.numRows() - 1; i++) {
320 a.set(i, i, a.get(i, i) * precision);
321 a.set(i + 1, i, a.get(i + 1, i) * precision);
322 }
323 a.set(fieldLength - 1, fieldLength - 1, a.get(fieldLength - 1, fieldLength - 1) * precision);
324 return a;
325 }
326
327 public SymmTridiagMatrix getStoredScaledWeightMatrix(double precision) {
328 SymmTridiagMatrix a = storedWeightMatrix.copy();
329 for (int i = 0; i < a.numRows() - 1; i++) {
330 a.set(i, i, a.get(i, i) * precision);
331 a.set(i + 1, i, a.get(i + 1, i) * precision);
332 }
333 a.set(fieldLength - 1, fieldLength - 1, a.get(fieldLength - 1, fieldLength - 1) * precision);
334 return a;
335 }
336
337 public SymmTridiagMatrix getScaledWeightMatrix(double precision, double lambda) {
338 if (lambda == 1)
339 return getScaledWeightMatrix(precision);
340
341 SymmTridiagMatrix a = weightMatrix.copy();
342 for (int i = 0; i < a.numRows() - 1; i++) {
343 a.set(i, i, precision * (1 - lambda + lambda * a.get(i, i)));
344 a.set(i + 1, i, a.get(i + 1, i) * precision * lambda);
345 }
346
347 a.set(fieldLength - 1, fieldLength - 1, precision * (1 - lambda + lambda * a.get(fieldLength - 1, fieldLength - 1)));
348 return a;
349 }
350
351 private void makeIntervalsKnown() {
352 if (!intervalsKnown) {
353 wrapSetupIntervals();
354 setupGMRFWeights();
355 intervalsKnown = true;
356 }
357 }
358
359 public int getCoalescentIntervalDimension() {
360 makeIntervalsKnown();
361 return coalescentIntervals.length;
362 }
363
364 public double getCoalescentInterval(int i) {
365 makeIntervalsKnown();
366 return coalescentIntervals[i];
367 }
368
369 /*public int getCoalescentIntervalLineageCount(int i) {
370 throw new RuntimeException("Not yet implemented");
371 }
372
373 public IntervalType getCoalescentIntervalType(int i) {
374 throw new RuntimeException("getCoalescentIntervalType(int i) in GMRFSkyrideLikelihood not yet implemented");
375 }*/
376
377 public int getNumberOfCoalescentEvents() {
378 return tree.getExternalNodeCount() - 1;
379 }
380
381 public double getCoalescentEventsStatisticValue(int i) {
382 return sufficientStatistics[i];
383 }
384
385 public double[] getCoalescentIntervalHeights() {
386 makeIntervalsKnown();
387 double[] a = new double[coalescentIntervals.length];
388
389 a[0] = coalescentIntervals[0];
390
391 for (int i = 1; i < a.length; i++) {
392 a[i] = a[i - 1] + coalescentIntervals[i];
393 }
394 return a;
395 }
396
397 public SymmTridiagMatrix getCopyWeightMatrix() {
398 return weightMatrix.copy();
399 }
400
401 public SymmTridiagMatrix getStoredScaledWeightMatrix(double precision, double lambda) {
402 if (lambda == 1)
403 return getStoredScaledWeightMatrix(precision);
404
405 SymmTridiagMatrix a = storedWeightMatrix.copy();
406 for (int i = 0; i < a.numRows() - 1; i++) {
407 a.set(i, i, precision * (1 - lambda + lambda * a.get(i, i)));
408 a.set(i + 1, i, a.get(i + 1, i) * precision * lambda);
409 }
410
411 a.set(fieldLength - 1, fieldLength - 1, precision * (1 - lambda + lambda * a.get(fieldLength - 1, fieldLength - 1)));
412 return a;
413 }
414
415
416 protected void storeState() {
417 super.storeState();
418 System.arraycopy(coalescentIntervals, 0, storedCoalescentIntervals, 0, coalescentIntervals.length);
419 System.arraycopy(sufficientStatistics, 0, storedSufficientStatistics, 0, sufficientStatistics.length);
420 storedWeightMatrix = weightMatrix.copy();
421 storedLogFieldLikelihood = logFieldLikelihood;
422 }
423
424
425 protected void restoreState() {
426 super.restoreState();
427 // TODO Just swap pointers
428 System.arraycopy(storedCoalescentIntervals, 0, coalescentIntervals, 0, storedCoalescentIntervals.length);
429 System.arraycopy(storedSufficientStatistics, 0, sufficientStatistics, 0, storedSufficientStatistics.length);
430 weightMatrix = storedWeightMatrix;
431 logFieldLikelihood = storedLogFieldLikelihood;
432 }
433
434 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
435 likelihoodKnown = false;
436 // Parameters (precision and popsizes do not change intervals or GMRF Q matrix
437 }
438
439 /**
440 * Calculates the log likelihood of this set of coalescent intervals,
441 * given a demographic model.
442 *
443 * @return coalescent part of density
444 */
445 protected double calculateLogCoalescentLikelihood() {
446 makeIntervalsKnown();
447
448 // Matrix operations taken from block update sampler to calculate data likelihood and field prior
449
450 double currentLike = 0;
451 double[] currentGamma = popSizeParameter.getParameterValues();
452
453 for (int i = 0; i < fieldLength; i++) {
454 currentLike += -currentGamma[i] - sufficientStatistics[i] * Math.exp(-currentGamma[i]);
455 }
456
457 return currentLike;// + LogNormalDistribution.logPdf(Math.exp(popSizeParameter.getParameterValue(coalescentIntervals.length - 1)), mu, sigma);
458 }
459
460 protected double calculateLogFieldLikelihood() {
461 makeIntervalsKnown();
462
463 double currentLike = 0;
464 DenseVector diagonal1 = new DenseVector(fieldLength);
465 DenseVector currentGamma = new DenseVector(popSizeParameter.getParameterValues());
466
467 SymmTridiagMatrix currentQ = getScaledWeightMatrix(precisionParameter.getParameterValue(0), lambdaParameter.getParameterValue(0));
468 currentQ.mult(currentGamma, diagonal1);
469
470 // currentLike += 0.5 * logGeneralizedDeterminant(currentQ) - 0.5 * currentGamma.dot(diagonal1);
471
472 currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * currentGamma.dot(diagonal1);
473 if (lambdaParameter.getParameterValue(0) == 1) {
474 currentLike -= (fieldLength - 1) / 2.0 * LOG_TWO_TIMES_PI;
475 } else {
476 currentLike -= fieldLength / 2.0 * LOG_TWO_TIMES_PI;
477 }
478
479 return currentLike;
480 }
481
482
483 // public static double logGeneralizedDeterminant(SymmTridiagMatrix X) {
484 // //Set up the eigenvalue solver
485 // SymmTridiagEVD eigen = new SymmTridiagEVD(X.numRows(), false);
486 // //Solve for the eigenvalues
487 // try {
488 // eigen.factor(X);
489 // } catch (NotConvergedException e) {
490 // throw new RuntimeException("Not converged error in generalized determinate calculation.\n" + e.getMessage());
491 // }
492 //
493 // //Get the eigenvalues
494 // double[] x = eigen.getEigenvalues();
495 //
496 // double a = 0;
497 // for (double d : x) {
498 // if (d > 0.00001)
499 // a += Math.log(d);
500 // }
501 //
502 // return a;
503 // }
504
505
506 public Parameter getPrecisionParameter() {
507 return precisionParameter;
508 }
509
510 public Parameter getPopSizeParameter() {
511 return popSizeParameter;
512 }
513
514 public Parameter getLambdaParameter() {
515 return lambdaParameter;
516 }
517
518 public SymmTridiagMatrix getWeightMatrix() {
519 return weightMatrix.copy();
520 }
521
522 public Parameter getBetaParameter() {
523 return betaParameter;
524 }
525
526 public MatrixParameter getDesignMatrix() {
527 return dMatrix;
528 }
529
530 public double calculateWeightedSSE() {
531 double weightedSSE = 0;
532 double currentPopSize = popSizeParameter.getParameterValue(0);
533 double currentInterval = coalescentIntervals[0];
534 for (int j = 1; j < fieldLength; j++) {
535 double nextPopSize = popSizeParameter.getParameterValue(j);
536 double nextInterval = coalescentIntervals[j];
537 double delta = nextPopSize - currentPopSize;
538 double weight = (currentInterval + nextInterval) / 2.0;
539 weightedSSE += delta * delta / weight;
540 currentPopSize = nextPopSize;
541 currentInterval = nextInterval;
542 }
543 return weightedSSE;
544
545 }
546
547 @Override
548 public Citation.Category getCategory() {
549 return Citation.Category.TREE_PRIORS;
550 }
551
552 @Override
553 public String getDescription() {
554 return "Skyride coalescent";
555 }
556
557 @Override
558 public List<Citation> getCitations() {
559 return Collections.singletonList(CITATION);
560 }
561
562 public static Citation CITATION = new Citation(
563 new Author[]{
564 new Author("VN", "Minin"),
565 new Author("EW", "Bloomquist"),
566 new Author("MA", "Suchard")
567 },
568 "Smooth skyride through a rough skyline: Bayesian coalescent-based inference of population dynamics",
569 2008,
570 "Mol Biol Evol",
571 25, 1459, 1471,
572 "10.1093/molbev/msn090"
573 );
574 }
575
576 /*
577
578 WinBUGS code to fixed tree: (A:4.0,(B:2.0,(C:0.5,D:1.0):1.0):2.0)
579
580 model {
581
582 stat1 ~ dexp(rate[1])
583 stat2 ~ dexp(rate[2])
584 stat3 ~ dexp(rate[3])
585
586 rate[1] <- 1 / exp(theta[1])
587 rate[2] <- 1 / exp(theta[2])
588 rate[3] <- 1 / exp(theta[3])
589
590 theta[1] ~ dnorm(0, 0.001)
591 theta[2] ~ dnorm(theta[1], weight[1])
592 theta[3] ~ dnorm(theta[2], weight[2])
593
594 weight[1] <- tau / 1.0
595 weight[2] <- tau / 1.5
596
597 tau ~ dgamma(1,0.3333)
598
599 stat1 <- 9 / 2
600 stat2 <- 6 / 2
601 stat3 <- 4 / 2
602
603 }
604 */