Debian Codegraph @

src/dr/evomodel/coalescent/operators/BayesianSkylineGibbsOperator.java

raw symbols SCIP
1 /*
2 * BayesianSkylineGibbsOperator.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.operators;
27
28 import dr.evolution.coalescent.ConstantPopulation;
29 import dr.evolution.util.Units;
30 import dr.evomodel.coalescent.BayesianSkylineLikelihood;
31 import dr.evomodel.coalescent.OldAbstractCoalescentLikelihood;
32 import dr.evomodelxml.coalescent.operators.BayesianSkylineGibbsOperatorParser;
33 import dr.inference.model.Parameter;
34 import dr.inference.operators.SimpleMCMCOperator;
35 import dr.math.distributions.ExponentialDistribution;
36 import dr.math.distributions.GammaDistribution;
37
38 /**
39 * A Gibbs operator for the Bayesian Skyline model, inspired by the Hey &
40 * Nielsen PNAS paper.
41 * <p/>
42 * The operator is implemented as a standard proposal generator, returning a
43 * Hastings ratio. The advantage of this scheme is that additional priors can be
44 * included without modifying the operator. This is only be efficient for 'mild'
45 * priors, since acceptance rates easily get very low because this operator
46 * changes many parameters simultaneously.
47 * <p/>
48 * The proposal generator can be modified by providing upper and lower bounds.
49 * Four types of prior are implemented, so that the proposal behaves as a true
50 * Gibbs operator if the chosen prior matches the actual prior.
51 * <p/>
52 * jeffreys= exponentialMarkov=
53 * false false Uniform prior
54 * true false Jeffrey's prior on the geometric average population size
55 * false true An exponential Markov prior (as ExponentialMarkov)
56 * true true Same, with a Jeffrey's prior on the most recent pop size
57 * <p/>
58 * In addition, if reverse="true", the exponential Markov prior works in reverse
59 * (any Jeffrey's prior applies to the last pop size parameter, and preceding
60 * pop sizes are exponentially distributed conditional on the successor)
61 * <p/>
62 * The 'shape' parameter determines the shape parameter of the Gamma distribution used in the "exponential"
63 * Markov prior. The default value is 1.0, corresponding to an exponential distribution; otherwise a Gamma
64 * distribution with that shape parameter, and a mean equal to the previous population size, is used.
65 * <p/>
66 * The 'iterations' parameter determines how many single-population-size Gibbs moves
67 * will be executed per operation. This should be set to once or twice the number
68 * of dimensions.
69 * <p/>
70 * TODO: It's easy to extend this to use Gamma Markov priors (either on Ne or on 1/Ne)
71 * instead of an exponential prior
72 *
73 * @author Gerton Lunter
74 */
75
76 public class BayesianSkylineGibbsOperator extends SimpleMCMCOperator {
77
78 public static final int STEPWISE_TYPE = 0;
79 public static final int LINEAR_TYPE = 1;
80 public static final int EXPONENTIAL_TYPE = 2;
81
82 private BayesianSkylineLikelihood bayesianSkylineLikelihood;
83 private Parameter populationSizeParameter;
84 private Parameter groupSizeParameter;
85
86 private double upperBound;
87 private double lowerBound;
88
89 private boolean jeffreysGeometricPrior; /* Jeffrey's prior on the geometric average */
90 private boolean jeffreysPrior; /* Jeffrey's prior on the first Ne */
91 private boolean exponentialMarkovPrior; /* Exponential or Gamma Markov prior */
92 private double shape; /* shape parameter of the Gamma prior (1.0 for exponential prior) */
93 private boolean reverse; /*
94 * If true, priors are parameterized by
95 * ancestral rather than descendant Ne
96 */
97
98 private int iterations; /* Number of Gibbs moves to make per operation */
99
100 public double getTargetAcceptanceProbability() {
101 return 1.00;
102 }
103
104 public double getMinimumAcceptanceLevel() {
105 return 0.99;
106 }
107
108 public double getMaximumAcceptanceLevel() {
109 return 1.01;
110 }
111
112 public double getMinimumGoodAcceptanceLevel() {
113 return 0.99;
114 }
115
116 public double getMaximumGoodAcceptanceLevel() {
117 return 1.01;
118 }
119
120 public BayesianSkylineGibbsOperator(
121 BayesianSkylineLikelihood bayesianSkylineLikelihood,
122 Parameter populationSizeParameter, Parameter groupSizeParameter,
123 int type, double weight, double lowerBound, double upperBound,
124 boolean jeffreysPrior, boolean exponentialMarkov, double shape, boolean reverse,
125 int iterations) {
126
127 this.bayesianSkylineLikelihood = bayesianSkylineLikelihood;
128 this.populationSizeParameter = populationSizeParameter;
129 this.groupSizeParameter = groupSizeParameter;
130 setWeight(weight);
131 this.lowerBound = lowerBound;
132 this.upperBound = upperBound;
133 this.exponentialMarkovPrior = exponentialMarkov;
134 this.shape = shape;
135 this.iterations = iterations;
136 if (exponentialMarkov) {
137 this.jeffreysPrior = jeffreysPrior;
138 this.jeffreysGeometricPrior = false;
139 } else {
140 this.jeffreysGeometricPrior = jeffreysPrior;
141 this.jeffreysPrior = false;
142 }
143 this.reverse = reverse;
144
145 assert (populationSizeParameter != null);
146 assert (groupSizeParameter != null);
147 assert (populationSizeParameter.getDimension() == groupSizeParameter
148 .getDimension());
149 assert (iterations >= 1);
150 assert (lowerBound < upperBound);
151
152 if (type != STEPWISE_TYPE) {
153 throw new IllegalArgumentException(
154 "Should only get stepwise type here - sorry.");
155 }
156
157 System.out.println("Using a Bayesian skyline Gibbs operator (lo="
158 + lowerBound + ", hi=" + upperBound + ", Jeffreys="
159 + jeffreysPrior + ", exponentialMarkov=" + exponentialMarkov
160 + " (shape=" + shape + "), reverse=" + reverse + ", iterations=" + iterations + ")");
161 }
162
163 public final String getPerformanceSuggestion() {
164 return "";
165 }
166
167 // Samples one new population size, from a Gamma distribution with the given
168 // shape and rate parameters,
169 // and, when required, taking account of the exponential Markov prior on
170 // either side
171 double getSample(double exponents[], double gammaRates[], double popSizes[], int index) {
172
173 int numGroups = popSizes.length;
174 int direction = reverse ? -1 : 1;
175 int firstIdx = reverse ? numGroups - 1 : 0;
176 int lastIdx = reverse ? 0 : numGroups - 1;
177
178 double exponent = exponents[index];
179 double rate = gammaRates[index];
180 double bias = 0.0;
181
182 // Include a Jeffrey's prior on the geometric average of population
183 // sizes
184 if (jeffreysGeometricPrior) {
185 exponent += 1.0 / numGroups;
186 }
187
188 // Include a Jeffrey's prior on the first population size
189 if (jeffreysPrior && index == firstIdx) {
190 exponent += 1.0;
191 }
192
193 // For a parameter other than the first, include an exponential prior
194 // (1/Nprev) exp(-N/Nprev)
195 // (The normalization factor is ignored, since it does not depend on N)
196 //
197 // Modified: include a Gamma prior
198 // N^(shape-1) exp(-N/scale) / scale^shape Gamma(shape) with scale = Nprev/shape
199 // All factors not depending on N are ignored
200 if (exponentialMarkovPrior && index != firstIdx) {
201 //bias = popSizes[index - direction];
202 bias = popSizes[index - direction] / shape;
203 exponent += 1.0 - shape;
204 }
205
206 // Take into account the dependent prior (1/N) exp(-Nnext/N)
207 // This time, the normalization factor, as well as the exponential
208 // factor, must be included
209 //
210 // Modified: include a Gamma prior
211 // Nnext^(shape-1) exp(-Nnext*shape/N) shape^shape / N^shape Gamma(shape)
212 if (exponentialMarkovPrior && index != lastIdx) {
213 //exponent += 1.0;
214 //rate = rate + popSizes[index + direction];
215 exponent += shape;
216 rate = rate + popSizes[index + direction] * shape;
217 }
218
219 // Check arguments
220 // Note: the requirement that the exponent be > 1.0 (i.e. shape parameter > 0.0)
221 // could be relaxed when there is nonzero bias, but this is not implemented
222 // in GammaDistribution.nextExpGamma
223
224 //if (exponent <= 1.0) {
225 // throw new IllegalArgumentException("Group size must be >= 2");
226 //}
227
228 // now sample
229 double sample;
230 int iters = 0;
231 do {
232
233 // now sample from (1/N)^exponent * exp(-rate/N) dN; this is
234 // equivalent to sampling
235 // from x^(exponent-2) * exp(-rate x) dx with x=1/N, which is the
236 // Gamma distribution
237 // with shape parameter exponent-1.
238 if (bias > 0) {
239 sample = 1.0 / GammaDistribution.nextExpGamma(exponent - 1.0, 1.0 / rate, bias);
240 } else {
241 sample = 1.0 / GammaDistribution.nextGamma(exponent - 1.0, 1.0 / rate);
242 }
243 iters += 1;
244
245 } while ((sample < lowerBound || sample > upperBound) && iters < 100);
246
247 if (iters == 100) {
248 // fail
249 return Double.NEGATIVE_INFINITY;
250 }
251
252 // calculate partial log likelihoods of old and new sample
253 double oldLogL = (-exponent * Math.log(popSizes[index])) - rate
254 / popSizes[index];
255 double newLogL = (-exponent * Math.log(sample)) - rate / sample;
256
257 if (bias > 0.0) {
258 oldLogL += ExponentialDistribution.logPdf(popSizes[index], 1.0 / bias);
259 newLogL += ExponentialDistribution.logPdf(sample, 1.0 / bias);
260 }
261
262 // store new sample
263 popSizes[index] = sample;
264
265 // return hastings ratio
266 return oldLogL - newLogL;
267
268 }
269
270 public double doOperation() {
271
272 if (!bayesianSkylineLikelihood.getIntervalsKnown())
273 bayesianSkylineLikelihood.setupIntervals();
274
275 assert (populationSizeParameter != null);
276 assert (groupSizeParameter != null);
277
278 // Now enter a loop similar to the likelihood calculation, except that
279 // we now just collect
280 // waiting times, and exponents of the population size parameters, for
281 // each group.
282
283 int groupIndex = 0;
284 int subIndex = 0;
285 int[] groupSizes = bayesianSkylineLikelihood.getGroupSizes();
286 double[] groupEnds = bayesianSkylineLikelihood.getGroupHeights();
287
288 ConstantPopulation cp = new ConstantPopulation(Units.Type.YEARS);
289 double exponent = 0.0;
290 double gammaRate = 0.0;
291 double currentTime = 0.0;
292
293 double[] populationSizes = new double[groupSizes.length];
294 double[] exponents = new double[groupSizes.length];
295 double[] gammaRates = new double[groupSizes.length];
296
297 // first collect the shape and rate parameters of the Gamma
298 // distributions describing the posteriors on N
299 for (int j = 0; j < bayesianSkylineLikelihood.getIntervalCount(); j++) {
300
301 // set the population size to the size of the middle of the current
302 // interval
303 double curpopsize = bayesianSkylineLikelihood.getPopSize(
304 groupIndex, currentTime + (bayesianSkylineLikelihood.getInterval(j) / 2.0),
305 groupEnds);
306 populationSizes[groupIndex] = curpopsize;
307
308 cp.setN0(curpopsize);
309
310 exponent += bayesianSkylineLikelihood.calculateIntervalShapeParameter(cp,
311 bayesianSkylineLikelihood.getInterval(j),
312 currentTime,
313 bayesianSkylineLikelihood.getLineageCount(j),
314 bayesianSkylineLikelihood.getIntervalType(j));
315 gammaRate += bayesianSkylineLikelihood.calculateIntervalRateParameter(cp,
316 bayesianSkylineLikelihood.getInterval(j),
317 currentTime,
318 bayesianSkylineLikelihood.getLineageCount(j),
319 bayesianSkylineLikelihood.getIntervalType(j))
320 * curpopsize;
321
322 if (bayesianSkylineLikelihood.getIntervalType(j) == OldAbstractCoalescentLikelihood.CoalescentEventType.COALESCENT) {
323 subIndex += 1;
324 if (subIndex >= groupSizes[groupIndex]) {
325
326 exponents[groupIndex] = exponent;
327 gammaRates[groupIndex] = gammaRate;
328
329 // Reset accumulators
330 exponent = 0.0;
331 gammaRate = 0.0;
332
333 // Next group
334 groupIndex += 1;
335 subIndex = 0;
336 }
337 }
338
339 // insert zero-length coalescent intervals (for multifurcating trees
340 int diff = bayesianSkylineLikelihood.getCoalescentEvents(j) - 1;
341 for (int k = 0; k < diff; k++) {
342
343 curpopsize = bayesianSkylineLikelihood.getPopSize(groupIndex,
344 currentTime + (bayesianSkylineLikelihood.getInterval(j) / 2.0),
345 groupEnds);
346 populationSizes[groupIndex] = curpopsize;
347
348 cp.setN0(curpopsize);
349
350 exponent += bayesianSkylineLikelihood.calculateIntervalShapeParameter(cp,
351 bayesianSkylineLikelihood.getInterval(j),
352 currentTime,
353 bayesianSkylineLikelihood.getLineageCount(j),
354 bayesianSkylineLikelihood.getIntervalType(j));
355 gammaRate += bayesianSkylineLikelihood.calculateIntervalRateParameter(cp,
356 bayesianSkylineLikelihood.getInterval(j),
357 currentTime,
358 bayesianSkylineLikelihood.getLineageCount(j),
359 bayesianSkylineLikelihood.getIntervalType(j))
360 * curpopsize;
361
362 subIndex += 1;
363 if (subIndex >= groupSizes[groupIndex]) {
364
365 exponents[groupIndex] = exponent;
366 gammaRates[groupIndex] = gammaRate;
367
368 // Reset accumulators
369 exponent = 0.0;
370 gammaRate = 0.0;
371
372 // Next group
373 groupIndex += 1;
374 subIndex = 0;
375
376 }
377 }
378
379 currentTime += bayesianSkylineLikelihood.getInterval(j);
380 }
381
382 // Next, sample new population sizes
383 double hastingsRatio = 0.0;
384 int numGibbsMoves = iterations;
385
386 boolean[] tabu = new boolean[groupSizes.length];
387 for (int i = 0; i < groupSizes.length; i++)
388 tabu[i] = false;
389
390 while (numGibbsMoves > 0) {
391
392 int randomCoord = dr.math.MathUtils.nextInt(groupSizes.length);
393
394 // do not bother to re-gibbs-sample coordinates when their
395 // conditional distribution has not changed, i.e. when their
396 // neighbours haven't been sampled
397 if (!tabu[randomCoord]) {
398
399 hastingsRatio += getSample(exponents, gammaRates, populationSizes, randomCoord);
400
401 // make current index tabu, but un-tabuize its neighbours
402 tabu[randomCoord] = true;
403 if (randomCoord != 0)
404 tabu[randomCoord - 1] = false;
405 if (randomCoord != groupSizes.length - 1)
406 tabu[randomCoord + 1] = false;
407 }
408
409 numGibbsMoves -= 1;
410
411 }
412
413 // store the new array of population sizes
414 for (int j = 0; j < groupIndex; j++) {
415 populationSizeParameter.setParameterValue(j, populationSizes[j]);
416 }
417
418 return hastingsRatio;
419
420 }
421
422 public final String getOperatorName() {
423 return BayesianSkylineGibbsOperatorParser.BAYESIAN_SKYLINE_GIBBS_OPERATOR;
424 }
425
426 }