Debian Codegraph @

src/dr/evomodel/coalescent/GMRFMultilocusSkyrideLikelihood.java

raw symbols SCIP
1 /*
2 * GMRFMultilocusSkyrideLikelihood.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 com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParameterList;
29 import dr.evolution.coalescent.IntervalType;
30 import dr.evolution.coalescent.TreeIntervals;
31 import dr.evolution.tree.Tree;
32 import dr.evomodel.tree.TreeModel;
33 import dr.evomodelxml.coalescent.GMRFSkyrideLikelihoodParser;
34 import dr.inference.model.MatrixParameter;
35 import dr.inference.model.Model;
36 import dr.inference.model.Parameter;
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.SymmTridiagMatrix;
42
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Collections;
46 import java.util.List;
47
48 /**
49 * @author Mandev Gill
50 * @author Marc A. Suchard
51 */
52
53 public class GMRFMultilocusSkyrideLikelihood extends GMRFSkyrideLikelihood
54 implements MultiLociTreeSet, CoalescentIntervalProvider, Citable {
55
56 public static final boolean DEBUG = false;
57
58 private double cutOff;
59 private int numGridPoints;
60 protected int oldFieldLength;
61 // number of coalescent events which occur in an interval with constant population size
62 protected double[] numCoalEvents;
63 protected double[] storedNumCoalEvents;
64 protected double[] gridPoints;
65 protected double theLastTime;
66 protected double diagonalValue;
67 // sortedPoints[i][0] is the time of the i-th grid point or sampling or coalescent event
68 // sortedPoints[i][1] is 0 if the i-th point is a grid point, 1 if it's a sampling point, and 2 if it's a coalescent point
69 // sortedPoints[i][2] is the number of lineages present in the interval starting at time sortedPoints[i][0]
70
71 protected Parameter phiParameter;
72 protected Parameter ploidyFactors;
73 protected double[] ploidySums;
74 protected double[] storedPloidySums;
75 protected SymmTridiagMatrix precMatrix;
76 protected SymmTridiagMatrix storedPrecMatrix;
77 private SkygridHelper skygridHelper;
78 protected List<Parameter> missingCov;
79 protected List<MatrixParameter> covariates;
80 protected List<Parameter> beta;
81 protected List<Parameter> covPrecParametersRecent;
82 protected List<Parameter> covPrecParametersDistant;
83 protected List<SymmTridiagMatrix> weightMatricesForMissingCovRecent;
84 protected List<SymmTridiagMatrix> weightMatricesForMissingCovDistant;
85 protected int[] firstObservedIndex;
86 protected int[] lastObservedIndex;
87
88 private double[] coalescentEventStatisticValues;
89
90 public GMRFMultilocusSkyrideLikelihood(List<Tree> treeList,
91 Parameter popParameter,
92 Parameter groupParameter,
93 Parameter precParameter,
94 Parameter lambda,
95 Parameter beta,
96 MatrixParameter dMatrix,
97 boolean timeAwareSmoothing,
98 double cutOff,
99 int numGridPoints,
100 Parameter phi,
101 Parameter ploidyFactorsParameter) {
102
103 super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD);
104
105 // adding the key word to the the model means the keyword will be logged in the
106 // header of the logfile.
107 this.addKeyword("skygrid");
108 if (treeList.size() > 1) {
109 this.addKeyword("multilocus");
110 }
111
112 this.popSizeParameter = popParameter;
113 this.groupSizeParameter = groupParameter;
114 this.precisionParameter = precParameter;
115 this.lambdaParameter = lambda;
116 this.betaParameter = beta;
117 this.dMatrix = dMatrix;
118 if (dMatrix != null) {
119 addVariable(dMatrix);
120 }
121 this.timeAwareSmoothing = timeAwareSmoothing;
122
123 this.cutOff = cutOff;
124 this.numGridPoints = numGridPoints;
125 this.phiParameter = phi;
126 this.ploidyFactors = ploidyFactorsParameter;
127
128 setupGridPoints();
129
130 addVariable(popSizeParameter);
131 addVariable(precisionParameter);
132 addVariable(lambdaParameter);
133 if (betaParameter != null) {
134 addVariable(betaParameter);
135 skygridHelper = new SkygridCovariateHelper();
136 } else {
137 skygridHelper = new SkygridHelper();
138 }
139 if (phiParameter != null) {
140 addVariable(phiParameter);
141 }
142 addVariable(ploidyFactors);
143
144
145 setTree(treeList);
146
147 int correctFieldLength = getCorrectFieldLength();
148
149 if (popSizeParameter.getDimension() <= 1) {
150 // popSize dimension hasn't been set yet, set it here:
151 popSizeParameter.setDimension(correctFieldLength);
152 }
153
154 fieldLength = popSizeParameter.getDimension();
155 if (correctFieldLength != fieldLength) {
156 throw new IllegalArgumentException("Population size parameter should have length " + correctFieldLength);
157 }
158
159 oldFieldLength = getCorrectOldFieldLength();
160
161
162 if (ploidyFactors.getDimension() != treeList.size()) {
163 throw new IllegalArgumentException("Ploidy factors parameter should have length " + treeList.size());
164 }
165
166
167 // Field length must be set by this point
168 wrapSetupIntervals();
169
170 coalescentIntervals = new double[oldFieldLength];
171 storedCoalescentIntervals = new double[oldFieldLength];
172 sufficientStatistics = new double[fieldLength];
173 storedSufficientStatistics = new double[fieldLength];
174 numCoalEvents = new double[fieldLength];
175 storedNumCoalEvents = new double[fieldLength];
176 ploidySums = new double[fieldLength];
177 storedPloidySums = new double[fieldLength];
178
179 setupGMRFWeights();
180 setupSufficientStatistics();
181
182 addStatistic(new DeltaStatistic());
183
184 initializationReport();
185
186 /* Force all entries in groupSizeParameter = 1 for compatibility with Tracer */
187 if (groupSizeParameter != null) {
188 for (int i = 0; i < groupSizeParameter.getDimension(); i++)
189 groupSizeParameter.setParameterValue(i, 1.0);
190 }
191
192 this.coalescentEventStatisticValues = new double[getNumberOfCoalescentEvents()];
193
194 }
195
196
197 //rewrite this constructor without duplicating so much code
198 public GMRFMultilocusSkyrideLikelihood(List<Tree> treeList,
199 Parameter popParameter,
200 Parameter groupParameter,
201 Parameter precParameter,
202 Parameter lambda,
203 Parameter betaParameter,
204 MatrixParameter dMatrix,
205 boolean timeAwareSmoothing,
206 Parameter specGridPoints,
207 List<MatrixParameter> covariates,
208 Parameter ploidyFactorsParameter,
209 List<Parameter> firstObservedIndexParameter,
210 List<Parameter> lastObservedIndexParameter,
211 List<Parameter> covPrecParametersRecent,
212 List<Parameter> covPrecParametersDistant,
213 List<Parameter> betaList) {
214
215 super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD);
216
217 // adding the key word to the the model means the keyword will be logged in the
218 // header of the logfile.
219 this.addKeyword("skygrid");
220 if (treeList.size() > 1) {
221 this.addKeyword("multilocus");
222 }
223
224 this.gridPoints = specGridPoints.getParameterValues();
225 this.numGridPoints = gridPoints.length;
226 this.cutOff = gridPoints[numGridPoints - 1];
227
228 if (firstObservedIndexParameter != null) {
229 firstObservedIndex = new int[firstObservedIndexParameter.size()];
230 for (int i = 0; i < firstObservedIndexParameter.size(); i++) {
231 this.firstObservedIndex[i] = (int) firstObservedIndexParameter.get(i).getParameterValue(0);
232 }
233 }
234
235 if (lastObservedIndexParameter != null) {
236 lastObservedIndex = new int[lastObservedIndexParameter.size()];
237 for (int i = 0; i < lastObservedIndexParameter.size(); i++) {
238 this.lastObservedIndex[i] = (int) lastObservedIndexParameter.get(i).getParameterValue(0);
239 }
240 }
241
242 /*else{
243 for(int i=0; i < beta.getDimension(); i++) {
244 this.lastObservedIndex[i] = popParameter.getDimension();
245 }
246 }*/
247
248 this.betaParameter = betaParameter;
249 if (betaParameter != null) {
250 addVariable(betaParameter);
251 }
252
253 this.popSizeParameter = popParameter;
254 this.groupSizeParameter = groupParameter;
255 this.precisionParameter = precParameter;
256 this.lambdaParameter = lambda;
257 this.beta = betaList;
258 this.dMatrix = dMatrix;
259 if (dMatrix != null) {
260 addVariable(dMatrix);
261 }
262 this.timeAwareSmoothing = timeAwareSmoothing;
263 this.ploidyFactors = ploidyFactorsParameter;
264 this.covariates = covariates;
265 if (covariates != null) {
266 for (MatrixParameter cov : covariates) {
267 addVariable(cov);
268 }
269 }
270 this.covPrecParametersRecent = covPrecParametersRecent;
271 if (covPrecParametersRecent != null) {
272 for (Parameter covPrecRecent : covPrecParametersRecent) {
273 addVariable(covPrecRecent);
274 }
275 }
276 this.covPrecParametersDistant = covPrecParametersDistant;
277 if (covPrecParametersDistant != null){
278 for(Parameter covPrecDistant : covPrecParametersDistant){
279 addVariable(covPrecDistant);
280 }
281 }
282
283 addVariable(popSizeParameter);
284 addVariable(precisionParameter);
285 addVariable(lambdaParameter);
286
287 addVariable(ploidyFactors);
288
289 setTree(treeList);
290
291 int correctFieldLength = getCorrectFieldLength();
292
293 if (popSizeParameter.getDimension() <= 1) {
294 // popSize dimension hasn't been set yet, set it here:
295 popSizeParameter.setDimension(correctFieldLength);
296 }
297
298 fieldLength = popSizeParameter.getDimension();
299 if (correctFieldLength != fieldLength) {
300 throw new IllegalArgumentException("Population size parameter should have length " + correctFieldLength);
301 }
302
303 oldFieldLength = getCorrectOldFieldLength();
304
305 if (ploidyFactors.getDimension() != treeList.size()) {
306 throw new IllegalArgumentException("Ploidy factor parameter should have length " + treeList.size());
307 }
308
309 // Field length must be set by this point
310
311 if (betaList != null || betaParameter != null) {
312 if (betaList != null) {
313 for (Parameter betaParam : betaList) {
314 addVariable(betaParam);
315 }
316 }
317 if (lastObservedIndexParameter != null || firstObservedIndexParameter != null) {
318 setupGMRFWeightsForMissingCov();
319 skygridHelper = new SkygridMissingCovariateHelper();
320 } else {
321 skygridHelper = new SkygridCovariateHelper();
322 }
323 } else {
324 skygridHelper = new SkygridHelper();
325 }
326
327 wrapSetupIntervals();
328 coalescentIntervals = new double[oldFieldLength];
329 storedCoalescentIntervals = new double[oldFieldLength];
330 sufficientStatistics = new double[fieldLength];
331 storedSufficientStatistics = new double[fieldLength];
332 numCoalEvents = new double[fieldLength];
333 storedNumCoalEvents = new double[fieldLength];
334 ploidySums = new double[fieldLength];
335 storedPloidySums = new double[fieldLength];
336
337 setupGMRFWeights();
338
339 addStatistic(new DeltaStatistic());
340
341 initializationReport();
342
343 }
344
345 protected void setTree(List<Tree> treeList) {
346 treesSet = this;
347 this.treeList = treeList;
348 makeTreeIntervalList(treeList, true);
349 numTrees = treeList.size();
350 }
351
352 private void makeTreeIntervalList(List<Tree> treeList, boolean add) {
353 if (intervalsList == null) {
354 intervalsList = new ArrayList<TreeIntervals>();
355 } else {
356 intervalsList.clear();
357 }
358 for (Tree tree : treeList) {
359 intervalsList.add(new TreeIntervals(tree));
360 if (add && tree instanceof TreeModel) {
361 addModel((TreeModel) tree);
362 }
363 }
364 }
365
366 protected int getCorrectFieldLength() {
367
368 return numGridPoints + 1;
369 }
370
371 protected int getCorrectOldFieldLength() {
372 int tips = 0;
373 for (Tree tree : treeList) {
374 tips += tree.getExternalNodeCount();
375 }
376 return tips - treeList.size();
377 }
378
379 protected void handleModelChangedEvent(Model model, Object object, int index) {
380
381 if (model instanceof TreeModel) {
382 TreeModel treeModel = (TreeModel) model;
383 int tn = treeList.indexOf(treeModel);
384 if (tn >= 0) {
385 // intervalsList.get(tn).setIntervalsUnknown(); // TODO Why is this slower (?) than remaking whole list?
386 makeTreeIntervalList(treeList, false);
387 intervalsKnown = false;
388 likelihoodKnown = false;
389 } else {
390 throw new RuntimeException("Unknown tree modified in GMRFMultilocusSkyrideLikelihood");
391 }
392 } else {
393 throw new RuntimeException("Unknown object modified in GMRFMultilocusSkyrideLikelihood");
394 }
395 }
396
397 public void initializationReport() {
398 System.out.println("Creating a GMRF smoothed skyride model for multiple loci (SkyGrid)");
399 System.out.println("\tPopulation sizes: " + popSizeParameter.getDimension());
400 }
401
402 public void wrapSetupIntervals() {
403 // Do nothing
404 }
405
406 int numTrees;
407
408
409 protected void setupGridPoints() {
410 if (gridPoints == null) {
411 gridPoints = new double[numGridPoints];
412 } else {
413 Arrays.fill(gridPoints, 0);
414 }
415
416 for (int pt = 0; pt < numGridPoints; pt++) {
417 gridPoints[pt] = (pt + 1) * (cutOff / numGridPoints);
418 }
419 }
420
421 protected void setupSufficientStatistics() {
422
423 //numCoalEvents = new double[fieldLength];
424 //sufficientStatistics = new double[fieldLength];
425
426 Arrays.fill(numCoalEvents, 0);
427 Arrays.fill(sufficientStatistics, 0);
428 Arrays.fill(ploidySums, 0);
429 //index of smallest grid point greater than at least one sampling/coalescent time in current tree
430 int minGridIndex;
431 //index of greatest grid point less than at least one sampling/coalescent time in current tree
432 int maxGridIndex;
433
434 int numLineages;
435
436 int currentGridIndex;
437 int currentTimeIndex;
438
439 double currentTime;
440 double nextTime;
441 double ploidyFactor;
442
443 //time of last coalescent event in tree
444 double lastCoalescentTime;
445
446 for (int i = 0; i < numTrees; i++) {
447 ploidyFactor = 1 / getPopulationFactor(i);
448 currentTimeIndex = 0;
449 currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
450 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
451 while (nextTime <= currentTime) {
452 currentTimeIndex++;
453 currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
454 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
455 }
456
457 numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
458 minGridIndex = 0;
459 while (minGridIndex < numGridPoints - 1 && gridPoints[minGridIndex] <= currentTime) { // MAS: Unclear about need for -1
460 minGridIndex++;
461 }
462 currentGridIndex = minGridIndex;
463
464 lastCoalescentTime = currentTime + intervalsList.get(i).getTotalDuration();
465
466 theLastTime = lastCoalescentTime;
467
468 maxGridIndex = numGridPoints - 1;
469 while ((maxGridIndex >= 0) && (gridPoints[maxGridIndex] >= lastCoalescentTime)) {
470 maxGridIndex = maxGridIndex - 1;
471 }
472
473 if (maxGridIndex >= 0 && minGridIndex < numGridPoints) {
474
475
476 //from likelihood of interval between first sampling time and gridPoints[minGridIndex]
477
478 while (nextTime < gridPoints[currentGridIndex]) {
479
480 //check to see if interval ends with coalescent event
481 if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
482
483 numCoalEvents[currentGridIndex]++;
484 }
485 sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
486 currentTime = nextTime;
487 currentTimeIndex++;
488 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
489
490 while (nextTime <= currentTime) {
491 currentTimeIndex++;
492 currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
493 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
494 }
495
496 numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
497
498 }
499
500 sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (gridPoints[currentGridIndex] - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
501 ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
502
503 currentGridIndex++;
504
505
506 //from likelihood of intervals between gridPoints[minGridIndex] and gridPoints[maxGridIndex]
507
508 while (currentGridIndex <= maxGridIndex) {
509 if (nextTime >= gridPoints[currentGridIndex]) {
510 sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (gridPoints[currentGridIndex] - gridPoints[currentGridIndex - 1]) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
511 ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
512
513 currentGridIndex++;
514 } else {
515
516 sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - gridPoints[currentGridIndex - 1]) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
517
518 //check to see if interval ends with coalescent event
519 if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
520 numCoalEvents[currentGridIndex]++;
521 }
522 currentTime = nextTime;
523 currentTimeIndex++;
524 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
525 while (nextTime <= currentTime) {
526 currentTimeIndex++;
527 currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
528 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
529 }
530
531 numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
532
533 while (nextTime < gridPoints[currentGridIndex]) {
534 //check to see if interval is coalescent interval or sampling interval
535 if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
536 numCoalEvents[currentGridIndex]++;
537 }
538 sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
539
540 currentTime = nextTime;
541 currentTimeIndex++;
542 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
543 while (nextTime <= currentTime) {
544 currentTimeIndex++;
545 currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
546 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
547 }
548
549 numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
550
551 }
552 sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (gridPoints[currentGridIndex] - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
553 ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
554
555 currentGridIndex++;
556 }
557 }
558
559 //from likelihood of interval between gridPoints[maxGridIndex] and lastCoalescentTime
560
561 sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - gridPoints[currentGridIndex - 1]) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
562
563 //check to see if interval ends with coalescent event
564 if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
565 numCoalEvents[currentGridIndex]++;
566 }
567
568 currentTime = nextTime;
569 currentTimeIndex++;
570
571 while ((currentTimeIndex + 1) < intervalsList.get(i).getIntervalCount()) {
572 // currentTime = nextTime;
573 // currentTimeIndex++;
574
575 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
576 while (nextTime <= currentTime) {
577 currentTimeIndex++;
578 currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
579 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
580 }
581
582 numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
583
584 //check to see if interval is coalescent interval or sampling interval
585
586
587 if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
588 numCoalEvents[currentGridIndex]++;
589 }
590 sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
591 currentTime = nextTime;
592 currentTimeIndex++;
593
594 }
595
596 // if tree does not overlap with any gridpoints/change-points, in which case logpopsize is constant
597
598 } else {
599 while ((currentTimeIndex + 1) < intervalsList.get(i).getIntervalCount()) {
600 //check to see if interval is coalescent interval or sampling interval
601 if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
602 numCoalEvents[currentGridIndex]++;
603 }
604 sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
605
606 currentTime = nextTime;
607 currentTimeIndex++;
608 if ((currentTimeIndex + 1) < intervalsList.get(i).getIntervalCount()) {
609 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
610
611 while (nextTime <= currentTime) {
612 currentTimeIndex++;
613 currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
614 nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
615 }
616
617 numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
618
619 }
620
621 }
622 ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
623
624 }
625 }
626
627 }
628
629 public double[] getNumCoalEvents() {
630 return numCoalEvents;
631 }
632
633 public int getNumberOfCoalescentEvents() {
634 return getCorrectOldFieldLength();
635 }
636
637 public double getCoalescentEventsStatisticValue(int i) {
638 if (i == 0) {
639
640 if (DEBUG) {
641 System.err.println("numTrees: " + numTrees);
642 System.err.println("getCoalescentIntervalDimension(): " + super.getCoalescentIntervalDimension());
643 System.err.println("getNumberOfCoalescentEvents(): " + getNumberOfCoalescentEvents());
644 System.err.println("getIntervalCount(): " + getIntervalCount());
645 System.err.println("intervalsList.size(): " + intervalsList.size());
646 System.err.println("intervalsList.get(0).getIntervalCount(): " + intervalsList.get(0).getIntervalCount());
647 }
648
649 if (numTrees > 1) {
650 throw new RuntimeException("Generalized stepping-stone sampling for the Skygrid not implemented for #trees > 1");
651 }
652 for (int j = 0; j < coalescentEventStatisticValues.length; j++) {
653 coalescentEventStatisticValues[j] = 0.0;
654 }
655 int counter = 0;
656
657 for (int j = 0; j < intervalsList.get(0).getIntervalCount(); j++) {
658 if (intervalsList.get(0).getIntervalType(j) == IntervalType.COALESCENT) {
659 //this.coalescentEventStatisticValues[counter] += getCoalescentInterval(j) * (getLineageCount(j) * (getLineageCount(j) - 1.0)) / 2.0;
660 this.coalescentEventStatisticValues[counter] += intervalsList.get(0).getInterval(j) * (intervalsList.get(0).getLineageCount(j) * (intervalsList.get(0).getLineageCount(j) - 1.0)) / 2.0;
661 counter++;
662 } else {
663 //this.coalescentEventStatisticValues[counter] += getCoalescentInterval(j) * (getLineageCount(j) * (getLineageCount(j) - 1.0)) / 2.0;
664 this.coalescentEventStatisticValues[counter] += intervalsList.get(0).getInterval(j) * (intervalsList.get(0).getLineageCount(j) * (intervalsList.get(0).getLineageCount(j) - 1.0)) / 2.0;
665 }
666 }
667 }
668 return coalescentEventStatisticValues[i];
669 //throw new RuntimeException("getCoalescentEventsStatisticValue(int i) not implemented for Bayesian Skygrid");
670 //return sufficientStatistics[i];
671 }
672
673 protected double calculateLogCoalescentLikelihood() {
674
675 if (!intervalsKnown) {
676 // intervalsKnown -> false when handleModelChanged event occurs in super.
677 wrapSetupIntervals();
678 setupSufficientStatistics();
679 intervalsKnown = true;
680 }
681
682 // Matrix operations taken from block update sampler to calculate data likelihood and field prior
683
684 double currentLike = 0;
685 double[] currentGamma = popSizeParameter.getParameterValues();
686
687 for (int i = 0; i < fieldLength; i++) {
688 currentLike += -numCoalEvents[i] * currentGamma[i] + ploidySums[i] - sufficientStatistics[i] * Math.exp(-currentGamma[i]);
689 }
690
691 return currentLike;
692 }
693
694
695 public double getLogLikelihood() {
696 if (!likelihoodKnown) {
697 logLikelihood = calculateLogCoalescentLikelihood();
698 logFieldLikelihood = skygridHelper.getLogFieldLikelihood();
699 likelihoodKnown = true;
700 }
701
702 return logLikelihood + logFieldLikelihood;
703 }
704
705 protected void setupGMRFWeights() {
706
707 //setupSufficientStatistics();
708
709 //Set up the weight Matrix
710 double[] offdiag = new double[fieldLength - 1];
711 double[] diag = new double[fieldLength];
712
713 diagonalValue = 2;
714 //First set up the offdiagonal entries;
715
716 for (int i = 0; i < fieldLength - 1; i++) {
717 offdiag[i] = -1;
718 }
719
720 //Then set up the diagonal entries;
721 for (int i = 1; i < fieldLength - 1; i++) {
722 // diag[i] = -(offdiag[i] + offdiag[i - 1]);
723 diag[i] = diagonalValue;
724 }
725 //Take care of the endpoints
726 //diag[0] = -offdiag[0];
727 //diag[fieldLength - 1] = -offdiag[fieldLength - 2];
728 diag[0] = diagonalValue - 1.0;
729 diag[fieldLength - 1] = diagonalValue - 1.0;
730
731
732 weightMatrix = new SymmTridiagMatrix(diag, offdiag);
733
734 }
735
736 protected double getFieldScalar() {
737 return 1.0;
738 }
739
740
741 protected void setupGMRFWeightsForMissingCov() {
742
743 if(firstObservedIndex != null){
744 weightMatricesForMissingCovRecent = new ArrayList<SymmTridiagMatrix>();
745
746 for (int i = 0; i < covPrecParametersRecent.size(); i++) {
747 double[] offdiagRec = new double[firstObservedIndex[i] - 2];
748 double[] diagRec = new double[firstObservedIndex[i] - 1];
749
750 for (int k = 0; k < firstObservedIndex[i] - 2; k++) {
751 offdiagRec[k] = -1;
752 }
753
754 for (int k = 1; k < firstObservedIndex[i] - 1; k++) {
755 diagRec[k] = 2.0;
756 }
757 diagRec[0] = 1.0;
758
759 weightMatricesForMissingCovRecent.add(i, new SymmTridiagMatrix(diagRec, offdiagRec));
760 }
761
762 }
763
764 if(lastObservedIndex != null) {
765 weightMatricesForMissingCovDistant = new ArrayList<SymmTridiagMatrix>();
766
767 for (int i = 0; i < covPrecParametersDistant.size(); i++) {
768 double[] offdiag = new double[fieldLength - lastObservedIndex[i] - 1];
769 double[] diag = new double[fieldLength - lastObservedIndex[i]];
770
771 //First set up the offdiagonal entries;
772
773 for (int k = 0; k < fieldLength - lastObservedIndex[i] - 1; k++) {
774 offdiag[k] = -1;
775 }
776
777 //Then set up the diagonal entries;
778 for (int k = 0; k < fieldLength - lastObservedIndex[i] - 1; k++) {
779 // diag[i] = -(offdiag[i] + offdiag[i - 1]);
780 diag[k] = 2.0;
781 }
782 //Take care of the endpoint
783 diag[fieldLength - lastObservedIndex[i] - 1] = 1.0;
784
785 weightMatricesForMissingCovDistant.add(i, new SymmTridiagMatrix(diag, offdiag));
786 }
787 }
788
789 }
790
791
792 public SymmTridiagMatrix getScaledWeightMatrixForMissingCovRecent(double precision, int covIndex, int firstObs) {
793 SymmTridiagMatrix a = weightMatricesForMissingCovRecent.get(covIndex).copy();
794 for (int i = 0; i < a.numRows() - 1; i++) {
795 a.set(i, i, a.get(i, i) * precision);
796 a.set(i + 1, i, a.get(i + 1, i) * precision);
797 }
798 a.set(firstObs - 2, firstObs - 2,
799 a.get(firstObs - 2, firstObs - 2) * precision);
800 return a;
801 }
802
803 public SymmTridiagMatrix getScaledWeightMatrixForMissingCovDistant(double precision, int covIndex, int lastObs) {
804 SymmTridiagMatrix a = weightMatricesForMissingCovDistant.get(covIndex).copy();
805 for (int i = 0; i < a.numRows() - 1; i++) {
806 a.set(i, i, a.get(i, i) * precision);
807 a.set(i + 1, i, a.get(i + 1, i) * precision);
808 }
809 a.set(fieldLength - lastObs - 1, fieldLength - lastObs - 1,
810 a.get(fieldLength - lastObs - 1, fieldLength - lastObs - 1) * precision);
811 return a;
812 }
813
814
815 private List<Tree> treeList;
816 private List<TreeIntervals> intervalsList;
817
818 public int nLoci() {
819 return treeList.size();
820 }
821
822 public Tree getTree(int nt) {
823 return treeList.get(nt);
824 }
825
826 public TreeIntervals getTreeIntervals(int nt) {
827 return intervalsList.get(nt);
828 }
829
830 public double getPopulationFactor(int nt) {
831 return ploidyFactors.getParameterValue(nt);
832 }
833
834 public List<Parameter> getBetaListParameter() {
835 return beta;
836 }
837
838 public List<MatrixParameter> getCovariates() {
839 return covariates;
840 }
841
842 public void storeTheState() {
843 for (TreeIntervals intervals : intervalsList) {
844 intervals.storeState();
845 }
846 }
847
848 public void restoreTheState() {
849 for (TreeIntervals intervals : intervalsList) {
850 intervals.restoreState();
851 }
852 }
853
854 protected void storeState() {
855 // System.arraycopy(numCoalEvents, 0, storedNumCoalEvents, 0, numCoalEvents.length);
856 super.storeState();
857 System.arraycopy(numCoalEvents, 0, storedNumCoalEvents, 0, numCoalEvents.length);
858 // storedPrecMatrix = precMatrix.copy();
859 System.arraycopy(ploidySums, 0, storedPloidySums, 0, ploidySums.length);
860 }
861
862
863 protected void restoreState() {
864 super.restoreState();
865
866 // Swap pointers
867 double[] tmp = numCoalEvents;
868 numCoalEvents = storedNumCoalEvents;
869 storedNumCoalEvents = tmp;
870 double[] tmp2 = ploidySums;
871 ploidySums = storedPloidySums;
872 storedPloidySums = tmp2;
873 }
874
875 /*public int getCoalescentIntervalLineageCount(int i) {
876 return 0;
877 }
878
879 public IntervalType getCoalescentIntervalType(int i) {
880 return null;
881 }*/
882
883 class SkygridHelper {
884
885 public SkygridHelper() {
886 }
887
888 protected void updateGammaWithCovariates(DenseVector currentGamma) {
889 // Do nothing
890 }
891
892 protected double handleMissingValues() {
893 return 0.0;
894 }
895
896 public double getLogFieldLikelihood() {
897
898 if (!intervalsKnown) {
899 //intervalsKnown -> false when handleModelChanged event occurs in super.
900 wrapSetupIntervals();
901 setupSufficientStatistics();
902 intervalsKnown = true;
903 }
904
905 DenseVector diagonal1 = new DenseVector(fieldLength);
906 DenseVector currentGamma = new DenseVector(popSizeParameter.getParameterValues());
907
908 updateGammaWithCovariates(currentGamma);
909
910 double currentLike = handleMissingValues();
911
912 SymmTridiagMatrix currentQ = getScaledWeightMatrix(precisionParameter.getParameterValue(0), lambdaParameter.getParameterValue(0));
913 currentQ.mult(currentGamma, diagonal1);
914
915 currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * currentGamma.dot(diagonal1);
916 if (lambdaParameter.getParameterValue(0) == 1) {
917 currentLike -= (fieldLength - 1) / 2.0 * LOG_TWO_TIMES_PI;
918 } else {
919 currentLike -= fieldLength / 2.0 * LOG_TWO_TIMES_PI;
920 }
921
922 return currentLike;
923 }
924 }
925
926 class SkygridCovariateHelper extends SkygridHelper {
927
928 public SkygridCovariateHelper() {
929 }
930
931 @Override
932 protected void updateGammaWithCovariates(DenseVector currentGamma) {
933
934 // Handle betaParameter / designMatrix
935
936 if (NEW_APPROACH) {
937
938 final int N = currentGamma.size();
939 double[] update = new double[N];
940
941 if (dMatrix != null) {
942 final int K = dMatrix.getColumnDimension();
943
944 if (N != dMatrix.getRowDimension()) {
945 throw new RuntimeException("Incorrect covariate dimensions (" + N + " != "
946 + dMatrix.getRowDimension() + ")");
947 }
948
949 for (int i = 0; i < N; ++i) {
950 for (int j = 0; j < K; ++j) {
951 update[i] += dMatrix.getParameterValue(i, j) * betaParameter.getParameterValue(j);
952 }
953 }
954 }
955
956 if (covariates != null) {
957 if (beta.size() != covariates.size()) {
958 throw new RuntimeException("beta.size(" + beta.size() + ") != covariates.size(" + covariates.size() + ")");
959 }
960
961 for (int k = 0; k < beta.size(); ++k) {
962
963 Parameter b = beta.get(k);
964 final int J = b.getDimension();
965 MatrixParameter covariate = covariates.get(k);
966
967 if ((J != covariate.getRowDimension()) ||
968 (N != covariate.getColumnDimension())) { // Note: XML current has covariates transposed
969 throw new RuntimeException("Incorrect dimensions in " + covariate.getId() + " (r=" + covariate.getRowDimension() +
970 ",c=" + covariate.getColumnDimension()+ ")");
971 }
972
973 for (int i = 0; i < N; ++i) {
974 for (int j = 0; j < J; ++j) {
975 update[i] += covariate.getParameterValue(j, i) * b.getParameterValue(j);
976 }
977 }
978 }
979 }
980
981 for (int i = 0; i < N; ++i) {
982 currentGamma.set(i, currentGamma.get(i) - update[i]);
983 }
984
985 } else {
986 DenseVector currentBeta = new DenseVector(beta.size());
987
988 for (int i = 0; i < beta.size(); i++) {
989 currentBeta.set(i, beta.get(i).getParameterValue(0));
990 }
991
992 //int numMissing = fieldLength - lastObservedIndex;
993 //DenseVector tempVectCov = new DenseVector(numMissing);
994
995 //System.err.println("covariates.size(): " + covariates.size());
996 //System.err.println("covariates.get(0).getColumnDimension: " + covariates.get(0).getColumnDimension());
997 //System.err.println("covariates.get(0).getRowDimension: " + covariates.get(0).getRowDimension());
998
999 for (int i = 0; i < covariates.size(); i++) {
1000 for (int j = 0; j < covariates.get(i).getColumnDimension(); j++) {
1001 // System.err.println("j: " + j);
1002 // System.err.println("covariates.get(i).getParameterValue(0,j): " + covariates.get(i).getParameterValue(0,j));
1003 currentGamma.set(j, currentGamma.get(j) - covariates.get(i).getParameterValue(0, j) * currentBeta.get(i));
1004 }
1005 }
1006 }
1007 }
1008 }
1009
1010 private static final boolean NEW_APPROACH = true;
1011
1012 class SkygridMissingCovariateHelper extends SkygridCovariateHelper {
1013
1014 public SkygridMissingCovariateHelper() {
1015 }
1016
1017 @Override
1018 protected double handleMissingValues() {
1019
1020 int numMissing;
1021 DenseVector tempVectMissingCov;
1022 SymmTridiagMatrix missingCovQ;
1023 DenseVector tempVectMissingCov2;
1024 int numMissingRecent;
1025
1026 double currentLike = 0.0;
1027
1028 if(lastObservedIndex != null) {
1029 for (int i = 0; i < covPrecParametersDistant.size(); i++) {
1030
1031 numMissing = fieldLength - lastObservedIndex[i];
1032 tempVectMissingCov = new DenseVector(numMissing);
1033 tempVectMissingCov2 = new DenseVector(numMissing);
1034
1035 missingCovQ = getScaledWeightMatrixForMissingCovDistant(covPrecParametersDistant.get(i).getParameterValue(0), i,
1036 lastObservedIndex[i]);
1037
1038 for (int j = 0; j < numMissing; j++) {
1039 tempVectMissingCov.set(j, covariates.get(i).getParameterValue(0, lastObservedIndex[i] + j) -
1040 covariates.get(i).getParameterValue(0, lastObservedIndex[i] - 1));
1041 }
1042
1043 missingCovQ.mult(tempVectMissingCov, tempVectMissingCov2);
1044 currentLike += 0.5 * (numMissing) * Math.log(covPrecParametersDistant.get(i).getParameterValue(0))
1045 - 0.5 * tempVectMissingCov.dot(tempVectMissingCov2);
1046 }
1047 }
1048
1049 if(firstObservedIndex != null){
1050
1051 for (int i = 0; i < covPrecParametersRecent.size(); i++) {
1052
1053 numMissingRecent = firstObservedIndex[i]-1;
1054 tempVectMissingCov = new DenseVector(numMissingRecent);
1055 tempVectMissingCov2 = new DenseVector(numMissingRecent);
1056
1057 missingCovQ = getScaledWeightMatrixForMissingCovRecent(covPrecParametersRecent.get(i).getParameterValue(0), i,
1058 firstObservedIndex[i]);
1059
1060 for (int j = 0; j < numMissingRecent; j++) {
1061 tempVectMissingCov.set(j, covariates.get(i).getParameterValue(0, j) -
1062 covariates.get(i).getParameterValue(0, firstObservedIndex[i]-1));
1063 }
1064
1065 missingCovQ.mult(tempVectMissingCov, tempVectMissingCov2);
1066 currentLike += 0.5 * (numMissingRecent) * Math.log(covPrecParametersRecent.get(i).getParameterValue(0))
1067 - 0.5 * tempVectMissingCov.dot(tempVectMissingCov2);
1068 }
1069 }
1070 return currentLike;
1071 }
1072
1073 }
1074
1075 @Override
1076 public Citation.Category getCategory() {
1077 return Citation.Category.TREE_PRIORS;
1078 }
1079
1080 @Override
1081 public String getDescription() {
1082 return "Skyride coalescent";
1083 }
1084
1085 @Override
1086 public List<Citation> getCitations() {
1087 return Arrays.asList(new Citation(
1088 new Author[]{
1089 new Author("MS", "Gill"),
1090 new Author("P", "Lemey"),
1091 new Author("NR", "Faria"),
1092 new Author("A", "Rambaut"),
1093 new Author("B", "Shapiro"),
1094 new Author("MA", "Suchard")
1095 },
1096 "Improving Bayesian population dynamics inference: a coalescent-based model for multiple loci",
1097 2013,
1098 "Mol Biol Evol",
1099 30, 713, 724
1100 ),
1101 new Citation(
1102 new Author[]{
1103 new Author("VN", "Minin"),
1104 new Author("EW", "Bloomquist"),
1105 new Author("MA", "Suchard")
1106 },
1107 "Smooth skyride through a rough skyline: Bayesian coalescent-based inference of population dynamics",
1108 2008,
1109 "Mol Biol Evol",
1110 25, 1459, 1471,
1111 "10.1093/molbev/msn090"
1112 )
1113 );
1114 }
1115 }