summaryrefslogtreecommitdiff
path: root/src/de/lmu/ifi/dbs/elki/math/statistics/distribution/GammaDistribution.java
blob: b2a79d81c7678bc255241b4d5409f93a80a6596f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
package de.lmu.ifi.dbs.elki.math.statistics.distribution;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2014
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Random;

import de.lmu.ifi.dbs.elki.logging.LoggingUtil;
import de.lmu.ifi.dbs.elki.math.MathUtil;
import de.lmu.ifi.dbs.elki.math.random.RandomFactory;
import de.lmu.ifi.dbs.elki.utilities.documentation.Reference;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter;

/**
 * Gamma Distribution, with random generation and density functions.
 * 
 * @author Erich Schubert
 */
public class GammaDistribution extends AbstractDistribution {
  /**
   * Euler–Mascheroni constant
   */
  public static final double EULERS_CONST = 0.5772156649015328606065120900824024;

  /**
   * LANCZOS-Coefficients for Gamma approximation.
   * 
   * These are said to have higher precision than those in "Numerical Recipes".
   * They probably come from
   * 
   * Paul Godfrey: http://my.fit.edu/~gabdo/gamma.txt
   */
  static final double[] LANCZOS = { 0.99999999999999709182, 57.156235665862923517, -59.597960355475491248, 14.136097974741747174, -0.49191381609762019978, .33994649984811888699e-4, .46523628927048575665e-4, -.98374475304879564677e-4, .15808870322491248884e-3, -.21026444172410488319e-3, .21743961811521264320e-3, -.16431810653676389022e-3, .84418223983852743293e-4, -.26190838401581408670e-4, .36899182659531622704e-5, };

  /**
   * Numerical precision to use (data type dependent!)
   * 
   * If you change this, make sure to test exhaustively!
   */
  static final double NUM_PRECISION = 1E-15;

  /**
   * Maximum number of iterations for regularizedGammaP. To prevent degeneration
   * for extreme values.
   * 
   * FIXME: is this too high, too low? Can we improve behavior for extreme
   * cases?
   */
  static final int MAX_ITERATIONS = 1000;

  /**
   * Alpha == k
   */
  private final double k;

  /**
   * Theta == 1 / Beta
   */
  private final double theta;

  /**
   * Constructor for Gamma distribution.
   * 
   * @param k k, alpha aka. "shape" parameter
   * @param theta Theta = 1.0/Beta aka. "scaling" parameter
   * @param random Random generator
   */
  public GammaDistribution(double k, double theta, Random random) {
    super(random);
    if (!(k > 0.0) || !(theta > 0.0)) { // Note: also tests for NaNs!
      throw new IllegalArgumentException("Invalid parameters for Gamma distribution: " + k + " " + theta);
    }

    this.k = k;
    this.theta = theta;
  }

  /**
   * Constructor for Gamma distribution.
   * 
   * @param k k, alpha aka. "shape" parameter
   * @param theta Theta = 1.0/Beta aka. "scaling" parameter
   * @param random Random generator
   */
  public GammaDistribution(double k, double theta, RandomFactory random) {
    super(random);
    if (!(k > 0.0) || !(theta > 0.0)) { // Note: also tests for NaNs!
      throw new IllegalArgumentException("Invalid parameters for Gamma distribution: " + k + " " + theta);
    }

    this.k = k;
    this.theta = theta;
  }

  /**
   * Constructor for Gamma distribution.
   * 
   * @param k k, alpha aka. "shape" parameter
   * @param theta Theta = 1.0/Beta aka. "scaling" parameter
   */
  public GammaDistribution(double k, double theta) {
    this(k, theta, (Random) null);
  }

  @Override
  public double pdf(double val) {
    return pdf(val, k, theta);
  }

  @Override
  public double cdf(double val) {
    return cdf(val, k, theta);
  }

  @Override
  public double quantile(double val) {
    return quantile(val, k, theta);
  }

  @Override
  public double nextRandom() {
    return nextRandom(k, theta, random);
  }

  /**
   * Simple toString explaining the distribution parameters.
   * 
   * Used in producing a model description.
   */
  @Override
  public String toString() {
    return "GammaDistribution(k=" + k + ", theta=" + theta + ")";
  }

  /**
   * @return the value of k
   */
  public double getK() {
    return k;
  }

  /**
   * @return the standard deviation
   */
  public double getTheta() {
    return theta;
  }

  /**
   * The CDF, static version.
   * 
   * @param val Value
   * @param k Shape k
   * @param theta Theta = 1.0/Beta aka. "scaling" parameter
   * @return cdf value
   */
  public static double cdf(double val, double k, double theta) {
    if (val < 0) {
      return 0.;
    }
    return regularizedGammaP(k, val * theta);
  }

  /**
   * The log CDF, static version.
   * 
   * @param val Value
   * @param k Shape k
   * @param theta Theta = 1.0/Beta aka. "scaling" parameter
   * @return cdf value
   */
  public static double logcdf(double val, double k, double theta) {
    if (val < 0) {
      return Double.NEGATIVE_INFINITY;
    }
    return logregularizedGammaP(k, val * theta);
  }

  /**
   * Gamma distribution PDF (with 0.0 for x &lt; 0)
   * 
   * @param x query value
   * @param k Alpha
   * @param theta Theta = 1 / Beta
   * @return probability density
   */
  public static double pdf(double x, double k, double theta) {
    if (x < 0) {
      return 0.0;
    }
    if (x == 0) {
      if (k == 1.0) {
        return theta;
      } else {
        return 0.0;
      }
    }
    if (k == 1.0) {
      return Math.exp(-x * theta) * theta;
    }

    return Math.exp((k - 1.0) * Math.log(x * theta) - x * theta - logGamma(k)) * theta;
  }

  /**
   * Gamma distribution PDF (with 0.0 for x &lt; 0)
   * 
   * @param x query value
   * @param k Alpha
   * @param theta Theta = 1 / Beta
   * @return probability density
   */
  public static double logpdf(double x, double k, double theta) {
    if (x < 0) {
      return Double.NEGATIVE_INFINITY;
    }
    if (x == 0) {
      if (k == 1.0) {
        return Math.log(theta);
      } else {
        return Double.NEGATIVE_INFINITY;
      }
    }
    if (k == 1.0) {
      return Math.log(theta) - x * theta;
    }

    return Math.log(theta) + (k - 1.0) * Math.log(x * theta) - x * theta - logGamma(k);
  }

  /**
   * Compute logGamma.
   * 
   * Based loosely on "Numerical Recpies" and the work of Paul Godfrey at
   * http://my.fit.edu/~gabdo/gamma.txt
   * 
   * TODO: find out which approximation really is the best...
   * 
   * @param x Parameter x
   * @return log(&#915;(x))
   */
  public static double logGamma(final double x) {
    if (Double.isNaN(x) || (x <= 0.0)) {
      return Double.NaN;
    }
    double g = 607.0 / 128.0;
    double tmp = x + g + .5;
    tmp = (x + 0.5) * Math.log(tmp) - tmp;
    double ser = LANCZOS[0];
    for (int i = LANCZOS.length - 1; i > 0; --i) {
      ser += LANCZOS[i] / (x + i);
    }
    return tmp + Math.log(MathUtil.SQRTTWOPI * ser / x);
  }

  /**
   * Compute the regular Gamma function.
   * 
   * Note: for numerical reasons, it is preferrable to use {@link #logGamma}
   * when possible! In particular, this method just computes
   * {@code Math.exp(logGamma(x))} anyway.
   * 
   * Try to postpone the {@code Math.exp} call to preserve numeric range!
   * 
   * @param x Position
   * @return Gamma at this position
   */
  public static double gamma(double x) {
    return Math.exp(logGamma(x));
  }

  /**
   * Returns the regularized gamma function P(a, x).
   * 
   * Includes the quadrature way of computing.
   * 
   * TODO: find "the" most accurate version of this. We seem to agree with
   * others for the first 10+ digits, but diverge a bit later than that.
   * 
   * @param a Parameter a
   * @param x Parameter x
   * @return Gamma value
   */
  public static double regularizedGammaP(final double a, final double x) {
    // Special cases
    if (Double.isInfinite(a) || Double.isInfinite(x) || !(a > 0.0) || !(x >= 0.0)) {
      return Double.NaN;
    }
    if (x == 0.0) {
      return 0.0;
    }
    if (x >= a + 1) {
      // Expected to converge faster
      return 1.0 - regularizedGammaQ(a, x);
    }
    // Loosely following "Numerical Recipes"
    double term = 1.0 / a;
    double sum = term;
    for (int n = 1; n < MAX_ITERATIONS; n++) {
      // compute next element in the series
      term = x / (a + n) * term;
      sum = sum + term;
      if (sum == Double.POSITIVE_INFINITY) {
        return 1.0;
      }
      if (Math.abs(term / sum) < NUM_PRECISION) {
        break;
      }
    }
    return Math.exp(-x + (a * Math.log(x)) - logGamma(a)) * sum;
  }

  /**
   * Returns the regularized gamma function log P(a, x).
   * 
   * Includes the quadrature way of computing.
   * 
   * TODO: find "the" most accurate version of this. We seem to agree with
   * others for the first 10+ digits, but diverge a bit later than that.
   * 
   * @param a Parameter a
   * @param x Parameter x
   * @return Gamma value
   */
  public static double logregularizedGammaP(final double a, final double x) {
    // Special cases
    if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) {
      return Double.NaN;
    }
    if (x == 0.0) {
      return Double.NEGATIVE_INFINITY;
    }
    if (x >= a + 1) {
      // Expected to converge faster
      // FIXME: and in log?
      return Math.log(1.0 - regularizedGammaQ(a, x));
    }
    // Loosely following "Numerical Recipes"
    double del = 1.0 / a;
    double sum = del;
    for (int n = 1; n < Integer.MAX_VALUE; n++) {
      // compute next element in the series
      del *= x / (a + n);
      sum = sum + del;
      if (Math.abs(del / sum) < NUM_PRECISION || sum >= Double.POSITIVE_INFINITY) {
        break;
      }
    }
    if (Double.isInfinite(sum)) {
      return 0;
    }
    // TODO: reread numerical recipes, can we replace log(sum)?
    return -x + (a * Math.log(x)) - logGamma(a) + Math.log(sum);
  }

  /**
   * Returns the regularized gamma function Q(a, x) = 1 - P(a, x).
   * 
   * Includes the continued fraction way of computing, based loosely on the book
   * "Numerical Recipes"; but probably not with the exactly same precision,
   * since we reimplemented this in our coding style, not literally.
   * 
   * TODO: find "the" most accurate version of this. We seem to agree with
   * others for the first 10+ digits, but diverge a bit later than that.
   * 
   * @param a parameter a
   * @param x parameter x
   * @return Result
   */
  public static double regularizedGammaQ(final double a, final double x) {
    if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) {
      return Double.NaN;
    }
    if (x == 0.0) {
      return 1.0;
    }
    if (x < a + 1.0) {
      // Expected to converge faster
      return 1.0 - regularizedGammaP(a, x);
    }
    // Compute using continued fraction approach.
    final double FPMIN = Double.MIN_VALUE / NUM_PRECISION;
    double b = x + 1 - a;
    double c = 1.0 / FPMIN;
    double d = 1.0 / b;
    double fac = d;
    for (int i = 1; i < MAX_ITERATIONS; i++) {
      double an = i * (a - i);
      b += 2;
      d = an * d + b;
      if (Math.abs(d) < FPMIN) {
        d = FPMIN;
      }
      c = b + an / c;
      if (Math.abs(c) < FPMIN) {
        c = FPMIN;
      }
      d = 1 / d;
      double del = d * c;
      fac *= del;
      if (Math.abs(del - 1.0) <= NUM_PRECISION) {
        break;
      }
    }
    return fac * Math.exp(-x + a * Math.log(x) - logGamma(a));
  }

  /**
   * Generate a random value with the generators parameters.
   * 
   * Along the lines of
   * 
   * - J.H. Ahrens, U. Dieter (1974): Computer methods for sampling from gamma,
   * beta, Poisson and binomial distributions, Computing 12, 223-246.
   * 
   * - J.H. Ahrens, U. Dieter (1982): Generating gamma variates by a modified
   * rejection technique, Communications of the ACM 25, 47-54.
   * 
   * @param k K parameter
   * @param theta Theta parameter
   * @param random Random generator
   */
  public static double nextRandom(double k, double theta, Random random) {
    /* Constants */
    final double q1 = 0.0416666664, q2 = 0.0208333723, q3 = 0.0079849875;
    final double q4 = 0.0015746717, q5 = -0.0003349403, q6 = 0.0003340332;
    final double q7 = 0.0006053049, q8 = -0.0004701849, q9 = 0.0001710320;
    final double a1 = 0.333333333, a2 = -0.249999949, a3 = 0.199999867;
    final double a4 = -0.166677482, a5 = 0.142873973, a6 = -0.124385581;
    final double a7 = 0.110368310, a8 = -0.112750886, a9 = 0.104089866;
    final double e1 = 1.000000000, e2 = 0.499999994, e3 = 0.166666848;
    final double e4 = 0.041664508, e5 = 0.008345522, e6 = 0.001353826;
    final double e7 = 0.000247453;

    if (k < 1.0) { // Base case, for small k
      final double b = 1.0 + 0.36788794412 * k; // Step 1
      while (true) {
        final double p = b * random.nextDouble();
        if (p <= 1.0) { // when gds <= 1
          final double gds = Math.exp(Math.log(p) / k);
          if (Math.log(random.nextDouble()) <= -gds) {
            return (gds / theta);
          }
        } else { // when gds > 1
          final double gds = -Math.log((b - p) / k);
          if (Math.log(random.nextDouble()) <= ((k - 1.0) * Math.log(gds))) {
            return (gds / theta);
          }
        }
      }
    } else {
      // Step 1. Preparations
      final double ss, s, d;
      if (k != -1.0) {
        ss = k - 0.5;
        s = Math.sqrt(ss);
        d = 5.656854249 - 12.0 * s;
      } else {
        // For k == -1.0:
        ss = 0.0;
        s = 0.0;
        d = 0.0;
      }
      // Random vector of maximum length 1
      final double v1, /* v2, */v12;
      { // Temporary values - candidate
        double tv1, tv2, tv12;
        do {
          tv1 = 2.0 * random.nextDouble() - 1.0;
          tv2 = 2.0 * random.nextDouble() - 1.0;
          tv12 = tv1 * tv1 + tv2 * tv2;
        }
        while (tv12 > 1.0);
        v1 = tv1;
        /* v2 = tv2; */
        v12 = tv12;
      }

      // double b = 0.0, c = 0.0;
      // double si = 0.0, q0 = 0.0;
      final double b, c, si, q0;

      // Simpler accept cases & parameter computation
      {
        final double t = v1 * Math.sqrt(-2.0 * Math.log(v12) / v12);
        final double x = s + 0.5 * t;
        final double gds = x * x;
        if (t >= 0.0) {
          return (gds / theta); // Immediate acceptance
        }

        // Random uniform
        final double un = random.nextDouble();
        // Squeeze acceptance
        if (d * un <= t * t * t) {
          return (gds / theta);
        }

        if (k != -1.0) { // Step 4. Set-up for hat case
          final double r = 1.0 / k;
          q0 = ((((((((q9 * r + q8) * r + q7) * r + q6) * r + q5) * r + q4) * r + q3) * r + q2) * r + q1) * r;
          if (k > 3.686) {
            if (k > 13.022) {
              b = 1.77;
              si = 0.75;
              c = 0.1515 / s;
            } else {
              b = 1.654 + 0.0076 * ss;
              si = 1.68 / s + 0.275;
              c = 0.062 / s + 0.024;
            }
          } else {
            b = 0.463 + s - 0.178 * ss;
            si = 1.235;
            c = 0.195 / s - 0.079 + 0.016 * s;
          }
        } else {
          // For k == -1.0:
          b = 0.0;
          c = 0.0;
          si = 0.0;
          q0 = 0.0;
        }
        // Compute v and q
        if (x > 0.0) {
          final double v = t / (s + s);
          final double q;
          if (Math.abs(v) > 0.25) {
            q = q0 - s * t + 0.25 * t * t + (ss + ss) * Math.log(1.0 + v);
          } else {
            q = q0 + 0.5 * t * t * ((((((((a9 * v + a8) * v + a7) * v + a6) * v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v;
          }
          // Quotient acceptance:
          if (Math.log(1.0 - un) <= q) {
            return (gds / theta);
          }
        }
      }

      // Double exponential deviate t
      while (true) {
        double e, u, sign_u, t;
        // Retry until t is sufficiently large
        do {
          e = -Math.log(random.nextDouble());
          u = random.nextDouble();
          u = u + u - 1.0;
          sign_u = (u > 0) ? 1.0 : -1.0;
          t = b + (e * si) * sign_u;
        }
        while (t <= -0.71874483771719);

        // New v(t) and q(t)
        final double v = t / (s + s);
        final double q;
        if (Math.abs(v) > 0.25) {
          q = q0 - s * t + 0.25 * t * t + (ss + ss) * Math.log(1.0 + v);
        } else {
          q = q0 + 0.5 * t * t * ((((((((a9 * v + a8) * v + a7) * v + a6) * v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v;
        }
        if (q <= 0.0) {
          continue; // retry
        }
        // Compute w(t)
        final double w;
        if (q > 0.5) {
          w = Math.exp(q) - 1.0;
        } else {
          w = ((((((e7 * q + e6) * q + e5) * q + e4) * q + e3) * q + e2) * q + e1) * q;
        }
        // Hat acceptance
        if (c * u * sign_u <= w * Math.exp(e - 0.5 * t * t)) {
          final double x = s + 0.5 * t;
          return (x * x / theta);
        }
      }
    }
  }

  /**
   * Approximate probit for chi squared distribution
   * 
   * Based on first half of algorithm AS 91
   * 
   * Reference:
   * <p>
   * Algorithm AS 91: The percentage points of the $\chi^2$ distribution<br />
   * D.J. Best, D. E. Roberts<br />
   * Journal of the Royal Statistical Society. Series C (Applied Statistics)
   * </p>
   * 
   * @param p Probit value
   * @param nu Shape parameter for Chi, nu = 2 * k
   * @param g log(nu)
   * @return Probit for chi squared
   */
  @Reference(title = "Algorithm AS 91: The percentage points of the $\\chi^2$ distribution", authors = "D.J. Best, D. E. Roberts", booktitle = "Journal of the Royal Statistical Society. Series C (Applied Statistics)")
  protected static double chisquaredProbitApproximation(final double p, double nu, double g) {
    final double EPS1 = 1e-2; // Approximation quality
    // Sanity checks
    if (Double.isNaN(p) || Double.isNaN(nu)) {
      return Double.NaN;
    }
    // Range check
    if (p <= 0) {
      return 0;
    }
    if (p >= 1) {
      return Double.POSITIVE_INFINITY;
    }
    // Invalid parameters
    if (nu <= 0) {
      return Double.NaN;
    }
    // Shape of gamma distribution, "XX" in AS 91
    final double k = 0.5 * nu;

    // For small chi squared values - AS 91
    final double logp = Math.log(p);
    if (nu < -1.24 * logp) {
      // FIXME: implement and use logGammap1 instead - more stable?
      //
      // final double lgam1pa = (alpha < 0.5) ? logGammap1(alpha) :
      // (Math.log(alpha) + g);
      // return Math.exp((lgam1pa + logp) / alpha + MathUtil.LOG2);
      // This is literal AS 91, above is the GNU R variant.
      return Math.pow(p * k * Math.exp(g + k * MathUtil.LOG2), 1. / k);
    } else if (nu > 0.32) {
      // Wilson and Hilferty estimate: - AS 91 at 3
      final double x = NormalDistribution.quantile(p, 0, 1);
      final double p1 = 2. / (9. * nu);
      final double a = x * Math.sqrt(p1) + 1 - p1;
      double ch = nu * a * a * a;

      // Better approximation for p tending to 1:
      if (ch > 2.2 * nu + 6) {
        ch = -2 * (Math.log1p(-p) - (k - 1) * Math.log(0.5 * ch) + g);
      }
      return ch;
    } else {
      // nu <= 0.32, AS 91 at 1
      final double C7 = 4.67, C8 = 6.66, C9 = 6.73, C10 = 13.32;
      final double ag = Math.log1p(-p) + g + (k - 1) * MathUtil.LOG2;
      double ch = 0.4;
      while (true) {
        final double p1 = 1 + ch * (C7 + ch);
        final double p2 = ch * (C9 + ch * (C8 + ch));
        final double t = -0.5 + (C7 + 2 * ch) / p1 - (C9 + ch * (C10 + 3 * ch)) / p2;
        final double delta = (1 - Math.exp(ag + 0.5 * ch) * p2 / p1) / t;
        ch -= delta;
        if (Math.abs(delta) > EPS1 * Math.abs(ch)) {
          return ch;
        }
      }
    }
  }

  /**
   * Compute probit (inverse cdf) for Gamma distributions.
   * 
   * Based on algorithm AS 91:
   * 
   * Reference:
   * <p>
   * Algorithm AS 91: The percentage points of the $\chi^2$ distribution<br />
   * D.J. Best, D. E. Roberts<br />
   * Journal of the Royal Statistical Society. Series C (Applied Statistics)
   * </p>
   * 
   * @param p Probability
   * @param k k, alpha aka. "shape" parameter
   * @param theta Theta = 1.0/Beta aka. "scaling" parameter
   * @return Probit for Gamma distribution
   */
  @Reference(title = "Algorithm AS 91: The percentage points of the $\\chi^2$ distribution", authors = "D.J. Best, D. E. Roberts", booktitle = "Journal of the Royal Statistical Society. Series C (Applied Statistics)")
  public static double quantile(double p, double k, double theta) {
    final double EPS2 = 5e-7; // final precision of AS 91
    final int MAXIT = 1000;

    // Avoid degenerates
    if (Double.isNaN(p) || Double.isNaN(k) || Double.isNaN(theta)) {
      return Double.NaN;
    }
    // Range check
    if (p <= 0) {
      return 0;
    }
    if (p >= 1) {
      return Double.POSITIVE_INFINITY;
    }
    // Shape parameter check
    if (k < 0 || theta <= 0) {
      return Double.NaN;
    }
    // Corner case - all at 0
    if (k == 0) {
      return 0.;
    }

    int max_newton_iterations = 1;
    // For small values, ensure some refinement iterations
    if (k < 1e-10) {
      max_newton_iterations = 7;
    }

    final double g = logGamma(k); // == logGamma(v/2)

    // Phase I, an initial rough approximation
    // First half of AS 91
    double ch = chisquaredProbitApproximation(p, 2 * k, g);
    // Second hald of AS 91 follows:
    // Refine ChiSquared approximation
    chisq: {
      if (Double.isInfinite(ch)) {
        // Cannot refine infinity
        max_newton_iterations = 0;
        break chisq;
      }
      if (ch < EPS2) {
        // Do not iterate, but refine with newton method
        max_newton_iterations = 20;
        break chisq;
      }
      if (p > 1 - 1e-14 || p < 1e-100) {
        // Not in appropriate value range for AS 91
        max_newton_iterations = 20;
        break chisq;
      }

      // Phase II: Iteration
      final double c = k - 1;
      final double ch0 = ch; // backup initial approximation
      for (int i = 1; i <= MAXIT; i++) {
        final double q = ch; // previous approximation
        final double p1 = 0.5 * ch;
        final double p2 = p - regularizedGammaP(k, p1);
        if (Double.isInfinite(p2) || ch <= 0) {
          ch = ch0;
          max_newton_iterations = 27;
          break chisq;
        }
        { // Taylor series of AS 91: iteration via "goto 4"
          final double t = p2 * Math.exp(k * MathUtil.LOG2 + g + p1 - c * Math.log(ch));
          final double b = t / ch;
          final double a = 0.5 * t - b * c;
          final double s1 = (210. + a * (140. + a * (105. + a * (84. + a * (70. + 60. * a))))) / 420.;
          final double s2 = (420. + a * (735. + a * (966. + a * (1141. + 1278 * a)))) / 2520.;
          final double s3 = (210. + a * (462. + a * (707. + 932. * a))) / 2520.;
          final double s4 = (252. + a * (672. + 1182. * a) + c * (294. + a * (889. + 1740. * a))) / 5040.;
          final double s5 = (84. + 2264. * a + c * (1175. + 606. * a)) / 2520.;
          final double s6 = (120. + c * (346. + 127. * c)) / 5040.;
          ch += t * (1 + 0.5 * t * s1 - b * c * (s1 - b * (s2 - b * (s3 - b * (s4 - b * (s5 - b * s6))))));
        }
        if (Math.abs(q - ch) < EPS2 * ch) {
          break chisq;
        }
        // Divergence treatment, from GNU R
        if (Math.abs(q - ch) > 0.1 * Math.abs(ch)) {
          ch = ((ch < q) ? 0.9 : 1.1) * q;
        }
      }
      LoggingUtil.warning("No convergence in AS 91 Gamma probit.");
      // no convergence in MAXIT iterations -- but we add Newton now...
    }
    double x = 0.5 * ch / theta;
    if (max_newton_iterations > 0) {
      // Refine result using final Newton steps.
      // TODO: add unit tests that show an improvement! Maybe in logscale only?
      x = gammaQuantileNewtonRefinement(Math.log(p), k, theta, max_newton_iterations, x);
    }
    return x;
  }

  /**
   * Refinement of ChiSquared probit using Newton iterations.
   * 
   * A trick used by GNU R to improve precision.
   * 
   * @param logpt Target value of log p
   * @param k Alpha
   * @param theta Theta = 1 / Beta
   * @param maxit Maximum number of iterations to do
   * @param x Initial estimate
   * @return Refined value
   */
  protected static double gammaQuantileNewtonRefinement(final double logpt, final double k, final double theta, final int maxit, double x) {
    final double EPS_N = 1e-15; // Precision threshold
    // 0 is not possible, try MIN_NORMAL instead
    if (x <= 0) {
      x = Double.MIN_NORMAL;
    }
    // Current estimation
    double logpc = logcdf(x, k, theta);
    if (x == Double.MIN_NORMAL && logpc > logpt * (1. + 1e-7)) {
      return 0.;
    }
    if (logpc == Double.NEGATIVE_INFINITY) {
      return 0.;
    }
    // Refine by newton iterations
    for (int i = 0; i < maxit; i++) {
      // Error of current approximation
      final double logpe = logpc - logpt;
      if (Math.abs(logpe) < Math.abs(EPS_N * logpt)) {
        break;
      }
      // Step size is controlled by PDF:
      final double g = logpdf(x, k, theta);
      if (g == Double.NEGATIVE_INFINITY) {
        break;
      }
      final double newx = x - logpe * Math.exp(logpc - g);
      // New estimate:
      logpc = logcdf(newx, k, theta);
      if (Math.abs(logpc - logpt) > Math.abs(logpe) || (i > 0 && Math.abs(logpc - logpt) == Math.abs(logpe))) {
        // no further improvement
        break;
      }
      x = newx;
    }
    return x;
  }

  /**
   * Compute the Psi / Digamma function
   * 
   * Reference:
   * <p>
   * J. M. Bernando<br />
   * Algorithm AS 103: Psi (Digamma) Function<br />
   * Statistical Algorithms
   * </p>
   * 
   * TODO: is there a more accurate version maybe in R?
   * 
   * @param x Position
   * @return digamma value
   */
  @Reference(authors = "J. M. Bernando", title = "Algorithm AS 103: Psi (Digamma) Function", booktitle = "Statistical Algorithms")
  public static double digamma(double x) {
    if (!(x > 0)) {
      return Double.NaN;
    }
    // Method of equation 5:
    if (x <= 1e-5) {
      return -EULERS_CONST - 1. / x;
    }
    // Method of equation 4:
    else if (x > 49.) {
      final double ix2 = 1. / (x * x);
      // Partial series expansion
      return Math.log(x) - 0.5 / x - ix2 * ((1.0 / 12.) + ix2 * (1.0 / 120. - ix2 / 252.));
      // + O(x^8) error
    } else {
      // Stirling expansion
      return digamma(x + 1.) - 1. / x;
    }
  }

  /**
   * Compute the Trigamma function. Based on digamma.
   * 
   * TODO: is there a more accurate version maybe in R?
   * 
   * @param x Position
   * @return trigamma value
   */
  public static double trigamma(double x) {
    if (!(x > 0)) {
      return Double.NaN;
    }
    // Method of equation 5:
    if (x <= 1e-5) {
      return 1. / (x * x);
    }
    // Method of equation 4:
    else if (x > 49.) {
      final double ix2 = 1. / (x * x);
      // Partial series expansion
      return 1 / x - ix2 / 2. + ix2 / x * (1.0 / 6. - ix2 * (1.0 / 30. + ix2 / 42.));
      // + O(x^8) error
    } else {
      // Stirling expansion
      return trigamma(x + 1.) - 1. / (x * x);
    }
  }

  /**
   * Parameterization class
   * 
   * TODO: allow alternate parameterization, with alpha+beta?
   * 
   * @author Erich Schubert
   * 
   * @apiviz.exclude
   */
  public static class Parameterizer extends AbstractDistribution.Parameterizer {
    /**
     * K parameter.
     */
    public static final OptionID K_ID = new OptionID("distribution.gamma.k", "Gamma distribution k = alpha parameter.");

    /**
     * Theta parameter.
     */
    public static final OptionID THETA_ID = new OptionID("distribution.gamma.theta", "Gamma distribution theta = 1/beta parameter.");

    /** Parameters. */
    double k, theta;

    @Override
    protected void makeOptions(Parameterization config) {
      super.makeOptions(config);

      DoubleParameter kP = new DoubleParameter(K_ID);
      if (config.grab(kP)) {
        k = kP.doubleValue();
      }

      DoubleParameter thetaP = new DoubleParameter(THETA_ID);
      if (config.grab(thetaP)) {
        theta = thetaP.doubleValue();
      }
    }

    @Override
    protected GammaDistribution makeInstance() {
      return new GammaDistribution(k, theta, rnd);
    }
  }
}