//
// 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
{
///
/// Discrete Univariate Poisson distribution.
///
///
/// Distribution is described at Wikipedia - Poisson distribution.
/// Knuth's method is used to generate Poisson distributed random variables.
/// f(x) = exp(-λ)*λ^x/x!;
///
public class Poisson : IDiscreteDistribution
{
System.Random _random;
readonly double _lambda;
///
/// Initializes a new instance of the class.
///
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// If is equal or less then 0.0.
public Poisson(double lambda)
{
if (!IsValidParameterSet(lambda))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
_random = SystemRandomSource.Default;
_lambda = lambda;
}
///
/// Initializes a new instance of the class.
///
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// The random number generator which is used to draw random samples.
/// If is equal or less then 0.0.
public Poisson(double lambda, System.Random randomSource)
{
if (!IsValidParameterSet(lambda))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
_random = randomSource ?? SystemRandomSource.Default;
_lambda = lambda;
}
///
/// Returns a that represents this instance.
///
///
/// A that represents this instance.
///
public override string ToString()
{
return $"Poisson(λ = {_lambda})";
}
///
/// Tests whether the provided values are valid parameters for this distribution.
///
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
public static bool IsValidParameterSet(double lambda)
{
return lambda > 0.0;
}
///
/// Gets the Poisson distribution parameter λ. Range: λ > 0.
///
public double Lambda => _lambda;
///
/// 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 distribution.
///
public double Mean => _lambda;
///
/// Gets the variance of the distribution.
///
public double Variance => _lambda;
///
/// Gets the standard deviation of the distribution.
///
public double StdDev => Math.Sqrt(_lambda);
///
/// Gets the entropy of the distribution.
///
/// Approximation, see Wikipedia Poisson distribution
public double Entropy => (0.5*Math.Log(2*Constants.Pi*Constants.E*_lambda)) - (1.0/(12.0*_lambda)) - (1.0/(24.0*_lambda*_lambda)) - (19.0/(360.0*_lambda*_lambda*_lambda));
///
/// Gets the skewness of the distribution.
///
public double Skewness => 1.0/Math.Sqrt(_lambda);
///
/// Gets the smallest element in the domain of the distributions which can be represented by an integer.
///
public int Minimum => 0;
///
/// Gets the largest element in the domain of the distributions which can be represented by an integer.
///
public int Maximum => int.MaxValue;
///
/// Gets the mode of the distribution.
///
public int Mode => (int)Math.Floor(_lambda);
///
/// Gets the median of the distribution.
///
/// Approximation, see Wikipedia Poisson distribution
public double Median => Math.Floor(_lambda + (1.0/3.0) - (0.02/_lambda));
///
/// Computes the probability mass (PMF) at k, i.e. P(X = k).
///
/// The location in the domain where we want to evaluate the probability mass function.
/// the probability mass at location .
public double Probability(int k)
{
return Math.Exp(-_lambda + (k*Math.Log(_lambda)) - SpecialFunctions.FactorialLn(k));
}
///
/// Computes the log probability mass (lnPMF) at k, i.e. ln(P(X = k)).
///
/// The location in the domain where we want to evaluate the log probability mass function.
/// the log probability mass at location .
public double ProbabilityLn(int k)
{
return -_lambda + (k*Math.Log(_lambda)) - SpecialFunctions.FactorialLn(k);
}
///
/// 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 1.0 - SpecialFunctions.GammaLowerRegularized(x + 1, _lambda);
}
///
/// Computes the probability mass (PMF) at k, i.e. P(X = k).
///
/// The location in the domain where we want to evaluate the probability mass function.
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// the probability mass at location .
public static double PMF(double lambda, int k)
{
if (!(lambda > 0.0))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return Math.Exp(-lambda + (k*Math.Log(lambda)) - SpecialFunctions.FactorialLn(k));
}
///
/// Computes the log probability mass (lnPMF) at k, i.e. ln(P(X = k)).
///
/// The location in the domain where we want to evaluate the log probability mass function.
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// the log probability mass at location .
public static double PMFLn(double lambda, int k)
{
if (!(lambda > 0.0))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return -lambda + (k*Math.Log(lambda)) - SpecialFunctions.FactorialLn(k);
}
///
/// 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 lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// the cumulative distribution at location .
///
public static double CDF(double lambda, double x)
{
if (!(lambda > 0.0))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return 1.0 - SpecialFunctions.GammaLowerRegularized(x + 1, lambda);
}
///
/// Generates one sample from the Poisson distribution.
///
/// The random source to use.
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// A random sample from the Poisson distribution.
static int SampleUnchecked(System.Random rnd, double lambda)
{
return (lambda < 30.0) ? DoSampleShort(rnd, lambda) : DoSampleLarge(rnd, lambda);
}
static void SamplesUnchecked(System.Random rnd, int[] values, double lambda)
{
if (lambda < 30.0)
{
var limit = Math.Exp(-lambda);
for (int i = 0; i < values.Length; i++)
{
var count = 0;
for (var product = rnd.NextDouble(); product >= limit; product *= rnd.NextDouble())
{
count++;
}
values[i] = count;
}
}
else
{
var c = 0.767 - (3.36/lambda);
var beta = Math.PI/Math.Sqrt(3.0*lambda);
var alpha = beta*lambda;
var k = Math.Log(c) - lambda - Math.Log(beta);
for (int i = 0; i < values.Length; i++)
{
for (;;)
{
var u = rnd.NextDouble();
var x = (alpha - Math.Log((1.0 - u)/u))/beta;
var n = (int)Math.Floor(x + 0.5);
if (n < 0)
{
continue;
}
var v = rnd.NextDouble();
var y = alpha - (beta*x);
var temp = 1.0 + Math.Exp(y);
var lhs = y + Math.Log(v/(temp*temp));
var rhs = k + (n*Math.Log(lambda)) - SpecialFunctions.FactorialLn(n);
if (lhs <= rhs)
{
values[i] = n;
break;
}
}
}
}
}
static IEnumerable SamplesUnchecked(System.Random rnd, double lambda)
{
if (lambda < 30.0)
{
while (true)
{
yield return DoSampleShort(rnd, lambda);
}
}
else
{
while (true)
{
yield return DoSampleLarge(rnd, lambda);
}
}
}
///
/// Generates one sample from the Poisson distribution by Knuth's method.
///
/// The random source to use.
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// A random sample from the Poisson distribution.
static int DoSampleShort(System.Random rnd, double lambda)
{
var limit = Math.Exp(-lambda);
var count = 0;
for (var product = rnd.NextDouble(); product >= limit; product *= rnd.NextDouble())
{
count++;
}
return count;
}
///
/// Generates one sample from the Poisson distribution by "Rejection method PA".
///
/// The random source to use.
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// A random sample from the Poisson distribution.
/// "Rejection method PA" from "The Computer Generation of Poisson Random Variables" by A. C. Atkinson,
/// Journal of the Royal Statistical Society Series C (Applied Statistics) Vol. 28, No. 1. (1979)
/// The article is on pages 29-35. The algorithm given here is on page 32.
static int DoSampleLarge(System.Random rnd, double lambda)
{
var c = 0.767 - (3.36/lambda);
var beta = Math.PI/Math.Sqrt(3.0*lambda);
var alpha = beta*lambda;
var k = Math.Log(c) - lambda - Math.Log(beta);
for (;;)
{
var u = rnd.NextDouble();
var x = (alpha - Math.Log((1.0 - u)/u))/beta;
var n = (int)Math.Floor(x + 0.5);
if (n < 0)
{
continue;
}
var v = rnd.NextDouble();
var y = alpha - (beta*x);
var temp = 1.0 + Math.Exp(y);
var lhs = y + Math.Log(v/(temp*temp));
var rhs = k + (n*Math.Log(lambda)) - SpecialFunctions.FactorialLn(n);
if (lhs <= rhs)
{
return n;
}
}
}
///
/// Samples a Poisson distributed random variable.
///
/// A sample from the Poisson distribution.
public int Sample()
{
return SampleUnchecked(_random, _lambda);
}
///
/// Fills an array with samples generated from the distribution.
///
public void Samples(int[] values)
{
SamplesUnchecked(_random, values, _lambda);
}
///
/// Samples an array of Poisson distributed random variables.
///
/// a sequence of successes in N trials.
public IEnumerable Samples()
{
return SamplesUnchecked(_random, _lambda);
}
///
/// Samples a Poisson distributed random variable.
///
/// The random number generator to use.
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// A sample from the Poisson distribution.
public static int Sample(System.Random rnd, double lambda)
{
if (!(lambda > 0.0))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SampleUnchecked(rnd, lambda);
}
///
/// Samples a sequence of Poisson distributed random variables.
///
/// The random number generator to use.
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// a sequence of samples from the distribution.
public static IEnumerable Samples(System.Random rnd, double lambda)
{
if (!(lambda > 0.0))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SamplesUnchecked(rnd, lambda);
}
///
/// Fills an array with samples generated from the distribution.
///
/// The random number generator to use.
/// The array to fill with the samples.
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// a sequence of samples from the distribution.
public static void Samples(System.Random rnd, int[] values, double lambda)
{
if (!(lambda > 0.0))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
SamplesUnchecked(rnd, values, lambda);
}
///
/// Samples a Poisson distributed random variable.
///
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// A sample from the Poisson distribution.
public static int Sample(double lambda)
{
if (!(lambda > 0.0))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SampleUnchecked(SystemRandomSource.Default, lambda);
}
///
/// Samples a sequence of Poisson distributed random variables.
///
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// a sequence of samples from the distribution.
public static IEnumerable Samples(double lambda)
{
if (!(lambda > 0.0))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SamplesUnchecked(SystemRandomSource.Default, lambda);
}
///
/// Fills an array with samples generated from the distribution.
///
/// The array to fill with the samples.
/// The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.
/// a sequence of samples from the distribution.
public static void Samples(int[] values, double lambda)
{
if (!(lambda > 0.0))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
SamplesUnchecked(SystemRandomSource.Default, values, lambda);
}
}
}