Probability distributions with expressive algebra and automatic visualization.
This package wraps scipy.stats distributions to provide:
User-friendly parameterization (mean/sd instead of loc/scale)
Automatic plotting in Jupyter notebooks via repr_html()
Algebraic composition: affine transforms, convolution, truncation
Probability queries: comparison operators returning rich Probability objects
Hypothesis testing helpers: p-values, critical values, rejection decisions
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.025Probability 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.6827Fluent API¶
Chain transformations for readable code::
normal(100, 15).standardize() # → Normal(0, 1)
normal().truncate(0, inf) # Half-normalHypothesis 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) # → TrueAvailable Distributions¶
Continuous: normal, t_dist, chi2, f_dist, beta, exponential, gamma, uniform Discrete: binomial, poisson
See Also¶
api/distributions : Tutorial with comprehensive examples
Classes:
| Name | Description |
|---|---|
ConvolvedDistribution | Distribution representing the sum of two independent random variables. |
Distribution | Wrapper for scipy.stats distributions with visualization. |
FoldedDistribution | Distribution of |
Probability | Rich probability result from distribution queries. |
TransformedDistribution | Distribution resulting from an affine transformation: Y = scale*X + shift. |
TruncatedDistribution | Distribution truncated to an interval [low, high]. |
Functions:
| Name | Description |
|---|---|
beta | Beta distribution. |
binomial | Binomial distribution. |
chi2 | Chi-squared distribution. |
exponential | Exponential distribution (rate parameterization). |
f_dist | F distribution. |
figure_to_html | Convert matplotlib figure to base64-encoded HTML img tag. |
gamma | Gamma distribution. |
normal | Normal (Gaussian) distribution. |
poisson | Poisson distribution. |
t | Student’s t distribution (location-scale parameterization). |
t_dist | Student’s t distribution. |
uniform | Uniform distribution. |
Modules:
| Name | Description |
|---|---|
algebra | Distribution algebra mixin. |
base | Distribution base class. |
core | Backward-compatibility re-exports for distribution classes. |
derived | Derived distribution types. |
factories | Distribution factory functions. |
plotting | Distribution plotting mixin. |
probability | Probability result class and visualization helpers. |
Classes¶
ConvolvedDistribution¶
ConvolvedDistribution(dist1: Distribution, dist2: Distribution, n_samples: int = MC_SAMPLES) -> NoneBases: 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:
| Name | Type | Description | Default |
|---|---|---|---|
dist1 | Distribution | First distribution (X). | required |
dist2 | Distribution | Second distribution (Y). | required |
n_samples | int | Number of samples for Monte Carlo estimation. | MC_SAMPLES |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF estimated from empirical distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
get_samples | Get or generate cached samples. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF estimated via kernel density estimation. |
plot | Plot the distribution. |
pmf | PMF estimated from sample frequencies. |
ppf | PPF (quantile function) estimated from samples. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from convolved distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Mean of sum: E[X] + E[Y]. |
median | float | Median estimated from samples. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Standard deviation of sum. |
var | float | Variance of sum (independent): Var[X] + Var[Y]. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatMean of sum: E[X] + E[Y].
median¶
median: floatMedian estimated from samples.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatStandard deviation of sum.
var¶
var: floatVariance of sum (independent): Var[X] + Var[Y].
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF estimated from empirical distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Empirical CDF values. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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.ndarrayGet or generate cached samples.
Returns:
| Type | Description |
|---|---|
ndarray | Sorted 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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF estimated via kernel density estimation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | KDE-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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF estimated from sample frequencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Frequency-estimated PMF values. |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF (quantile function) estimated from samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Estimated quantile values. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from convolved distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples from X + Y. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (1 - CDF). |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798Distribution¶
Distribution(dist: rv_frozen, name: str, params: dict[str, float]) -> NoneBases: DistributionPlotMixin, DistributionAlgebraMixin
Wrapper for scipy.stats distributions with visualization.
Provides a unified interface for probability distributions with:
Probability functions (pdf/pmf, cdf, ppf)
Random sampling (rvs)
Moments (mean, var, std)
Visualization with shading support
Automatic notebook rendering
Algebraic composition (affine transforms, convolution, truncation)
Probability queries via comparison operators
Hypothesis testing helpers
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist | rv_frozen | Frozen scipy.stats distribution. | required |
name | str | Display name for the distribution. | required |
params | dict[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.96Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | Cumulative distribution function. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | Probability density function (continuous distributions only). |
plot | Plot the distribution. |
pmf | Probability mass function (discrete distributions only). |
ppf | Percent point function (inverse CDF / quantile function). |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random variates. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function (1 - CDF). |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Distribution mean (expected value). |
median | float | Distribution median. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Distribution standard deviation. |
var | float | Distribution variance. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatDistribution mean (expected value).
median¶
median: floatDistribution median.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatDistribution standard deviation.
var¶
var: floatDistribution variance.
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCumulative distribution function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate the CDF. | required |
Returns:
| Type | Description |
|---|---|
ndarray | CDF values (P(X <= x)) at each point. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayProbability density function (continuous distributions only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate the PDF. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayProbability mass function (discrete distributions only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate the PMF. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values at each point. |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPercent point function (inverse CDF / quantile function).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Values x such that P(X <= x) = q. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random variates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples from the distribution. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function (1 - CDF).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (P(X > x)) at each point. |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798FoldedDistribution¶
FoldedDistribution(base: Distribution, n_samples: int = MC_SAMPLES) -> NoneBases: Distribution
Distribution of |X| - the absolute value of X.
Uses simulation for CDF/PPF computations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base | Distribution | The original distribution. | required |
n_samples | int | Number of samples for Monte Carlo estimation. | MC_SAMPLES |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF of folded distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
get_samples | Get or generate cached samples. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF of folded distribution: f_ |
plot | Plot the distribution. |
pmf | PMF of folded distribution. |
ppf | PPF of folded distribution. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from folded distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function of folded distribution. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Mean of folded distribution. |
median | float | Median of folded distribution. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Standard deviation of folded distribution. |
var | float | Variance of folded distribution. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatMean of folded distribution.
median¶
median: floatMedian of folded distribution.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatStandard deviation of folded distribution.
var¶
var: floatVariance of folded distribution.
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Empirical CDF values. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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.ndarrayGet or generate cached samples.
Returns:
| Type | Description |
|---|---|
ndarray | Sorted array of Monte Carlo samples from |
interval¶
interval(confidence: float = 0.95) -> tuple[float, float]Central confidence interval containing given probability mass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF of folded distribution: f_|X|(y) = f_X(y) + f_X(-y) for y >= 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values (zero for negative x). |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Estimated quantile values. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (1 - CDF). |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798Probability¶
Probability(value: float, expr: str, dist_name: str) -> NoneRich 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:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value (between 0 and 1). | required |
expr | str | Expression describing the event (e.g., “X > 1.96”). | required |
dist_name | str | Display 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
# TrueAttributes:
| Name | Type | Description |
|---|---|---|
dist_name | str | |
expr | str | |
value | float |
Attributes¶
dist_name¶
dist_name: strexpr¶
expr: strvalue¶
value: floatTransformedDistribution¶
TransformedDistribution(base: Distribution, scale: float, shift: float) -> NoneBases: 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:
| Name | Type | Description | Default |
|---|---|---|---|
base | Distribution | The original distribution. | required |
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF of transformed distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF of transformed distribution. |
plot | Plot the distribution. |
pmf | PMF of transformed distribution. |
ppf | PPF of transformed distribution. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from transformed distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function of transformed distribution. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Transformed mean: scale * E[X] + shift. |
median | float | Transformed median: scale * median[X] + shift. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Transformed standard deviation: |
var | float | Transformed variance: scale^2 * Var[X]. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatTransformed mean: scale * E[X] + shift.
median¶
median: floatTransformed median: scale * median[X] + shift.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatTransformed standard deviation: |scale| * SD[X].
var¶
var: floatTransformed variance: scale^2 * Var[X].
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | CDF values at each point. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values at each point. |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Values x such that P(Y <= x) = q. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values at each point. |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798TruncatedDistribution¶
TruncatedDistribution(base: Distribution, low: float = float('-inf'), high: float = float('inf')) -> NoneBases: 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:
| Name | Type | Description | Default |
|---|---|---|---|
base | Distribution | The original distribution. | required |
low | float | Lower bound (inclusive). | float(‘-inf’) |
high | float | Upper bound (inclusive). | float(‘inf’) |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF of truncated distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF of truncated distribution. |
plot | Plot the distribution. |
pmf | PMF of truncated distribution. |
ppf | PPF of truncated distribution. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from truncated distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function of truncated distribution. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Mean of truncated distribution. |
median | float | Median of truncated distribution. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Standard deviation of truncated distribution. |
var | float | Variance of truncated distribution. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatMean of truncated distribution.
median¶
median: floatMedian of truncated distribution.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatStandard deviation of truncated distribution.
var¶
var: floatVariance of truncated distribution.
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | CDF values (0 below low, 1 above high). |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values (zero outside truncation bounds). |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Quantile values within truncation bounds. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples within truncation bounds. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (1 - CDF). |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798Functions¶
beta¶
beta(a: float, b: float) -> DistributionBeta distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a | float | Shape parameter alpha (must be positive). | required |
b | float | Shape parameter beta (must be positive). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
d = beta(a=2, b=5)
d.mean
# 0.285...binomial¶
binomial(n: int, p: float) -> DistributionBinomial distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of trials (must be non-negative integer). | required |
p | float | Probability of success (must be in [0, 1]). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> DistributionChi-squared distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df | float | Degrees of freedom (must be positive). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
c = chi2(df=5)
c.ppf(0.95) # Critical value
# 11.07...exponential¶
exponential(rate: float = 1.0) -> DistributionExponential distribution (rate parameterization).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rate | float | Rate parameter lambda (must be positive). Mean = 1/rate. Default 1.0. | 1.0 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
d = exponential(rate=0.5)
d.mean
# 2.0f_dist¶
f_dist(df1: float, df2: float) -> DistributionF distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df1 | float | Numerator degrees of freedom (must be positive). | required |
df2 | float | Denominator degrees of freedom (must be positive). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> strConvert matplotlib figure to base64-encoded HTML img tag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fig | Figure | Matplotlib figure to convert. | required |
dpi | int | Resolution for the PNG image. | 100 |
Returns:
| Type | Description |
|---|---|
str | HTML string with embedded base64 PNG. |
gamma¶
gamma(shape: float, rate: float | None = None, scale: float | None = None) -> DistributionGamma distribution.
Accepts either rate or scale parameterization (not both).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape | float | Shape parameter (must be positive). | required |
rate | float | None | Rate parameter (1/scale). If provided, scale must be None. | None |
scale | float | None | Scale parameter. If provided, rate must be None. Default is scale=1 if neither specified. | None |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
g = gamma(shape=2, rate=0.5)
g.mean
# 4.0
g = gamma(shape=2, scale=2) # Equivalent
g.mean
# 4.0normal¶
normal(mean: float = 0, sd: float = 1) -> DistributionNormal (Gaussian) distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean | float | Mean of the distribution. Default 0. | 0 |
sd | float | Standard deviation (must be positive). Default 1. | 1 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> DistributionPoisson distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mu | float | Expected number of events (rate, must be positive). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> DistributionStudent’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:
| Name | Type | Description | Default |
|---|---|---|---|
df | float | Degrees of freedom (must be positive). | required |
loc | float | Location parameter. Default 0.0. | 0.0 |
scale | float | Scale parameter (must be positive). Default 1.0. | 1.0 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
d = t(df=10)
d.ppf(0.975) # Critical value for 95% CIt_dist¶
t_dist(df: float, mean: float = 0, sd: float = 1) -> DistributionStudent’s t distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df | float | Degrees of freedom (must be positive). | required |
mean | float | Location parameter. Default 0. | 0 |
sd | float | Scale parameter (must be positive). Default 1. | 1 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> DistributionUniform distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound. Default 0. | 0 |
high | float | Upper bound (must be > low). Default 1. | 1 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
d = uniform(low=0, high=10)
d.mean
# 5.0Modules¶
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:
| Name | Description |
|---|---|
DistributionAlgebraMixin | Mixin 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:
| Name | Description |
|---|---|
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
Functions¶
add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New 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:
| Name | Description |
|---|---|
Distribution | Wrapper for scipy.stats distributions with visualization. |
Attributes¶
Classes¶
Distribution¶
Distribution(dist: rv_frozen, name: str, params: dict[str, float]) -> NoneBases: DistributionPlotMixin, DistributionAlgebraMixin
Wrapper for scipy.stats distributions with visualization.
Provides a unified interface for probability distributions with:
Probability functions (pdf/pmf, cdf, ppf)
Random sampling (rvs)
Moments (mean, var, std)
Visualization with shading support
Automatic notebook rendering
Algebraic composition (affine transforms, convolution, truncation)
Probability queries via comparison operators
Hypothesis testing helpers
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist | rv_frozen | Frozen scipy.stats distribution. | required |
name | str | Display name for the distribution. | required |
params | dict[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.96Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | Cumulative distribution function. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | Probability density function (continuous distributions only). |
plot | Plot the distribution. |
pmf | Probability mass function (discrete distributions only). |
ppf | Percent point function (inverse CDF / quantile function). |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random variates. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function (1 - CDF). |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Distribution mean (expected value). |
median | float | Distribution median. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Distribution standard deviation. |
var | float | Distribution variance. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatDistribution mean (expected value).
median¶
median: floatDistribution median.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatDistribution standard deviation.
var¶
var: floatDistribution variance.
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCumulative distribution function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate the CDF. | required |
Returns:
| Type | Description |
|---|---|
ndarray | CDF values (P(X <= x)) at each point. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayProbability density function (continuous distributions only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate the PDF. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayProbability mass function (discrete distributions only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate the PMF. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values at each point. |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPercent point function (inverse CDF / quantile function).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Values x such that P(X <= x) = q. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random variates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples from the distribution. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function (1 - CDF).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (P(X > x)) at each point. |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798core¶
Backward-compatibility re-exports for distribution classes.
This module re-exports all distribution classes from their new locations:
base.py: Distribution base classderived.py: TransformedDistribution, ConvolvedDistribution, TruncatedDistribution, FoldedDistribution
Import from this module or directly from the submodules.
Classes:
| Name | Description |
|---|---|
ConvolvedDistribution | Distribution representing the sum of two independent random variables. |
Distribution | Wrapper for scipy.stats distributions with visualization. |
FoldedDistribution | Distribution of |
TransformedDistribution | Distribution resulting from an affine transformation: Y = scale*X + shift. |
TruncatedDistribution | Distribution truncated to an interval [low, high]. |
Classes¶
ConvolvedDistribution¶
ConvolvedDistribution(dist1: Distribution, dist2: Distribution, n_samples: int = MC_SAMPLES) -> NoneBases: 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:
| Name | Type | Description | Default |
|---|---|---|---|
dist1 | Distribution | First distribution (X). | required |
dist2 | Distribution | Second distribution (Y). | required |
n_samples | int | Number of samples for Monte Carlo estimation. | MC_SAMPLES |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF estimated from empirical distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
get_samples | Get or generate cached samples. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF estimated via kernel density estimation. |
plot | Plot the distribution. |
pmf | PMF estimated from sample frequencies. |
ppf | PPF (quantile function) estimated from samples. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from convolved distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Mean of sum: E[X] + E[Y]. |
median | float | Median estimated from samples. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Standard deviation of sum. |
var | float | Variance of sum (independent): Var[X] + Var[Y]. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatMean of sum: E[X] + E[Y].
median¶
median: floatMedian estimated from samples.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatStandard deviation of sum.
var¶
var: floatVariance of sum (independent): Var[X] + Var[Y].
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF estimated from empirical distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Empirical CDF values. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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.ndarrayGet or generate cached samples.
Returns:
| Type | Description |
|---|---|
ndarray | Sorted 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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF estimated via kernel density estimation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | KDE-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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF estimated from sample frequencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Frequency-estimated PMF values. |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF (quantile function) estimated from samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Estimated quantile values. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from convolved distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples from X + Y. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (1 - CDF). |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798Distribution¶
Distribution(dist: rv_frozen, name: str, params: dict[str, float]) -> NoneBases: DistributionPlotMixin, DistributionAlgebraMixin
Wrapper for scipy.stats distributions with visualization.
Provides a unified interface for probability distributions with:
Probability functions (pdf/pmf, cdf, ppf)
Random sampling (rvs)
Moments (mean, var, std)
Visualization with shading support
Automatic notebook rendering
Algebraic composition (affine transforms, convolution, truncation)
Probability queries via comparison operators
Hypothesis testing helpers
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist | rv_frozen | Frozen scipy.stats distribution. | required |
name | str | Display name for the distribution. | required |
params | dict[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.96Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | Cumulative distribution function. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | Probability density function (continuous distributions only). |
plot | Plot the distribution. |
pmf | Probability mass function (discrete distributions only). |
ppf | Percent point function (inverse CDF / quantile function). |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random variates. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function (1 - CDF). |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Distribution mean (expected value). |
median | float | Distribution median. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Distribution standard deviation. |
var | float | Distribution variance. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatDistribution mean (expected value).
median¶
median: floatDistribution median.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatDistribution standard deviation.
var¶
var: floatDistribution variance.
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCumulative distribution function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate the CDF. | required |
Returns:
| Type | Description |
|---|---|
ndarray | CDF values (P(X <= x)) at each point. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayProbability density function (continuous distributions only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate the PDF. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayProbability mass function (discrete distributions only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate the PMF. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values at each point. |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPercent point function (inverse CDF / quantile function).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Values x such that P(X <= x) = q. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random variates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples from the distribution. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function (1 - CDF).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (P(X > x)) at each point. |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798FoldedDistribution¶
FoldedDistribution(base: Distribution, n_samples: int = MC_SAMPLES) -> NoneBases: Distribution
Distribution of |X| - the absolute value of X.
Uses simulation for CDF/PPF computations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base | Distribution | The original distribution. | required |
n_samples | int | Number of samples for Monte Carlo estimation. | MC_SAMPLES |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF of folded distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
get_samples | Get or generate cached samples. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF of folded distribution: f_ |
plot | Plot the distribution. |
pmf | PMF of folded distribution. |
ppf | PPF of folded distribution. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from folded distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function of folded distribution. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Mean of folded distribution. |
median | float | Median of folded distribution. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Standard deviation of folded distribution. |
var | float | Variance of folded distribution. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatMean of folded distribution.
median¶
median: floatMedian of folded distribution.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatStandard deviation of folded distribution.
var¶
var: floatVariance of folded distribution.
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Empirical CDF values. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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.ndarrayGet or generate cached samples.
Returns:
| Type | Description |
|---|---|
ndarray | Sorted array of Monte Carlo samples from |
interval¶
interval(confidence: float = 0.95) -> tuple[float, float]Central confidence interval containing given probability mass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF of folded distribution: f_|X|(y) = f_X(y) + f_X(-y) for y >= 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values (zero for negative x). |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Estimated quantile values. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (1 - CDF). |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798TransformedDistribution¶
TransformedDistribution(base: Distribution, scale: float, shift: float) -> NoneBases: 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:
| Name | Type | Description | Default |
|---|---|---|---|
base | Distribution | The original distribution. | required |
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF of transformed distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF of transformed distribution. |
plot | Plot the distribution. |
pmf | PMF of transformed distribution. |
ppf | PPF of transformed distribution. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from transformed distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function of transformed distribution. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Transformed mean: scale * E[X] + shift. |
median | float | Transformed median: scale * median[X] + shift. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Transformed standard deviation: |
var | float | Transformed variance: scale^2 * Var[X]. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatTransformed mean: scale * E[X] + shift.
median¶
median: floatTransformed median: scale * median[X] + shift.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatTransformed standard deviation: |scale| * SD[X].
var¶
var: floatTransformed variance: scale^2 * Var[X].
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | CDF values at each point. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values at each point. |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Values x such that P(Y <= x) = q. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values at each point. |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798TruncatedDistribution¶
TruncatedDistribution(base: Distribution, low: float = float('-inf'), high: float = float('inf')) -> NoneBases: 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:
| Name | Type | Description | Default |
|---|---|---|---|
base | Distribution | The original distribution. | required |
low | float | Lower bound (inclusive). | float(‘-inf’) |
high | float | Upper bound (inclusive). | float(‘inf’) |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF of truncated distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF of truncated distribution. |
plot | Plot the distribution. |
pmf | PMF of truncated distribution. |
ppf | PPF of truncated distribution. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from truncated distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function of truncated distribution. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Mean of truncated distribution. |
median | float | Median of truncated distribution. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Standard deviation of truncated distribution. |
var | float | Variance of truncated distribution. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatMean of truncated distribution.
median¶
median: floatMedian of truncated distribution.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatStandard deviation of truncated distribution.
var¶
var: floatVariance of truncated distribution.
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | CDF values (0 below low, 1 above high). |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values (zero outside truncation bounds). |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Quantile values within truncation bounds. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples within truncation bounds. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (1 - CDF). |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798derived¶
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:
| Name | Description |
|---|---|
ConvolvedDistribution | Distribution representing the sum of two independent random variables. |
FoldedDistribution | Distribution of |
TransformedDistribution | Distribution resulting from an affine transformation: Y = scale*X + shift. |
TruncatedDistribution | Distribution truncated to an interval [low, high]. |
Attributes¶
Classes¶
ConvolvedDistribution¶
ConvolvedDistribution(dist1: Distribution, dist2: Distribution, n_samples: int = MC_SAMPLES) -> NoneBases: 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:
| Name | Type | Description | Default |
|---|---|---|---|
dist1 | Distribution | First distribution (X). | required |
dist2 | Distribution | Second distribution (Y). | required |
n_samples | int | Number of samples for Monte Carlo estimation. | MC_SAMPLES |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF estimated from empirical distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
get_samples | Get or generate cached samples. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF estimated via kernel density estimation. |
plot | Plot the distribution. |
pmf | PMF estimated from sample frequencies. |
ppf | PPF (quantile function) estimated from samples. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from convolved distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Mean of sum: E[X] + E[Y]. |
median | float | Median estimated from samples. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Standard deviation of sum. |
var | float | Variance of sum (independent): Var[X] + Var[Y]. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatMean of sum: E[X] + E[Y].
median¶
median: floatMedian estimated from samples.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatStandard deviation of sum.
var¶
var: floatVariance of sum (independent): Var[X] + Var[Y].
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF estimated from empirical distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Empirical CDF values. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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.ndarrayGet or generate cached samples.
Returns:
| Type | Description |
|---|---|
ndarray | Sorted 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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF estimated via kernel density estimation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | KDE-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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF estimated from sample frequencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Frequency-estimated PMF values. |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF (quantile function) estimated from samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Estimated quantile values. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from convolved distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples from X + Y. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (1 - CDF). |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798FoldedDistribution¶
FoldedDistribution(base: Distribution, n_samples: int = MC_SAMPLES) -> NoneBases: Distribution
Distribution of |X| - the absolute value of X.
Uses simulation for CDF/PPF computations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base | Distribution | The original distribution. | required |
n_samples | int | Number of samples for Monte Carlo estimation. | MC_SAMPLES |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF of folded distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
get_samples | Get or generate cached samples. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF of folded distribution: f_ |
plot | Plot the distribution. |
pmf | PMF of folded distribution. |
ppf | PPF of folded distribution. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from folded distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function of folded distribution. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Mean of folded distribution. |
median | float | Median of folded distribution. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Standard deviation of folded distribution. |
var | float | Variance of folded distribution. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatMean of folded distribution.
median¶
median: floatMedian of folded distribution.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatStandard deviation of folded distribution.
var¶
var: floatVariance of folded distribution.
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Empirical CDF values. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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.ndarrayGet or generate cached samples.
Returns:
| Type | Description |
|---|---|
ndarray | Sorted array of Monte Carlo samples from |
interval¶
interval(confidence: float = 0.95) -> tuple[float, float]Central confidence interval containing given probability mass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF of folded distribution: f_|X|(y) = f_X(y) + f_X(-y) for y >= 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values (zero for negative x). |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Estimated quantile values. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function of folded distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (1 - CDF). |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798TransformedDistribution¶
TransformedDistribution(base: Distribution, scale: float, shift: float) -> NoneBases: 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:
| Name | Type | Description | Default |
|---|---|---|---|
base | Distribution | The original distribution. | required |
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF of transformed distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF of transformed distribution. |
plot | Plot the distribution. |
pmf | PMF of transformed distribution. |
ppf | PPF of transformed distribution. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from transformed distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function of transformed distribution. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Transformed mean: scale * E[X] + shift. |
median | float | Transformed median: scale * median[X] + shift. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Transformed standard deviation: |
var | float | Transformed variance: scale^2 * Var[X]. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatTransformed mean: scale * E[X] + shift.
median¶
median: floatTransformed median: scale * median[X] + shift.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatTransformed standard deviation: |scale| * SD[X].
var¶
var: floatTransformed variance: scale^2 * Var[X].
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | CDF values at each point. |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values at each point. |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Values x such that P(Y <= x) = q. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function of transformed distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values at each point. |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798TruncatedDistribution¶
TruncatedDistribution(base: Distribution, low: float = float('-inf'), high: float = float('inf')) -> NoneBases: 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:
| Name | Type | Description | Default |
|---|---|---|---|
base | Distribution | The original distribution. | required |
low | float | Lower bound (inclusive). | float(‘-inf’) |
high | float | Upper bound (inclusive). | float(‘inf’) |
Functions:
| Name | Description |
|---|---|
abs | Absolute value distribution: |
add_distribution | Add two independent random variables: X + Y. |
affine_transform | Apply affine transformation: scale*X + shift. |
between | P(low <= X <= high) - probability within an interval. |
cdf | CDF of truncated distribution. |
compute_x_range | Compute sensible x-range for plotting. |
critical | Compute critical value(s) for hypothesis testing. |
interval | Central confidence interval containing given probability mass. |
lik | Compute likelihood of data under this distribution. |
loglik | Compute log-likelihood of data under this distribution. |
make_prob | Helper to create Probability with distribution context. |
outside | P(X < low or X > high) - probability outside an interval. |
p | Quantile function alias for ppf. |
p_value | Compute p-value for observed statistic. |
parse_shade_region | Parse shade_region argument to actual bounds. |
pdf | PDF of truncated distribution. |
plot | Plot the distribution. |
pmf | PMF of truncated distribution. |
ppf | PPF of truncated distribution. |
prob | Unified probability function (pdf or pmf based on type). |
reject | Determine if null hypothesis should be rejected. |
rvs | Generate random samples from truncated distribution. |
sample | Generate n random samples using a numpy Generator. |
scale | Scale distribution by multiplying by factor. |
sf | Survival function of truncated distribution. |
shift | Shift distribution by adding delta to all values. |
standardize | Standardize to mean=0, sd=1. |
truncate | Truncate distribution to an interval. |
Attributes:
| Name | Type | Description |
|---|---|---|
iqr | float | Interquartile range (Q3 - Q1). |
is_discrete | bool | Whether this is a discrete distribution. |
mean | float | Mean of truncated distribution. |
median | float | Median of truncated distribution. |
name | str | Distribution name. |
params | dict[str, float] | Distribution parameters. |
q1 | float | First quartile (25th percentile). |
q3 | float | Third quartile (75th percentile). |
std | float | Standard deviation of truncated distribution. |
var | float | Variance of truncated distribution. |
Attributes¶
iqr¶
iqr: floatInterquartile range (Q3 - Q1).
is_discrete¶
is_discrete: boolWhether this is a discrete distribution.
mean¶
mean: floatMean of truncated distribution.
median¶
median: floatMedian of truncated distribution.
name¶
name: strDistribution name.
params¶
params: dict[str, float]Distribution parameters.
q1¶
q1: floatFirst quartile (25th percentile).
q3¶
q3: floatThird quartile (75th percentile).
std¶
std: floatStandard deviation of truncated distribution.
var¶
var: floatVariance of truncated distribution.
Functions¶
abs¶
abs() -> FoldedDistributionAbsolute value distribution: |X|.
Returns:
| Type | Description |
|---|---|
FoldedDistribution | FoldedDistribution representing |
Examples:
d = normal().abs() # Half-normal (folded at 0)
d.mean # Approximately 0.798add_distribution¶
add_distribution(other: Distribution) -> DistributionAdd two independent random variables: X + Y.
Uses closed-form solutions when available, otherwise falls back to simulation-backed ConvolvedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Distribution | Another independent distribution to add. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing X + Y. |
affine_transform¶
affine_transform(scale: float, shift: float) -> DistributionApply affine transformation: scale*X + shift.
Dispatches to closed-form solutions for location-scale families, otherwise returns TransformedDistribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Multiplicative factor. | required |
shift | float | Additive constant. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New distribution representing scale*X + shift. |
between¶
between(low: float, high: float) -> ProbabilityP(low <= X <= high) - probability within an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal(100, 15)
d.between(85, 115)
# P(85 <= X <= 115) = 0.6827cdf¶
cdf(x: ArrayLike) -> np.ndarrayCDF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | CDF values (0 below low, 1 above high). |
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test: - “two”: Returns (lower, upper) critical values - “left”: Returns lower critical value - “right”: Returns upper critical value | ‘two’ |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
confidence | float | Probability mass in the interval (default 0.95). | 0.95 |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | Tuple of (lower, upper) bounds. |
lik¶
lik(data: ArrayLike) -> floatCompute likelihood of data under this distribution.
Warning: For numerical stability, prefer loglik() for inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Product of probabilities: prod(f(x_i)). |
Examples:
d = normal(0, 1)
d.lik([0])
# 0.3989...loglik¶
loglik(data: ArrayLike) -> floatCompute log-likelihood of data under this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | ArrayLike | Observed data points. | required |
Returns:
| Type | Description |
|---|---|
float | Sum 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) -> ProbabilityHelper to create Probability with distribution context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value. | required |
expr | str | Expression string for display. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
outside¶
outside(low: float, high: float) -> ProbabilityP(X < low or X > high) - probability outside an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound of interval. | required |
high | float | Upper bound of interval. | required |
Returns:
| Type | Description |
|---|---|
Probability | Probability object with rich display. |
Examples:
d = normal()
d.outside(-1.96, 1.96)
# P(X < -1.96 or X > 1.96) = 0.05p¶
p(q: float) -> floatQuantile function alias for ppf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | float | Probability (between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
float | Value x such that P(X <= x) = q. |
Examples:
d = normal()
d.p(0.975) # Same as d.ppf(0.975)
# 1.96p_value¶
p_value(x: float, tail: Literal['two', 'left', 'right'] = 'two') -> ProbabilityCompute p-value for observed statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
tail | Literal[‘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:
| Type | Description |
|---|---|
Probability | Probability object representing the p-value. |
Examples:
t = t_dist(df=29)
t.p_value(2.3, tail="two")
# P(|X| > 2.3) = 0.0285parse_shade_region¶
parse_shade_region(shade_region: tuple[float, float] | str | None) -> tuple[float, float] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple of (low, high) bounds, or None if no shading. |
pdf¶
pdf(x: ArrayLike) -> np.ndarrayPDF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PDF 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
pmf¶
pmf(x: ArrayLike) -> np.ndarrayPMF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | PMF values (zero outside truncation bounds). |
ppf¶
ppf(q: ArrayLike) -> np.ndarrayPPF of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | ArrayLike | Quantiles (probabilities between 0 and 1). | required |
Returns:
| Type | Description |
|---|---|
ndarray | Quantile values within truncation bounds. |
prob¶
prob(x: ArrayLike) -> np.ndarrayUnified probability function (pdf or pmf based on type).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Probability values (density for continuous, mass for discrete). |
reject¶
reject(x: float, alpha: float = 0.05, tail: Literal['two', 'left', 'right'] = 'two') -> boolDetermine if null hypothesis should be rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | float | Observed test statistic. | required |
alpha | float | Significance level. | 0.05 |
tail | Literal[‘two’, ‘left’, ‘right’] | Type of test. | ‘two’ |
Returns:
| Type | Description |
|---|---|
bool | True if null hypothesis should be rejected. |
Examples:
t = t_dist(df=29)
t.reject(2.3, alpha=0.05)
# Truervs¶
rvs(size: int | tuple[int, ...] = 1, seed: int | np.random.Generator | None = None) -> np.ndarrayGenerate random samples from truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size | int | tuple[int, ...] | Number of samples or shape of output array. | 1 |
seed | int | Generator | None | Random seed or Generator for reproducibility. | None |
Returns:
| Type | Description |
|---|---|
ndarray | Array of random samples within truncation bounds. |
sample¶
sample(n: int, rng: np.random.Generator) -> np.ndarrayGenerate n random samples using a numpy Generator.
Compatible with the simulation Distribution protocol, allowing internal Distribution objects to be used in model.simulate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of samples to generate. | required |
rng | Generator | NumPy random number generator for reproducibility. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Array of n samples from this distribution. |
scale¶
scale(factor: float) -> DistributionScale distribution by multiplying by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor | float | Multiplicative scale factor. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New scaled distribution. |
Examples:
d = normal(0, 1).scale(2)
d.std
# 2.0sf¶
sf(x: ArrayLike) -> np.ndarraySurvival function of truncated distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | ArrayLike | Points at which to evaluate. | required |
Returns:
| Type | Description |
|---|---|
ndarray | Survival function values (1 - CDF). |
shift¶
shift(delta: float) -> DistributionShift distribution by adding delta to all values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta | float | Amount to add to the mean. | required |
Returns:
| Type | Description |
|---|---|
Distribution | New shifted distribution. |
Examples:
d = normal(0, 1).shift(5)
d.mean
# 5.0standardize¶
standardize() -> DistributionStandardize to mean=0, sd=1.
Returns:
| Type | Description |
|---|---|
Distribution | New distribution with zero mean and unit variance. |
Examples:
d = normal(100, 15).standardize()
d.mean
# 0.0
d.std
# 1.0truncate¶
truncate(low: float = float('-inf'), high: float = float('inf')) -> TruncatedDistributionTruncate distribution to an interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound (inclusive). Defaults to -inf. | float(‘-inf’) |
high | float | Upper bound (inclusive). Defaults to +inf. | float(‘inf’) |
Returns:
| Type | Description |
|---|---|
TruncatedDistribution | TruncatedDistribution over the specified interval. |
Examples:
d = normal().truncate(0, np.inf) # Half-normal
d.mean # Approximately 0.798factories¶
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:
| Name | Description |
|---|---|
beta | Beta distribution. |
binomial | Binomial distribution. |
chi2 | Chi-squared distribution. |
exponential | Exponential distribution (rate parameterization). |
f_dist | F distribution. |
gamma | Gamma distribution. |
normal | Normal (Gaussian) distribution. |
poisson | Poisson distribution. |
t | Student’s t distribution (location-scale parameterization). |
t_dist | Student’s t distribution. |
uniform | Uniform distribution. |
Classes¶
Functions¶
beta¶
beta(a: float, b: float) -> DistributionBeta distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a | float | Shape parameter alpha (must be positive). | required |
b | float | Shape parameter beta (must be positive). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
d = beta(a=2, b=5)
d.mean
# 0.285...binomial¶
binomial(n: int, p: float) -> DistributionBinomial distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n | int | Number of trials (must be non-negative integer). | required |
p | float | Probability of success (must be in [0, 1]). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> DistributionChi-squared distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df | float | Degrees of freedom (must be positive). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
c = chi2(df=5)
c.ppf(0.95) # Critical value
# 11.07...exponential¶
exponential(rate: float = 1.0) -> DistributionExponential distribution (rate parameterization).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rate | float | Rate parameter lambda (must be positive). Mean = 1/rate. Default 1.0. | 1.0 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
d = exponential(rate=0.5)
d.mean
# 2.0f_dist¶
f_dist(df1: float, df2: float) -> DistributionF distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df1 | float | Numerator degrees of freedom (must be positive). | required |
df2 | float | Denominator degrees of freedom (must be positive). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> DistributionGamma distribution.
Accepts either rate or scale parameterization (not both).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape | float | Shape parameter (must be positive). | required |
rate | float | None | Rate parameter (1/scale). If provided, scale must be None. | None |
scale | float | None | Scale parameter. If provided, rate must be None. Default is scale=1 if neither specified. | None |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
g = gamma(shape=2, rate=0.5)
g.mean
# 4.0
g = gamma(shape=2, scale=2) # Equivalent
g.mean
# 4.0normal¶
normal(mean: float = 0, sd: float = 1) -> DistributionNormal (Gaussian) distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean | float | Mean of the distribution. Default 0. | 0 |
sd | float | Standard deviation (must be positive). Default 1. | 1 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> DistributionPoisson distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mu | float | Expected number of events (rate, must be positive). | required |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> DistributionStudent’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:
| Name | Type | Description | Default |
|---|---|---|---|
df | float | Degrees of freedom (must be positive). | required |
loc | float | Location parameter. Default 0.0. | 0.0 |
scale | float | Scale parameter (must be positive). Default 1.0. | 1.0 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
d = t(df=10)
d.ppf(0.975) # Critical value for 95% CIt_dist¶
t_dist(df: float, mean: float = 0, sd: float = 1) -> DistributionStudent’s t distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df | float | Degrees of freedom (must be positive). | required |
mean | float | Location parameter. Default 0. | 0 |
sd | float | Scale parameter (must be positive). Default 1. | 1 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution 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) -> DistributionUniform distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low | float | Lower bound. Default 0. | 0 |
high | float | Upper bound (must be > low). Default 1. | 1 |
Returns:
| Type | Description |
|---|---|
Distribution | Distribution object. |
Examples:
d = uniform(low=0, high=10)
d.mean
# 5.0plotting¶
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:
| Name | Description |
|---|---|
DistributionPlotMixin | Mixin 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:
| Name | Description |
|---|---|
compute_x_range | Compute sensible x-range for plotting. |
parse_shade_region | Parse shade_region argument to actual bounds. |
plot | Plot the distribution. |
Functions¶
compute_x_range¶
compute_x_range() -> tuple[float, float]Compute sensible x-range for plotting.
Returns:
| Type | Description |
|---|---|
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] | NoneParse shade_region argument to actual bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shade_region | tuple[float, float] | str | None | Region specification (tuple, string shortcut, or None). | required |
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None | Tuple 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) -> FigurePlot the distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax | Axes | None | Matplotlib axes. If None, creates new figure. | None |
shade_region | tuple[float, float] | str | None | Region 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_direction | Literal[‘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_alpha | float | Transparency for shaded region. | 0.3 |
shade_color | str | None | Color for shaded region (defaults to line color). | None |
show_mean | bool | Show vertical line at mean. | False |
show_median | bool | Show vertical line at median. | False |
x_range | tuple[float, float] | None | Custom x-axis range (auto-computed if None). | None |
figsize | tuple[float, float] | Figure size in inches. | (6, 4) |
color | str | None | Line/bar color (uses palette default if None). | None |
title | str | None | Plot title (auto-generated if None). | None |
Returns:
| Type | Description |
|---|---|
Figure | Matplotlib Figure object. |
Functions¶
probability¶
Probability result class and visualization helpers.
Classes:
| Name | Description |
|---|---|
Probability | Rich probability result from distribution queries. |
Functions:
| Name | Description |
|---|---|
figure_to_html | Convert matplotlib figure to base64-encoded HTML img tag. |
Attributes:
| Name | Type | Description |
|---|---|---|
MC_SAMPLES | ||
rv_frozen |
Attributes¶
MC_SAMPLES¶
MC_SAMPLES = 100000rv_frozen¶
rv_frozen = rv_continuous_frozen | rv_discrete_frozenClasses¶
Probability¶
Probability(value: float, expr: str, dist_name: str) -> NoneRich 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:
| Name | Type | Description | Default |
|---|---|---|---|
value | float | The probability value (between 0 and 1). | required |
expr | str | Expression describing the event (e.g., “X > 1.96”). | required |
dist_name | str | Display 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
# TrueAttributes:
| Name | Type | Description |
|---|---|---|
dist_name | str | |
expr | str | |
value | float |
Attributes¶
dist_name¶
dist_name: strexpr¶
expr: strvalue¶
value: floatFunctions¶
figure_to_html¶
figure_to_html(fig: Figure, dpi: int = 100) -> strConvert matplotlib figure to base64-encoded HTML img tag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fig | Figure | Matplotlib figure to convert. | required |
dpi | int | Resolution for the PNG image. | 100 |
Returns:
| Type | Description |
|---|---|
str | HTML string with embedded base64 PNG. |