// // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2019 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 IStation.Numerics.Random; using IStation.Numerics.Statistics; using System; using System.Collections.Generic; using System.Linq; namespace IStation.Numerics.Distributions { public class InverseGaussian : IContinuousDistribution { System.Random _random; /// /// Gets the mean (μ) of the distribution. Range: μ > 0. /// public double Mu { get; } /// /// Gets the shape (λ) of the distribution. Range: λ > 0. /// public double Lambda { get; } /// /// Initializes a new instance of the InverseGaussian class. /// /// The mean (μ) of the distribution. Range: μ > 0. /// The shape (λ) of the distribution. Range: λ > 0. /// The random number generator which is used to draw random samples. public InverseGaussian(double mu, double lambda, System.Random randomSource = null) { if (!IsValidParameterSet(mu, lambda)) { throw new ArgumentException("Invalid parametrization for the distribution."); } _random = randomSource ?? SystemRandomSource.Default; Mu = mu; Lambda = lambda; } /// /// A string representation of the distribution. /// /// a string representation of the distribution. public override string ToString() { return $"InverseGaussian(μ = {Mu}, λ = {Lambda})"; } /// /// Tests whether the provided values are valid parameters for this distribution. /// /// The mean (μ) of the distribution. Range: μ > 0. /// The shape (λ) of the distribution. Range: λ > 0. public static bool IsValidParameterSet(double mu, double lambda) { var allFinite = mu.IsFinite() && lambda.IsFinite(); return allFinite && mu > 0.0 && lambda > 0.0; } /// /// Gets 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 Inverse Gaussian distribution. /// public double Mean => Mu; /// /// Gets the variance of the Inverse Gaussian distribution. /// public double Variance => Math.Pow(Mu, 3) / Lambda; /// /// Gets the standard deviation of the Inverse Gaussian distribution. /// public double StdDev => Math.Sqrt(Variance); /// /// Gets the median of the Inverse Gaussian distribution. /// No closed form analytical expression exists, so this value is approximated numerically and can throw an exception. /// public double Median => InvCDF(0.5); /// /// Gets the minimum of the Inverse Gaussian distribution. /// public double Minimum => 0.0; /// /// Gets the maximum of the Inverse Gaussian distribution. /// public double Maximum => double.PositiveInfinity; /// /// Gets the skewness of the Inverse Gaussian distribution. /// public double Skewness => 3 * Math.Sqrt(Mu / Lambda); /// /// Gets the kurtosis of the Inverse Gaussian distribution. /// public double Kurtosis => 15 * Mu / Lambda; /// /// Gets the mode of the Inverse Gaussian distribution. /// public double Mode => Mu * (Math.Sqrt(1 + (9 * Mu * Mu) / (4 * Lambda * Lambda)) - (3 * Mu) / (2 * Lambda)); /// /// Gets the entropy of the Inverse Gaussian distribution (currently not supported). /// public double Entropy => throw new NotSupportedException(); /// /// Generates a sample from the inverse Gaussian distribution. /// /// a sample from the distribution. public double Sample() { return SampleUnchecked(_random, Mu, Lambda); } /// /// Fills an array with samples generated from the distribution. /// /// The array to fill with the samples. public void Samples(double[] values) { SamplesUnchecked(_random, values, Mu, Lambda); } /// /// Generates a sequence of samples from the inverse Gaussian distribution. /// /// a sequence of samples from the distribution. public IEnumerable Samples() { return SamplesUnchecked(_random, Mu, Lambda); } /// /// Generates a sample from the inverse Gaussian distribution. /// /// The random number generator to use. /// The mean (μ) of the distribution. Range: μ > 0. /// The shape (λ) of the distribution. Range: λ > 0. /// a sample from the distribution. public static double Sample(System.Random rnd, double mu, double lambda) { if (!IsValidParameterSet(mu, lambda)) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SampleUnchecked(rnd, mu, lambda); } /// /// Fills an array with samples generated from the distribution. /// /// The random number generator to use. /// The array to fill with the samples. /// The mean (μ) of the distribution. Range: μ > 0. /// The shape (λ) of the distribution. Range: λ > 0. public static void Samples(System.Random rnd, double[] values, double mu, double lambda) { if (!IsValidParameterSet(mu, lambda)) { throw new ArgumentException("Invalid parametrization for the distribution."); } SamplesUnchecked(rnd, values, mu, lambda); } /// /// Generates a sequence of samples from the Burr distribution. /// /// The random number generator to use. /// The mean (μ) of the distribution. Range: μ > 0. /// The shape (λ) of the distribution. Range: λ > 0. /// a sequence of samples from the distribution. public static IEnumerable Samples(System.Random rnd, double mu, double lambda) { if (!IsValidParameterSet(mu, lambda)) { throw new ArgumentException("Invalid parametrization for the distribution."); } return SamplesUnchecked(rnd, mu, lambda); } internal static double SampleUnchecked(System.Random rnd, double mu, double lambda) { double v = IStation.Numerics.Distributions.Normal.Sample(rnd, 0, 1); double test = rnd.NextDouble(); return InverseGaussianSampleImpl(mu, lambda, v, test); } internal static void SamplesUnchecked(System.Random rnd, double[] values, double mu, double lambda) { if (values.Length == 0) { return; } double[] v = new double[values.Length]; IStation.Numerics.Distributions.Normal.Samples(rnd, v, 0, 1); double[] test = rnd.NextDoubles(values.Length); for (var j = 0; j < values.Length; ++j) { values[j] = InverseGaussianSampleImpl(mu, lambda, v[j], test[j]); } } internal static IEnumerable SamplesUnchecked(System.Random rnd, double mu, double lambda) { while (true) { yield return SampleUnchecked(rnd, mu, lambda); } } internal static double InverseGaussianSampleImpl(double mu, double lambda, double normalSample, double uniformSample) { double y = normalSample * normalSample; double x = mu + (mu * mu * y) / (2 * lambda) - (mu / (2 * lambda)) * Math.Sqrt(4 * mu * lambda * y + mu * mu * y * y); if (uniformSample <= mu / (mu + x)) return x; else return mu * mu / x; } /// /// 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 DensityImpl(Mu, Lambda, 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 DensityLnImpl(Mu, Lambda, 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 CumulativeDistributionImpl(Mu, Lambda, x); } /// /// Computes the inverse cumulative distribution (CDF) of the distribution at p, i.e. solving for P(X ≤ x) = p. /// /// The location at which to compute the inverse cumulative distribution function. /// the inverse cumulative distribution at location . public double InvCDF(double p) { Func equationToSolve = (x) => CumulativeDistribution(x) - p; if (RootFinding.NewtonRaphson.TryFindRoot(equationToSolve, Density, Mode, 0, double.PositiveInfinity, 1e-8, 100, out double quantile)) return quantile; else throw new NonConvergenceException("Numerical estimation of the statistic has failed. The used solver did not succeed in finding a root."); } /// /// Computes the probability density of the distribution (PDF) at x, i.e. ∂P(X ≤ x)/∂x. /// /// The mean (μ) of the distribution. Range: μ > 0. /// The shape (λ) of the distribution. Range: λ > 0. /// The location at which to compute the density. /// the density at . /// public static double PDF(double mu, double lambda, double x) { if (!IsValidParameterSet(mu, lambda)) { throw new ArgumentException("Invalid parametrization for the distribution."); } return DensityImpl(mu, lambda, x); } /// /// Computes the log probability density of the distribution (lnPDF) at x, i.e. ln(∂P(X ≤ x)/∂x). /// /// The mean (μ) of the distribution. Range: μ > 0. /// The shape (λ) of the distribution. Range: λ > 0. /// The location at which to compute the log density. /// the log density at . /// public static double PDFLn(double mu, double lambda, double x) { if (!IsValidParameterSet(mu, lambda)) { throw new ArgumentException("Invalid parametrization for the distribution."); } return DensityLnImpl(mu, lambda, x); } /// /// Computes the cumulative distribution (CDF) of the distribution at x, i.e. P(X ≤ x). /// /// The mean (μ) of the distribution. Range: μ > 0. /// The shape (λ) of the distribution. Range: λ > 0. /// The location at which to compute the cumulative distribution function. /// the cumulative distribution at location . /// public static double CDF(double mu, double lambda, double x) { if (!IsValidParameterSet(mu, lambda)) { throw new ArgumentException("Invalid parametrization for the distribution."); } return CumulativeDistributionImpl(mu, lambda, x); } /// /// Computes the inverse cumulative distribution (CDF) of the distribution at p, i.e. solving for P(X ≤ x) = p. /// /// The mean (μ) of the distribution. Range: μ > 0. /// The shape (λ) of the distribution. Range: λ > 0. /// The location at which to compute the inverse cumulative distribution function. /// the inverse cumulative distribution at location . /// public static double ICDF(double mu, double lambda, double p) { if (!IsValidParameterSet(mu, lambda)) { throw new ArgumentException("Invalid parametrization for the distribution."); } var igDist = new InverseGaussian(mu, lambda); return igDist.InvCDF(p); } /// /// Estimates the Inverse Gaussian parameters from sample data with maximum-likelihood. /// /// The samples to estimate the distribution parameters from. /// The random number generator which is used to draw random samples. Optional, can be null. /// An Inverse Gaussian distribution. public static InverseGaussian Estimate(IEnumerable samples, System.Random randomSource = null) { var sampleVec = samples.ToArray(); var muHat = sampleVec.Mean(); var lambdahat = 1 / (1 / samples.HarmonicMean() - 1 / muHat); return new InverseGaussian(muHat, lambdahat, randomSource); } internal static double DensityImpl(double mu, double lambda, double x) { return Math.Sqrt(lambda / (2 * Math.PI * Math.Pow(x, 3))) * Math.Exp(-((lambda * Math.Pow(x - mu, 2)) / (2 * mu * mu * x))); } internal static double DensityLnImpl(double mu, double lambda, double x) { return Math.Log(Math.Sqrt(lambda / (2 * Math.PI * Math.Pow(x, 3)))) - ((lambda * Math.Pow(x - mu, 2)) / (2 * mu * mu * x)); } internal static double CumulativeDistributionImpl(double mu, double lambda, double x) { return Normal.CDF(0, 1, Math.Sqrt(lambda / x) * (x / mu - 1)) + Math.Exp(2 * lambda / mu) * Normal.CDF(0, 1, -Math.Sqrt(lambda / x) * (x / mu + 1)); } } }