Debian Codegraph @

src/dr/math/distributions/InverseGaussianDistribution.java

raw symbols SCIP
1 /*
2 * InverseGaussianDistribution.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.math.distributions;
27
28 import dr.math.UnivariateFunction;
29 import dr.math.interfaces.OneVariableFunction;
30 import dr.math.iterations.BisectionZeroFinder;
31 import dr.math.iterations.NewtonZeroFinder;
32
33 /**
34 * normal distribution (pdf, cdf, quantile)
35 *
36 * @author Wai Lok Sibon Li
37 * @version $Id: InverseGaussianDistribution.java,v 1.7 2008/04/24 20:26:01 rambaut Exp $
38 *
39 * Reading: Chhikara, R. S., and Folks, J. Leroy, (1989). The
40 * inverse Gaussian distribution: Theory, methodology, and applications. Marcel Dekker, New York.
41 */
42 public class InverseGaussianDistribution implements Distribution {
43 //
44 // Public stuff
45 //
46
47 /**
48 * Constructor
49 *
50 * @param mean mean
51 * @param shape shape
52 */
53 public InverseGaussianDistribution(double mean, double shape) {
54 this.m = mean;
55 this.shape = shape;
56 this.sd = calculateSD(mean, shape);
57 }
58
59 public double getMean() {
60 return m;
61 }
62
63 public void setMean(double value) {
64 m = value;
65 }
66
67 public double getShape() {
68 return shape;
69 }
70
71 public void setShape(double value) {
72 shape = value;
73 sd = calculateSD(m, shape);
74 }
75
76 public static double calculateSD(double mean, double shape) {
77 return Math.sqrt((mean * mean * mean) / shape);
78 }
79 //public double getSD() {
80 //return sd;
81 //}
82
83 //public void setSD(double value) {
84 //sd = value;
85 //}
86
87 public double pdf(double x) {
88 return pdf(x, m, shape);
89 }
90
91 public double logPdf(double x) {
92 return logPdf(x, m, shape);
93 }
94
95 public double cdf(double x) {
96 return cdf(x, m, shape);
97 }
98
99 public double quantile(double y) {
100 return quantile(y, m, shape);
101 }
102
103 public double mean() {
104 return mean(m, shape);
105 }
106
107 public double variance() {
108 return variance(m, shape);
109 }
110
111 public final UnivariateFunction getProbabilityDensityFunction() {
112 return pdfFunction;
113 }
114
115 private UnivariateFunction pdfFunction = new UnivariateFunction() {
116 public final double evaluate(double x) {
117 return pdf(x);
118 }
119
120 public final double getLowerBound() {
121 return 0.0;
122 //return Double.NEGATIVE_INFINITY;
123 }
124
125 public final double getUpperBound() {
126 return Double.POSITIVE_INFINITY;
127 }
128 };
129
130 /**
131 * probability density function
132 *
133 * @param x argument
134 * @param m mean
135 * @param shape shape parameter
136 * @return pdf at x
137 */
138 public static double pdf(double x, double m, double shape) {
139 double a = Math.sqrt(shape / (2.0 * Math.PI * x * x * x));
140 double b = ((-shape) * (x - m) * (x - m)) / (2.0 * m * m * x);
141 return a * Math.exp(b);
142 }
143
144 /**
145 * the natural log of the probability density function of the distribution
146 *
147 * @param x argument
148 * @param m mean
149 * @param shape shape parameter
150 * @return log pdf at x
151 */
152 public static double logPdf(double x, double m, double shape) {
153 double a = Math.sqrt(shape / (2.0 * Math.PI * x * x * x));
154 double b = ((-shape) * (x - m) * (x - m)) / (2.0 * m * m * x);
155 return Math.log(a) + b;
156 }
157
158 /**
159 * cumulative density function
160 *
161 * @param x argument
162 * @param m mean
163 * @param shape shape parameter
164 * @return cdf at x
165 */
166 public static double cdf(double x, double m, double shape) {
167 if (x <= 0 || m <= 0 || shape <= 0) {
168 return Double.NaN;
169 }
170 /* Taken from R code, package SuppDists */
171 double a = Math.sqrt(shape / x);
172 double b = x / m;
173 //double p1 = NormalDistribution.cdf(a*(b - 1.0),0.0,1.0);
174 double p1 = NormalDistribution.cdf(a * (b - 1.0), 0.0, 1.0, false);
175 //double p2 = NormalDistribution.cdf(-a*(b + 1.0),0.0,1.0);
176 double p2 = NormalDistribution.cdf(-a * (b + 1.0), 0.0, 1.0, false);
177 if (p2 == 0.0) {
178 return p1;
179 }
180 else {
181 double c=2.0 * shape / m;
182 if (c>=0x1.fffffffffffffP+1023) {// Double.MAX_EXPONENT is Java 1.6 feature
183 return Double.POSITIVE_INFINITY;
184 }
185 return p1 + Math.exp(c) * p2;
186 }
187
188 /* Another implementation of the inverse Gaussian cdf that doesn't use the Normal distribution function
189 * Is not as accurate (due to error function issues)
190 */
191 // double a = Math.sqrt(shape / (2.0 * x)) * ((x / m) - 1);
192 // double b = (1.0 + ErrorFunction.erf(a));
193 // double c = Math.sqrt(shape / (2.0 * x)) * ((x / m) + 1);
194 // double d = ((2.0 * shape) / m) + Math.log(1 - ErrorFunction.erf(c));
195 // return 0.5*b + 0.5*Math.exp(d);
196 }
197
198 /**
199 * quantiles (=inverse cumulative density function)
200 * <p/>
201 *
202 * Same implementation as SuppleDists in R.
203 *
204 * Using Whitmore and Yalovsky for an initial guess. Works well for
205 * large t=lambda/mu > 2 perhaps
206 * Whitmore, G.A. and Yalovsky, M. (1978). A normalizing logarithmic
207 * transformation for inverse Gaussian random variables,
208 * Technometrics 20-2, 207-208
209 * For small t, with x<0.5 mu, use gamma approx to 1/x -- alpha=1/2 and beta =2/lambda and 1-p
210 * When x>0.5mu, approx x with gamma for p, and exponentiate -- don't know why this works.
211 *
212 * There are cases which even this method produces inaccurate results (e.g. when shape = 351). Therefore,
213 * we have a catch that will determine whether or not the result is accurate enough and if not,
214 * then a zerofinder will be used to find a more accurate approximation.
215 *
216 * @param z argument
217 * @param m mean
218 * @param shape shape parameter
219 * @return icdf at z
220 */
221 public static double quantile(double z, double m, double shape) {
222 if(z < 0.01 || z > 0.99) {
223 System.err.print("Quantile is " + z);
224 throw new RuntimeException("Quantile is too low/high to calculate (numerical estimation for extreme values is incomplete)");
225 }
226
227 /* Approximation method used by Mudholkar GS, Natarajan R (1999)
228 * Approximations for the inverse gaussian probabilities and percentiles.
229 * Communications in Statistics - Simulation and Computation 28: 1051 - 1071.
230 */
231 double initialGuess;
232 if (shape / m > 2.0) {
233 initialGuess=(NormalDistribution.quantile(z,0.0,1.0)-0.5*Math.sqrt(m/shape))/Math.sqrt(shape/m);
234 initialGuess=m*Math.exp(initialGuess);
235 }
236 else {
237 initialGuess=shape/(GammaDistribution.quantile(1.0-z,0.5,1.0)*2.0);
238 if (initialGuess > m / 2.0) { // too large for the gamma approx
239 initialGuess=m*Math.exp(GammaDistribution.quantile(z,0.5,1.0)*0.1); // this seems to work for the upper tail ???
240 }
241 }
242 // double phi = shape / m;
243 // if(phi>50.0) {
244 // Use Normal Distribution
245 // initialGuess = (NormalDistribution.quantile(z, m,Math.sqrt(m*m*m/shape)));//-0.5*Math.sqrt(m/shape))/Math.sqrt(m*m*m/shape);
246 // }
247
248 final InverseGaussianDistribution f = new InverseGaussianDistribution(m, shape);
249 final double y = z;
250 NewtonZeroFinder zeroFinder = new NewtonZeroFinder(new OneVariableFunction() {
251 public double value (double x) {
252 return f.cdf(x) - y;
253 }
254 }, initialGuess);
255 zeroFinder.evaluate();
256
257 if(Double.isNaN(zeroFinder.getResult()) || zeroFinder.getPrecision() > 0.000005) {
258 zeroFinder = new NewtonZeroFinder(new OneVariableFunction() {
259 public double value (double x) {
260 return f.cdf(x) - y;
261 }
262 }, initialGuess);
263 zeroFinder.initializeIterations();
264 int i;
265 double previousPrecision = 0.0, previousResult = Double.NaN;
266 double max = 10000.0, min = 0.00001;
267 for(i=0; i < 50; i++) {
268 zeroFinder.evaluateIteration();
269 double precision = f.cdf(zeroFinder.getResult()) - z;
270 if((previousPrecision > 0 && precision < 0) || (previousPrecision < 0 && precision > 0)) {
271 max = Math.max(previousResult, zeroFinder.getResult());
272 min = Math.min(previousResult, zeroFinder.getResult());
273 max = Math.min(10000.0, max);
274 break;
275 }
276
277 previousPrecision = precision;
278 previousResult = zeroFinder.getResult();
279
280 }
281 return calculateZeroFinderApproximation(z, m, shape, min, max, initialGuess);
282 }
283 return zeroFinder.getResult();
284 }
285
286 /** Finds the approximation of the inverse Gaussian quantile using a zero finder
287 * until it converges
288 *
289 * @param z quantile
290 * @param m mean
291 * @param shape shape
292 * @param min min search value
293 * @param max max search value
294 * @param initialGuess first guess of the quantile
295 * @return estimated x value at quantile z
296 */
297 private static double calculateZeroFinderApproximation(double z, double m, double shape, double min, double max, double initialGuess) {
298 final InverseGaussianDistribution f = new InverseGaussianDistribution(m, shape);
299 final double y = z;
300 BisectionZeroFinder bisectionZeroFinder = new BisectionZeroFinder(new OneVariableFunction() {
301 public double value(double x) {
302 return f.cdf(x) - y;
303 }
304 }, min, max);
305 bisectionZeroFinder.setInitialValue(initialGuess);
306 bisectionZeroFinder.initializeIterations();
307
308 double bestValue = Double.NaN; /* I found that the converged value is not necesssarily the best */
309 double bestPrecision = 10;
310 double precision = 10;
311 double previousPrecision = 10;
312 int count = 0;
313 while(precision > 0.001 && count < 10) {
314 bisectionZeroFinder.evaluateIteration();
315 precision = Math.abs(f.cdf(bisectionZeroFinder.getResult()) - z);
316 if(precision < bestPrecision) {
317 bestPrecision = precision;
318 bestValue = bisectionZeroFinder.getResult();
319 }
320 else if(previousPrecision == precision) {
321 count++;
322 }
323 previousPrecision = precision;
324 }
325 bisectionZeroFinder.finalizeIterations();
326 /* Turns out the final answer is not necessarily the most accurate */
327 //return bisectionZeroFinder.getResult();
328 return bestValue;
329 }
330
331
332 /** Calculates the gamma approximation of the quantile estimate of Inverse Gaussian
333 * Shifted Gamma
334 * (see Mudholkar GS, Natarajan R (1999))
335 * UNUSED METHOD
336 *
337 * @param z quantile
338 * @param m mean
339 * @param shape shape
340 * @return approximation of x
341 */
342 private static double calculateShiftedGammaApproximation(double z, double m, double shape) {
343 double a = (3 * m * m) / (4 * shape);
344 double b = (m / 3);
345 double nu = (8 * shape) / (9 * m);
346 return a * ChiSquareDistribution.quantile(z, nu) + b;
347 }
348
349 /** Calculates the gamma approximation of the quantile estimate of Inverse Gaussian
350 * Shifted Gamma adapted to reciprocal Inverse Gaussian
351 * (see Mudholkar GS, Natarajan R (1999))
352 * UNUSED METHOD
353 *
354 * @param z quantile
355 * @param m mean
356 * @param shape shape
357 * @return approximation of x
358 */
359 private static double calculateShiftedGammaApproximationWithRIG(double z, double m, double shape) {
360 double a = (3 * shape + 8 * m)/(4 * shape * (shape + 2 * m));
361 double b = (shape + 3 * m)/(m * (3 * shape + 8 * m));
362 double nu = (8 * Math.pow((shape + 2 * m), 3)) / (m * Math.pow((8 * m + 3 * shape), 2));
363 double y_hat = a * ChiSquareDistribution.quantile(z, nu) + b;
364 return 1 / y_hat;
365 }
366
367 /** Finds the approximation of the inverse Gaussian quantile using a zero finder
368 * given a set number of maximum iterations
369 * UNUSED METHOD
370 *
371 * @param z quantile
372 * @param m mean
373 * @param shape shape
374 * @param numIterations number of iterations used to approximate value
375 * @param min min search value
376 * @param max max search value
377 * @return estimated x value at quantile z
378 */
379 private static double calculateZeroFinderApproximation(double z, double m, double shape, int numIterations, double min, double max) {
380 final InverseGaussianDistribution f = new InverseGaussianDistribution(m, shape);
381 final double y = z;
382 BisectionZeroFinder bisectionZeroFinder = new BisectionZeroFinder(new OneVariableFunction() {
383 public double value(double x) {
384 return f.cdf(x) - y;
385 }
386 }, min, max);
387 //}, 0.0001, 100000);
388
389 bisectionZeroFinder.setMaximumIterations(numIterations);
390 bisectionZeroFinder.evaluate();
391 return bisectionZeroFinder.getResult();
392 }
393
394 /**
395 * mean
396 *
397 * @param m mean
398 * @param shape shape parameter
399 * @return mean
400 */
401 public static double mean(double m, double shape) {
402 return m;
403 }
404
405 /**
406 * variance
407 *
408 * @param m mean
409 * @param shape shape parameter
410 * @return variance
411 */
412 public static double variance(double m, double shape) {
413 double sd = calculateSD(m, shape);
414 return sd * sd;
415 }
416
417 // Private
418
419 protected double m, sd, shape;
420
421 }