Skip to content

Distributions and randomness

How random events are modelled and drawn. For event distributions, prefer building a DiscreteDist (plus a precomputed dist.alias_sampler()) over rolling your own from raw draws; the generators further down are the underlying source of randomness. The distribution classes live in dynaplex.modelling; the generators are imported from the top-level dynaplex package. For a high-level tour of what DiscreteDist can do — the supported families, convolution and mixing, the three ways to draw, and the tail truncation to be aware of — see Discrete distributions.

Distributions and samplers

DiscreteDist

An integer-valued probability distribution as an immutable value.

Stores a trimmed probability mass function plus an offset: the support is [offset, offset + len(probs) - 1]. Construct via the classmethod factories (DiscreteDist.poisson(3.2), DiscreteDist.custom(probs), ...), typically in an MDP's __init__, and store in a (const) field. All methods are callable from compiled DynaML code.

Whenever the distribution is static (the same for every state — the usual case), precompute an O(1) sampler once via alias_sampler and draw through that; sample is for the exceptional state-dependent case.

Example
dist = DiscreteDist.poisson(3.2)
mean = dist.expectation()       # 3.2
x = dist.sample(rng)            # one O(n) inverse-CDF draw

sampler = dist.alias_sampler()  # build once ...
y = sampler.sample(rng)         # ... then O(1) per draw

constant classmethod

constant(value: int) -> DiscreteDist

The point mass at value.

custom classmethod

custom(probs: list[float] | Array1D[np.float64], offset: int = 0) -> DiscreteDist

A distribution from an explicit PMF over offset, offset+1, ... (validated + trimmed).

trim_lo staticmethod

trim_lo(probs: Array1D[np.float64]) -> int

Index of the first entry a trim keeps.

trim_hi staticmethod

trim_hi(probs: Array1D[np.float64]) -> int

Index of the last entry a trim keeps (-1 if it keeps none).

poisson classmethod

poisson(mean: float) -> DiscreteDist

Poisson with the given mean (>= 0).

geometric classmethod

geometric(mean: float) -> DiscreteDist

Geometric on {0, 1, ...} with the given mean (>= 0): success prob 1/(1+mean).

geometric_from_prob classmethod

geometric_from_prob(p: float) -> DiscreteDist

Geometric on {0, 1, ...}: P(X == k) = p * (1-p)**k, with p in (0, 1].

binomial classmethod

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

Binomial: n trials (>= 0), success probability p in [0, 1].

negative_binomial classmethod

negative_binomial(r: float, p: float) -> DiscreteDist

Negative binomial: r > 0 successes, success probability p in (0, 1].

adan_eenige_resing classmethod

adan_eenige_resing(mean: float, stdev: float) -> DiscreteDist

Build the distribution with the given first two moments, by the fit of Adan, van Eenige & Resing (1995).

Turns (mean, standard deviation) into a concrete DiscreteDist: selects Poisson / mixed-binomial / mixed-negative-binomial / mixed-geometric by a = cv**2 - 1/mean. Requires mean > 0, stdev >= 0 and stdev**2 > delta*(1-delta) with delta = mean - floor(mean) (or a near-integer mean with near-zero stdev); raises DynaPlexError otherwise — see least_variance_for_moment_fit.

least_variance_for_moment_fit staticmethod

least_variance_for_moment_fit(mean: float) -> float

The least variance a distribution with the given mean can have under the AER fit.

poisson_sample classmethod

poisson_sample(mean: float, rng: np.random.Generator | Generator | EventProbe) -> int

One draw from Poisson(mean), mean >= 0.

The union rng parameter is an overload set (as in sample): the generator members call the draw kernel; an EventProbe enumerates the family's PMF, building it only when its per-position cache misses (event_probe.py).

geometric_sample classmethod

geometric_sample(mean: float, rng: np.random.Generator | Generator | EventProbe) -> int

One draw from the geometric on {0, 1, ...} with the given mean (>= 0).

geometric_from_prob_sample classmethod

geometric_from_prob_sample(p: float, rng: np.random.Generator | Generator | EventProbe) -> int

One draw from the geometric on {0, 1, ...} with success prob p in (0, 1].

binomial_sample classmethod

binomial_sample(n: int, p: float, rng: np.random.Generator | Generator | EventProbe) -> int

One draw from Binomial(n, p).

negative_binomial_sample classmethod

negative_binomial_sample(r: int, p: float, rng: np.random.Generator | Generator | EventProbe) -> int

One draw from NegativeBinomial(r, p); r is integral here (legacy sampler).

adan_eenige_resing_sample classmethod

adan_eenige_resing_sample(mean: float, stdev: float, rng: np.random.Generator | Generator | EventProbe) -> int

One draw from the Adan-van Eenige-Resing two-moment fit (component picked per draw, legacy-style).

min

min() -> int

Smallest value in the support.

max

max() -> int

Largest value in the support.

probability_at

probability_at(value: int) -> float

P(X == value); 0.0 outside the support.

expectation

expectation() -> float

E[X].

variance

variance() -> float

Var[X].

std

std() -> float

Standard deviation of X.

entropy

entropy() -> float

Shannon entropy (natural log).

fractile

fractile(alpha: float) -> int

Smallest value v with P(X <= v) >= alpha (single cumulative scan).

sample

sample(rng: np.random.Generator | Generator | EventProbe) -> int

One draw: inverse-CDF linear scan on rng.random() (parity-safe).

Static distribution? Use an alias sampler instead.

If the distribution is the same for every state — the usual case, built once in the MDP's __init__ — do not draw through this method. Precompute alias_sampler once, store it next to the distribution, and call sampler.sample(rng): O(1) per draw instead of a scan over the support. Reserve dist.sample for the exceptional case where the distribution object itself depends on the current state (e.g. non-stationary demand).

The union parameter declares an overload set: the method compiles once per generator type (numpy PCG64 / DynaPlex-native xoshiro256++) and the call site dispatches by exact argument type. The EventProbe member enumerates instead of drawing (constexpr branch; the exact solver).

conditional_sample

conditional_sample(rng: np.random.Generator | Generator, minimum_value: int) -> int

One draw of X | X >= minimum_value (rescaled uniform, no rejection).

Union rng parameter = overload set, as in sample.

alias_sampler

alias_sampler() -> AliasSampler

Precompute an AliasSampler for this distribution — O(1) per draw, two rng draws. The right choice for long-lived distributions sampled many times.

Build once (e.g. in the MDP __init__) and store alongside the distribution; see modelling/samplers.py for the trade-offs.

mix

mix(other: DiscreteDist, prob_of_other: float) -> DiscreteDist

The mixture (1 - prob_of_other) * self + prob_of_other * other.

Kernel-backed on BOTH doors: CPython calls the pybind door here; compiled code never reaches this body — the frontend intercepts the method call and lowers it to the DP!dist.mix builtin running the same kernel. (The retired pure-Python loop body survives as the bit-identity mirror in test_discrete_dist.py.)

add

add(other: DiscreteDist) -> DiscreteDist

The distribution of X + Y for independent X ~ self, Y ~ other (convolution).

Kernel-backed on BOTH doors, like mix: pybind here, the DP!dist.add builtin in compiled code.

take_maximum_with

take_maximum_with(value: int) -> DiscreteDist

The distribution of max(X, value).

invert

invert() -> DiscreteDist

The distribution of -X.

AliasSampler

Precomputed Walker/Vose alias-table sampler for a DiscreteDist.

O(1) per draw regardless of support size, two rng.random() per draw. The recommended sampler for long-lived distributions sampled many times; note the draw stream differs from DiscreteDist.sample. Build via dist.alias_sampler().

min

min() -> int

Smallest value in the support.

max

max() -> int

Largest value in the support.

sample

sample(rng: np.random.Generator | Generator | EventProbe) -> int

One draw: uniform bucket, then a biased coin — two draws, O(1).

Union rng parameter = overload set, as in DiscreteDist.sample; the EventProbe member enumerates instead of drawing (constexpr branch).

Random number generation

default_rng

default_rng(seed: int) -> Generator

Create a DynaPlex-native (xoshiro256++) RNG from a single int64 seed.

In compiled/interpreted code this lowers to the C++ DP!DPNativeGenerator; in CPython it returns the bound Generator (same shared C++ kernels, bit-identical draws).

Generator

Generator(seed: typing.SupportsInt | typing.SupportsIndex)

DynaPlex-native RNG (xoshiro256++, SplitMix64 seeding) — what dynaplex.default_rng(seed) returns in CPython. random()/uniform()/choice()/permutation()/shuffle() run the exact backend kernels (bit-identical to compiled code); capsule + lock implement the numpy BitGenerator protocol over the same state, so np.random.Generator(gen) works too. At runtime any other numpy Generator method (normal, integers, ...) resolves by delegation onto the same stream; that surface is deliberately ABSENT from this stub so the static view equals what compiled DynaML accepts.

state property writable

state: tuple

The 4 xoshiro256++ lanes as a tuple of uint64 ints (get/set).

choice

choice(a: typing.Any, p: typing.Any = None) -> typing.Any

A random element from a — or from range(a) when a is an int. Runs the exact backend kernel, bit-identical to compiled DynaML code. The weighted form (p=) is accepted only when HAS_WEIGHTED_CHOICE is True (dev builds); release wheels raise ValueError and point at DiscreteDist.custom(probs).

permutation

permutation(n: typing.SupportsInt | typing.SupportsIndex) -> list[int]

A uniformly random order of 0..n-1 as a list. Runs the exact backend kernel (backwards Fisher-Yates over Lemire draws), bit-identical to compiled DynaML code; DynaPlex's own stream, not numpy's.

random

random() -> float

A uniform random float in [0.0, 1.0). Runs the exact backend kernel, bit-identical to compiled DynaML code.

shuffle

shuffle(xs: typing.Any) -> None

Reorder a list or 1-D array in place, with the same draws as permutation. Runs the exact backend kernel, bit-identical to compiled DynaML code.

uniform

uniform(low: typing.SupportsFloat | typing.SupportsIndex, high: typing.SupportsFloat | typing.SupportsIndex) -> float

A uniform random float in [low, high). Runs the exact backend kernel, bit-identical to compiled DynaML code.