Skip to content

HMath.Probability

Module index · Numerical conventions

Description

Checked probability models. Gamma uses shape/scale, geometric and negative binomial count failures before successes, Gumbel/GEV model maxima, Student-t is standardized, and triangular parameters are lowermodeupper. Discrete densities are zero away from integer support; CDF=P(X<=x), survival=P(X>x). Quantiles use inf{x:F(x)>=p}. Log zero is -infinity by contract. Finite reference summation/integration budgets are explicit in the code. DiscreteUniform endpoints must be exactly representable integers (|bound|<=2^53), and Skellam log-mass order is capped at 1000000; CDF tails outside its finite numerical summation window saturate to zero/one.

On this page

API Purpose
Distribution Parameterized probability law.
Bernoulli Declaration and type contract below.
Binomial Declaration and type contract below.
NegativeBinomial Declaration and type contract below.
Geometric Declaration and type contract below.
Hypergeometric Declaration and type contract below.
Poisson Declaration and type contract below.
Categorical Declaration and type contract below.
DiscreteUniform Declaration and type contract below.
Uniform Declaration and type contract below.
Normal Declaration and type contract below.
LogNormal Declaration and type contract below.
Exponential Declaration and type contract below.
Gamma Declaration and type contract below.
Beta Declaration and type contract below.
ChiSquare Declaration and type contract below.
StudentT Declaration and type contract below.
FisherF Declaration and type contract below.
Cauchy Declaration and type contract below.
Laplace Declaration and type contract below.
Logistic Declaration and type contract below.
Weibull Declaration and type contract below.
Pareto Declaration and type contract below.
Rayleigh Declaration and type contract below.
Maxwell Declaration and type contract below.
Gumbel Declaration and type contract below.
GeneralizedExtremeValue Declaration and type contract below.
BetaBinomial Declaration and type contract below.
Skellam Declaration and type contract below.
VonMises Declaration and type contract below.
Triangular Declaration and type contract below.
TruncatedNormal Declaration and type contract below.
Mixture Declaration and type contract below.
Empirical Declaration and type contract below.
GaussianKDE Declaration and type contract below.
validateDistribution Check finite parameters, support ordering, probability normalization, and declared per-family reference budgets.
density Probability mass for discrete families or density for continuous families.
logDensity Log density or mass; zero probability is negative infinity, while an integrable endpoint singularity is positive infinity.
cdf P(X<=x).
survival P(X>x), using direct upper tails for normal, gamma, beta, t, F, binomial and Poisson to avoid cancellation.
quantile Generalized inverse CDF, p in [0,1]; endpoints return mathematical support bounds, including infinities.
hazard Density divided by survival.
logLikelihood Sum of independent observation log probabilities.
moments Mean and population variance.
entropy Shannon or differential entropy in nats.
sample Draw a model sample and updated immutable RNG; specialized gammanormalcount samplers are reused, with inverse-CDF sampling for remaining families.
fitNormal Normal maximum-likelihood fit; variance divides by n.
fitExponential Maximum-likelihood rate for nonnegative observations with strictly positive total.
fitBernoulli Maximum-likelihood probability for nonempty binary observations.
fitMLEGrid Select the maximum-likelihood model from an explicit finite candidate grid; this is grid search, not continuous parameter optimization.
fitMAPGrid Select the maximum log-likelihood plus caller-supplied log prior over a finite model grid.
betaBernoulliUpdate Conjugate Beta prior update from success/failure observations, returning posterior concentrations (alpha,beta).
gammaPoissonUpdate Conjugate Poisson-rate update; arguments and result use Gamma shaperate, deliberately distinct from the Gamma distribution constructor shapescale.
normalNormalUpdate Known-variance conjugate normal mean update.
conditionalProbability Compute P(A|B) from joint P(A intersection B) and strictly positive P(B).
bayes Normalize prior probabilities times observation likelihoods.
expectation Reference expectation under a distribution.
goodnessOfFit Two-sided one-sample Kolmogorov distance against a specified CDF.
gaussianKDE Construct an equal-weight Gaussian kernel density with strictly positive bandwidth and finite nonempty observations.
multinomialPMF Multinomial mass for probabilities summing to one and nonnegative count vector; log-gamma arithmetic avoids factorial overflow.
dirichletDensity Dirichlet density on the strictly positive simplex interior.
multivariateNormalLogDensity Log density for a finite mean/point and symmetric positive-definite covariance, validated by Cholesky.
sampleMultivariateNormal Cholesky-transform independent standard normals; returns a vector and updated state.
wishartLogDensity Wishart log density for real degrees of freedom nu>p-1 and positive-definite p-by-p scale and observation matrices.
sampleWishart Reference Wishart draw as the sum of nu Gaussian outer products; requires integer nu>=p and nu<=100000.
Markov Opaque finite row-stochastic transition matrix.
markov Validate and construct a row-stochastic matrix with 1..1024 states; row sums tolerate absolute error 1e-12.
transition Advance a normalized state-probability row vector by one Markov step.
stationary Stationary probabilities by damped power iteration, with caller iteration budget and positive residual tolerance.
HMM Opaque finite-state categorical-emission hidden Markov model.
hmm Validate initial probabilities, square transition matrix and equally sized categorical-emission rows.
forward Scaled forward returns log likelihood, normalized alpha rows and per-time scaling constants.
backward Scaled backward messages using the same per-time normalizers as forward; terminal message is the all-ones vector.
posteriorStates Posterior state probabilities at each observation time from normalized alpha-beta products.
viterbi Most likely state path and its joint log probability, via max-product dynamic programming in log space.
baumWelch Baum--Welch EM for one observation sequence, pseudocount>=0.

Documentation

Distribution

data Distribution Source #

Parameterized probability law. Constructors carry: Bernoulli p; Binomial trials p; NegativeBinomial successes p; Geometric p; Hypergeometric population successes draws; Poisson rate; Categorical probabilities; DiscreteUniform lo hi; Uniform lo hi; Normal mean standardDeviation; LogNormal logMean logStandardDeviation; Exponential rate; Gamma shape scale; Beta alpha beta; ChiSquare degrees; StudentT degrees; FisherF numeratorDegrees denominatorDegrees; CauchyLaplaceLogistic location scale; Weibull shape scale; Pareto scale shape; Rayleigh/Maxwell scale; Gumbel location scale; GeneralizedExtremeValue location scale shape; BetaBinomial trials alpha beta; Skellam rate1 rate2; VonMises meanAngle concentration; Triangular lo mode hi; TruncatedNormal mean standardDeviation lo hi; Mixture weightedLaws; Empirical samples; GaussianKDE bandwidth samples. Call validateDistribution to check finite parameters,support,normalization,and family budgets before numerical use.

Instances

Instances details
Show Distribution Source # 
Instance details

Defined in HMath.Probability

Eq Distribution Source # 
Instance details

Defined in HMath.Probability

validateDistribution

validateDistribution :: Distribution -> Either MathError () Source #

Check finite parameters, support ordering, probability normalization, and declared per-family reference budgets.

density

density :: Distribution -> Double -> Either MathError Double Source #

Probability mass for discrete families or density for continuous families. At integrable density singularities the result can be positive infinity; outside support it is zero.

logDensity

logDensity :: Distribution -> Double -> Either MathError Double Source #

Log density or mass; zero probability is negative infinity, while an integrable endpoint singularity is positive infinity. Observations must be finite.

cdf

cdf :: Distribution -> Double -> Either MathError Double Source #

P(X<=x). Gamma/beta and classical transformed families use analytic special-function identities. Remaining finite-support continuous cases use 2048-panel Simpson integration; Skellam drops a tail beyond 14 standard deviations plus 20 counts.

survival

survival :: Distribution -> Double -> Either MathError Double Source #

P(X>x), using direct upper tails for normal, gamma, beta, t, F, binomial and Poisson to avoid cancellation. Other families use the CDF complement.

quantile

quantile :: Distribution -> Double -> Either MathError Double Source #

Generalized inverse CDF, p in [0,1]; endpoints return mathematical support bounds, including infinities. Interior values use analytic transforms or bounded bracketing/bisection.

hazard

hazard :: Distribution -> Double -> Either MathError Double Source #

Density divided by survival. For zero survival returns positive infinity by convention.

logLikelihood

logLikelihood :: Distribution -> [Double] -> Either MathError Double Source #

Sum of independent observation log probabilities. Impossible data produce negative infinity.

moments

moments :: Distribution -> Either MathError (Double, Double) Source #

Mean and population variance. Infinite/nonexistent moments return a domain error rather than a numeric value that could be mistaken for a finite moment.

entropy

entropy :: Distribution -> Either MathError Double Source #

Shannon or differential entropy in nats. Closed forms are used when available; other families use the documented expectation quadrature.

sample

sample :: Distribution -> RNG -> Either MathError (Double, RNG) Source #

Draw a model sample and updated immutable RNG; specialized gammanormalcount samplers are reused, with inverse-CDF sampling for remaining families.

fitNormal

fitNormal :: [Double] -> Either MathError Distribution Source #

Normal maximum-likelihood fit; variance divides by n. Constant data are rejected because this continuous family requires positive standard deviation.

fitExponential

fitExponential :: [Double] -> Either MathError Distribution Source #

Maximum-likelihood rate for nonnegative observations with strictly positive total.

fitBernoulli

fitBernoulli :: [Double] -> Either MathError Distribution Source #

Maximum-likelihood probability for nonempty binary observations.

fitMLEGrid

fitMLEGrid :: [Distribution] -> [Double] -> Either MathError Distribution Source #

Select the maximum-likelihood model from an explicit finite candidate grid; this is grid search, not continuous parameter optimization.

fitMAPGrid

fitMAPGrid :: [Distribution] -> [Double] -> (Distribution -> Double) -> Either MathError Distribution Source #

Select the maximum log-likelihood plus caller-supplied log prior over a finite model grid. Log priors must be finite.

betaBernoulliUpdate

betaBernoulliUpdate :: Double -> Double -> [Bool] -> Either MathError (Double, Double) Source #

Conjugate Beta prior update from success/failure observations, returning posterior concentrations (alpha,beta).

gammaPoissonUpdate

gammaPoissonUpdate :: Double -> Double -> [Int] -> Either MathError (Double, Double) Source #

Conjugate Poisson-rate update; arguments and result use Gamma shaperate, deliberately distinct from the Gamma distribution constructor shapescale.

normalNormalUpdate

normalNormalUpdate :: Double -> Double -> Double -> [Double] -> Either MathError (Double, Double) Source #

Known-variance conjugate normal mean update. Arguments are prior mean, prior variance, observation variance and observations; returns posterior mean/variance.

conditionalProbability

conditionalProbability :: Double -> Double -> Either MathError Double Source #

Compute P(A|B) from joint P(A intersection B) and strictly positive P(B).

bayes

bayes :: [Double] -> [Double] -> Either MathError [Double] Source #

Normalize prior probabilities times observation likelihoods. A zero-evidence observation is rejected.

expectation

expectation :: Distribution -> (Double -> Double) -> Either MathError Double Source #

Reference expectation under a distribution. Empirical/mixture cases are exact weighted sums; count families truncate at 1e-10 tail quantiles, continuous families use 4096 midpoint probability-space nodes. No certified quadrature error is claimed.

goodnessOfFit

goodnessOfFit :: Distribution -> [Double] -> Either MathError Double Source #

Two-sided one-sample Kolmogorov distance against a specified CDF. Returns the distance only; no discrete-null p-value is implied.

gaussianKDE

gaussianKDE :: Double -> [Double] -> Either MathError Distribution Source #

Construct an equal-weight Gaussian kernel density with strictly positive bandwidth and finite nonempty observations.

multinomialPMF

multinomialPMF :: [Double] -> [Int] -> Either MathError Double Source #

Multinomial mass for probabilities summing to one and nonnegative count vector; log-gamma arithmetic avoids factorial overflow.

dirichletDensity

dirichletDensity :: [Double] -> [Double] -> Either MathError Double Source #

Dirichlet density on the strictly positive simplex interior. Concentration and coordinate vectors must have matching nonzero length.

multivariateNormalLogDensity

multivariateNormalLogDensity :: [Double] -> Matrix Double -> [Double] -> Either MathError Double Source #

Log density for a finite mean/point and symmetric positive-definite covariance, validated by Cholesky.

sampleMultivariateNormal

sampleMultivariateNormal :: [Double] -> Matrix Double -> RNG -> Either MathError ([Double], RNG) Source #

Cholesky-transform independent standard normals; returns a vector and updated state.

wishartLogDensity

wishartLogDensity :: Double -> Matrix Double -> Matrix Double -> Either MathError Double Source #

Wishart log density for real degrees of freedom nu>p-1 and positive-definite p-by-p scale and observation matrices.

sampleWishart

sampleWishart :: Int -> Matrix Double -> RNG -> Either MathError (Matrix Double, RNG) Source #

Reference Wishart draw as the sum of nu Gaussian outer products; requires integer nu>=p and nu<=100000.

Markov

data Markov Source #

Opaque finite row-stochastic transition matrix.

Instances

Instances details
Show Markov Source # 
Instance details

Defined in HMath.Probability

Eq Markov Source # 
Instance details

Defined in HMath.Probability

Methods

(==) :: Markov -> Markov -> Bool #

(/=) :: Markov -> Markov -> Bool #

markov

markov :: [[Double]] -> Either MathError Markov Source #

Validate and construct a row-stochastic matrix with 1..1024 states; row sums tolerate absolute error 1e-12.

transition

transition :: Markov -> [Double] -> Either MathError [Double] Source #

Advance a normalized state-probability row vector by one Markov step.

stationary

stationary :: Int -> Double -> Markov -> Either MathError [Double] Source #

Stationary probabilities by damped power iteration, with caller iteration budget and positive residual tolerance. Reducible chains can have multiple stationary laws.

HMM

data HMM Source #

Opaque finite-state categorical-emission hidden Markov model.

Instances

Instances details
Show HMM Source # 
Instance details

Defined in HMath.Probability

Methods

showsPrec :: Int -> HMM -> ShowS #

show :: HMM -> String #

showList :: [HMM] -> ShowS #

Eq HMM Source # 
Instance details

Defined in HMath.Probability

Methods

(==) :: HMM -> HMM -> Bool #

(/=) :: HMM -> HMM -> Bool #

hmm

hmm :: [Double] -> [[Double]] -> [[Double]] -> Either MathError HMM Source #

Validate initial probabilities, square transition matrix and equally sized categorical-emission rows.

forward

forward :: HMM -> [Int] -> Either MathError (Double, [[Double]], [Double]) Source #

Scaled forward returns log likelihood, normalized alpha rows and per-time scaling constants. This avoids the product underflow of raw probability DP.

backward

backward :: HMM -> [Int] -> Either MathError [[Double]] Source #

Scaled backward messages using the same per-time normalizers as forward; terminal message is the all-ones vector.

posteriorStates

posteriorStates :: HMM -> [Int] -> Either MathError [[Double]] Source #

Posterior state probabilities at each observation time from normalized alpha-beta products.

viterbi

viterbi :: HMM -> [Int] -> Either MathError ([Int], Double) Source #

Most likely state path and its joint log probability, via max-product dynamic programming in log space.

baumWelch

baumWelch :: Int -> Double -> HMM -> [Int] -> Either MathError HMM Source #

Baum--Welch EM for one observation sequence, pseudocount>=0. Transition rows with zero expected occupancy retain their old row. Fixed iteration budget.