/* * GammaDistribution.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.math.distributions; import cern.jet.random.Gamma; import cern.jet.random.engine.MersenneTwister; import cern.jet.random.engine.RandomEngine; import dr.math.GammaFunction; import dr.math.MathUtils; import dr.math.UnivariateFunction; import org.apache.commons.math.MathException; import org.apache.commons.math.distribution.GammaDistributionImpl; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * gamma distribution. *
* (Parameters: shape, scale; mean: scale*shape; variance: scale^2*shape) * * @author Korbinian Strimmer * @author Gerton Lunter * @version $Id: GammaDistribution.java,v 1.9 2006/03/30 11:12:47 rambaut Exp $ */ public class GammaDistribution implements Distribution { // // Public stuff // /** * Constructor */ public GammaDistribution(double shape, double scale) { this.shape = shape; this.scale = scale; this.samples = 0; if (TRY_COLT) { randomEngine = new MersenneTwister(MathUtils.nextInt()); System.out.println("Colt Gamma(" + shape + "," + scale + ")"); coltGamma = new Gamma(shape, 1.0/scale, randomEngine); } } public double getShape() { return shape; } public void setShape(double value) { shape = value; } public double getScale() { return scale; } public void setScale(double value) { scale = value; } public double pdf(double x) { if (TRY_COLT) { return coltGamma.pdf(x); } else { return pdf(x, shape, scale); } } public double logPdf(double x) { if (TRY_COLT) { return Math.log(coltGamma.pdf(x)); } else { return logPdf(x, shape, scale); } } public double cdf(double x) { if (TRY_COLT) { return coltGamma.cdf(x); } else { return cdf(x, shape, scale); } } public double quantile(double y) { return quantile(y, shape, scale); } public double mean() { return mean(shape, scale); } public double variance() { return variance(shape, scale); } public double nextGamma() { return nextGamma(shape, scale); } public final UnivariateFunction getProbabilityDensityFunction() { return pdfFunction; } private final UnivariateFunction pdfFunction = new UnivariateFunction() { public final double evaluate(double x) { return pdf(x); } public final double getLowerBound() { return 0.0; } public final double getUpperBound() { return Double.POSITIVE_INFINITY; } }; /** * probability density function of the Gamma distribution * * @param x argument * @param shape shape parameter * @param scale scale parameter * @return pdf value */ public static double pdf(double x, double shape, double scale) { // return Math.pow(scale,-shape)*Math.pow(x, shape-1.0)/ // Math.exp(x/scale + GammaFunction.lnGamma(shape)); if (x < 0) return 0; // to make BEAUti plot continue // throw new IllegalArgumentException(); if (x == 0) { if (shape == 1.0) return 1.0 / scale; else return 0.0; } if (shape == 0.0) // uninformative return 1.0 / x; if (shape == -0.5) { // Gelman 2008, hierarchical variance, -1 degrees of freedom return Math.sqrt(x); } final double xs = x / scale; if (shape == 1.0) { return Math.exp(-xs) / scale; } final double a = Math.exp((shape - 1.0) * Math.log(xs) - xs - GammaFunction.lnGamma(shape)); return a / scale; } /** * the natural log of the probability density function of the distribution * * @param x argument * @param shape shape parameter * @param scale scale parameter * @return log pdf value */ public static double logPdf(double x, double shape, double scale) { // double a = Math.pow(scale,-shape) * Math.pow(x, shape-1.0); // double b = x/scale + GammaFunction.lnGamma(shape); // return Math.log(a) - b; // AR - changed this to return -ve inf instead of throwing an // exception... This makes things // much easier when using this to calculate log likelihoods. // if (x < 0) throw new IllegalArgumentException(); if (x < 0) return Double.NEGATIVE_INFINITY; if (x == 0) { if (shape == 1.0) return Math.log(1.0 / scale); else return Double.NEGATIVE_INFINITY; } if (shape == 1.0) { return (-x / scale) - Math.log(scale); } if (shape == 0.0) // uninformative return -Math.log(x); if (shape == -0.5) { // Gelman 2008, hierarchical variance, -1 degrees of freedom return 0.5 * Math.log(x); } /*return ((shape - 1.0) * Math.log(x/scale) - x / scale - GammaFunction .lnGamma(shape)) - Math.log(scale);*/ return ((shape - 1.0) * (Math.log(x) - Math.log(scale)) - x / scale - GammaFunction .lnGamma(shape)) - Math.log(scale); } /** * cumulative density function of the Gamma distribution * * @param x argument * @param shape shape parameter * @param scale scale parameter * @return cdf value */ public static double cdf(double x, double shape, double scale) { if (x < 0.0 || shape <= 0.0) { return 0; } return GammaFunction.incompleteGammaP(shape, x / scale); } /** * quantile (inverse cumulative density function) of the Gamma distribution * * @param y argument * @param shape shape parameter * @param scale scale parameter * @return icdf value */ public static double quantile(double y, double shape, double scale) { return 0.5 * scale * pointChi2(y, 2.0 * shape); } /** * mean of the Gamma distribution * * @param shape shape parameter * @param scale scale parameter * @return mean */ public static double mean(double shape, double scale) { return scale * shape; } /** * variance of the Gamma distribution. * * @param shape shape parameter * @param scale scale parameter * @return variance */ public static double variance(double shape, double scale) { return scale * scale * shape; } /** * sample from the Gamma distribution. This could be calculated using * quantile, but current algorithm is faster. * * @param shape shape parameter * @param scale scale parameter * @return sample */ public static double nextGamma(double shape, double scale) { if (TRY_COLT) { return coltGamma.nextDouble(shape, 1.0/scale); } return nextGamma(shape, scale, false); } public static double nextGamma(double shape, double scale, boolean slowCode) { double sample = 0.0; if (shape < 0.00001) { if (shape < 0) { System.out.println("Negative shape parameter"); throw new IllegalArgumentException("Negative shape parameter"); } /* * special case: shape==0.0 is an improper distribution; but * sampling works if very small values are ignored (v. large ones * don't happen) This is useful e.g. for sampling from the truncated * Gamma(0,x)-distribution. */ double minimum = 1.0e-20; double maximum = 50; double normalizingConstant = Math.log(maximum) - Math.log(minimum); // Draw from 1/x (with boundaries), and shape by exp(-x) do { sample = Math.exp(Math.log(minimum) + normalizingConstant * MathUtils.nextDouble()); } while (Math.exp(-sample) < MathUtils.nextDouble()); // This distribution is actually scale-free, so multiplying by // 'scale' is not necessary return sample; } if (slowCode && Math.floor(shape) == shape && shape > 4.0) { for (int i = 0; i < shape; i++) sample += -Math.log(MathUtils.nextDouble()); return sample * scale; } else { // Fast special cases if (shape == 1.0) { return -Math.log(MathUtils.nextDouble()) * scale; } if (shape == 2.0) { return -Math.log(MathUtils.nextDouble() * MathUtils.nextDouble()) * scale; } if (shape == 3.0) { return -Math.log(MathUtils.nextDouble() * MathUtils.nextDouble() * MathUtils.nextDouble()) * scale; } if (shape == 4.0) { return -Math.log(MathUtils.nextDouble() * MathUtils.nextDouble() * MathUtils.nextDouble() * MathUtils.nextDouble()) * scale; } } // general case do { try { sample = quantile(MathUtils.nextDouble(), shape, scale); } catch (IllegalArgumentException e) { // random doubles do go outside the permissible range 0.000002 < // q < 0.999998 sample = 0.0; } } while (sample == 0.0); return sample; } /** * Sample from the gamma distribution, modified by a factor exp( * -(x*bias)^-1 ), i.e. from x^(shape - 1) exp(-x/scale) exp(-1/(bias*x)) * * Works by rejection sampling, using a shifted ordinary Gamma as proposal * distribution. * * (For an older, less efficient algorithm that breaks down for shape <= 1.0, * see revision 287) */ public static double nextExpGamma(double shape, double scale, double bias) { return nextExpGamma(shape, scale, bias, false); } public static double nextExpGamma(double shape, double scale, double bias, boolean slowCode) { double sample; double accept; int iters = 0; if (slowCode) { // for testing purposes -- this can get stuck completely for small bias parameters do { sample = nextGamma(shape, scale); accept = Math.exp(-1.0 / (bias * sample)); } while (MathUtils.nextDouble() > accept); } else { if (shape < 0) { //return scale / (nextExpGamma(-shape, scale, bias) * bias); return 1.0 / nextExpGamma(-shape, bias, scale); } if (shape == 0) { // sample from the restriction to x >= median, and sample the other half by using // the self-similarity transformation x -> scale / (bias*x) double median = Math.sqrt(scale / bias); double rejection_mode = 1.0 / bias; // mode of rejection distribution, x^-1 e^(-1/bias x) if (rejection_mode < median) rejection_mode = median; double rejection_norm = (1.0 / rejection_mode) * Math.exp(-1.0 / (bias * rejection_mode)); do { sample = nextGamma(1.0, scale) + median; accept = (1.0 / sample) * Math.exp(-1.0 / (sample * bias)) / rejection_norm; iters += 1; } while (MathUtils.nextDouble() > accept && iters < 10000); if (iters == 10000) { System.out.println("Severe Warning: nextExpGamma (shape=0) failed to generate a sample - returning bogus value!"); } if (MathUtils.nextDouble() > 0.5) { sample = scale / (bias * sample); } return sample; } // Current algorithm works for all shape parameters > 0, but it becomes very inefficient // for v. small shape parameters. if (shape <= 0.0) { System.out.println("nextExpGamma: Illegal argument (shape parameter is must be positive)"); throw new IllegalArgumentException(""); } // the function -1/(bias*x) is bounded by x/(bias x0^2) + C, with C = -2/(bias*x0), so that these functions // coincide precisely when x=x0. This gives the scale parameter of the majorating Gamma distribution // // First calculate the value that maximizes the acceptance probability at the mean of the proposal distribution double x0 = (shape * scale + Math.sqrt(4 * scale / bias + shape * shape * scale * scale)) / 2.0; // calculate the scale parameter of the majorating Gamma distribution double majorandScale = 1.0 / ((1.0 / scale) - 1.0 / (bias * x0 * x0)); // now do rejection sampling do { sample = nextGamma(shape, majorandScale); accept = Math.exp(-(sample / x0 - 1) * (sample / x0 - 1) / (bias * sample)); iters += 1; } while (MathUtils.nextDouble() > accept && iters < 10000); if (accept > 1.0) { System.out.println("PROBLEM!! This should be impossible!! Contact the authors."); } if (majorandScale < 0.0) { System.out.println("PROBLEM!! This should be impossible too!! Contact the authors."); } if (iters == 10000) { System.out.println("Severe Warning: nextExpGamma failed to generate a sample - returning bogus value!"); } } return sample; } // Private private static double pointChi2(double prob, double v) { // Returns z so that Prob{x