Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Probability distributions with expressive algebra and automatic visualization.

This package wraps scipy.stats distributions to provide:

Distribution Algebra

Distributions support algebraic operations::

d = 2 * normal(5, 1) + 3  # Affine transform → Normal(13, 2)
z = normal() + normal()   # Sum of RVs → Normal(0, √2)
p = normal() > 1.96       # Probability query → P(X > 1.96) = 0.025

Probability Queries

Comparison operators return rich Probability objects::

d = normal(100, 15)
d > 130              # P(X > 130) = 0.0228
d.between(85, 115)   # P(85 ≤ X ≤ 115) = 0.6827

Fluent API

Chain transformations for readable code::

normal(100, 15).standardize()  # → Normal(0, 1)
normal().truncate(0, inf)      # Half-normal

Hypothesis Testing

Built-in methods for common testing tasks::

t = t_dist(df=29)
t.p_value(2.3, tail="two")     # → P(|X| > 2.3) = 0.0285
t.critical(alpha=0.05)         # → (-2.045, 2.045)
t.reject(2.3, alpha=0.05)      # → True

Available Distributions

Continuous: normal, t_dist, chi2, f_dist, beta, exponential, gamma, uniform Discrete: binomial, poisson

See Also

api/distributions : Tutorial with comprehensive examples

Classes:

NameDescription
ConvolvedDistributionDistribution representing the sum of two independent random variables.
DistributionWrapper for scipy.stats distributions with visualization.
FoldedDistributionDistribution of
ProbabilityRich probability result from distribution queries.
TransformedDistributionDistribution resulting from an affine transformation: Y = scale*X + shift.
TruncatedDistributionDistribution truncated to an interval [low, high].

Functions:

NameDescription
betaBeta distribution.
binomialBinomial distribution.
chi2Chi-squared distribution.
exponentialExponential distribution (rate parameterization).
f_distF distribution.
figure_to_htmlConvert matplotlib figure to base64-encoded HTML img tag.
gammaGamma distribution.
normalNormal (Gaussian) distribution.
poissonPoisson distribution.
tStudent’s t distribution (location-scale parameterization).
t_distStudent’s t distribution.
uniformUniform distribution.

Modules:

NameDescription
algebraDistribution algebra mixin.
baseDistribution base class.
coreBackward-compatibility re-exports for distribution classes.
derivedDerived distribution types.
factoriesDistribution factory functions.
plottingDistribution plotting mixin.
probabilityProbability result class and visualization helpers.

Classes

ConvolvedDistribution

ConvolvedDistribution(dist1: Distribution, dist2: Distribution, n_samples: int = MC_SAMPLES) -> None

Bases: Distribution

Distribution representing the sum of two independent random variables.

Uses Monte Carlo simulation for CDF/PPF computations when no closed-form solution is available.

Parameters:

NameTypeDescriptionDefault
dist1DistributionFirst distribution (X).required
dist2DistributionSecond distribution (Y).required
n_samplesintNumber of samples for Monte Carlo estimation.MC_SAMPLES

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF estimated from empirical distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
get_samplesGet or generate cached samples.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF estimated via kernel density estimation.
plotPlot the distribution.
pmfPMF estimated from sample frequencies.
ppfPPF (quantile function) estimated from samples.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from convolved distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatMean of sum: E[X] + E[Y].
medianfloatMedian estimated from samples.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatStandard deviation of sum.
varfloatVariance of sum (independent): Var[X] + Var[Y].

Attributes

iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Mean of sum: E[X] + E[Y].

median
median: float

Median estimated from samples.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Standard deviation of sum.

var
var: float

Variance of sum (independent): Var[X] + Var[Y].

Functions

abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF estimated from empirical distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayEmpirical CDF values.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
get_samples
get_samples() -> np.ndarray

Get or generate cached samples.

Returns:

TypeDescription
ndarraySorted array of Monte Carlo samples from X + Y.
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF estimated via kernel density estimation.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayKDE-estimated PDF values.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF estimated from sample frequencies.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayFrequency-estimated PMF values.
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF (quantile function) estimated from samples.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayEstimated quantile values.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from convolved distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples from X + Y.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (1 - CDF).
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798

Distribution

Distribution(dist: rv_frozen, name: str, params: dict[str, float]) -> None

Bases: DistributionPlotMixin, DistributionAlgebraMixin

Wrapper for scipy.stats distributions with visualization.

Provides a unified interface for probability distributions with:

Parameters:

NameTypeDescriptionDefault
distrv_frozenFrozen scipy.stats distribution.required
namestrDisplay name for the distribution.required
paramsdict[str, float]User-facing parameter dictionary for display.required

Examples:

# Use factory functions instead of direct instantiation
from distributions import normal, t_dist
d = normal(mean=0, sd=1)
d.cdf(1.96)  # 0.975
d.ppf(0.975)  # 1.96

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCumulative distribution function.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfProbability density function (continuous distributions only).
plotPlot the distribution.
pmfProbability mass function (discrete distributions only).
ppfPercent point function (inverse CDF / quantile function).
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random variates.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function (1 - CDF).
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatDistribution mean (expected value).
medianfloatDistribution median.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatDistribution standard deviation.
varfloatDistribution variance.

Attributes

iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Distribution mean (expected value).

median
median: float

Distribution median.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Distribution standard deviation.

var
var: float

Distribution variance.

Functions

abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

Cumulative distribution function.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate the CDF.required

Returns:

TypeDescription
ndarrayCDF values (P(X <= x)) at each point.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

Probability density function (continuous distributions only).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate the PDF.required

Returns:

TypeDescription
ndarrayPDF values at each point.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

Probability mass function (discrete distributions only).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate the PMF.required

Returns:

TypeDescription
ndarrayPMF values at each point.
ppf
ppf(q: ArrayLike) -> np.ndarray

Percent point function (inverse CDF / quantile function).

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayValues x such that P(X <= x) = q.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random variates.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples from the distribution.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function (1 - CDF).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (P(X > x)) at each point.
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798

FoldedDistribution

FoldedDistribution(base: Distribution, n_samples: int = MC_SAMPLES) -> None

Bases: Distribution

Distribution of |X| - the absolute value of X.

Uses simulation for CDF/PPF computations.

Parameters:

NameTypeDescriptionDefault
baseDistributionThe original distribution.required
n_samplesintNumber of samples for Monte Carlo estimation.MC_SAMPLES

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF of folded distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
get_samplesGet or generate cached samples.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF of folded distribution: f_
plotPlot the distribution.
pmfPMF of folded distribution.
ppfPPF of folded distribution.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from folded distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function of folded distribution.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatMean of folded distribution.
medianfloatMedian of folded distribution.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatStandard deviation of folded distribution.
varfloatVariance of folded distribution.

Attributes

iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Mean of folded distribution.

median
median: float

Median of folded distribution.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Standard deviation of folded distribution.

var
var: float

Variance of folded distribution.

Functions

abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF of folded distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayEmpirical CDF values.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
get_samples
get_samples() -> np.ndarray

Get or generate cached samples.

Returns:

TypeDescription
ndarraySorted array of Monte Carlo samples from
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF of folded distribution: f_|X|(y) = f_X(y) + f_X(-y) for y >= 0.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPDF values (zero for negative x).
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF of folded distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPMF values (zero for negative x).
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF of folded distribution.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayEstimated quantile values.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from folded distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function of folded distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (1 - CDF).
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798

Probability

Probability(value: float, expr: str, dist_name: str) -> None

Rich probability result from distribution queries.

Returned by comparison operators on distributions (e.g., normal() > 1.96). Behaves like a float for numeric operations while providing descriptive display.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value (between 0 and 1).required
exprstrExpression describing the event (e.g., “X > 1.96”).required
dist_namestrDisplay name of the distribution (e.g., “Normal(0, 1)”).required

Examples:

d = normal()
p = d > 1.96
p
# P(X > 1.96) = 0.025
float(p)
# 0.025
p < 0.05  # threshold check
# True

Attributes:

NameTypeDescription
dist_namestr
exprstr
valuefloat

Attributes

dist_name
dist_name: str
expr
expr: str
value
value: float

TransformedDistribution

TransformedDistribution(base: Distribution, scale: float, shift: float) -> None

Bases: Distribution

Distribution resulting from an affine transformation: Y = scale*X + shift.

Used when closed-form parameters aren’t available. Delegates to the base distribution with appropriate transformations applied.

Parameters:

NameTypeDescriptionDefault
baseDistributionThe original distribution.required
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF of transformed distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF of transformed distribution.
plotPlot the distribution.
pmfPMF of transformed distribution.
ppfPPF of transformed distribution.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from transformed distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function of transformed distribution.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatTransformed mean: scale * E[X] + shift.
medianfloatTransformed median: scale * median[X] + shift.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatTransformed standard deviation:
varfloatTransformed variance: scale^2 * Var[X].

Attributes

iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Transformed mean: scale * E[X] + shift.

median
median: float

Transformed median: scale * median[X] + shift.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Transformed standard deviation: |scale| * SD[X].

var
var: float

Transformed variance: scale^2 * Var[X].

Functions

abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayCDF values at each point.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPDF values at each point.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPMF values at each point.
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayValues x such that P(Y <= x) = q.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from transformed distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values at each point.
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798

TruncatedDistribution

TruncatedDistribution(base: Distribution, low: float = float('-inf'), high: float = float('inf')) -> None

Bases: Distribution

Distribution truncated to an interval [low, high].

The PDF is normalized to integrate to 1 over the truncation region.

Note: Truncation is exact for Normal bases. For other distributions, the truncated normal approximation is used, which may not match the true truncated distribution.

Parameters:

NameTypeDescriptionDefault
baseDistributionThe original distribution.required
lowfloatLower bound (inclusive).float(‘-inf’)
highfloatUpper bound (inclusive).float(‘inf’)

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF of truncated distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF of truncated distribution.
plotPlot the distribution.
pmfPMF of truncated distribution.
ppfPPF of truncated distribution.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from truncated distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function of truncated distribution.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatMean of truncated distribution.
medianfloatMedian of truncated distribution.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatStandard deviation of truncated distribution.
varfloatVariance of truncated distribution.

Attributes

iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Mean of truncated distribution.

median
median: float

Median of truncated distribution.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Standard deviation of truncated distribution.

var
var: float

Variance of truncated distribution.

Functions

abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayCDF values (0 below low, 1 above high).
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPDF values (zero outside truncation bounds).
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPMF values (zero outside truncation bounds).
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayQuantile values within truncation bounds.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from truncated distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples within truncation bounds.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (1 - CDF).
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798

Functions

beta

beta(a: float, b: float) -> Distribution

Beta distribution.

Parameters:

NameTypeDescriptionDefault
afloatShape parameter alpha (must be positive).required
bfloatShape parameter beta (must be positive).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = beta(a=2, b=5)
d.mean
# 0.285...

binomial

binomial(n: int, p: float) -> Distribution

Binomial distribution.

Parameters:

NameTypeDescriptionDefault
nintNumber of trials (must be non-negative integer).required
pfloatProbability of success (must be in [0, 1]).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

b = binomial(n=20, p=0.3)
b.mean
# 6.0
b.pmf(6)  # P(X = 6)
# 0.191...

chi2

chi2(df: float) -> Distribution

Chi-squared distribution.

Parameters:

NameTypeDescriptionDefault
dffloatDegrees of freedom (must be positive).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

c = chi2(df=5)
c.ppf(0.95)  # Critical value
# 11.07...

exponential

exponential(rate: float = 1.0) -> Distribution

Exponential distribution (rate parameterization).

Parameters:

NameTypeDescriptionDefault
ratefloatRate parameter lambda (must be positive). Mean = 1/rate. Default 1.0.1.0

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = exponential(rate=0.5)
d.mean
# 2.0

f_dist

f_dist(df1: float, df2: float) -> Distribution

F distribution.

Parameters:

NameTypeDescriptionDefault
df1floatNumerator degrees of freedom (must be positive).required
df2floatDenominator degrees of freedom (must be positive).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

f = f_dist(df1=5, df2=20)
f.ppf(0.95)  # Critical value
# 2.71...

figure_to_html

figure_to_html(fig: Figure, dpi: int = 100) -> str

Convert matplotlib figure to base64-encoded HTML img tag.

Parameters:

NameTypeDescriptionDefault
figFigureMatplotlib figure to convert.required
dpiintResolution for the PNG image.100

Returns:

TypeDescription
strHTML string with embedded base64 PNG.

gamma

gamma(shape: float, rate: float | None = None, scale: float | None = None) -> Distribution

Gamma distribution.

Accepts either rate or scale parameterization (not both).

Parameters:

NameTypeDescriptionDefault
shapefloatShape parameter (must be positive).required
ratefloat | NoneRate parameter (1/scale). If provided, scale must be None.None
scalefloat | NoneScale parameter. If provided, rate must be None. Default is scale=1 if neither specified.None

Returns:

TypeDescription
DistributionDistribution object.

Examples:

g = gamma(shape=2, rate=0.5)
g.mean
# 4.0
g = gamma(shape=2, scale=2)  # Equivalent
g.mean
# 4.0

normal

normal(mean: float = 0, sd: float = 1) -> Distribution

Normal (Gaussian) distribution.

Parameters:

NameTypeDescriptionDefault
meanfloatMean of the distribution. Default 0.0
sdfloatStandard deviation (must be positive). Default 1.1

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = normal()  # Standard normal: mean=0, sd=1
d = normal(mean=100, sd=15)
d.cdf(115)  # P(X <= 115)
# 0.8413...

poisson

poisson(mu: float) -> Distribution

Poisson distribution.

Parameters:

NameTypeDescriptionDefault
mufloatExpected number of events (rate, must be positive).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = poisson(mu=5)
d.pmf(3)  # P(X = 3)
# 0.140...

t

t(df: float, loc: float = 0.0, scale: float = 1.0) -> Distribution

Student’s t distribution (location-scale parameterization).

Student’s t-distribution using loc/scale parameter names (scipy convention), as an alternative to t_dist() which uses mean/sd naming.

Parameters:

NameTypeDescriptionDefault
dffloatDegrees of freedom (must be positive).required
locfloatLocation parameter. Default 0.0.0.0
scalefloatScale parameter (must be positive). Default 1.0.1.0

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = t(df=10)
d.ppf(0.975)  # Critical value for 95% CI

t_dist

t_dist(df: float, mean: float = 0, sd: float = 1) -> Distribution

Student’s t distribution.

Parameters:

NameTypeDescriptionDefault
dffloatDegrees of freedom (must be positive).required
meanfloatLocation parameter. Default 0.0
sdfloatScale parameter (must be positive). Default 1.1

Returns:

TypeDescription
DistributionDistribution object.

Examples:

t = t_dist(df=29)
t.ppf(0.975)  # Critical value for 95% CI
# 2.045...

uniform

uniform(low: float = 0, high: float = 1) -> Distribution

Uniform distribution.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound. Default 0.0
highfloatUpper bound (must be > low). Default 1.1

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = uniform(low=0, high=10)
d.mean
# 5.0

Modules

algebra

Distribution algebra mixin.

Provides algebraic operations (affine transforms, convolution, operator overloads) for Distribution objects.

DistributionAlgebraMixin: Mixin class adding algebra to Distribution. DistributionAlgebraMixin: Mixin class adding algebra to Distribution.

Classes:

NameDescription
DistributionAlgebraMixinMixin providing algebraic operations for distributions.

Classes

DistributionAlgebraMixin

Mixin providing algebraic operations for distributions.

_name: str display name. _name: str display name. _params: dict[str, float] parameter dictionary. affine_transform(scale, shift) -> Distribution. add_distribution(other) -> Distribution.

Functions:

NameDescription
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
Functions
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.

base

Distribution base class.

Provides the Distribution class wrapping scipy.stats with algebraic composition, probability queries, hypothesis testing, and visualization.

Distribution: Base distribution wrapper with full algebra support. Distribution: Base distribution wrapper with full algebra support.

Classes:

NameDescription
DistributionWrapper for scipy.stats distributions with visualization.

Attributes

Classes

Distribution
Distribution(dist: rv_frozen, name: str, params: dict[str, float]) -> None

Bases: DistributionPlotMixin, DistributionAlgebraMixin

Wrapper for scipy.stats distributions with visualization.

Provides a unified interface for probability distributions with:

Parameters:

NameTypeDescriptionDefault
distrv_frozenFrozen scipy.stats distribution.required
namestrDisplay name for the distribution.required
paramsdict[str, float]User-facing parameter dictionary for display.required

Examples:

# Use factory functions instead of direct instantiation
from distributions import normal, t_dist
d = normal(mean=0, sd=1)
d.cdf(1.96)  # 0.975
d.ppf(0.975)  # 1.96

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCumulative distribution function.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfProbability density function (continuous distributions only).
plotPlot the distribution.
pmfProbability mass function (discrete distributions only).
ppfPercent point function (inverse CDF / quantile function).
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random variates.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function (1 - CDF).
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatDistribution mean (expected value).
medianfloatDistribution median.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatDistribution standard deviation.
varfloatDistribution variance.
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Distribution mean (expected value).

median
median: float

Distribution median.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Distribution standard deviation.

var
var: float

Distribution variance.

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

Cumulative distribution function.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate the CDF.required

Returns:

TypeDescription
ndarrayCDF values (P(X <= x)) at each point.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

Probability density function (continuous distributions only).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate the PDF.required

Returns:

TypeDescription
ndarrayPDF values at each point.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

Probability mass function (discrete distributions only).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate the PMF.required

Returns:

TypeDescription
ndarrayPMF values at each point.
ppf
ppf(q: ArrayLike) -> np.ndarray

Percent point function (inverse CDF / quantile function).

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayValues x such that P(X <= x) = q.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random variates.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples from the distribution.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function (1 - CDF).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (P(X > x)) at each point.
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798

core

Backward-compatibility re-exports for distribution classes.

This module re-exports all distribution classes from their new locations:

Import from this module or directly from the submodules.

Classes:

NameDescription
ConvolvedDistributionDistribution representing the sum of two independent random variables.
DistributionWrapper for scipy.stats distributions with visualization.
FoldedDistributionDistribution of
TransformedDistributionDistribution resulting from an affine transformation: Y = scale*X + shift.
TruncatedDistributionDistribution truncated to an interval [low, high].

Classes

ConvolvedDistribution
ConvolvedDistribution(dist1: Distribution, dist2: Distribution, n_samples: int = MC_SAMPLES) -> None

Bases: Distribution

Distribution representing the sum of two independent random variables.

Uses Monte Carlo simulation for CDF/PPF computations when no closed-form solution is available.

Parameters:

NameTypeDescriptionDefault
dist1DistributionFirst distribution (X).required
dist2DistributionSecond distribution (Y).required
n_samplesintNumber of samples for Monte Carlo estimation.MC_SAMPLES

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF estimated from empirical distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
get_samplesGet or generate cached samples.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF estimated via kernel density estimation.
plotPlot the distribution.
pmfPMF estimated from sample frequencies.
ppfPPF (quantile function) estimated from samples.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from convolved distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatMean of sum: E[X] + E[Y].
medianfloatMedian estimated from samples.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatStandard deviation of sum.
varfloatVariance of sum (independent): Var[X] + Var[Y].
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Mean of sum: E[X] + E[Y].

median
median: float

Median estimated from samples.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Standard deviation of sum.

var
var: float

Variance of sum (independent): Var[X] + Var[Y].

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF estimated from empirical distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayEmpirical CDF values.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
get_samples
get_samples() -> np.ndarray

Get or generate cached samples.

Returns:

TypeDescription
ndarraySorted array of Monte Carlo samples from X + Y.
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF estimated via kernel density estimation.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayKDE-estimated PDF values.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF estimated from sample frequencies.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayFrequency-estimated PMF values.
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF (quantile function) estimated from samples.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayEstimated quantile values.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from convolved distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples from X + Y.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (1 - CDF).
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798
Distribution
Distribution(dist: rv_frozen, name: str, params: dict[str, float]) -> None

Bases: DistributionPlotMixin, DistributionAlgebraMixin

Wrapper for scipy.stats distributions with visualization.

Provides a unified interface for probability distributions with:

Parameters:

NameTypeDescriptionDefault
distrv_frozenFrozen scipy.stats distribution.required
namestrDisplay name for the distribution.required
paramsdict[str, float]User-facing parameter dictionary for display.required

Examples:

# Use factory functions instead of direct instantiation
from distributions import normal, t_dist
d = normal(mean=0, sd=1)
d.cdf(1.96)  # 0.975
d.ppf(0.975)  # 1.96

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCumulative distribution function.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfProbability density function (continuous distributions only).
plotPlot the distribution.
pmfProbability mass function (discrete distributions only).
ppfPercent point function (inverse CDF / quantile function).
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random variates.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function (1 - CDF).
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatDistribution mean (expected value).
medianfloatDistribution median.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatDistribution standard deviation.
varfloatDistribution variance.
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Distribution mean (expected value).

median
median: float

Distribution median.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Distribution standard deviation.

var
var: float

Distribution variance.

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

Cumulative distribution function.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate the CDF.required

Returns:

TypeDescription
ndarrayCDF values (P(X <= x)) at each point.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

Probability density function (continuous distributions only).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate the PDF.required

Returns:

TypeDescription
ndarrayPDF values at each point.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

Probability mass function (discrete distributions only).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate the PMF.required

Returns:

TypeDescription
ndarrayPMF values at each point.
ppf
ppf(q: ArrayLike) -> np.ndarray

Percent point function (inverse CDF / quantile function).

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayValues x such that P(X <= x) = q.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random variates.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples from the distribution.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function (1 - CDF).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (P(X > x)) at each point.
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798
FoldedDistribution
FoldedDistribution(base: Distribution, n_samples: int = MC_SAMPLES) -> None

Bases: Distribution

Distribution of |X| - the absolute value of X.

Uses simulation for CDF/PPF computations.

Parameters:

NameTypeDescriptionDefault
baseDistributionThe original distribution.required
n_samplesintNumber of samples for Monte Carlo estimation.MC_SAMPLES

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF of folded distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
get_samplesGet or generate cached samples.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF of folded distribution: f_
plotPlot the distribution.
pmfPMF of folded distribution.
ppfPPF of folded distribution.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from folded distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function of folded distribution.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatMean of folded distribution.
medianfloatMedian of folded distribution.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatStandard deviation of folded distribution.
varfloatVariance of folded distribution.
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Mean of folded distribution.

median
median: float

Median of folded distribution.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Standard deviation of folded distribution.

var
var: float

Variance of folded distribution.

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF of folded distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayEmpirical CDF values.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
get_samples
get_samples() -> np.ndarray

Get or generate cached samples.

Returns:

TypeDescription
ndarraySorted array of Monte Carlo samples from
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF of folded distribution: f_|X|(y) = f_X(y) + f_X(-y) for y >= 0.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPDF values (zero for negative x).
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF of folded distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPMF values (zero for negative x).
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF of folded distribution.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayEstimated quantile values.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from folded distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function of folded distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (1 - CDF).
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798
TransformedDistribution
TransformedDistribution(base: Distribution, scale: float, shift: float) -> None

Bases: Distribution

Distribution resulting from an affine transformation: Y = scale*X + shift.

Used when closed-form parameters aren’t available. Delegates to the base distribution with appropriate transformations applied.

Parameters:

NameTypeDescriptionDefault
baseDistributionThe original distribution.required
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF of transformed distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF of transformed distribution.
plotPlot the distribution.
pmfPMF of transformed distribution.
ppfPPF of transformed distribution.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from transformed distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function of transformed distribution.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatTransformed mean: scale * E[X] + shift.
medianfloatTransformed median: scale * median[X] + shift.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatTransformed standard deviation:
varfloatTransformed variance: scale^2 * Var[X].
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Transformed mean: scale * E[X] + shift.

median
median: float

Transformed median: scale * median[X] + shift.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Transformed standard deviation: |scale| * SD[X].

var
var: float

Transformed variance: scale^2 * Var[X].

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayCDF values at each point.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPDF values at each point.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPMF values at each point.
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayValues x such that P(Y <= x) = q.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from transformed distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values at each point.
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798
TruncatedDistribution
TruncatedDistribution(base: Distribution, low: float = float('-inf'), high: float = float('inf')) -> None

Bases: Distribution

Distribution truncated to an interval [low, high].

The PDF is normalized to integrate to 1 over the truncation region.

Note: Truncation is exact for Normal bases. For other distributions, the truncated normal approximation is used, which may not match the true truncated distribution.

Parameters:

NameTypeDescriptionDefault
baseDistributionThe original distribution.required
lowfloatLower bound (inclusive).float(‘-inf’)
highfloatUpper bound (inclusive).float(‘inf’)

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF of truncated distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF of truncated distribution.
plotPlot the distribution.
pmfPMF of truncated distribution.
ppfPPF of truncated distribution.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from truncated distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function of truncated distribution.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatMean of truncated distribution.
medianfloatMedian of truncated distribution.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatStandard deviation of truncated distribution.
varfloatVariance of truncated distribution.
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Mean of truncated distribution.

median
median: float

Median of truncated distribution.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Standard deviation of truncated distribution.

var
var: float

Variance of truncated distribution.

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayCDF values (0 below low, 1 above high).
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPDF values (zero outside truncation bounds).
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPMF values (zero outside truncation bounds).
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayQuantile values within truncation bounds.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from truncated distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples within truncation bounds.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (1 - CDF).
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798

derived

Derived distribution types.

Provides distribution classes for transformed, convolved, truncated, and folded distributions built from a base Distribution.

TransformedDistribution: Affine-transformed distribution (Y = scaleX + shift). TransformedDistribution: Affine-transformed distribution (Y = scaleX + shift). ConvolvedDistribution: Sum of independent random variables (X + Y). TruncatedDistribution: Distribution truncated to an interval [low, high]. FoldedDistribution: Absolute value distribution |X|.

Classes:

NameDescription
ConvolvedDistributionDistribution representing the sum of two independent random variables.
FoldedDistributionDistribution of
TransformedDistributionDistribution resulting from an affine transformation: Y = scale*X + shift.
TruncatedDistributionDistribution truncated to an interval [low, high].

Attributes

Classes

ConvolvedDistribution
ConvolvedDistribution(dist1: Distribution, dist2: Distribution, n_samples: int = MC_SAMPLES) -> None

Bases: Distribution

Distribution representing the sum of two independent random variables.

Uses Monte Carlo simulation for CDF/PPF computations when no closed-form solution is available.

Parameters:

NameTypeDescriptionDefault
dist1DistributionFirst distribution (X).required
dist2DistributionSecond distribution (Y).required
n_samplesintNumber of samples for Monte Carlo estimation.MC_SAMPLES

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF estimated from empirical distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
get_samplesGet or generate cached samples.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF estimated via kernel density estimation.
plotPlot the distribution.
pmfPMF estimated from sample frequencies.
ppfPPF (quantile function) estimated from samples.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from convolved distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatMean of sum: E[X] + E[Y].
medianfloatMedian estimated from samples.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatStandard deviation of sum.
varfloatVariance of sum (independent): Var[X] + Var[Y].
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Mean of sum: E[X] + E[Y].

median
median: float

Median estimated from samples.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Standard deviation of sum.

var
var: float

Variance of sum (independent): Var[X] + Var[Y].

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF estimated from empirical distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayEmpirical CDF values.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
get_samples
get_samples() -> np.ndarray

Get or generate cached samples.

Returns:

TypeDescription
ndarraySorted array of Monte Carlo samples from X + Y.
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF estimated via kernel density estimation.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayKDE-estimated PDF values.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF estimated from sample frequencies.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayFrequency-estimated PMF values.
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF (quantile function) estimated from samples.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayEstimated quantile values.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from convolved distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples from X + Y.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (1 - CDF).
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798
FoldedDistribution
FoldedDistribution(base: Distribution, n_samples: int = MC_SAMPLES) -> None

Bases: Distribution

Distribution of |X| - the absolute value of X.

Uses simulation for CDF/PPF computations.

Parameters:

NameTypeDescriptionDefault
baseDistributionThe original distribution.required
n_samplesintNumber of samples for Monte Carlo estimation.MC_SAMPLES

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF of folded distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
get_samplesGet or generate cached samples.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF of folded distribution: f_
plotPlot the distribution.
pmfPMF of folded distribution.
ppfPPF of folded distribution.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from folded distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function of folded distribution.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatMean of folded distribution.
medianfloatMedian of folded distribution.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatStandard deviation of folded distribution.
varfloatVariance of folded distribution.
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Mean of folded distribution.

median
median: float

Median of folded distribution.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Standard deviation of folded distribution.

var
var: float

Variance of folded distribution.

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF of folded distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayEmpirical CDF values.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
get_samples
get_samples() -> np.ndarray

Get or generate cached samples.

Returns:

TypeDescription
ndarraySorted array of Monte Carlo samples from
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF of folded distribution: f_|X|(y) = f_X(y) + f_X(-y) for y >= 0.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPDF values (zero for negative x).
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF of folded distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPMF values (zero for negative x).
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF of folded distribution.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayEstimated quantile values.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from folded distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function of folded distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (1 - CDF).
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798
TransformedDistribution
TransformedDistribution(base: Distribution, scale: float, shift: float) -> None

Bases: Distribution

Distribution resulting from an affine transformation: Y = scale*X + shift.

Used when closed-form parameters aren’t available. Delegates to the base distribution with appropriate transformations applied.

Parameters:

NameTypeDescriptionDefault
baseDistributionThe original distribution.required
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF of transformed distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF of transformed distribution.
plotPlot the distribution.
pmfPMF of transformed distribution.
ppfPPF of transformed distribution.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from transformed distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function of transformed distribution.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatTransformed mean: scale * E[X] + shift.
medianfloatTransformed median: scale * median[X] + shift.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatTransformed standard deviation:
varfloatTransformed variance: scale^2 * Var[X].
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Transformed mean: scale * E[X] + shift.

median
median: float

Transformed median: scale * median[X] + shift.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Transformed standard deviation: |scale| * SD[X].

var
var: float

Transformed variance: scale^2 * Var[X].

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayCDF values at each point.
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPDF values at each point.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPMF values at each point.
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF of transformed distribution.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayValues x such that P(Y <= x) = q.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from transformed distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function of transformed distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values at each point.
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798
TruncatedDistribution
TruncatedDistribution(base: Distribution, low: float = float('-inf'), high: float = float('inf')) -> None

Bases: Distribution

Distribution truncated to an interval [low, high].

The PDF is normalized to integrate to 1 over the truncation region.

Note: Truncation is exact for Normal bases. For other distributions, the truncated normal approximation is used, which may not match the true truncated distribution.

Parameters:

NameTypeDescriptionDefault
baseDistributionThe original distribution.required
lowfloatLower bound (inclusive).float(‘-inf’)
highfloatUpper bound (inclusive).float(‘inf’)

Functions:

NameDescription
absAbsolute value distribution:
add_distributionAdd two independent random variables: X + Y.
affine_transformApply affine transformation: scale*X + shift.
betweenP(low <= X <= high) - probability within an interval.
cdfCDF of truncated distribution.
compute_x_rangeCompute sensible x-range for plotting.
criticalCompute critical value(s) for hypothesis testing.
intervalCentral confidence interval containing given probability mass.
likCompute likelihood of data under this distribution.
loglikCompute log-likelihood of data under this distribution.
make_probHelper to create Probability with distribution context.
outsideP(X < low or X > high) - probability outside an interval.
pQuantile function alias for ppf.
p_valueCompute p-value for observed statistic.
parse_shade_regionParse shade_region argument to actual bounds.
pdfPDF of truncated distribution.
plotPlot the distribution.
pmfPMF of truncated distribution.
ppfPPF of truncated distribution.
probUnified probability function (pdf or pmf based on type).
rejectDetermine if null hypothesis should be rejected.
rvsGenerate random samples from truncated distribution.
sampleGenerate n random samples using a numpy Generator.
scaleScale distribution by multiplying by factor.
sfSurvival function of truncated distribution.
shiftShift distribution by adding delta to all values.
standardizeStandardize to mean=0, sd=1.
truncateTruncate distribution to an interval.

Attributes:

NameTypeDescription
iqrfloatInterquartile range (Q3 - Q1).
is_discreteboolWhether this is a discrete distribution.
meanfloatMean of truncated distribution.
medianfloatMedian of truncated distribution.
namestrDistribution name.
paramsdict[str, float]Distribution parameters.
q1floatFirst quartile (25th percentile).
q3floatThird quartile (75th percentile).
stdfloatStandard deviation of truncated distribution.
varfloatVariance of truncated distribution.
Attributes
iqr
iqr: float

Interquartile range (Q3 - Q1).

is_discrete
is_discrete: bool

Whether this is a discrete distribution.

mean
mean: float

Mean of truncated distribution.

median
median: float

Median of truncated distribution.

name
name: str

Distribution name.

params
params: dict[str, float]

Distribution parameters.

q1
q1: float

First quartile (25th percentile).

q3
q3: float

Third quartile (75th percentile).

std
std: float

Standard deviation of truncated distribution.

var
var: float

Variance of truncated distribution.

Functions
abs
abs() -> FoldedDistribution

Absolute value distribution: |X|.

Returns:

TypeDescription
FoldedDistributionFoldedDistribution representing

Examples:

d = normal().abs()  # Half-normal (folded at 0)
d.mean  # Approximately 0.798
add_distribution
add_distribution(other: Distribution) -> Distribution

Add two independent random variables: X + Y.

Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.

Parameters:

NameTypeDescriptionDefault
otherDistributionAnother independent distribution to add.required

Returns:

TypeDescription
DistributionNew distribution representing X + Y.
affine_transform
affine_transform(scale: float, shift: float) -> Distribution

Apply affine transformation: scale*X + shift.

Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.

Parameters:

NameTypeDescriptionDefault
scalefloatMultiplicative factor.required
shiftfloatAdditive constant.required

Returns:

TypeDescription
DistributionNew distribution representing scale*X + shift.
between
between(low: float, high: float) -> Probability

P(low <= X <= high) - probability within an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827
cdf
cdf(x: ArrayLike) -> np.ndarray

CDF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayCDF values (0 below low, 1 above high).
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
critical
critical(alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> float | tuple[float, float]

Compute critical value(s) for hypothesis testing.

Parameters:

NameTypeDescriptionDefault
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value‘two’

Returns:

TypeDescription
float | tuple[float, float]Critical value(s) for the specified test.

Examples:

t = t_dist(df=29)
t.critical(alpha=0.05, tail="two")
# (-2.045, 2.045)
interval
interval(confidence: float = 0.95) -> tuple[float, float]

Central confidence interval containing given probability mass.

Parameters:

NameTypeDescriptionDefault
confidencefloatProbability mass in the interval (default 0.95).0.95

Returns:

TypeDescription
tuple[float, float]Tuple of (lower, upper) bounds.
lik
lik(data: ArrayLike) -> float

Compute likelihood of data under this distribution.

Warning: For numerical stability, prefer loglik() for inference.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatProduct of probabilities: prod(f(x_i)).

Examples:

d = normal(0, 1)
d.lik([0])
# 0.3989...
loglik
loglik(data: ArrayLike) -> float

Compute log-likelihood of data under this distribution.

Parameters:

NameTypeDescriptionDefault
dataArrayLikeObserved data points.required

Returns:

TypeDescription
floatSum of log-probabilities: sum(log(f(x_i))).

Examples:

d = normal(0, 1)
d.loglik([0, 0.5, -0.5])
# -3.112...
make_prob
make_prob(value: float, expr: str) -> Probability

Helper to create Probability with distribution context.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value.required
exprstrExpression string for display.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.
outside
outside(low: float, high: float) -> Probability

P(X < low or X > high) - probability outside an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound of interval.required
highfloatUpper bound of interval.required

Returns:

TypeDescription
ProbabilityProbability object with rich display.

Examples:

d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05
p
p(q: float) -> float

Quantile function alias for ppf.

Parameters:

NameTypeDescriptionDefault
qfloatProbability (between 0 and 1).required

Returns:

TypeDescription
floatValue x such that P(X <= x) = q.

Examples:

d = normal()
d.p(0.975)  # Same as d.ppf(0.975)
# 1.96
p_value
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> Probability

Compute p-value for observed statistic.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
tailLiteral[‘two’, ‘left’, ‘right’]Type of test: - “two”: Two-tailed (more extreme in either direction) - “left”: Left-tailed (smaller values) - “right”: Right-tailed (larger values)‘two’

Returns:

TypeDescription
ProbabilityProbability object representing the p-value.

Examples:

t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
pdf
pdf(x: ArrayLike) -> np.ndarray

PDF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPDF values (zero outside truncation bounds).
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.
pmf
pmf(x: ArrayLike) -> np.ndarray

PMF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayPMF values (zero outside truncation bounds).
ppf
ppf(q: ArrayLike) -> np.ndarray

PPF of truncated distribution.

Parameters:

NameTypeDescriptionDefault
qArrayLikeQuantiles (probabilities between 0 and 1).required

Returns:

TypeDescription
ndarrayQuantile values within truncation bounds.
prob
prob(x: ArrayLike) -> np.ndarray

Unified probability function (pdf or pmf based on type).

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarrayProbability values (density for continuous, mass for discrete).
reject
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> bool

Determine if null hypothesis should be rejected.

Parameters:

NameTypeDescriptionDefault
xfloatObserved test statistic.required
alphafloatSignificance level.0.05
tailLiteral[‘two’, ‘left’, ‘right’]Type of test.‘two’

Returns:

TypeDescription
boolTrue if null hypothesis should be rejected.

Examples:

t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# True
rvs
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarray

Generate random samples from truncated distribution.

Parameters:

NameTypeDescriptionDefault
sizeint | tuple[int, ...]Number of samples or shape of output array.1
seedint | Generator | NoneRandom seed or Generator for reproducibility.None

Returns:

TypeDescription
ndarrayArray of random samples within truncation bounds.
sample
sample(n: int, rng: np.random.Generator) -> np.ndarray

Generate n random samples using a numpy Generator.

Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().

Parameters:

NameTypeDescriptionDefault
nintNumber of samples to generate.required
rngGeneratorNumPy random number generator for reproducibility.required

Returns:

TypeDescription
ndarrayArray of n samples from this distribution.
scale
scale(factor: float) -> Distribution

Scale distribution by multiplying by factor.

Parameters:

NameTypeDescriptionDefault
factorfloatMultiplicative scale factor.required

Returns:

TypeDescription
DistributionNew scaled distribution.

Examples:

d = normal(0, 1).scale(2)
d.std
# 2.0
sf
sf(x: ArrayLike) -> np.ndarray

Survival function of truncated distribution.

Parameters:

NameTypeDescriptionDefault
xArrayLikePoints at which to evaluate.required

Returns:

TypeDescription
ndarraySurvival function values (1 - CDF).
shift
shift(delta: float) -> Distribution

Shift distribution by adding delta to all values.

Parameters:

NameTypeDescriptionDefault
deltafloatAmount to add to the mean.required

Returns:

TypeDescription
DistributionNew shifted distribution.

Examples:

d = normal(0, 1).shift(5)
d.mean
# 5.0
standardize
standardize() -> Distribution

Standardize to mean=0, sd=1.

Returns:

TypeDescription
DistributionNew distribution with zero mean and unit variance.

Examples:

d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0
truncate
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistribution

Truncate distribution to an interval.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound (inclusive). Defaults to -inf.float(‘-inf’)
highfloatUpper bound (inclusive). Defaults to +inf.float(‘inf’)

Returns:

TypeDescription
TruncatedDistributionTruncatedDistribution over the specified interval.

Examples:

d = normal().truncate(0, np.inf)  # Half-normal
d.mean  # Approximately 0.798

factories

Distribution factory functions.

Provides user-friendly constructors for common probability distributions with intuitive parameterization (e.g., mean/sd instead of loc/scale).

normal, t_dist, chi2, f_dist, beta, binomial, poisson, normal, t_dist, chi2, f_dist, beta, binomial, poisson, exponential, gamma, uniform

Functions:

NameDescription
betaBeta distribution.
binomialBinomial distribution.
chi2Chi-squared distribution.
exponentialExponential distribution (rate parameterization).
f_distF distribution.
gammaGamma distribution.
normalNormal (Gaussian) distribution.
poissonPoisson distribution.
tStudent’s t distribution (location-scale parameterization).
t_distStudent’s t distribution.
uniformUniform distribution.

Classes

Functions

beta
beta(a: float, b: float) -> Distribution

Beta distribution.

Parameters:

NameTypeDescriptionDefault
afloatShape parameter alpha (must be positive).required
bfloatShape parameter beta (must be positive).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = beta(a=2, b=5)
d.mean
# 0.285...
binomial
binomial(n: int, p: float) -> Distribution

Binomial distribution.

Parameters:

NameTypeDescriptionDefault
nintNumber of trials (must be non-negative integer).required
pfloatProbability of success (must be in [0, 1]).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

b = binomial(n=20, p=0.3)
b.mean
# 6.0
b.pmf(6)  # P(X = 6)
# 0.191...
chi2
chi2(df: float) -> Distribution

Chi-squared distribution.

Parameters:

NameTypeDescriptionDefault
dffloatDegrees of freedom (must be positive).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

c = chi2(df=5)
c.ppf(0.95)  # Critical value
# 11.07...
exponential
exponential(rate: float = 1.0) -> Distribution

Exponential distribution (rate parameterization).

Parameters:

NameTypeDescriptionDefault
ratefloatRate parameter lambda (must be positive). Mean = 1/rate. Default 1.0.1.0

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = exponential(rate=0.5)
d.mean
# 2.0
f_dist
f_dist(df1: float, df2: float) -> Distribution

F distribution.

Parameters:

NameTypeDescriptionDefault
df1floatNumerator degrees of freedom (must be positive).required
df2floatDenominator degrees of freedom (must be positive).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

f = f_dist(df1=5, df2=20)
f.ppf(0.95)  # Critical value
# 2.71...
gamma
gamma(shape: float, rate: float | None = None, scale: float | None = None) -> Distribution

Gamma distribution.

Accepts either rate or scale parameterization (not both).

Parameters:

NameTypeDescriptionDefault
shapefloatShape parameter (must be positive).required
ratefloat | NoneRate parameter (1/scale). If provided, scale must be None.None
scalefloat | NoneScale parameter. If provided, rate must be None. Default is scale=1 if neither specified.None

Returns:

TypeDescription
DistributionDistribution object.

Examples:

g = gamma(shape=2, rate=0.5)
g.mean
# 4.0
g = gamma(shape=2, scale=2)  # Equivalent
g.mean
# 4.0
normal
normal(mean: float = 0, sd: float = 1) -> Distribution

Normal (Gaussian) distribution.

Parameters:

NameTypeDescriptionDefault
meanfloatMean of the distribution. Default 0.0
sdfloatStandard deviation (must be positive). Default 1.1

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = normal()  # Standard normal: mean=0, sd=1
d = normal(mean=100, sd=15)
d.cdf(115)  # P(X <= 115)
# 0.8413...
poisson
poisson(mu: float) -> Distribution

Poisson distribution.

Parameters:

NameTypeDescriptionDefault
mufloatExpected number of events (rate, must be positive).required

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = poisson(mu=5)
d.pmf(3)  # P(X = 3)
# 0.140...
t
t(df: float, loc: float = 0.0, scale: float = 1.0) -> Distribution

Student’s t distribution (location-scale parameterization).

Student’s t-distribution using loc/scale parameter names (scipy convention), as an alternative to t_dist() which uses mean/sd naming.

Parameters:

NameTypeDescriptionDefault
dffloatDegrees of freedom (must be positive).required
locfloatLocation parameter. Default 0.0.0.0
scalefloatScale parameter (must be positive). Default 1.0.1.0

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = t(df=10)
d.ppf(0.975)  # Critical value for 95% CI
t_dist
t_dist(df: float, mean: float = 0, sd: float = 1) -> Distribution

Student’s t distribution.

Parameters:

NameTypeDescriptionDefault
dffloatDegrees of freedom (must be positive).required
meanfloatLocation parameter. Default 0.0
sdfloatScale parameter (must be positive). Default 1.1

Returns:

TypeDescription
DistributionDistribution object.

Examples:

t = t_dist(df=29)
t.ppf(0.975)  # Critical value for 95% CI
# 2.045...
uniform
uniform(low: float = 0, high: float = 1) -> Distribution

Uniform distribution.

Parameters:

NameTypeDescriptionDefault
lowfloatLower bound. Default 0.0
highfloatUpper bound (must be > low). Default 1.1

Returns:

TypeDescription
DistributionDistribution object.

Examples:

d = uniform(low=0, high=10)
d.mean
# 5.0

plotting

Distribution plotting mixin.

Provides visualization methods for Distribution objects including PDF/PMF plotting, shading, and notebook rendering.

DistributionPlotMixin: Mixin class adding plot methods to Distribution. DistributionPlotMixin: Mixin class adding plot methods to Distribution.

Classes:

NameDescription
DistributionPlotMixinMixin providing visualization methods for distributions.

Attributes

Classes

DistributionPlotMixin

Mixin providing visualization methods for distributions.

_dist: Frozen scipy.stats distribution. _dist: Frozen scipy.stats distribution. _name: str display name. _params: dict[str, float] parameter dictionary. _is_discrete: bool whether distribution is discrete. mean: float property. median: float property. interval(confidence) -> tuple[float, float]. ppf(q) -> np.ndarray.

Functions:

NameDescription
compute_x_rangeCompute sensible x-range for plotting.
parse_shade_regionParse shade_region argument to actual bounds.
plotPlot the distribution.
Functions
compute_x_range
compute_x_range() -> tuple[float, float]

Compute sensible x-range for plotting.

Returns:

TypeDescription
tuple[float, float]Tuple of (low, high) x values covering the distribution.
parse_shade_region
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | None

Parse shade_region argument to actual bounds.

Parameters:

NameTypeDescriptionDefault
shade_regiontuple[float, float] | str | NoneRegion specification (tuple, string shortcut, or None).required

Returns:

TypeDescription
tuple[float, float] | NoneTuple of (low, high) bounds, or None if no shading.
plot
plot(*, ax: Axes | None = None, shade_region: tuple[float, float] | str | None = None, shade_direction: Literal['between', 'outside', 'left', 'right'] = 'between', shade_alpha: float = 0.3, shade_color: str | None = None, show_mean: bool = False, show_median: bool = False, x_range: tuple[float, float] | None = None, figsize: tuple[float, float] = (6, 4), color: str | None = None, title: str | None = None) -> Figure

Plot the distribution.

Parameters:

NameTypeDescriptionDefault
axAxes | NoneMatplotlib axes. If None, creates new figure.None
shade_regiontuple[float, float] | str | NoneRegion to shade. Can be: - tuple[float, float]: Shade between these x values - “ci95”, “ci99”, “ci90”: Shade confidence interval - “critical_left”: Shade left tail (alpha=0.05) - “critical_right”: Shade right tail (alpha=0.05) - “critical_two”: Shade both tails (alpha=0.025 each)None
shade_directionLiteral[‘between’, ‘outside’, ‘left’, ‘right’]How to shade relative to bounds: - “between”: Shade area between bounds (default for CI) - “outside”: Shade area outside bounds (rejection regions) - “left”: Shade left of lower bound - “right”: Shade right of upper bound‘between’
shade_alphafloatTransparency for shaded region.0.3
shade_colorstr | NoneColor for shaded region (defaults to line color).None
show_meanboolShow vertical line at mean.False
show_medianboolShow vertical line at median.False
x_rangetuple[float, float] | NoneCustom x-axis range (auto-computed if None).None
figsizetuple[float, float]Figure size in inches.(6, 4)
colorstr | NoneLine/bar color (uses palette default if None).None
titlestr | NonePlot title (auto-generated if None).None

Returns:

TypeDescription
FigureMatplotlib Figure object.

Functions

probability

Probability result class and visualization helpers.

Classes:

NameDescription
ProbabilityRich probability result from distribution queries.

Functions:

NameDescription
figure_to_htmlConvert matplotlib figure to base64-encoded HTML img tag.

Attributes:

NameTypeDescription
MC_SAMPLES
rv_frozen

Attributes

MC_SAMPLES
MC_SAMPLES = 100000
rv_frozen
rv_frozen = rv_continuous_frozen | rv_discrete_frozen

Classes

Probability
Probability(value: float, expr: str, dist_name: str) -> None

Rich probability result from distribution queries.

Returned by comparison operators on distributions (e.g., normal() > 1.96). Behaves like a float for numeric operations while providing descriptive display.

Parameters:

NameTypeDescriptionDefault
valuefloatThe probability value (between 0 and 1).required
exprstrExpression describing the event (e.g., “X > 1.96”).required
dist_namestrDisplay name of the distribution (e.g., “Normal(0, 1)”).required

Examples:

d = normal()
p = d > 1.96
p
# P(X > 1.96) = 0.025
float(p)
# 0.025
p < 0.05  # threshold check
# True

Attributes:

NameTypeDescription
dist_namestr
exprstr
valuefloat
Attributes
dist_name
dist_name: str
expr
expr: str
value
value: float

Functions

figure_to_html
figure_to_html(fig: Figure, dpi: int = 100) -> str

Convert matplotlib figure to base64-encoded HTML img tag.

Parameters:

NameTypeDescriptionDefault
figFigureMatplotlib figure to convert.required
dpiintResolution for the PNG image.100

Returns:

TypeDescription
strHTML string with embedded base64 PNG.