Debian Codegraph @

src/dr/evomodel/coalescent/BayesianSkylineLikelihood.java

raw symbols SCIP
1 /*
2 * BayesianSkylineLikelihood.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.ConstantPopulation;
29 import dr.evolution.coalescent.ExponentialBSPGrowth;
30 import dr.evolution.tree.Tree;
31 import dr.evolution.util.Units;
32 import dr.evomodel.tree.TreeModel;
33 import dr.evomodelxml.coalescent.BayesianSkylineLikelihoodParser;
34 import dr.inference.model.Parameter;
35 import dr.inference.model.Statistic;
36 import dr.math.MathUtils;
37 import dr.util.Author;
38 import dr.util.Citable;
39 import dr.util.Citation;
40
41 import java.util.Collections;
42 import java.util.Date;
43 import java.util.List;
44
45 /**
46 * A likelihood function for the generalized skyline plot coalescent. Takes a tree and population size and group size parameters.
47 *
48 * @version $Id: BayesianSkylineLikelihood.java,v 1.5 2006/03/06 11:26:49 rambaut Exp $
49 *
50 * @author Alexei Drummond
51 */
52 public class BayesianSkylineLikelihood extends OldAbstractCoalescentLikelihood implements Citable {
53
54 // PUBLIC STUFF
55
56 public static final int STEPWISE_TYPE = 0;
57 public static final int LINEAR_TYPE = 1;
58 public static final int EXPONENTIAL_TYPE = 2;
59
60 public BayesianSkylineLikelihood(Tree tree,
61 Parameter popSizeParameter,
62 Parameter groupSizeParameter,
63 int type) {
64 super(BayesianSkylineLikelihoodParser.SKYLINE_LIKELIHOOD);
65
66 // adding the key word to the the model means the keyword will be logged in the
67 // header of the logfile.
68 this.addKeyword("skyline");
69
70 this.groupSizeParameter = groupSizeParameter;
71 this.popSizeParameter = popSizeParameter;
72 int events = tree.getExternalNodeCount() - 1;
73 int paramDim1 = popSizeParameter.getDimension();
74 int paramDim2 = groupSizeParameter.getDimension();
75 this.type = type;
76
77 if (type == EXPONENTIAL_TYPE) {
78 if (paramDim1 != (paramDim2+1)) {
79 throw new IllegalArgumentException("Dimension of population parameter must be one greater than dimension of group size parameter.");
80 }
81 } else if (type == LINEAR_TYPE) {
82 if (paramDim1 != (paramDim2+1)) {
83 throw new IllegalArgumentException("Dimension of population parameter must be one greater than dimension of group size parameter.");
84 }
85 } else { // STEPWISE_TYPE
86 if (paramDim1 != paramDim2) {
87 throw new IllegalArgumentException("Dimension of population parameter and group size parameters should be the same.");
88 }
89 }
90
91 if (paramDim2 > events) {
92 throw new IllegalArgumentException("There are more groups than coalescent nodes in the tree.");
93 }
94
95 int eventsCovered = 0;
96 for (int i = 0; i < getGroupCount(); i++) {
97 eventsCovered += getGroupSize(i);
98 }
99
100 if (eventsCovered != events) {
101
102 if (eventsCovered == 0 || eventsCovered == paramDim2) {
103 double[] uppers = new double[paramDim2];
104 double[] lowers = new double[paramDim2];
105
106 // For these special cases we assume that the XML has not specified initial group sizes
107 // or has set all to 1 and we set them here automatically...
108 int eventsEach = events / paramDim2;
109 int eventsExtras = events % paramDim2;
110 for (int i = 0; i < paramDim2; i++) {
111 if (i < eventsExtras) {
112 groupSizeParameter.setParameterValue(i, eventsEach + 1);
113 } else {
114 groupSizeParameter.setParameterValue(i, eventsEach);
115 }
116 uppers[i] = Double.MAX_VALUE;
117 lowers[i] = 1.0;
118 }
119
120 if (type == EXPONENTIAL_TYPE || type == LINEAR_TYPE) {
121 lowers[0] = 2.0;
122 }
123 groupSizeParameter.addBounds(new Parameter.DefaultBounds(uppers, lowers));
124 } else {
125 // ... otherwise assume the user has made a mistake setting initial group sizes.
126 throw new IllegalArgumentException("The sum of the initial group sizes does not match the number of coalescent events in the tree.");
127 }
128 }
129
130 if ((type == EXPONENTIAL_TYPE || type == LINEAR_TYPE) && groupSizeParameter.getParameterValue(0) < 2.0) {
131 throw new IllegalArgumentException("For linear or exponential model first group size must be >= 2.");
132 }
133
134 this.tree = tree;
135 if (tree instanceof TreeModel) {
136 addModel((TreeModel)tree);
137 }
138 addVariable(popSizeParameter);
139
140 addVariable(groupSizeParameter);
141
142 setupIntervals();
143
144 addStatistic(new GroupHeightStatistic());
145 }
146
147 // **************************************************************
148 // Likelihood IMPLEMENTATION
149 // **************************************************************
150
151 /**
152 * Calculates the log likelihood of this set of coalescent intervals,
153 * given a demographic model.
154 */
155 public double getLogLikelihood() {
156
157 setupIntervals();
158
159 double logL = 0.0;
160
161 double currentTime = 0.0;
162
163 int groupIndex=0;
164 int[] groupSizes = getGroupSizes();
165 double[] groupEnds = getGroupHeights();
166
167 int subIndex = 0;
168
169 if (type == EXPONENTIAL_TYPE) {
170 ExponentialBSPGrowth eg = new ExponentialBSPGrowth(Units.Type.YEARS);
171
172 for (int j = 0; j < intervalCount; j++) {
173 double startGroupPopSize = popSizeParameter.getParameterValue(groupIndex);
174 double endGroupPopSize = popSizeParameter.getParameterValue(groupIndex+1);
175 double startTime = currentTime;
176 double endTime = currentTime + intervals[j];
177
178 eg.setup(startGroupPopSize, endGroupPopSize, endTime - startTime);
179
180 if (getIntervalType(j) == CoalescentEventType.COALESCENT) {
181 subIndex += 1;
182 if (subIndex >= groupSizes[groupIndex]) {
183 groupIndex += 1;
184 subIndex = 0;
185 }
186 }
187
188 logL += calculateIntervalLikelihood(eg, intervals[j], currentTime, lineageCounts[j], getIntervalType(j));
189
190 // insert zero-length coalescent intervals
191 int diff = getCoalescentEvents(j)-1;
192 for (int k = 0; k < diff; k++) {
193 eg.setup(startGroupPopSize, startGroupPopSize, endTime - startTime);
194 logL += calculateIntervalLikelihood(eg, 0.0, currentTime, lineageCounts[j]-k-1,
195 CoalescentEventType.COALESCENT);
196 subIndex += 1;
197 if (subIndex >= groupSizes[groupIndex]) {
198 groupIndex += 1;
199 subIndex = 0;
200 }
201 }
202
203 currentTime += intervals[j];
204 }
205 } else {
206 ConstantPopulation cp = new ConstantPopulation(Units.Type.YEARS);
207
208 for (int j = 0; j < intervalCount; j++) {
209
210 // set the population size to the size of the middle of the current interval
211 final double ps = getPopSize(groupIndex, currentTime + (intervals[j]/2.0), groupEnds);
212 cp.setN0(ps);
213 if (getIntervalType(j) == CoalescentEventType.COALESCENT) {
214 subIndex += 1;
215 if (subIndex >= groupSizes[groupIndex]) {
216 groupIndex += 1;
217 subIndex = 0;
218 }
219 }
220
221 logL += calculateIntervalLikelihood(cp, intervals[j], currentTime, lineageCounts[j], getIntervalType(j));
222
223 // insert zero-length coalescent intervals
224 int diff = getCoalescentEvents(j)-1;
225 for (int k = 0; k < diff; k++) {
226 cp.setN0(getPopSize(groupIndex, currentTime, groupEnds));
227 logL += calculateIntervalLikelihood(cp, 0.0, currentTime, lineageCounts[j]-k-1,
228 CoalescentEventType.COALESCENT);
229 subIndex += 1;
230 if (subIndex >= groupSizes[groupIndex]) {
231 groupIndex += 1;
232 subIndex = 0;
233 }
234 }
235
236 currentTime += intervals[j];
237 }
238 }
239 return logL;
240 }
241
242 /**
243 * @return the pop size for the given time. If linear model is being used then this pop size is
244 * interpolated between the two pop sizes at either end of the grouped interval.
245 */
246 public final double getPopSize(int groupIndex, double midTime, double[] groupHeights) {
247 if (type == LINEAR_TYPE) {
248
249 double startGroupPopSize = popSizeParameter.getParameterValue(groupIndex);
250 double endGroupPopSize = popSizeParameter.getParameterValue(groupIndex+1);
251
252 double startGroupTime = 0.0;
253 if (groupIndex > 0) {
254 startGroupTime = groupHeights[groupIndex-1];
255 }
256 double endGroupTime = groupHeights[groupIndex];
257
258 // calculate the gradient
259 double m = (endGroupPopSize-startGroupPopSize)/(endGroupTime-startGroupTime);
260
261 // calculate the population size at midTime using linear interpolation
262 final double midPopSize = (m * (midTime-startGroupTime)) + startGroupPopSize;
263
264 return midPopSize;
265 } else {
266 return popSizeParameter.getParameterValue(groupIndex);
267 }
268 }
269
270 /* GAL: made public to give BayesianSkylineGibbsOperator access */
271 public final int[] getGroupSizes() {
272 if ((type == EXPONENTIAL_TYPE || type == LINEAR_TYPE) && groupSizeParameter.getParameterValue(0) < 2.0) {
273 throw new IllegalArgumentException("For linear model first group size must be >= 2.");
274 }
275
276 int[] groupSizes = new int[groupSizeParameter.getDimension()];
277
278 for (int i = 0; i < groupSizes.length; i++) {
279 double g = groupSizeParameter.getParameterValue(i);
280 if (g != Math.round(g)) {
281 throw new RuntimeException("Group size " + i + " should be integer but found:" + g);
282 }
283 groupSizes[i] = (int)Math.round(g);
284 }
285 return groupSizes;
286 }
287
288 private int getGroupCount() {
289 return groupSizeParameter.getDimension();
290 }
291
292 private int getGroupSize(int groupIndex) {
293 double g = groupSizeParameter.getParameterValue(groupIndex);
294 if (g != Math.round(g)) {
295 throw new RuntimeException("Group size " + groupIndex + " should be integer but found:" + g);
296 }
297 return (int)Math.round(g);
298 }
299
300 /* GAL: made public to give BayesianSkylineGibbsOperator access */
301 public final double[] getGroupHeights() {
302 double[] groupEnds = new double[getGroupCount()];
303
304 double timeEnd = 0.0;
305 int groupIndex = 0;
306 int subIndex = 0;
307 for (int i = 0; i < intervalCount; i++) {
308
309 timeEnd += intervals[i];
310
311 if (getIntervalType(i) == CoalescentEventType.COALESCENT) {
312 subIndex += 1;
313 if (subIndex >= getGroupSize(groupIndex)) {
314 groupEnds[groupIndex] = timeEnd;
315 groupIndex += 1;
316 subIndex = 0;
317 }
318 }
319 }
320 groupEnds[getGroupCount()-1] = timeEnd;
321
322 return groupEnds;
323 }
324
325 private double getGroupHeight(int groupIndex) {
326 return getGroupHeights()[groupIndex];
327 }
328
329 final public int getType() {
330 return type;
331 }
332
333 final public Parameter getPopSizeParameter() {
334 return popSizeParameter;
335 }
336
337 final public Parameter getGroupSizeParameter() {
338 return groupSizeParameter;
339 }
340
341 // ****************************************************************
342 // Implementing Demographic Reconstructor
343 // ****************************************************************
344
345 public String getTitle() {
346 final String title = "Bayesian Skyline (" + (type == STEPWISE_TYPE ? "stepwise" : "linear") + ")\n" +
347 "Generated " + (new Date()).toString() + " [seed=" + MathUtils.getSeed() + "]";
348 return title;
349 }
350
351 // ****************************************************************
352 // Inner classes
353 // ****************************************************************
354
355 public class GroupHeightStatistic extends Statistic.Abstract {
356
357 public GroupHeightStatistic() {
358 super("groupHeight");
359 }
360
361 public int getDimension() { return getGroupCount(); }
362
363 public double getStatisticValue(int i) {
364 return getGroupHeight(i);
365 }
366
367 }
368
369 // ****************************************************************
370 // Private and protected stuff
371 // ****************************************************************
372
373 /** The demographic model. */
374 private final Parameter popSizeParameter;
375
376 private final Parameter groupSizeParameter;
377
378 private final int type;
379
380 @Override
381 public Citation.Category getCategory() {
382 return Citation.Category.TREE_PRIORS;
383 }
384
385 @Override
386 public String getDescription() {
387 return "Bayesian Skyline Coalescent";
388 }
389
390 @Override
391 public List<Citation> getCitations() {
392 return Collections.singletonList(CITATION);
393 }
394
395 public static Citation CITATION = new Citation(
396 new Author[]{
397 new Author("AJ", "Drummond"),
398 new Author("A", "Rambaut"),
399 new Author("B", "Shapiro"),
400 new Author("OG", "Pybus")
401 },
402 "Bayesian coalescent inference of past population dynamics from molecular sequences",
403 2005,
404 "Mol Biol Evol",
405 22, 1185, 1192
406 );
407 }