//
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 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 System.Linq;
using IStation.Numerics.Random;
using IStation.Numerics.Statistics;
using IStation.Numerics.Threading;
namespace IStation.Numerics.Distributions
{
///
/// Continuous Univariate Log-Normal distribution.
/// For details about this distribution, see
/// Wikipedia - Log-Normal distribution.
///
public class LogNormal : IContinuousDistribution
{
System.Random _random;
readonly double _mu;
readonly double _sigma;
///
/// Initializes a new instance of the class.
/// The distribution will be initialized with the default
/// random number generator.
///
/// The log-scale (μ) of the logarithm of the distribution.
/// The shape (σ) of the logarithm of the distribution. Range: σ ≥ 0.
public LogNormal(double mu, double sigma)
{
if (!IsValidParameterSet(mu, sigma))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
_random = SystemRandomSource.Default;
_mu = mu;
_sigma = sigma;
}
///
/// Initializes a new instance of the class.
/// The distribution will be initialized with the default
/// random number generator.
///
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// The random number generator which is used to draw random samples.
public LogNormal(double mu, double sigma, System.Random randomSource)
{
if (!IsValidParameterSet(mu, sigma))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
_random = randomSource ?? SystemRandomSource.Default;
_mu = mu;
_sigma = sigma;
}
///
/// Constructs a log-normal distribution with the desired mu and sigma parameters.
///
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// The random number generator which is used to draw random samples. Optional, can be null.
/// A log-normal distribution.
public static LogNormal WithMuSigma(double mu, double sigma, System.Random randomSource = null)
{
return new LogNormal(mu, sigma, randomSource);
}
///
/// Constructs a log-normal distribution with the desired mean and variance.
///
/// The mean of the log-normal distribution.
/// The variance of the log-normal distribution.
/// The random number generator which is used to draw random samples. Optional, can be null.
/// A log-normal distribution.
public static LogNormal WithMeanVariance(double mean, double var, System.Random randomSource = null)
{
var sigma2 = Math.Log(var/(mean*mean) + 1.0);
return new LogNormal(Math.Log(mean) - sigma2/2.0, Math.Sqrt(sigma2), randomSource);
}
///
/// Estimates the log-normal distribution 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.
/// A log-normal distribution.
/// MATLAB: lognfit
public static LogNormal Estimate(IEnumerable samples, System.Random randomSource = null)
{
var muSigma = samples.Select(s => Math.Log(s)).MeanStandardDeviation();
return new LogNormal(muSigma.Item1, muSigma.Item2, randomSource);
}
///
/// A string representation of the distribution.
///
/// a string representation of the distribution.
public override string ToString()
{
return $"LogNormal(μ = {_mu}, σ = {_sigma})";
}
///
/// Tests whether the provided values are valid parameters for this distribution.
///
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
public static bool IsValidParameterSet(double mu, double sigma)
{
return sigma >= 0.0 && !double.IsNaN(mu);
}
///
/// Gets the log-scale (μ) (mean of the logarithm) of the distribution.
///
public double Mu => _mu;
///
/// Gets the shape (σ) (standard deviation of the logarithm) of the distribution. Range: σ ≥ 0.
///
public double Sigma => _sigma;
///
/// 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 mu of the log-normal distribution.
///
public double Mean => Math.Exp(_mu + (_sigma*_sigma/2.0));
///
/// Gets the variance of the log-normal distribution.
///
public double Variance
{
get
{
var sigma2 = _sigma*_sigma;
return (Math.Exp(sigma2) - 1.0)*Math.Exp(_mu + _mu + sigma2);
}
}
///
/// Gets the standard deviation of the log-normal distribution.
///
public double StdDev
{
get
{
var sigma2 = _sigma*_sigma;
return Math.Sqrt((Math.Exp(sigma2) - 1.0)*Math.Exp(_mu + _mu + sigma2));
}
}
///
/// Gets the entropy of the log-normal distribution.
///
public double Entropy => 0.5 + Math.Log(_sigma) + _mu + Constants.LogSqrt2Pi;
///
/// Gets the skewness of the log-normal distribution.
///
public double Skewness
{
get
{
var expsigma2 = Math.Exp(_sigma*_sigma);
return (expsigma2 + 2.0)*Math.Sqrt(expsigma2 - 1);
}
}
///
/// Gets the mode of the log-normal distribution.
///
public double Mode => Math.Exp(_mu - (_sigma*_sigma));
///
/// Gets the median of the log-normal distribution.
///
public double Median => Math.Exp(_mu);
///
/// Gets the minimum of the log-normal distribution.
///
public double Minimum => 0.0;
///
/// Gets the maximum of the log-normal 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)
{
if (x < 0.0)
{
return 0.0;
}
var a = (Math.Log(x) - _mu)/_sigma;
return Math.Exp(-0.5*a*a)/(x*_sigma*Constants.Sqrt2Pi);
}
///
/// 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)
{
if (x < 0.0)
{
return double.NegativeInfinity;
}
var a = (Math.Log(x) - _mu)/_sigma;
return (-0.5*a*a) - Math.Log(x*_sigma) - Constants.LogSqrt2Pi;
}
///
/// 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 x < 0.0 ? 0.0
: 0.5*SpecialFunctions.Erfc((_mu - Math.Log(x))/(_sigma*Constants.Sqrt2));
}
///
/// 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 p <= 0.0 ? 0.0 : p >= 1.0 ? double.PositiveInfinity
: Math.Exp(_mu - _sigma*Constants.Sqrt2*SpecialFunctions.ErfcInv(2.0*p));
}
///
/// Generates a sample from the log-normal distribution using the Box-Muller algorithm.
///
/// a sample from the distribution.
public double Sample()
{
return SampleUnchecked(_random, _mu, _sigma);
}
///
/// Fills an array with samples generated from the distribution.
///
public void Samples(double[] values)
{
SamplesUnchecked(_random, values, _mu, _sigma);
}
///
/// Generates a sequence of samples from the log-normal distribution using the Box-Muller algorithm.
///
/// a sequence of samples from the distribution.
public IEnumerable Samples()
{
return SamplesUnchecked(_random, _mu, _sigma);
}
static double SampleUnchecked(System.Random rnd, double mu, double sigma)
{
return Math.Exp(Normal.SampleUnchecked(rnd, mu, sigma));
}
static IEnumerable SamplesUnchecked(System.Random rnd, double mu, double sigma)
{
return Normal.SamplesUnchecked(rnd, mu, sigma).Select(Math.Exp);
}
static void SamplesUnchecked(System.Random rnd, double[] values, double mu, double sigma)
{
Normal.SamplesUnchecked(rnd, values, mu, sigma);
CommonParallel.For(0, values.Length, 4096, (a, b) =>
{
for (int i = a; i < b; i++)
{
values[i] = Math.Exp(values[i]);
}
});
}
///
/// 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 log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// the density at .
///
/// MATLAB: lognpdf
public static double PDF(double mu, double sigma, double x)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
if (x < 0.0)
{
return 0.0;
}
var a = (Math.Log(x) - mu)/sigma;
return Math.Exp(-0.5*a*a)/(x*sigma*Constants.Sqrt2Pi);
}
///
/// 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 density.
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// the log density at .
///
public static double PDFLn(double mu, double sigma, double x)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
if (x < 0.0)
{
return double.NegativeInfinity;
}
var a = (Math.Log(x) - mu)/sigma;
return (-0.5*a*a) - Math.Log(x*sigma) - Constants.LogSqrt2Pi;
}
///
/// 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 log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// the cumulative distribution at location .
///
/// MATLAB: logncdf
public static double CDF(double mu, double sigma, double x)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return x < 0.0 ? 0.0
: 0.5*(1.0 + SpecialFunctions.Erf((Math.Log(x) - mu)/(sigma*Constants.Sqrt2)));
}
///
/// 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 log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// the inverse cumulative density at .
///
/// MATLAB: logninv
public static double InvCDF(double mu, double sigma, double p)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return p <= 0.0 ? 0.0 : p >= 1.0 ? double.PositiveInfinity
: Math.Exp(mu - sigma*Constants.Sqrt2*SpecialFunctions.ErfcInv(2.0*p));
}
///
/// Generates a sample from the log-normal distribution using the Box-Muller algorithm.
///
/// The random number generator to use.
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// a sample from the distribution.
public static double Sample(System.Random rnd, double mu, double sigma)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SampleUnchecked(rnd, mu, sigma);
}
///
/// Generates a sequence of samples from the log-normal distribution using the Box-Muller algorithm.
///
/// The random number generator to use.
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// a sequence of samples from the distribution.
public static IEnumerable Samples(System.Random rnd, double mu, double sigma)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SamplesUnchecked(rnd, mu, sigma);
}
///
/// Fills an array with samples generated from the distribution.
///
/// The random number generator to use.
/// The array to fill with the samples.
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// a sequence of samples from the distribution.
public static void Samples(System.Random rnd, double[] values, double mu, double sigma)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
SamplesUnchecked(rnd, values, mu, sigma);
}
///
/// Generates a sample from the log-normal distribution using the Box-Muller algorithm.
///
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// a sample from the distribution.
public static double Sample(double mu, double sigma)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SampleUnchecked(SystemRandomSource.Default, mu, sigma);
}
///
/// Generates a sequence of samples from the log-normal distribution using the Box-Muller algorithm.
///
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// a sequence of samples from the distribution.
public static IEnumerable Samples(double mu, double sigma)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SamplesUnchecked(SystemRandomSource.Default, mu, sigma);
}
///
/// Fills an array with samples generated from the distribution.
///
/// The array to fill with the samples.
/// The log-scale (μ) of the distribution.
/// The shape (σ) of the distribution. Range: σ ≥ 0.
/// a sequence of samples from the distribution.
public static void Samples(double[] values, double mu, double sigma)
{
if (sigma < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
SamplesUnchecked(SystemRandomSource.Default, values, mu, sigma);
}
}
}