Debian Codegraph @

src/dr/math/distributions/GammaDistribution.java

raw symbols SCIP
1 /*
2 * GammaDistribution.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 cern.jet.random.Gamma;
29 import cern.jet.random.engine.MersenneTwister;
30 import cern.jet.random.engine.RandomEngine;
31 import dr.math.GammaFunction;
32 import dr.math.MathUtils;
33 import dr.math.UnivariateFunction;
34 import org.apache.commons.math.MathException;
35 import org.apache.commons.math.distribution.GammaDistributionImpl;
36
37 import java.util.ArrayList;
38 import java.util.Collections;
39 import java.util.List;
40
41 /**
42 * gamma distribution.
43 * <p/>
44 * (Parameters: shape, scale; mean: scale*shape; variance: scale^2*shape)
45 *
46 * @author Korbinian Strimmer
47 * @author Gerton Lunter
48 * @version $Id: GammaDistribution.java,v 1.9 2006/03/30 11:12:47 rambaut Exp $
49 */
50 public class GammaDistribution implements Distribution {
51 //
52 // Public stuff
53 //
54
55 /**
56 * Constructor
57 */
58 public GammaDistribution(double shape, double scale) {
59 this.shape = shape;
60 this.scale = scale;
61 this.samples = 0;
62
63 if (TRY_COLT) {
64 randomEngine = new MersenneTwister(MathUtils.nextInt());
65 System.out.println("Colt Gamma(" + shape + "," + scale + ")");
66 coltGamma = new Gamma(shape, 1.0/scale, randomEngine);
67 }
68 }
69
70 public double getShape() {
71 return shape;
72 }
73
74 public void setShape(double value) {
75 shape = value;
76 }
77
78 public double getScale() {
79 return scale;
80 }
81
82 public void setScale(double value) {
83 scale = value;
84 }
85
86 public double pdf(double x) {
87 if (TRY_COLT) {
88 return coltGamma.pdf(x);
89 } else {
90 return pdf(x, shape, scale);
91 }
92 }
93
94 public double logPdf(double x) {
95 if (TRY_COLT) {
96 return Math.log(coltGamma.pdf(x));
97 } else {
98 return logPdf(x, shape, scale);
99 }
100 }
101
102 public double cdf(double x) {
103 if (TRY_COLT) {
104 return coltGamma.cdf(x);
105 } else {
106 return cdf(x, shape, scale);
107 }
108 }
109
110 public double quantile(double y) {
111 return quantile(y, shape, scale);
112 }
113
114 public double mean() {
115 return mean(shape, scale);
116 }
117
118 public double variance() {
119 return variance(shape, scale);
120 }
121
122 public double nextGamma() {
123 return nextGamma(shape, scale);
124 }
125
126 public final UnivariateFunction getProbabilityDensityFunction() {
127 return pdfFunction;
128 }
129
130 private final UnivariateFunction pdfFunction = new UnivariateFunction() {
131 public final double evaluate(double x) {
132 return pdf(x);
133 }
134
135 public final double getLowerBound() {
136 return 0.0;
137 }
138
139 public final double getUpperBound() {
140 return Double.POSITIVE_INFINITY;
141 }
142 };
143
144 /**
145 * probability density function of the Gamma distribution
146 *
147 * @param x argument
148 * @param shape shape parameter
149 * @param scale scale parameter
150 * @return pdf value
151 */
152 public static double pdf(double x, double shape, double scale) {
153 // return Math.pow(scale,-shape)*Math.pow(x, shape-1.0)/
154 // Math.exp(x/scale + GammaFunction.lnGamma(shape));
155 if (x < 0) return 0; // to make BEAUti plot continue
156 // throw new IllegalArgumentException();
157 if (x == 0) {
158 if (shape == 1.0)
159 return 1.0 / scale;
160 else
161 return 0.0;
162 }
163
164 if (shape == 0.0) // uninformative
165 return 1.0 / x;
166
167 if (shape == -0.5) { // Gelman 2008, hierarchical variance, -1 degrees of freedom
168 return Math.sqrt(x);
169 }
170
171 final double xs = x / scale;
172
173 if (shape == 1.0) {
174 return Math.exp(-xs) / scale;
175 }
176
177 final double a = Math.exp((shape - 1.0) * Math.log(xs) - xs
178 - GammaFunction.lnGamma(shape));
179
180 return a / scale;
181 }
182
183 /**
184 * the natural log of the probability density function of the distribution
185 *
186 * @param x argument
187 * @param shape shape parameter
188 * @param scale scale parameter
189 * @return log pdf value
190 */
191 public static double logPdf(double x, double shape, double scale) {
192 // double a = Math.pow(scale,-shape) * Math.pow(x, shape-1.0);
193 // double b = x/scale + GammaFunction.lnGamma(shape);
194 // return Math.log(a) - b;
195
196 // AR - changed this to return -ve inf instead of throwing an
197 // exception... This makes things
198 // much easier when using this to calculate log likelihoods.
199 // if (x < 0) throw new IllegalArgumentException();
200 if (x < 0)
201 return Double.NEGATIVE_INFINITY;
202
203 if (x == 0) {
204 if (shape == 1.0)
205 return Math.log(1.0 / scale);
206 else
207 return Double.NEGATIVE_INFINITY;
208 }
209 if (shape == 1.0) {
210 return (-x / scale) - Math.log(scale);
211 }
212 if (shape == 0.0) // uninformative
213 return -Math.log(x);
214
215 if (shape == -0.5) { // Gelman 2008, hierarchical variance, -1 degrees of freedom
216 return 0.5 * Math.log(x);
217 }
218
219 /*return ((shape - 1.0) * Math.log(x/scale) - x / scale - GammaFunction
220 .lnGamma(shape))
221 - Math.log(scale);*/
222
223 return ((shape - 1.0) * (Math.log(x) - Math.log(scale)) - x / scale - GammaFunction
224 .lnGamma(shape))
225 - Math.log(scale);
226 }
227
228 /**
229 * cumulative density function of the Gamma distribution
230 *
231 * @param x argument
232 * @param shape shape parameter
233 * @param scale scale parameter
234 * @return cdf value
235 */
236 public static double cdf(double x, double shape, double scale) {
237 if (x < 0.0 || shape <= 0.0) {
238 return 0;
239 }
240 return GammaFunction.incompleteGammaP(shape, x / scale);
241 }
242
243 /**
244 * quantile (inverse cumulative density function) of the Gamma distribution
245 *
246 * @param y argument
247 * @param shape shape parameter
248 * @param scale scale parameter
249 * @return icdf value
250 */
251 public static double quantile(double y, double shape, double scale) {
252 return 0.5 * scale * pointChi2(y, 2.0 * shape);
253 }
254
255 /**
256 * mean of the Gamma distribution
257 *
258 * @param shape shape parameter
259 * @param scale scale parameter
260 * @return mean
261 */
262 public static double mean(double shape, double scale) {
263 return scale * shape;
264 }
265
266 /**
267 * variance of the Gamma distribution.
268 *
269 * @param shape shape parameter
270 * @param scale scale parameter
271 * @return variance
272 */
273 public static double variance(double shape, double scale) {
274 return scale * scale * shape;
275 }
276
277 /**
278 * sample from the Gamma distribution. This could be calculated using
279 * quantile, but current algorithm is faster.
280 *
281 * @param shape shape parameter
282 * @param scale scale parameter
283 * @return sample
284 */
285 public static double nextGamma(double shape, double scale) {
286 if (TRY_COLT) {
287 return coltGamma.nextDouble(shape, 1.0/scale);
288 }
289 return nextGamma(shape, scale, false);
290 }
291
292 public static double nextGamma(double shape, double scale, boolean slowCode) {
293
294 double sample = 0.0;
295
296 if (shape < 0.00001) {
297
298 if (shape < 0) {
299 System.out.println("Negative shape parameter");
300 throw new IllegalArgumentException("Negative shape parameter");
301 }
302
303 /*
304 * special case: shape==0.0 is an improper distribution; but
305 * sampling works if very small values are ignored (v. large ones
306 * don't happen) This is useful e.g. for sampling from the truncated
307 * Gamma(0,x)-distribution.
308 */
309
310 double minimum = 1.0e-20;
311 double maximum = 50;
312 double normalizingConstant = Math.log(maximum) - Math.log(minimum);
313 // Draw from 1/x (with boundaries), and shape by exp(-x)
314 do {
315 sample = Math.exp(Math.log(minimum) + normalizingConstant
316 * MathUtils.nextDouble());
317 } while (Math.exp(-sample) < MathUtils.nextDouble());
318 // This distribution is actually scale-free, so multiplying by
319 // 'scale' is not necessary
320 return sample;
321 }
322
323 if (slowCode && Math.floor(shape) == shape && shape > 4.0) {
324 for (int i = 0; i < shape; i++)
325 sample += -Math.log(MathUtils.nextDouble());
326 return sample * scale;
327 } else {
328
329 // Fast special cases
330 if (shape == 1.0) {
331 return -Math.log(MathUtils.nextDouble()) * scale;
332 }
333 if (shape == 2.0) {
334 return -Math.log(MathUtils.nextDouble()
335 * MathUtils.nextDouble())
336 * scale;
337 }
338 if (shape == 3.0) {
339 return -Math.log(MathUtils.nextDouble()
340 * MathUtils.nextDouble() * MathUtils.nextDouble())
341 * scale;
342 }
343 if (shape == 4.0) {
344 return -Math.log(MathUtils.nextDouble()
345 * MathUtils.nextDouble() * MathUtils.nextDouble()
346 * MathUtils.nextDouble())
347 * scale;
348 }
349 }
350
351 // general case
352 do {
353 try {
354 sample = quantile(MathUtils.nextDouble(), shape, scale);
355 } catch (IllegalArgumentException e) {
356 // random doubles do go outside the permissible range 0.000002 <
357 // q < 0.999998
358 sample = 0.0;
359 }
360 } while (sample == 0.0);
361 return sample;
362 }
363
364 /**
365 * Sample from the gamma distribution, modified by a factor exp(
366 * -(x*bias)^-1 ), i.e. from x^(shape - 1) exp(-x/scale) exp(-1/(bias*x))
367 * <p/>
368 * Works by rejection sampling, using a shifted ordinary Gamma as proposal
369 * distribution.
370 * <p/>
371 * (For an older, less efficient algorithm that breaks down for shape <= 1.0,
372 * see revision 287)
373 */
374 public static double nextExpGamma(double shape, double scale, double bias) {
375 return nextExpGamma(shape, scale, bias, false);
376 }
377
378 public static double nextExpGamma(double shape, double scale, double bias,
379 boolean slowCode) {
380
381 double sample;
382 double accept;
383 int iters = 0;
384
385 if (slowCode) {
386
387 // for testing purposes -- this can get stuck completely for small bias parameters
388 do {
389 sample = nextGamma(shape, scale);
390 accept = Math.exp(-1.0 / (bias * sample));
391 } while (MathUtils.nextDouble() > accept);
392
393 } else {
394
395 if (shape < 0) {
396
397 //return scale / (nextExpGamma(-shape, scale, bias) * bias);
398 return 1.0 / nextExpGamma(-shape, bias, scale);
399
400 }
401
402 if (shape == 0) {
403
404 // sample from the restriction to x >= median, and sample the other half by using
405 // the self-similarity transformation x -> scale / (bias*x)
406
407 double median = Math.sqrt(scale / bias);
408 double rejection_mode = 1.0 / bias; // mode of rejection distribution, x^-1 e^(-1/bias x)
409 if (rejection_mode < median)
410 rejection_mode = median;
411 double rejection_norm = (1.0 / rejection_mode) * Math.exp(-1.0 / (bias * rejection_mode));
412 do {
413 sample = nextGamma(1.0, scale) + median;
414 accept = (1.0 / sample) * Math.exp(-1.0 / (sample * bias)) / rejection_norm;
415 iters += 1;
416 } while (MathUtils.nextDouble() > accept && iters < 10000);
417 if (iters == 10000) {
418 System.out.println("Severe Warning: nextExpGamma (shape=0) failed to generate a sample - returning bogus value!");
419 }
420 if (MathUtils.nextDouble() > 0.5) {
421 sample = scale / (bias * sample);
422 }
423 return sample;
424 }
425
426 // Current algorithm works for all shape parameters > 0, but it becomes very inefficient
427 // for v. small shape parameters.
428 if (shape <= 0.0) {
429 System.out.println("nextExpGamma: Illegal argument (shape parameter is must be positive)");
430 throw new IllegalArgumentException("");
431 }
432
433 // the function -1/(bias*x) is bounded by x/(bias x0^2) + C, with C = -2/(bias*x0), so that these functions
434 // coincide precisely when x=x0. This gives the scale parameter of the majorating Gamma distribution
435 //
436 // First calculate the value that maximizes the acceptance probability at the mean of the proposal distribution
437 double x0 = (shape * scale + Math.sqrt(4 * scale / bias + shape * shape * scale * scale)) / 2.0;
438
439 // calculate the scale parameter of the majorating Gamma distribution
440 double majorandScale = 1.0 / ((1.0 / scale) - 1.0 / (bias * x0 * x0));
441
442 // now do rejection sampling
443 do {
444 sample = nextGamma(shape, majorandScale);
445 accept = Math.exp(-(sample / x0 - 1) * (sample / x0 - 1) / (bias * sample));
446 iters += 1;
447 } while (MathUtils.nextDouble() > accept && iters < 10000);
448
449 if (accept > 1.0) {
450 System.out.println("PROBLEM!! This should be impossible!! Contact the authors.");
451 }
452 if (majorandScale < 0.0) {
453 System.out.println("PROBLEM!! This should be impossible too!! Contact the authors.");
454 }
455 if (iters == 10000) {
456 System.out.println("Severe Warning: nextExpGamma failed to generate a sample - returning bogus value!");
457 }
458 }
459
460 return sample;
461
462 }
463
464 // Private
465
466 private static double pointChi2(double prob, double v) {
467 // Returns z so that Prob{x<z}=prob where x is Chi2 distributed with df
468 // = v
469 // RATNEST FORTRAN by
470 // Best DJ & Roberts DE (1975) The percentage points of the
471 // Chi2 distribution. Applied Statistics 24: 385-388. (AS91)
472
473 final double e = 0.5e-6, aa = 0.6931471805, p = prob;
474 double ch, a, q, p1, p2, t, x, b, s1, s2, s3, s4, s5, s6;
475 double epsi = .01;
476 if( p < 0.000002 || p > 1 - 0.000002) {
477 epsi = .000001;
478 }
479 // if (p < 0.000002 || p > 0.999998 || v <= 0) {
480 // throw new IllegalArgumentException("Arguments out of range p" + p + " v " + v);
481 // }
482 double g = GammaFunction.lnGamma(v / 2);
483 double xx = v / 2;
484 double c = xx - 1;
485 if (v < -1.24 * Math.log(p)) {
486 ch = Math.pow((p * xx * Math.exp(g + xx * aa)), 1 / xx);
487 if (ch - e < 0) {
488 return ch;
489 }
490 } else {
491 if (v > 0.32) {
492 x = NormalDistribution.quantile(p, 0, 1);
493 p1 = 0.222222 / v;
494 ch = v * Math.pow((x * Math.sqrt(p1) + 1 - p1), 3.0);
495 if (ch > 2.2 * v + 6) {
496 ch = -2 * (Math.log(1 - p) - c * Math.log(.5 * ch) + g);
497 }
498 } else {
499 ch = 0.4;
500 a = Math.log(1 - p);
501
502
503 do {
504 q = ch;
505 p1 = 1 + ch * (4.67 + ch);
506 p2 = ch * (6.73 + ch * (6.66 + ch));
507 t = -0.5 + (4.67 + 2 * ch) / p1
508 - (6.73 + ch * (13.32 + 3 * ch)) / p2;
509 ch -= (1 - Math.exp(a + g + .5 * ch + c * aa) * p2 / p1)
510 / t;
511 } while (Math.abs(q / ch - 1) - epsi > 0);
512 }
513 }
514 do {
515 q = ch;
516 p1 = 0.5 * ch;
517 if ((t = GammaFunction.incompleteGammaP(xx, p1, g)) < 0) {
518 throw new IllegalArgumentException(
519 "Arguments out of range: t < 0");
520 }
521 p2 = p - t;
522 t = p2 * Math.exp(xx * aa + g + p1 - c * Math.log(ch));
523 b = t / ch;
524 a = 0.5 * t - b * c;
525
526 s1 = (210 + a * (140 + a * (105 + a * (84 + a * (70 + 60 * a))))) / 420;
527 s2 = (420 + a * (735 + a * (966 + a * (1141 + 1278 * a)))) / 2520;
528 s3 = (210 + a * (462 + a * (707 + 932 * a))) / 2520;
529 s4 = (252 + a * (672 + 1182 * a) + c * (294 + a * (889 + 1740 * a))) / 5040;
530 s5 = (84 + 264 * a + c * (175 + 606 * a)) / 2520;
531 s6 = (120 + c * (346 + 127 * c)) / 5040;
532 ch += t
533 * (1 + 0.5 * t * s1 - b
534 * c
535 * (s1 - b
536 * (s2 - b
537 * (s3 - b
538 * (s4 - b * (s5 - b * s6))))));
539 } while (Math.abs(q / ch - 1) > e);
540
541 return (ch);
542 }
543
544 public static void main(String[] args) {
545
546 testQuantile(1e-10, 0.878328435043444, 0.0013696236839573005);
547 testQuantile(0.5, 0.878328435043444, 0.0013696236839573005);
548 testQuantile(1.0 - 1e-10, 0.878328435043444, 0.0013696236839573005);
549
550 testQuantileCM(1e-10, 0.878328435043444, 0.0013696236839573005);
551 testQuantileCM(0.5, 0.878328435043444, 0.0013696236839573005);
552 testQuantileCM(1.0 - 1e-10, 0.878328435043444, 0.0013696236839573005);
553
554 for (double i = 0.0125; i < 1.0; i += 0.025) {
555 System.out.print(i + ": ");
556 try {
557 System.out.println(new GammaDistributionImpl(0.878328435043444, 0.0013696236839573005).inverseCumulativeProbability(i));
558 } catch (MathException e) {
559 System.out.println(e.getMessage());
560 }
561 }
562
563 GammaDistribution gamma = new GammaDistribution(0.01,100.0);
564 double[] samples = new double[100000];
565 double sum = 0.0;
566 for (int i = 0; i < samples.length; i++) {
567 samples[i] = gamma.nextGamma();
568 sum += samples[i];
569 }
570 double mean = sum/(double)samples.length;
571 System.out.println("Mean = " + mean);
572 double variance = 0.0;
573 for (int i = 0; i < samples.length; i++) {
574 variance += Math.pow((samples[i] - mean),2.0);
575 }
576 variance = variance/(double)samples.length;
577 System.out.println("Variance = " + variance);
578
579 // System.out
580 // .println("K-S critical values: 1.22(10%), 1.36(5%), 1.63(1%)\n");
581 //
582 // int iters = 30000;
583 // testExpGamma(1.0, 0.01, 7, iters);
584 // testExpGamma(1.0, 0.01, 5, iters);
585 // testExpGamma(2.0, 0.01, 10000, iters);
586 // testExpGamma(1.0, 0.01, 10000, iters);
587 // testExpGamma(0.1, 0.01, 10000, iters);
588 // testExpGamma(0.01, 0.01, 10000, iters);
589 //
590 // testExpGamma(2.0, 0.01, 10, iters);
591 // testExpGamma(1.5, 0.01, 10, iters);
592 // testExpGamma(1.0, 0.01, 10, iters);
593 // testExpGamma(0.9, 0.01, 10, iters);
594 // testExpGamma(0.5, 0.01, 10, iters);
595 // testExpGamma(0.4, 0.01, 10, iters);
596 // testExpGamma(0.3, 0.01, 10, iters);
597 // testExpGamma(0.2, 0.01, 10, iters);
598 // testExpGamma(0.1, 0.01, 10, iters);
599 //
600 // // test distributions with severe bias, where rejection sampling doesn't
601 // // work anymore
602 // testExpGamma2(2.0, 0.01, 1, iters, 0.112946);
603 // testExpGamma2(2.0, 0.01, 0.1, iters, 0.328874);
604 // testExpGamma2(2.0, 0.01, 0.01, iters, 1.01255);
605 // testExpGamma2(1.0, 0.01, 0.0003, iters, 5.781);
606 // testExpGamma2(4.0, 0.01, 0.0003, iters, 5.79604);
607 // testExpGamma2(20.0, 0.01, 0.0003, iters, 5.87687);
608 // testExpGamma2(10.0, 0.01, 0.01, iters, 1.05374);
609 // testExpGamma2(1.0, 0.01, 0.05, iters, 0.454734);
610 // // test the basic Gamma distribution
611 // test(1.0, 1.0, iters);
612 // test(2.0, 1.0, iters);
613 // test(3.0, 1.0, iters);
614 // test(4.0, 1.0, iters);
615 // test(100.0, 1.0, iters);
616 // testAddition(0.5, 1.0, 2, iters);
617 // testAddition(0.25, 1.0, 4, iters);
618 // testAddition(0.1, 1.0, 10, iters);
619 // testAddition(10, 1.0, 10, iters);
620 // testAddition(20, 1.0, 10, iters);
621 // test(0.001, 1.0, iters);
622 // test(1.0, 2.0, iters);
623 // test(10.0, 1.0, iters);
624 // test(16.0, 1.0, iters);
625 // test(16.0, 0.1, iters);
626 // test(100.0, 1.0, iters);
627 // test(0.5, 1.0, iters);
628 // test(0.5, 0.1, iters);
629 // test(0.1, 1.0, iters);
630 // test(0.9, 1.0, iters);
631 // // test distributions with milder biases, and compare with results from
632 // // simple rejection sampling
633 // testExpGamma(2.0, 0.000001, 1000000, iters);
634 // testExpGamma(2.0, 0.000001, 100000, iters);
635 // testExpGamma(2.0, 0.000001, 70000, iters);
636 // testExpGamma(10.0, 0.01, 7, iters);
637 // testExpGamma(10.0, 0.01, 5, iters);
638 // testExpGamma(1.0, 0.01, 100, iters);
639 // testExpGamma(1.0, 0.01, 10, iters);
640 // testExpGamma(1.0, 0.01, 7, iters / 3);
641 // testExpGamma(1.0, 0.01, 5, iters / 3);
642 // testExpGamma(1.0, 0.00001, 1000000, iters);
643 // testExpGamma(1.0, 0.00001, 100000, iters);
644 // testExpGamma(1.0, 0.00001, 10000, iters);
645 // testExpGamma(1.0, 0.00001, 5000, iters / 3); /*
646 // * this one takes some
647 // * time
648 // */
649 // testExpGamma(2.0, 1.0, 0.5, iters);
650 // testExpGamma(2.0, 1.0, 1.0, iters);
651 // testExpGamma(2.0, 1.0, 2.0, iters);
652 // testExpGamma(3.0, 3.0, 2.0, iters);
653 // testExpGamma(10.0, 3.0, 5.0, iters);
654 // testExpGamma(1.0, 3.0, 5.0, iters);
655 // testExpGamma(1.0, 10.0, 5.0, iters);
656 // testExpGamma(2.0, 10.0, 5.0, iters);
657 // // test the basic Gamma distribution
658 // test(1.0, 1.0, iters);
659 // test(2.0, 1.0, iters);
660 // test(3.0, 1.0, iters);
661 // test(4.0, 1.0, iters);
662 // test(100.0, 1.0, iters);
663 // testAddition(0.5, 1.0, 2, iters);
664 // testAddition(0.25, 1.0, 4, iters);
665 // testAddition(0.1, 1.0, 10, iters);
666 // testAddition(10, 1.0, 10, iters);
667 // testAddition(20, 1.0, 10, iters);
668 // test(0.001, 1.0, iters);
669 // test(1.0, 2.0, iters);
670 // test(10.0, 1.0, iters);
671 // test(16.0, 1.0, iters);
672 // test(16.0, 0.1, iters);
673 // test(100.0, 1.0, iters);
674 // test(0.5, 1.0, iters);
675 // test(0.5, 0.1, iters);
676 // test(0.1, 1.0, iters);
677 // test(0.9, 1.0, iters);
678
679 }
680
681 private static void testQuantile(double y, double shape, double scale) {
682
683 long time = System.currentTimeMillis();
684
685 double value = 0;
686 for (int i = 0; i < 1000; i++) {
687 value = quantile(y, shape, scale);
688 }
689 value = quantile(y, shape, scale);
690 long elapsed = System.currentTimeMillis() - time;
691
692
693 System.out.println("Quantile, "+ y +", for shape=" + shape + ", scale=" + scale
694 + " : " + value + ", time=" + elapsed + "ms");
695
696 }
697 private static void testQuantileCM(double y, double shape, double scale) {
698
699 long time = System.currentTimeMillis();
700
701 double value = 0;
702 try {
703 for (int i = 0; i < 1000; i++) {
704 value = (new org.apache.commons.math.distribution.GammaDistributionImpl(shape, scale)).inverseCumulativeProbability(y);
705 }
706 value = (new org.apache.commons.math.distribution.GammaDistributionImpl(shape, scale)).inverseCumulativeProbability(y);
707 } catch (MathException e) {
708 e.printStackTrace();
709 }
710 long elapsed = System.currentTimeMillis() - time;
711
712
713 System.out.println("commons.maths inverseCDF, "+ y +", for shape=" + shape + ", scale=" + scale
714 + " : " + value + ", time=" + elapsed + "ms");
715
716 }
717
718 /* assumes the two arrays are the same size */
719 private static double KolmogorovSmirnov(List<Double> l1, List<Double> l2) {
720
721 int idx2 = 0;
722 int max = 0;
723 for (int i = 0; i < l1.size(); i++) {
724 while (idx2 < l2.size() && l2.get(idx2) < l1.get(i) ) {
725 idx2++;
726 }
727 max = Math.max(max, idx2 - i);
728 }
729 return max / Math.sqrt(2.0 * l1.size());
730 }
731
732 private static void testExpGamma2(double shape, double scale, double bias,
733 int iterations, double mean) {
734
735 double s0 = 0;
736 double s1 = 0;
737 double s2 = 0;
738 List<Double> fast = new ArrayList<Double>(0);
739
740 for (int i = 0; i < iterations; i++) {
741 double sample = nextExpGamma(shape, scale, bias, false);
742 s0 += 1;
743 s1 += sample;
744 s2 += sample * sample;
745 fast.add(sample);
746 }
747 Collections.sort(fast);
748 double expmean = s1 / s0;
749 double expvar = (s2 - s1 * s1 / s0) / s0;
750 double z = (mean - expmean) / Math.sqrt(expvar / iterations);
751 System.out.println("Equal-mean test: (shape=" + shape + " scale="
752 + scale + " bias=" + bias + " mean=" + expmean + " expected="
753 + mean + " var=" + expvar + " median="
754 + fast.get(iterations / 2) + "): z=" + z);
755 }
756
757 private static void testExpGamma(double shape, double scale, double bias,
758 int iterations) {
759
760 List<Double> slow = new ArrayList<Double>(0);
761 List<Double> fast = new ArrayList<Double>(0);
762
763 long time = System.currentTimeMillis();
764 for (int i = 0; i < iterations; i++) {
765 slow.add(nextExpGamma(shape, scale, bias, true));
766 }
767 long slowtime = System.currentTimeMillis();
768 for (int i = 0; i < iterations; i++) {
769 fast.add(nextExpGamma(shape, scale, bias, false));
770 }
771 long fasttime = System.currentTimeMillis() - slowtime;
772 slowtime -= time;
773
774 Collections.sort(slow);
775 Collections.sort(fast);
776
777 System.out.println("KS test for shape=" + shape + ", bias=" + bias
778 + " : " + KolmogorovSmirnov(slow, fast) + " and "
779 + KolmogorovSmirnov(fast, slow) + " slow=" + slowtime + "ms, fast=" + fasttime + "ms");
780
781 }
782
783 private static void test(double shape, double scale, int iterations) {
784
785 List<Double> slow = new ArrayList<Double>(0);
786 List<Double> fast = new ArrayList<Double>(0);
787
788 for (int i = 0; i < iterations; i++) {
789 slow.add(nextGamma(shape, scale, true));
790 fast.add(nextGamma(shape, scale, false));
791 }
792
793 Collections.sort(slow);
794 Collections.sort(fast);
795
796 System.out.println("KS test for shape=" + shape + " : "
797 + KolmogorovSmirnov(slow, fast) + " and "
798 + KolmogorovSmirnov(fast, slow));
799
800 }
801
802 private static void testAddition(double shape, double scale, int N,
803 int iterations) {
804
805 List<Double> slow = new ArrayList<Double>(0);
806 List<Double> fast = new ArrayList<Double>(0);
807 List<Double> test = new ArrayList<Double>(0);
808
809 for (int i = 0; i < iterations; i++) {
810 double s = 0.0;
811 for (int j = 0; j < N; j++) {
812 s += nextGamma(shape, scale, true);
813 }
814 slow.add(s);
815 s = 0.0;
816 for (int j = 0; j < N; j++) {
817 s += nextGamma(shape, scale, false);
818 }
819 fast.add(s);
820 test.add(nextGamma(shape * N, scale, true));
821 }
822
823 Collections.sort(slow);
824 Collections.sort(fast);
825 Collections.sort(test);
826
827 System.out.println("KS test for shape=" + shape + " : slow="
828 + KolmogorovSmirnov(slow, test) + " & "
829 + KolmogorovSmirnov(test, slow) + "; fast="
830 + KolmogorovSmirnov(fast, test) + " & "
831 + KolmogorovSmirnov(test, fast));
832
833 }
834
835 protected double shape, scale;
836 protected int samples;
837
838 private static final boolean TRY_COLT = false;
839 private static RandomEngine randomEngine;
840 private static Gamma coltGamma;
841
842 }
843