Debian Codegraph @

src/dr/inference/trace/MarginalLikelihoodAnalysis.java

raw symbols SCIP
1 /*
2 * MarginalLikelihoodAnalysis.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 package dr.inference.trace;
26
27 import dr.math.LogTricks;
28 import dr.math.MathUtils;
29 import dr.util.TaskListener;
30
31 import java.util.ArrayList;
32 import java.util.List;
33
34 /**
35 * @author Marc Suchard
36 * @author Alexei Drummond
37 * <p/>
38 * Source translated from model_P.c (a component of BAli-Phy by Benjamin Redelings and Marc Suchard
39 */
40 public class MarginalLikelihoodAnalysis {
41
42 private final String traceName;
43 private final List<Double> sample;
44 private final long burnin;
45 private final String analysisType; // "harmonic" for harmonic mean, "smoothed" for smoothed harmonic mean, "aicm" for AICM, "arithmetic" for arithmetic mean
46 private final int bootstrapLength;
47
48 private boolean marginalLikelihoodCalculated = false;
49 private double logMarginalLikelihood;
50 private double bootstrappedSE;
51
52
53 // public MarginalLikelihoodAnalysis(double[] sample, String traceName, int burnin) {
54 // this(sample, traceName, burnin, false, 1000);
55 // }
56
57 public String getTraceName() {
58 return traceName;
59 }
60
61 public long getBurnin() {
62 return burnin;
63 }
64
65 /**
66 * Constructor
67 *
68 * @param sample
69 * @param traceName used for 'toString' display purposes only
70 * @param burnin used for 'toString' display purposes only
71 * @param analysisType
72 * @param bootstrapLength a value of zero will turn off bootstrapping
73 */
74 public MarginalLikelihoodAnalysis(List<Double> sample, String traceName, long burnin, String analysisType, int bootstrapLength) {
75 this.sample = sample;
76 this.traceName = traceName;
77 this.burnin = burnin;
78 this.analysisType = analysisType;
79 this.bootstrapLength = bootstrapLength;
80 // System.err.println("setting burnin to "+burnin);
81 }
82
83 public double calculateLogMarginalLikelihood(List<Double> sample) {
84 if (analysisType.equals("aicm")) {
85 return logMarginalLikelihoodAICM(sample);
86 } else if (analysisType.equals("smoothed")) {
87 return logMarginalLikelihoodSmoothed(sample);
88 } else if (analysisType.equals("arithmetic")) {
89 return logMarginalLikelihoodArithmetic(sample);
90 } else {
91 return logMarginalLikelihoodHarmonic(sample);
92 }
93 }
94
95 /**
96 * Calculates the log marginal likelihood of a model using the arithmetic mean estimator
97 *
98 * @param v a posterior sample of logLikelihoods
99 * @return the log marginal likelihood
100 */
101 public double logMarginalLikelihoodArithmetic(List<Double> v) {
102
103 int size = v.size();
104
105 double sum = LogTricks.logZero;
106
107 for (int i = 0; i < size; i++) {
108 if (!Double.isNaN(v.get(i)) && !Double.isInfinite(v.get(i))) {
109 sum = LogTricks.logSum(sum, v.get(i));
110 } else {
111 size--;
112 }
113 }
114
115 return sum - StrictMath.log(size);
116
117 }
118
119 /**
120 * Calculates the log marginal likelihood of a model using Newton and Raftery's harmonic mean estimator
121 *
122 * @param v a posterior sample of logLikelihoods
123 * @return the log marginal likelihood
124 */
125
126 public double logMarginalLikelihoodHarmonic(List<Double> v) {
127
128 double sum = 0;
129 final int size = v.size();
130 for (int i = 0; i < size; i++)
131 sum += v.get(i);
132
133 double denominator = LogTricks.logZero;
134
135 for (int i = 0; i < size; i++)
136 denominator = LogTricks.logSum(denominator, sum - v.get(i));
137
138 return sum - denominator + StrictMath.log(size);
139 }
140
141 /**
142 * Calculates the AICM of a model using method-of-moments from Raftery et al. (2007)
143 *
144 * @param v a posterior sample of logLikelihoods
145 * @return the AICM (lower values are better)
146 */
147
148 public double logMarginalLikelihoodAICM(List<Double> v) {
149
150 double sum = 0;
151 final int size = v.size();
152 for (int i = 0; i < size; i++)
153 sum += v.get(i);
154
155 double mean = sum / (double) size;
156
157 double var = 0;
158 for (int i = 0; i < size; i++)
159 var += (v.get(i)-mean) * (v.get(i)-mean);
160 var /= (double) size - 1;
161
162 return 2 * var - 2 * mean;
163
164 }
165
166 public void calculate() {
167
168 logMarginalLikelihood = calculateLogMarginalLikelihood(sample);
169 if (bootstrapLength > 1) {
170 final int sampleLength = sample.size();
171 List<Double> bsSample = new ArrayList<Double>();
172 Double[] bootstrappedLogML = new Double[bootstrapLength];
173 double sum = 0;
174
175 double progress = 0.0;
176 double delta = 1.0 / bootstrapLength;
177
178 //System.err.println("HME = " + logMarginalLikelihood);
179
180 for (int i = 0; i < bootstrapLength; i++) {
181 // if (i % 10 == 0) {
182 // System.err.println((i+1) + "/" + bootstrapLength);
183 // }
184
185 fireProgress(progress);
186 progress += delta;
187
188 int[] indices = MathUtils.sampleIndicesWithReplacement(sampleLength);
189 for (int k = 0; k < sampleLength; k++) {
190 bsSample.add(sample.get(indices[k]));
191 }
192 bootstrappedLogML[i] = calculateLogMarginalLikelihood(bsSample);
193 sum += bootstrappedLogML[i];
194 bsSample.clear();
195 }
196 sum /= bootstrapLength;
197 double bootstrappedAverage = sum;
198 // Summarize bootstrappedLogML
199 double var = 0;
200 for (int i = 0; i < bootstrapLength; i++) {
201 var += (bootstrappedLogML[i] - bootstrappedAverage) *
202 (bootstrappedLogML[i] - bootstrappedAverage);
203 }
204 var /= (bootstrapLength - 1.0);
205 bootstrappedSE = Math.sqrt(var);
206 }
207
208 fireProgress(1.0);
209
210 marginalLikelihoodCalculated = true;
211 }
212
213 /**
214 * Calculates the log marginal likelihood of a model using Newton and Raftery's smoothed estimator
215 *
216 * @param v a posterior sample of logLikelihood
217 * @param delta proportion of pseudo-samples from the prior
218 * @param Pdata current estimate of the log marginal likelihood
219 * @return the log marginal likelihood
220 */
221 @SuppressWarnings({"SuspiciousNameCombination"})
222 public double logMarginalLikelihoodSmoothed(List<Double> v, double delta, double Pdata) {
223
224 final double logDelta = StrictMath.log(delta);
225 final double logInvDelta = StrictMath.log(1.0 - delta);
226 final int n = v.size();
227 final double logN = StrictMath.log(n);
228
229 final double offset = logInvDelta - Pdata;
230
231 double bottom = logN + logDelta - logInvDelta;
232 double top = bottom + Pdata;
233
234 for (int i = 0; i < n; i++) {
235 double weight = -LogTricks.logSum(logDelta, offset + v.get(i));
236 top = LogTricks.logSum(top, weight + v.get(i));
237 bottom = LogTricks.logSum(bottom, weight);
238 }
239
240 return top - bottom;
241 }
242
243 public double getLogMarginalLikelihood() {
244 if (!marginalLikelihoodCalculated) {
245 calculate();
246 }
247 return logMarginalLikelihood;
248 }
249
250 public double getBootstrappedSE() {
251 if (!marginalLikelihoodCalculated) {
252 calculate();
253 }
254 return bootstrappedSE;
255 }
256
257 public String toString() {
258 StringBuilder sb = new StringBuilder();
259
260 if (analysisType.equals("smoothed")) {
261 sb.append("log marginal likelihood (using smoothed harmonic mean)");
262 }
263 else if (analysisType.equals("aicm")) {
264 sb.append("AICM");
265 }
266 else if (analysisType.equals("arithmetic")) {
267 sb.append("log marginal likelihood (using arithmetic mean)");
268 }
269 else {
270 sb.append("log marginal likelihood (using harmonic mean)");
271 }
272
273 sb.append(" from ")
274 .append(traceName)
275 .append(" = ")
276 .append(String.format("%5.4f", getLogMarginalLikelihood()));
277 if (bootstrapLength > 1) {
278 sb.append(" +/- ")
279 .append(String.format("%5.4f", getBootstrappedSE()));
280 } else {
281 sb.append(" ");
282 }
283
284 sb.append(" burnin=").append(burnin);
285 if (bootstrapLength > 1)
286 sb.append(" replicates=").append(bootstrapLength);
287 // sb.append("\n");
288
289 return sb.toString();
290
291 }
292
293 public double logMarginalLikelihoodSmoothed(List<Double> v) {
294
295 final double delta = 0.01; // todo make class adjustable by accessor/setter
296
297 // Start with harmonic estimator as first guess
298 double Pdata = logMarginalLikelihoodHarmonic(v);
299
300 double deltaP = 1.0;
301
302 int iterations = 0;
303
304 double dx;
305
306 final double tolerance = 1E-3; // todo make class adjustable by accessor/setter
307
308 while (Math.abs(deltaP) > tolerance) {
309 double g1 = logMarginalLikelihoodSmoothed(v, delta, Pdata) - Pdata;
310 double Pdata2 = Pdata + g1;
311 dx = g1 * 10.0;
312 double g2 = logMarginalLikelihoodSmoothed(v, delta, Pdata + dx) - (Pdata + dx);
313 double dgdx = (g2 - g1) / dx; // find derivative at Pdata
314
315 double Pdata3 = Pdata - g1 / dgdx; // find new evaluation point
316 if (Pdata3 < 2.0 * Pdata || Pdata3 > 0 || Pdata3 > 0.5 * Pdata) // step is too large
317 Pdata3 = Pdata + 10.0 * g1;
318
319 double g3 = logMarginalLikelihoodSmoothed(v, delta, Pdata3) - Pdata3;
320
321 // Try to do a Newton's method step
322 if (Math.abs(g3) <= Math.abs(g2) && ((g3 > 0) || (Math.abs(dgdx) > 0.01))) {
323 deltaP = Pdata3 - Pdata;
324 Pdata = Pdata3;
325 } // otherwise try to go 10 times as far as one step
326 else if (Math.abs(g2) <= Math.abs(g1)) {
327 Pdata2 += g2;
328 deltaP = Pdata2 - Pdata;
329 Pdata = Pdata2;
330 } // otherwise go just one step
331 else {
332 deltaP = g1;
333 Pdata += g1;
334 }
335
336 iterations++;
337
338 if (iterations > 400) { // todo make class adjustable by acessor/setter
339 System.err.println("Probabilities are not converging!!!"); // todo should throw exception
340 return LogTricks.logZero;
341 }
342 }
343 return Pdata;
344 }
345
346 private TaskListener listener = null;
347
348 public void setTaskListener(TaskListener listener) {
349 this.listener = listener;
350 }
351
352 private void fireProgress(double progress) {
353 if (listener != null) {
354 listener.progress(progress);
355 }
356 }
357
358 }