Debian Codegraph @

src/dr/evomodel/epidemiology/casetocase/periodpriors/NormalPeriodPriorDistribution.java

raw symbols SCIP
1 /*
2 * NormalPeriodPriorDistribution.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.epidemiology.casetocase.periodpriors;
27
28 import dr.inference.loggers.LogColumn;
29 import dr.inference.model.Parameter;
30 import dr.math.distributions.NormalDistribution;
31 import dr.math.distributions.NormalGammaDistribution;
32 import dr.math.functionEval.GammaFunction;
33 import dr.xml.*;
34 import org.apache.commons.math.MathException;
35 import org.apache.commons.math.distribution.TDistributionImpl;
36
37 import java.util.ArrayList;
38 import java.util.Arrays;
39
40 /**
41 The assumption here is that the periods are drawn from a normal distribution with unknown mean and variance.
42 The hyperprior is the conjugate, normal-gamma distribution.
43
44 @author Matthew Hall
45 */
46 public class NormalPeriodPriorDistribution extends AbstractPeriodPriorDistribution {
47
48 public static final String NORMAL = "normalPeriodPriorDistribution";
49 public static final String LOG = "log";
50 public static final String ID = "id";
51 public static final String MU = "mu";
52 public static final String LAMBDA = "lambda";
53 public static final String ALPHA = "alpha";
54 public static final String BETA = "beta";
55
56 private NormalGammaDistribution hyperprior;
57
58 private Parameter posteriorMean;
59 private Parameter posteriorBeta;
60 private Parameter posteriorExpectedPrecision;
61
62 double normalApproximationThreshold = 30;
63
64 private ArrayList<Double> dataValues;
65 private double[] currentParameters;
66
67 public NormalPeriodPriorDistribution(String name, boolean log, NormalGammaDistribution hyperprior){
68 super(name, log);
69 this.hyperprior = hyperprior;
70 posteriorBeta = new Parameter.Default(1);
71 posteriorMean = new Parameter.Default(1);
72 posteriorExpectedPrecision = new Parameter.Default(1);
73 addVariable(posteriorBeta);
74 addVariable(posteriorMean);
75 addVariable(posteriorExpectedPrecision);
76 }
77
78 public NormalPeriodPriorDistribution(String name, boolean log, double mu_0, double lambda_0,
79 double alpha_0, double beta_0){
80 this(name, log, new NormalGammaDistribution(mu_0, lambda_0, alpha_0, beta_0));
81 reset();
82 }
83
84 public void reset(){
85 dataValues = new ArrayList<Double>();
86 currentParameters = hyperprior.getParameters();
87 logL = 0;
88 }
89
90 // this returns the posterior predictive probability of the new value, and updates the total
91
92 public double calculateLogPosteriorProbability(double newValue, double minValue){
93 double out = calculateLogPosteriorPredictiveProbability(newValue);
94 if(minValue != Double.NEGATIVE_INFINITY){
95 out -= calculateLogPosteriorPredictiveCDF(minValue, true);
96 }
97 logL += out;
98 update(newValue);
99 return out;
100 }
101
102 public double calculateLogPosteriorCDF(double limit, boolean upper) {
103 return calculateLogPosteriorPredictiveCDF(limit, upper);
104 }
105
106
107 public double calculateLogPosteriorPredictiveProbability(double value){
108 double mean = currentParameters[0];
109 double sd = Math.sqrt(currentParameters[3]*(currentParameters[1]+1)
110 /(currentParameters[2]*currentParameters[1]));
111 double scaledValue = (value - mean)/sd;
112 double out;
113
114 if(2*currentParameters[2]<=normalApproximationThreshold) {
115 TDistributionImpl tDist = new TDistributionImpl(2 * currentParameters[2]);
116
117 out = Math.log(tDist.density(scaledValue));
118
119
120 } else {
121
122 out = NormalDistribution.logPdf(scaledValue, 0, 1);
123
124 }
125
126 return out;
127 }
128
129 public double calculateLogPosteriorPredictiveCDF(double value, boolean upperTail){
130 double mean = currentParameters[0];
131 double sd = Math.sqrt(currentParameters[3]*(currentParameters[1]+1)
132 /(currentParameters[2]*currentParameters[1]));
133 double scaledValue = (value - mean)/sd;
134 double out;
135
136 if(2*currentParameters[2]<=normalApproximationThreshold) {
137 TDistributionImpl tDist = new TDistributionImpl(2 * currentParameters[2]);
138
139 try {
140 out = upperTail ? Math.log(tDist.cumulativeProbability(-scaledValue))
141 : Math.log(tDist.cumulativeProbability(scaledValue));
142 } catch (MathException e){
143 throw new RuntimeException(e.toString());
144 }
145
146 } else {
147
148 out = upperTail ? NormalDistribution.standardCDF(-scaledValue, true) :
149 NormalDistribution.standardCDF(scaledValue, true);
150
151 }
152 return out;
153 }
154
155
156 private void update(double newData){
157 dataValues.add(newData);
158
159 double[] originalParameters=hyperprior.getParameters();
160 double lambda_0 = originalParameters[1];
161
162 double oldMu = currentParameters[0];
163 double oldLambda = currentParameters[1];
164 double oldAlpha = currentParameters[2];
165 double oldBeta = currentParameters[3];
166
167 double count = dataValues.size();
168
169 double newMu = (newData - oldMu)/(lambda_0 + count) + oldMu;
170 double newLambda = oldLambda + 1;
171 double newAlpha = oldAlpha + 0.5;
172 double newBeta = oldBeta + oldLambda*Math.pow(newData - oldMu, 2)/(2*(oldLambda+1));
173
174 posteriorMean.setParameterValue(0, newMu);
175 posteriorBeta.setParameterValue(0, newBeta);
176 posteriorExpectedPrecision.setParameterValue(0, newAlpha/newBeta);
177
178 currentParameters = new double[]{newMu, newLambda, newAlpha, newBeta};
179 }
180
181
182
183 public double calculateLogLikelihood(double[] values){
184
185 int count = values.length;
186
187 double[] infPredictiveDistributionParameters=hyperprior.getParameters();
188
189 double mu_0 = infPredictiveDistributionParameters[0];
190 double lambda_0 = infPredictiveDistributionParameters[1];
191 double alpha_0 = infPredictiveDistributionParameters[2];
192 double beta_0 = infPredictiveDistributionParameters[3];
193
194 double lambda_n = lambda_0 + count;
195 double alpha_n = alpha_0 + count/2;
196 double sum = 0;
197 for (Double infPeriod : values) {
198 sum += infPeriod;
199 }
200 double mean = sum/count;
201
202 double sumOfDifferences = 0;
203 for (Double infPeriod : values) {
204 sumOfDifferences += Math.pow(infPeriod-mean,2);
205 }
206
207 posteriorMean.setParameterValue(0, (lambda_0*mu_0 + sum)/(lambda_0 + count));
208
209 double beta_n = beta_0 + 0.5*sumOfDifferences
210 + lambda_0*count*Math.pow(mean-mu_0, 2)/(2*(lambda_0+count));
211
212 posteriorBeta.setParameterValue(0, beta_n);
213 posteriorExpectedPrecision.setParameterValue(0, alpha_n/beta_n);
214
215 logL = GammaFunction.logGamma(alpha_n)
216 - GammaFunction.logGamma(alpha_0)
217 + alpha_0*Math.log(beta_0)
218 - alpha_n*Math.log(beta_n)
219 + 0.5*Math.log(lambda_0)
220 - 0.5*Math.log(lambda_n)
221 - (count/2)*Math.log(2*Math.PI);
222
223
224 return logL;
225 }
226
227 public LogColumn[] getColumns() {
228 ArrayList<LogColumn> columns = new ArrayList<LogColumn>(Arrays.asList(super.getColumns()));
229
230 columns.add(new LogColumn.Abstract(getModelName()+"_posteriorMean"){
231 protected String getFormattedValue() {
232 return String.valueOf(posteriorMean.getParameterValue(0));
233 }
234 });
235
236 columns.add(new LogColumn.Abstract(getModelName()+"_posteriorBeta"){
237 protected String getFormattedValue() {
238 return String.valueOf(posteriorBeta.getParameterValue(0));
239 }
240 });
241
242 columns.add(new LogColumn.Abstract(getModelName()+"_posteriorExpectedPrecision"){
243 protected String getFormattedValue() {
244 return String.valueOf(posteriorExpectedPrecision.getParameterValue(0));
245 }
246 });
247
248 return columns.toArray(new LogColumn[columns.size()]);
249 }
250
251 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
252
253 public String getParserName() {
254 return NORMAL;
255 }
256
257 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
258 String id = (String) xo.getAttribute(ID);
259
260 double mu = xo.getDoubleAttribute(MU);
261 double lambda = xo.getDoubleAttribute(LAMBDA);
262 double alpha = xo.getDoubleAttribute(ALPHA);
263 double beta = xo.getDoubleAttribute(BETA);
264
265 boolean log;
266 log = xo.hasAttribute(LOG) ? xo.getBooleanAttribute(LOG) : false;
267
268 return new NormalPeriodPriorDistribution(id, log, mu, lambda, alpha, beta);
269
270 }
271
272 public XMLSyntaxRule[] getSyntaxRules() {
273 return rules;
274 }
275
276 private final XMLSyntaxRule[] rules = {
277 AttributeRule.newBooleanRule(LOG, true),
278 AttributeRule.newStringRule(ID, false),
279 AttributeRule.newDoubleRule(MU, false),
280 AttributeRule.newDoubleRule(LAMBDA, false),
281 AttributeRule.newDoubleRule(ALPHA, false),
282 AttributeRule.newDoubleRule(BETA, false)
283 };
284
285 public String getParserDescription() {
286 return "Calculates the probability of a set of doubles being drawn from the prior posterior distribution" +
287 "of a normal distribution of unknown mean and variance";
288 }
289
290 public Class getReturnType() {
291 return NormalPeriodPriorDistribution.class;
292 }
293 };
294
295 }