// // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2014 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using IStation.Numerics.Random; namespace IStation.Numerics.Distributions { /// /// Continuous Univariate Gamma distribution. /// For details about this distribution, see /// Wikipedia - Gamma distribution. /// /// /// The Gamma distribution is parametrized by a shape and inverse scale parameter. When we want /// to specify a Gamma distribution which is a point distribution we set the shape parameter to be the /// location of the point distribution and the inverse scale as positive infinity. The distribution /// with shape and inverse scale both zero is undefined. /// /// Random number generation for the Gamma distribution is based on the algorithm in: /// "A Simple Method for Generating Gamma Variables" - Marsaglia & Tsang /// ACM Transactions on Mathematical Software, Vol. 26, No. 3, September 2000, Pages 363–372. /// public class Gamma : IContinuousDistribution { System.Random _random; readonly double _shape; readonly double _rate; /// /// Initializes a new instance of the Gamma class. /// /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. public Gamma(double shape, double rate) { if (!IsValidParameterSet(shape, rate)) { throw new ArgumentException("Invalid parametrization for the distribution."); } _random = SystemRandomSource.Default; _shape = shape; _rate = rate; } /// /// Initializes a new instance of the Gamma class. /// /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// The random number generator which is used to draw random samples. public Gamma(double shape, double rate, System.Random randomSource) { if (!IsValidParameterSet(shape, rate)) { throw new ArgumentException("Invalid parametrization for the distribution."); } _random = randomSource ?? SystemRandomSource.Default; _shape = shape; _rate = rate; } /// /// Constructs a Gamma distribution from a shape and scale parameter. The distribution will /// be initialized with the default random number generator. /// /// The shape (k) of the Gamma distribution. Range: k ≥ 0. /// The scale (θ) of the Gamma distribution. Range: θ ≥ 0 /// The random number generator which is used to draw random samples. Optional, can be null. public static Gamma WithShapeScale(double shape, double scale, System.Random randomSource = null) { return new Gamma(shape, 1.0/scale, randomSource); } /// /// Constructs a Gamma distribution from a shape and inverse scale parameter. The distribution will /// be initialized with the default random number generator. /// /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// The random number generator which is used to draw random samples. Optional, can be null. public static Gamma WithShapeRate(double shape, double rate, System.Random randomSource = null) { return new Gamma(shape, rate, randomSource); } /// /// A string representation of the distribution. /// /// a string representation of the distribution. public override string ToString() { return $"Gamma(α = {_shape}, β = {_rate})"; } /// /// Tests whether the provided values are valid parameters for this distribution. /// /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. public static bool IsValidParameterSet(double shape, double rate) { return shape >= 0.0 && rate >= 0.0; } /// /// Gets or sets the shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// public double Shape => _shape; /// /// Gets or sets the rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// public double Rate => _rate; /// /// Gets or sets the scale (θ) of the Gamma distribution. /// public double Scale => 1.0/_rate; /// /// Gets or sets the random number generator which is used to draw random samples. /// public System.Random RandomSource { get => _random; set => _random = value ?? SystemRandomSource.Default; } /// /// Gets the mean of the Gamma distribution. /// public double Mean { get { if (double.IsPositiveInfinity(_rate)) { return _shape; } if (_rate == 0.0 && _shape == 0.0) { return double.NaN; } return _shape/_rate; } } /// /// Gets the variance of the Gamma distribution. /// public double Variance { get { if (double.IsPositiveInfinity(_rate)) { return 0.0; } if (_rate == 0.0 && _shape == 0.0) { return double.NaN; } return _shape/(_rate*_rate); } } /// /// Gets the standard deviation of the Gamma distribution. /// public double StdDev { get { if (double.IsPositiveInfinity(_rate)) { return 0.0; } if (_rate == 0.0 && _shape == 0.0) { return double.NaN; } return Math.Sqrt(_shape/(_rate*_rate)); } } /// /// Gets the entropy of the Gamma distribution. /// public double Entropy { get { if (double.IsPositiveInfinity(_rate)) { return 0.0; } if (_rate == 0.0 && _shape == 0.0) { return double.NaN; } return _shape - Math.Log(_rate) + SpecialFunctions.GammaLn(_shape) + ((1.0 - _shape)*SpecialFunctions.DiGamma(_shape)); } } /// /// Gets the skewness of the Gamma distribution. /// public double Skewness { get { if (double.IsPositiveInfinity(_rate)) { return 0.0; } if (_rate == 0.0 && _shape == 0.0) { return double.NaN; } return 2.0/Math.Sqrt(_shape); } } /// /// Gets the mode of the Gamma distribution. /// public double Mode { get { if (double.IsPositiveInfinity(_rate)) { return _shape; } if (_rate == 0.0 && _shape == 0.0) { return double.NaN; } return (_shape - 1.0)/_rate; } } /// /// Gets the median of the Gamma distribution. /// public double Median => throw new NotSupportedException(); /// /// Gets the minimum of the Gamma distribution. /// public double Minimum => 0.0; /// /// Gets the maximum of the Gamma distribution. /// public double Maximum => double.PositiveInfinity; /// /// Computes the probability density of the distribution (PDF) at x, i.e. ∂P(X ≤ x)/∂x. /// /// The location at which to compute the density. /// the density at . /// public double Density(double x) { return PDF(_shape, _rate, x); } /// /// Computes the log probability density of the distribution (lnPDF) at x, i.e. ln(∂P(X ≤ x)/∂x). /// /// The location at which to compute the log density. /// the log density at . /// public double DensityLn(double x) { return PDFLn(_shape, _rate, x); } /// /// Computes the cumulative distribution (CDF) of the distribution at x, i.e. P(X ≤ x). /// /// The location at which to compute the cumulative distribution function. /// the cumulative distribution at location . /// public double CumulativeDistribution(double x) { return CDF(_shape, _rate, x); } /// /// Computes the inverse of the cumulative distribution function (InvCDF) for the distribution /// at the given probability. This is also known as the quantile or percent point function. /// /// The location at which to compute the inverse cumulative density. /// the inverse cumulative density at . /// public double InverseCumulativeDistribution(double p) { return InvCDF(_shape, _rate, p); } /// /// Generates a sample from the Gamma distribution. /// /// a sample from the distribution. public double Sample() { return SampleUnchecked(_random, _shape, _rate); } /// /// Fills an array with samples generated from the distribution. /// public void Samples(double[] values) { SamplesUnchecked(_random, values, _shape, _rate); } /// /// Generates a sequence of samples from the Gamma distribution. /// /// a sequence of samples from the distribution. public IEnumerable Samples() { return SamplesUnchecked(_random, _shape, _rate); } /// /// Sampling implementation based on: /// "A Simple Method for Generating Gamma Variables" - Marsaglia & Tsang /// ACM Transactions on Mathematical Software, Vol. 26, No. 3, September 2000, Pages 363–372. /// This method performs no parameter checks. /// /// The random number generator to use. /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// A sample from a Gamma distributed random variable. internal static double SampleUnchecked(System.Random rnd, double shape, double rate) { if (double.IsPositiveInfinity(rate)) { return shape; } var a = shape; var alphafix = 1.0; // Fix when alpha is less than one. if (shape < 1.0) { a = shape + 1.0; alphafix = Math.Pow(rnd.NextDouble(), 1.0/shape); } var d = a - (1.0/3.0); var c = 1.0/Math.Sqrt(9.0*d); while (true) { var x = Normal.Sample(rnd, 0.0, 1.0); var v = 1.0 + (c*x); while (v <= 0.0) { x = Normal.Sample(rnd, 0.0, 1.0); v = 1.0 + (c*x); } v = v*v*v; var u = rnd.NextDouble(); x = x*x; if (u < 1.0 - (0.0331*x*x)) { return alphafix*d*v/rate; } if (Math.Log(u) < (0.5*x) + (d*(1.0 - v + Math.Log(v)))) { return alphafix*d*v/rate; } } } internal static void SamplesUnchecked(System.Random rnd, double[] values, double shape, double rate) { for (int i = 0; i < values.Length; i++) { values[i] = SampleUnchecked(rnd, shape, rate); } } internal static IEnumerable SamplesUnchecked(System.Random rnd, double location, double scale) { while (true) { yield return SampleUnchecked(rnd, location, scale); } } /// /// Computes the probability density of the distribution (PDF) at x, i.e. ∂P(X ≤ x)/∂x. /// /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// The location at which to compute the density. /// the density at . /// public static double PDF(double shape, double rate, double x) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } if (double.IsPositiveInfinity(rate)) { return x == shape ? double.PositiveInfinity : 0.0; } if (shape == 0.0 && rate == 0.0) { return 0.0; } if (shape == 1.0) { return rate*Math.Exp(-rate*x); } if (shape > 160.0) { return Math.Exp(PDFLn(shape, rate, x)); } return Math.Pow(rate, shape)*Math.Pow(x, shape - 1.0)*Math.Exp(-rate*x)/SpecialFunctions.Gamma(shape); } /// /// Computes the log probability density of the distribution (lnPDF) at x, i.e. ln(∂P(X ≤ x)/∂x). /// /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// The location at which to compute the density. /// the log density at . /// public static double PDFLn(double shape, double rate, double x) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } if (double.IsPositiveInfinity(rate)) { return x == shape ? double.PositiveInfinity : double.NegativeInfinity; } if (shape == 0.0 && rate == 0.0) { return double.NegativeInfinity; } if (shape == 1.0) { return Math.Log(rate) - (rate*x); } return (shape*Math.Log(rate)) + ((shape - 1.0)*Math.Log(x)) - (rate*x) - SpecialFunctions.GammaLn(shape); } /// /// Computes the cumulative distribution (CDF) of the distribution at x, i.e. P(X ≤ x). /// /// The location at which to compute the cumulative distribution function. /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// the cumulative distribution at location . /// public static double CDF(double shape, double rate, double x) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } if (double.IsPositiveInfinity(rate)) { return x >= shape ? 1.0 : 0.0; } if (shape == 0.0 && rate == 0.0) { return 0.0; } return SpecialFunctions.GammaLowerRegularized(shape, x*rate); } /// /// Computes the inverse of the cumulative distribution function (InvCDF) for the distribution /// at the given probability. This is also known as the quantile or percent point function. /// /// The location at which to compute the inverse cumulative density. /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// the inverse cumulative density at . /// public static double InvCDF(double shape, double rate, double p) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SpecialFunctions.GammaLowerRegularizedInv(shape, p)/rate; } /// /// Generates a sample from the Gamma distribution. /// /// The random number generator to use. /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// a sample from the distribution. public static double Sample(System.Random rnd, double shape, double rate) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SampleUnchecked(rnd, shape, rate); } /// /// Generates a sequence of samples from the Gamma distribution. /// /// The random number generator to use. /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// a sequence of samples from the distribution. public static IEnumerable Samples(System.Random rnd, double shape, double rate) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SamplesUnchecked(rnd, shape, rate); } /// /// Fills an array with samples generated from the distribution. /// /// The random number generator to use. /// The array to fill with the samples. /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// a sequence of samples from the distribution. public static void Samples(System.Random rnd, double[] values, double shape, double rate) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } SamplesUnchecked(rnd, values, shape, rate); } /// /// Generates a sample from the Gamma distribution. /// /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// a sample from the distribution. public static double Sample(double shape, double rate) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SampleUnchecked(SystemRandomSource.Default, shape, rate); } /// /// Generates a sequence of samples from the Gamma distribution. /// /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// a sequence of samples from the distribution. public static IEnumerable Samples(double shape, double rate) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SamplesUnchecked(SystemRandomSource.Default, shape, rate); } /// /// Fills an array with samples generated from the distribution. /// /// The array to fill with the samples. /// The shape (k, α) of the Gamma distribution. Range: α ≥ 0. /// The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0. /// a sequence of samples from the distribution. public static void Samples(double[] values, double shape, double rate) { if (shape < 0.0 || rate < 0.0) { throw new ArgumentException("Invalid parametrization for the distribution."); } SamplesUnchecked(SystemRandomSource.Default, values, shape, rate); } } }