mixle.stats.univariate.discrete package

Discrete univariate distribution namespace.

Every class implemented under this package is re-exported here so the namespace exposes the API it actually contains (MXR-080-1231). Before this, the package exposed only its submodule names, so from mixle.stats.univariate.discrete import BernoulliAccumulator failed while from mixle.stats import BernoulliAccumulator worked – the subpackage advertised modules and hid the classes inside them.

mixle.stats remains the consolidated public API and re-exports these same objects; this package is the narrower namespace for callers who want only discrete univariate families.

class BernoulliAccumulator(name=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted success and observation counts.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted success and count statistics for one observation.

Parameters:
  • x (bool | int)

  • weight (float)

  • estimate (BernoulliDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate weighted statistics from encoded observations.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (BernoulliDistribution | None)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded observations.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge another Bernoulli sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float])

Return type:

BernoulliAccumulator

value()[source]

Return the accumulated count and success total.

Return type:

tuple[float, float]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

x (tuple[float, float])

Return type:

BernoulliAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

BernoulliDataEncoder

class BernoulliAccumulatorFactory(name=None, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for BernoulliAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Bernoulli accumulator.

Return type:

BernoulliAccumulator

class BernoulliDataEncoder[source]

Bases: DataSequenceEncoder

Encode Bernoulli observations as a boolean numpy array.

seq_encode(x)[source]

Encode Bernoulli observations as a boolean array.

Parameters:

x (Sequence[bool | int])

Return type:

ndarray

class BernoulliDistribution(p, name=None, keys=None, prior=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Bernoulli distribution over {False, True} with success probability p.

Parameters:
  • p (float)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

classmethod compute_capabilities()[source]

Describe backend support for generated Bernoulli kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Bernoulli distributions.

static exp_family_sufficient_statistics(x, engine)[source]

Return Bernoulli sufficient statistics for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_legacy_sufficient_statistics(x, params, engine)[source]

Return per-row Bernoulli sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return Bernoulli natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return Bernoulli log partition for generated scoring.

Parameters:
Return type:

Any

set_prior(prior)[source]

Attach a Beta parameter prior and precompute conjugate-prior expectations.

With a Beta(a, b) prior on the success probability p this caches the digamma terms so that expected_log_density evaluates the variational Bayes expectation E_q[log p(x | p)] via E[log p] = digamma(a) - digamma(a+b) and E[log(1-p)] = digamma(b) - digamma(a+b). Any other prior (including None) leaves the distribution a plain point model.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

expected_log_density(x)[source]

Variational expectation E_q[log p(x | p)] under the Beta prior.

Falls back to the plug-in log_density(x) when no conjugate prior is attached.

Parameters:

x (bool | int)

Return type:

float

seq_expected_log_density(x)[source]

Vectorized expected_log_density over sequence-encoded observations.

Parameters:

x (ndarray)

Return type:

ndarray

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (bool | int)

Return type:

float

log_density(x)[source]

Return the log-density or log-mass at a single observation.

Parameters:

x (bool | int)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-density values for sequence-encoded observations.

Parameters:

x (ndarray)

Return type:

ndarray

static backend_log_density_from_params(x, p, engine)[source]

Engine-neutral Bernoulli log-mass from explicit parameters.

Parameters:
Return type:

Any

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked Bernoulli parameters for a homogeneous mixture kernel.

Parameters:
Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of Bernoulli log masses.

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]

Return stacked Bernoulli sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any]

support_size()[source]

The two outcomes {0, 1}.

Return type:

int

to_fisher(**kwargs)[source]

Return the Bernoulli’s count-family Fisher view.

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

cdf(x)[source]

Cumulative distribution function P(X <= x) over {0, 1}.

Parameters:

x (float)

Return type:

float

skewness()[source]

Skewness (1-2p)/sqrt(p(1-p)).

Return type:

float

kurtosis()[source]

Excess kurtosis (1-6p(1-p))/(p(1-p)).

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q) over {0, 1}.

Parameters:

q (float)

Return type:

float

entropy()[source]

Shannon entropy -p log p - (1-p) log(1-p) (nats).

Return type:

float

mode()[source]

Mode (0 if p<1/2 else 1).

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

BernoulliSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

BernoulliEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution for vectorized methods.

Return type:

BernoulliDataEncoder

enumerator()[source]

Return an enumerator over the distribution support when available.

Return type:

BernoulliEnumerator

class BernoulliEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate False/True in descending probability order.

Parameters:

dist (BernoulliDistribution)

class BernoulliEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]

Bases: ParameterEstimator

Estimate a Bernoulli distribution from weighted success counts.

Parameters:
  • pseudo_count (float | None)

  • suff_stat (float | None)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

accumulator_factory()[source]

Return an accumulator factory for Bernoulli sufficient statistics.

Return type:

BernoulliAccumulatorFactory

model_log_density(model)[source]

Log-density of the model’s success probability under the Beta prior (ELBO global term).

Parameters:

model (BernoulliDistribution)

Return type:

float

estimate(nobs, suff_stat)[source]

Estimate the Bernoulli success probability from weighted counts.

The distribution is defined on the open interval (0, 1), so a sample that is all successes or all failures – whose maximum-likelihood p is exactly 1 or 0 – is clamped _P_BOUNDARY (1e-12) away from the endpoint. When that clamp binds it is reported on the returned model through numerical_repairs() as bernoulli-p-clamped(...), and so through fit_provenance().repairs; an ordinary fit whose p is already interior records nothing.

Parameters:
Return type:

BernoulliDistribution

class BernoulliSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw iid Bernoulli observations.

Parameters:
  • dist (BernoulliDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one sample or a list of iid samples.

Parameters:
Return type:

bool | Sequence[bool]

class BetaBinomialAccumulator(n, name=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted first and second moments for beta-binomial estimation.

Parameters:
  • n (int)

  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted first and second moments for one count.

Parameters:
  • x (int)

  • weight (float)

  • estimate (BetaBinomialDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one count.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate weighted moments from encoded counts.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (BetaBinomialDistribution | None)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded counts.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge another beta-binomial sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

BetaBinomialAccumulator

value()[source]

Return accumulated sum, second moment sum, and count.

Return type:

tuple[float, float, float]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

x (tuple[float, float, float])

Return type:

BetaBinomialAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

BetaBinomialDataEncoder

class BetaBinomialAccumulatorFactory(n, name=None, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for BetaBinomialAccumulator.

Parameters:
  • n (int)

  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh beta-binomial accumulator.

Return type:

BetaBinomialAccumulator

class BetaBinomialDataEncoder(n)[source]

Bases: DataSequenceEncoder

Encode beta-binomial counts as a float array.

Parameters:

n (int)

seq_encode(x)[source]

Encode exact counts in the fixed support {0, ..., n}.

Parameters:

x (Sequence[int])

Return type:

ndarray

class BetaBinomialDistribution(n, a, b, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Beta-binomial distribution over {0, ..., n} with shape parameters a, b > 0.

Parameters:
density(x)[source]

Return the probability mass at a single count x.

Parameters:

x (int)

Return type:

float

log_density(x)[source]

Return the log probability mass at x (-inf outside {0, ..., n} or non-integer – a fractional count is not a valid beta-binomial outcome).

Parameters:

x (int)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-mass for an array of counts (-inf outside {0, ..., n} or non-integer – a fractional count is not a valid beta-binomial outcome).

Parameters:

x (ndarray)

Return type:

ndarray

support_size()[source]

n + 1 outcomes {0, ..., n}.

Return type:

int

cdf(x)[source]

Cumulative distribution function P(X <= x): a log-space partial sum of the pmf over {0..n}.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q) over {0..n}: the smallest count whose cdf reaches q (search on the cdf).

Parameters:

q (float)

Return type:

float

enumerator()[source]

Returns BetaBinomialEnumerator iterating the support in descending probability order.

Return type:

BetaBinomialEnumerator

sampler(seed=None)[source]

Return a sampler for drawing counts from this distribution.

Parameters:

seed (int | None)

Return type:

BetaBinomialSampler

estimator(pseudo_count=None)[source]

Return a method-of-moments estimator for a, b at the fixed number of trials n.

Parameters:

pseudo_count (float | None)

Return type:

BetaBinomialEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution for vectorized methods.

Return type:

BetaBinomialDataEncoder

class BetaBinomialEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate the bounded beta-binomial support {0, …, n} in descending probability order.

Unlike the binomial, the beta-binomial pmf is not always unimodal (it is U-shaped for a < 1, b < 1), so a two-pointer walk from a mode is not safe here; the finite support is materialized and sorted instead (the CategoricalEnumerator pattern), with value-order tie-breaks.

Parameters:

dist (BetaBinomialDistribution)

class BetaBinomialEstimator(n, pseudo_count=None, suff_stat=None, min_conc=1.0e-6, max_conc=1.0e8, name=None, keys=None)[source]

Bases: ParameterEstimator

Method-of-moments estimator for the beta-binomial shape parameters.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for beta-binomial moments.

Return type:

BetaBinomialAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate beta-binomial shape parameters from weighted moments.

Parameters:
Return type:

BetaBinomialDistribution

class BetaBinomialSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw counts as p ~ Beta(a, b) then k ~ Binomial(n, p).

Parameters:
  • dist (BetaBinomialDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one count or an array of iid counts.

Parameters:
Return type:

int | ndarray

class BinomialAccumulator(max_val=None, min_val=None, name=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted Binomial count, sum, and observed support bounds.

Parameters:
  • max_val (int | None)

  • min_val (int | None)

  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulates Binomial sufficient statistics for weighted single observation.

Add x*weight to attribute sum, and increase the count by weight.

Parameters:
  • x (int) – Data observed.

  • weight (float) – Weight for observation.

  • estimate (Optional[BinomialDistribution]) – Previous estimate of BinomialDistribution obtained from prior data.

Returns:

None (updates BinomialAccumulator sufficient statistics.)

Return type:

None

initialize(x, weight, rng)[source]

Initialize BinomialAccumulator sufficient statistics for one weighted observation.

Parameters:
  • x (int) – Data observed.

  • weight (float) – Weight for observation.

  • rng (Optional[RandomState]) – RandomState not needed. No randomness in initialization.

Returns:

None (updates BinomialAccumulator sufficient statistics.)

Return type:

None

seq_update(x, weights, estimate)[source]

Accumulates Binomial sufficient statistics for encoded sequence.

Parameters:
  • x (E) – Encoded sequence of observations.

  • weights (np.ndarray) – Numpy array of floats for weighting each observation.

  • estimate (Optional[BinomialDistribution]) – Previous estimate of BinomialDistribution obtained from prior data.:

Returns:

None

Return type:

None

seq_update_engine(x, weights, estimate, engine)[source]

Engine-resident accumulation of count/sum statistics (numpy or torch).

The weighted sum and count reductions run on the active engine; the scalar min/max support bounds remain host bookkeeping. Matches seq_update.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Vectorized initialization of BinomialAccumulator sufficient statistics with weights.

Calls seq_update().

Parameters:
  • x (E) – Encoded sequence of observations.

  • weights (np.ndarray) – Numpy array of floats for weighting each observation.

  • rng (Optional[RandomState]) – RandomState not needed. No randomness in initialization.

Returns:

None

Return type:

None

combine(suff_stat)[source]

Combine the sufficient statistics of BinomialAccumulator with suff_stat.

Parameters:

suff_stat (Tuple[float, float, Optional[int], Optional[int]]) – Count, sum of observations, optional min_val observed, and optional max_val observed.

Returns:

None

Return type:

BinomialAccumulator

value()[source]

Returns the sufficient statistics, and member variables min_val and max_val.

Returns:

Tuple[float,float, Optional[int], Optional[int]] containing suff stats count, sum and attributes min_val

max_val if they are not None.

Return type:

tuple[float, float, int | None, int | None]

from_value(x)[source]

Set BinomialAccumulator suff stats and member variables from suff_stat tuple defined in value().

Takes tuple of (count, sum, min_val, max_val) for setting values of BinomialAccumulator.

Parameters:

x (Tuple[float,float, Optional[int], Optional[int]]) – containing suff stats count, sum and attributes min_val max_val if they are not None.

Returns:

None, sets sufficient statistics and member variables.

Return type:

BinomialAccumulator

scale(c)[source]

Scale linear count/sum statistics while preserving support bounds.

Parameters:

c (float)

Return type:

BinomialAccumulator

acc_to_encoder()[source]

Create the encoder for binomial observations.

Note: Used for seq_initialize.

Returns:

BinomialDataEncoder()

Return type:

BinomialDataEncoder

class BinomialAccumulatorFactory(max_val=None, min_val=0, name=None, keys=None)[source]

Bases: StatisticAccumulatorFactory

Create Binomial accumulators with configured support-bound metadata.

Parameters:
  • max_val (int | None)

  • min_val (int | None)

  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh binomial accumulator.

Returns:

BinomialAccumulator.

Return type:

BinomialAccumulator

class BinomialDataEncoder(min_val=None, max_val=None)[source]

Bases: DataSequenceEncoder

Data encoder for iid integer binomial observations.

Parameters:
  • min_val (int | None)

  • max_val (int | None)

encoding_signature()[source]

The part of this encoder’s identity that determines the encoded column layout: none of it.

min_val/max_val are acceptance bounds – seq_encode() passes them to exact_integer_observations as minimum/maximum and nothing else. The columns it emits carry the observed range of the data itself, not the encoder’s bounds, so two BinomialDataEncoders differing only in bounds encode any mutually-acceptable data identically.

That distinction matters to consumers that hold an already-encoded batch and need to know whether a different encoder instance describes the same layout – the compiled fused-kernel path being the one in tree. Judging that by __eq__ rejected an ordinary EM step, because BinomialEstimator’s M-step re-derives (n, min_val) from the data and so legitimately produces an encoder with different bounds each iteration. __eq__ stays strict, since “same encoder” is a different (and still useful) question from “same encoding”.

Return type:

tuple

row_count(x)[source]

Return the number of observations represented by the indexed payload.

Parameters:

x (tuple[ndarray, ndarray, ndarray, int, int])

Return type:

int

seq_encode(x)[source]

Encode List[int] for vectorized seq calls in Accumulator and Distribution.

Parameters:

x (List[int]) – List of integers.

Returns:

Tuple[np.ndarray, np.ndarray, np.ndarray, int, int] containing unique values in x, indices of ux to

reconstruct x, numpy array of x, min value of x, and max value of x.

Return type:

tuple[ndarray, ndarray, ndarray, int, int]

class BinomialDistribution(p, n, min_val=None, name=None, keys=None, prior=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Binomial distribution over min_val + {0, ..., n} with success probability p.

Parameters:
  • p (float)

  • n (int)

  • min_val (int | None)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

classmethod compute_capabilities()[source]

Declare backend support for generated Binomial density kernels.

classmethod compute_declaration()[source]

Return the generated-compute declaration for the Binomial distribution.

static exp_family_sufficient_statistics(x, engine)[source]

Return Binomial sufficient statistics from encoded observations.

The parameter-dependent support shift is handled by exp_family_sufficient_statistics_from_params when generated scoring supplies the declaration-stacked parameter bundle.

Parameters:
Return type:

tuple[Any, …]

static exp_family_sufficient_statistics_from_params(x, params, engine)[source]

Return Binomial sufficient statistics for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return Binomial natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return Binomial log partition for generated scoring.

Parameters:
Return type:

Any

static exp_family_base_measure(x, engine)[source]

Return the observation-only Binomial base measure.

Parameters:
Return type:

Any

static exp_family_base_measure_from_params(x, params, engine)[source]

Return Binomial support/base measure for generated scoring.

Parameters:
Return type:

Any

set_prior(prior)[source]

Attach a Beta parameter prior and precompute conjugate-prior expectations.

With a Beta(a, b) prior on the success probability p this caches (E[log p], E[log(1-p)]) = (digamma(a) - digamma(a+b), digamma(b) - digamma(a+b)) so that expected_log_density evaluates the variational Bayes expectation E_q[log p(x | p)]. Any other prior (including None) leaves the distribution a plain point model.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

expected_log_density(x)[source]

Variational expectation E_q[log p(x | p)] under the Beta prior.

Uses the cached digamma expectations of log p and log(1-p); falls back to the plug-in log_density(x) when no conjugate prior is attached.

Parameters:

x (int)

Return type:

float

seq_expected_log_density(x)[source]

Vectorized expected_log_density over sequence-encoded observations.

Parameters:

x (tuple[ndarray, ndarray, ndarray, int, int])

Return type:

ndarray

density(x)[source]

Returns the probability mass of integer value x.

If x is not an integer between [0,n) or [min_val, n-1-min_val), density is 0.0.

Parameters:

x (int) – Integer value for density evaluation.

Returns:

Probability mass of x for binomial(n,p) with min_val=min_val. 0.0 if x is not in support.

Return type:

float

log_density(x)[source]

Returns the log-probability mass of integer value x.

If x is not an integer between [0,n) or [min_val, n-1-min_val), log-density is -inf.

Parameters:

x (int) – Integer value for density evaluation.

Returns:

Log-probability mass of x for binomial(n,p) with min_val=min_val. -inf if x is not in support.

Return type:

float

seq_log_density(x)[source]

Vectorized evaluation of log-density for sequence encoded data.

Input value x must be obtained from a call to BinomialDataEncoder.seq_encode(data). Returns numpy array of log-density evaluated at all observations contained in encoded data x.

Parameters:

x (Tuple[np.ndarray, np.ndarray, np.ndarray, int, int]) – containing unique values in x, indices of ux to reconstruct x, numpy array of x, min value of x, and max value of x.

Returns:

Numpy array of log-density evaluated at all observations contained in encoded data x.

Return type:

ndarray

static backend_log_density_from_params(vals, n, p, min_val, engine)[source]

Engine-neutral binomial log-density from explicit parameters.

Parameters:
Return type:

Any

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked binomial parameters for a homogeneous mixture kernel.

A stacked binomial mixture requires components to share the same trial count and shifted support. Mixtures with heterogeneous supports fall back to the generic kernel.

Parameters:
Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of binomial log densities.

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]

Return stacked Binomial sufficient statistics using estimator-owned support bounds.

Parameters:
Return type:

tuple[Any, Any, Any, Any]

support_size()[source]

n + 1 outcomes min_val + {0, ..., n}.

Return type:

int

to_fisher(**kwargs)[source]

Return the Binomial’s count-family Fisher view.

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

cdf(x)[source]

Cumulative distribution function P(X <= x) over min_val + {0..n}.

Parameters:

x (float)

Return type:

float

skewness()[source]

Skewness (1-2p)/sqrt(npq).

Return type:

float

kurtosis()[source]

Excess kurtosis (1-6pq)/(npq).

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q) over min_val + {0..n} (via scipy binom).

Parameters:

q (float)

Return type:

float

mode()[source]

Mode min_val + floor((n+1)p).

Return type:

float

sampler(seed=None)[source]

Returns BinomialSampler for generating samples from BinomialDistribution(n,p,min_val).

Parameters:
  • Optional[int] (seed) – Used to set seed on random number generator for sampling.

  • seed (int | None)

Returns:

BinomialSampler for BinomialDistribution with seed.

Return type:

BinomialSampler

estimator(pseudo_count=None)[source]

Creates a BinomialEstimator for estimating parameters of BinomialDistribution.

Parameters:

pseudo_count (Optional[float]) – If set, inflates counts for currently set sufficient statistic (p).

Returns:

BinomialEstimator object.

Return type:

BinomialEstimator

dist_to_encoder()[source]

Create the encoder for sequence-encoded binomial observations.

Returns:

BinomialDataEncoder object.

Return type:

BinomialDataEncoder

enumerator()[source]

Returns BinomialEnumerator iterating the support in descending probability order.

Return type:

BinomialEnumerator

quantized_index(max_bits, bin_width_bits=1.0)[source]

Build a bounded bit-quantized index by walking the binomial mode outward.

Parameters:
Return type:

QuantizedEnumerationIndex

quantized_multi_cross_index(others, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view over finite binomial supports.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

quantized_cross_index(other, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view over two binomial supports.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

class BinomialEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate bounded Binomial support values in descending probability order.

Parameters:

dist (BinomialDistribution)

class BinomialEstimator(max_val=None, min_val=0, pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]

Bases: ParameterEstimator

Estimate Binomial probability and support parameters from sufficient statistics.

Parameters:
  • max_val (int | None)

  • min_val (int | None)

  • pseudo_count (float | None)

  • suff_stat (float | None)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

accumulator_factory()[source]

Create a BinomialAccumulatorFactory from estimator member variables.

Returns:

BinomialAccumulatorFactory

Return type:

BinomialAccumulatorFactory

model_log_density(model)[source]

Log-density of the model’s success probability under the Beta prior (ELBO global term).

Parameters:

model (BinomialDistribution)

Return type:

float

estimate(nobs, suff_stat)[source]

Estimate a binomial distribution from accumulated sufficient statistics.

nobs is accepted for estimator API consistency but is not used. The sufficient statistic is (count, sum, min_val, max_val). When a prior statistic and pseudo_count are present, they shrink the empirical success probability toward the estimator’s prior probability.

Parameters:
class BinomialSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw independent samples from a BinomialDistribution.

Parameters:
  • dist (BinomialDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw samples from BinomialSampler.

Parameters:
  • size (Optional[int]) – Number of samples to draw from BinomialSampler (1 if size is None).

  • batched (bool)

Returns:

An integer sample from BinomialDistribution(n,p,min_val), or List[int] of samples with length = size.

Return type:

int | list[int]

class CategoricalAccumulator(keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulator for weighted categorical label counts.

Parameters:

keys (str | None)

update(x, weight, estimate)[source]

Adds weight to the category_count for category x.

If x is new Category label, a new key in the dict count_map is created and the count is incremented by weight.

Parameters:
  • x (Any) – Category label.

  • weight (float) – Weight for the observation x.

  • estimate (Optional['CategoricalDistribution']) – Kept for consistency with update method in SequenceEncodableStatisticAccumulator.

Returns:

None, updates sufficient_stat of Accumulator, count_map.

Return type:

None

initialize(x, weight, rng)[source]

Initializes the CategoricalAccumulator sufficient statistics one observation at a time.

This delegates to update(), since initialization has no random component.

Parameters:
  • x (Any) – Category label.

  • weight (float) – Weight incrementing suff stat count_map counts for the observation x.

  • rng (Optional[RandomState]) – Kept for consistency with update method in SequenceEncodableStatisticAccumulator.

Returns:

None, initializes sufficient_stat of Accumulator, count_map.

Return type:

None

get_seq_lambda()[source]

Return the sequence-update kernel used by generated accumulation code.

seq_update(x, weights, estimate)[source]

Vectorized accumulation of Categorical sufficient statistics from encoded sequence of data.

Requires data as encoded sequence from CategoricalDataEncoder.seq_encode(data).

Parameters:
  • x (Tuple[np.ndarray,np.ndarray]) – Tuple of numpy indices for unique categories, and numpy array unique objects that index xs maps to.

  • weights (np.ndarray) – weights for each observation in encoded data set.

  • estimate (Optional['CategoricalDistribution']) – Kept for consistency with update method in SequenceEncodableStatisticAccumulator.

Returns:

None

Return type:

None

seq_initialize(x, weights, rng)[source]

Vectorized initialization of Categorical sufficient statistics from encoded sequence of data.

Requires data as encoded sequence from CategoricalDataEncoder.seq_encode(data). This delegates to seq_update(), since initialization has no random component.

Parameters:
  • x (Tuple[np.ndarray,np.ndarray]) – Tuple of numpy indices for unique categories, and numpy array unique objects that index xs maps to.

  • weights (np.ndarray) – weights for each observation in encoded data set.

  • rng (Optional[RandomState]) – Kept for consistency with update method in SequenceEncodableStatisticAccumulator.

Returns:

None

Return type:

None

combine(suff_stat)[source]

Combine the sufficient statistics of CategoricalAccumulator with suff_stat.

Parameters:

suff_stat (Dict[Any, float]) – Prior data observations aggregated into dictionary with category levels as keys and counts as values.

Returns:

None, updates the count_map of CategoricalAccumulator.

Return type:

CategoricalAccumulator

value()[source]

Returns sufficient statistic of CategoricalAccumulator.

Sufficient statistic value is a dictionary with category as keys and counts of categories as values.

Returns:

Dict[Any, float] of sufficient statistic.

Return type:

dict[Any, float]

from_value(x)[source]

Set CategoricalAccumulator sufficient statistics and member variables from suff_stat dict defined in value().

Takes sufficient statistic value from dictionary with category as keys and counts of categories as values. Sets count_map to the passed value x.

Parameters:

x (Dict[Any, float]) – Dictionary with category as keys and counts of categories as values

Returns:

CategoricalAccumulator with member variable sufficient statistics set to x.

Return type:

CategoricalAccumulator

acc_to_encoder()[source]

Return an encoder compatible with categorical observations.

Return type:

CategoricalDataEncoder

class CategoricalAccumulatorFactory(keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for categorical count accumulators.

Parameters:

keys (str | None)

make()[source]

Return a fresh categorical accumulator.

Return type:

CategoricalAccumulator

class CategoricalDataEncoder[source]

Bases: DataSequenceEncoder

Sequence encoder for categorical observations used by vectorized seq_* methods.

seq_encode(x)[source]

Encode a list of category labels for vectorized seq_* methods.

Parameters:

x (List[Any]) – List of category labels.

Returns:

Tuple of integer category indices and the object array mapping those indices back to labels.

Return type:

tuple[ndarray, ndarray]

row_count(x)[source]

Return the observation count from the categorical index vector.

Parameters:

x (Any)

Return type:

int

class CategoricalDistribution(pmap=MISSING, default_value=0.0, name=None, keys=None, prob_map=MISSING, prior=None, scoring_only=False)[source]

Bases: SequenceEncodableProbabilityDistribution

Categorical distribution over hashable labels.

Parameters:
classmethod compute_capabilities()[source]

Return compute-backend metadata for categorical scoring.

classmethod compute_declaration()[source]

Return the symbolic declaration for categorical probability maps.

static exp_family_sufficient_statistics(x, engine)[source]

Return a shape-only fallback; category-aware statistics come from ..._from_params.

Parameters:
Return type:

tuple[Any, …]

static exp_family_sufficient_statistics_from_params(x, params, engine)[source]

Return the one-hot label indicator T(x) of shape (n, K) (zeros for off-support labels).

Categories are ordered canonically by sorted(pmap, key=repr) so the columns line up with exp_family_natural_parameters().

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return the natural parameter eta = log(pmap) over categories in canonical key order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the log partition A = 0 (normalization is carried by eta = log p).

Parameters:
Return type:

Any

static exp_family_base_measure_from_params(x, params, engine)[source]

Return log h(x) = 0 on the support (a key of pmap) and -inf for off-support labels.

Parameters:
Return type:

Any

get_prior()[source]

Return the conjugate parameter prior over the category-probability simplex (or None).

Return type:

SequenceEncodableProbabilityDistribution | None

set_prior(prior)[source]

Attach a parameter prior and precompute conjugate-prior expectations.

With a DictDirichlet(alpha) prior over the category probabilities this caches the variational expected log-probabilities E[log p_k] = digamma(alpha_k) - digamma(sum_k alpha_k) for each key of pmap so that expected_log_density(x) = E[log p_x] - log(1 + default_value). A scalar alpha is treated as a symmetric Dirichlet of dimension len(pmap). Any other prior (including None) leaves the distribution a plain point model.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

expected_log_density(x)[source]

Variational expectation E_q[log p(x)] under the DictDirichlet prior.

Falls back to the plug-in log_density(x) when no conjugate prior is attached.

Parameters:

x (Any)

Return type:

float

seq_expected_log_density(x)[source]

Vectorized expected_log_density over sequence-encoded observations.

Parameters:

x (tuple[ndarray, ndarray])

Return type:

ndarray

density(x)[source]

Density evaluation of CategoricalDistribution.

p_mat(x) = p_i, if x in pmap.keys(), else p_mat(x) = default_value.

With default_value > 0 and a pmap that does not cover the full label space, this is a smoothed scoring function, not a normalized probability measure – see the default_value note on __init__().

Parameters:

x (Any) – Evaluate CategoricalDistribution density value at x.

Returns:

float density value at x

Return type:

float

density_semantics()[source]

Report what log_density actually returns, derived from the parameters.

This keys off is_normalized_probability, so an object whose numbers do not describe a law does not claim to be one (MXR-080-1841). Three shapes report LIKELIHOOD_FACTOR:

  • scoring_only, the author’s declaration that this is an evaluation-only factor,

  • default_value != 0 open-world smoothing, which spreads mass over every unseen label and so has no finite total,

  • a pmap that does not sum to one – including the empty pmap, whose total is zero.

An earlier revision returned EXACT for the last two, because _owned_generative_components refuses LIKELIHOOD_FACTOR and mixtures, HMMs and segment models in this repository are all built from categoricals of exactly those shapes: a component that won zero responsibility this iteration, the explicit no-evidence state fitted on all-empty sequences, and deliberately unnormalized components. Labelling them honestly made them non-composable, so the label was bent instead. That was the wrong half to bend: composition inconvenience cannot turn a non-law into an exact law.

The composition layer now decides admissibility for itself, by asking a factor whether it differs from a law only by scale (see composable_as_component and _owned_generative_components), so both questions get a truthful answer.

composable_as_component()[source]

Whether a latent model may use this factor as a component (MXR-080-1841).

A mixture, HMM or segment model normalizes responsibilities across components, so a component that differs from a law by a positive constant scale is absorbed into its own mixing weight and leaves the E-step unchanged; a zero-mass component simply wins no responsibility. A categorical is a lookup over a discrete support, so an unnormalized or empty pmap is exactly such a scaled law and stays admissible.

scoring_only is not: it is an author’s declaration that the object is not generative at all, and a declaration is not something the composition layer may reason its way around.

Return type:

bool

log_density(x)[source]

Log-Density evaluation of CategoricalDistribution.

log(p_mat(x)) = log(p_i), if x in pmap.keys(), else log(p_mat(x)) = log(default_value).

With default_value > 0 and a pmap that does not cover the full label space, this is a smoothed scoring function, not a normalized probability measure – see the default_value note on __init__().

Parameters:

x (Any) – Evaluate CategoricalDistribution density value at x.

Returns:

Log-density of Categorical distribution evaluated at x.

Return type:

float

seq_log_density(x)[source]

Vectorized evaluation of log-density for sequence encoded data.

Input value x must be obtained from a call to CategoricalDataEncoder.seq_encode(data). Returns numpy array of log-density evaluated at all observations contained in encoded data x.

Parameters:

x (tuple[ndarray, ndarray]) – (Tuple[np.ndarray,np.ndarray]): Tuple of numpy indices for unique categories, and numpy array unique objects that index xs maps to.

Returns:

Numpy array of log-density evaluated at all observations contained in encoded data x.

Return type:

ndarray

backend_seq_log_density(x, engine)[source]

Engine-neutral log-density for encoded object categories.

The object-to-index lookup remains Python-side at the encoding boundary; the selected log-probability vector is an engine tensor, so simplex-map parameters can still participate in autograd.

Parameters:
Return type:

Any

gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]

Return distribution-owned state for autograd fitting.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked categorical probabilities for shared finite supports.

Parameters:
  • dists (Sequence[CategoricalDistribution])

  • engine (Any)

Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of categorical log densities.

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]

Return per-component legacy count maps from engine-resident posterior weights.

Parameters:
Return type:

tuple[dict[Any, float], …]

support_size()[source]

Number of categories in the support.

Return type:

int

to_fisher(**kwargs)[source]

Return the categorical’s one-hot Fisher view (generic fallback for default-augmented maps).

sampler(seed=None)[source]

Return a sampler for iid draws from this distribution.

Parameters:

seed (int | None) – Optional random seed.

Returns:

A configured CategoricalSampler.

Return type:

CategoricalSampler

estimator(pseudo_count=None)[source]

Return an estimator initialized from this distribution’s support.

Parameters:

pseudo_count (float | None) – Optional smoothing count applied to current probabilities.

Returns:

A CategoricalEstimator.

Return type:

CategoricalEstimator

dist_to_encoder()[source]

Return an encoder for categorical observations.

Return type:

CategoricalDataEncoder

enumerator()[source]

Return an enumerator over support labels in descending probability order.

Return type:

CategoricalEnumerator

quantized_index(max_bits, bin_width_bits=1.0)[source]

Build a bounded bit-quantized index directly from the finite support map.

Parameters:
Return type:

QuantizedEnumerationIndex

quantized_multi_cross_index(others, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view for finite categorical maps.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

quantized_cross_index(other, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view for two finite categorical maps.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

class CategoricalEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerator over finite categorical support in descending probability order.

Parameters:

dist (CategoricalDistribution)

class CategoricalEstimator(pseudo_count=None, suff_stat=None, default_value=False, name=None, keys=None, prior=None)[source]

Bases: ParameterEstimator

Estimator for categorical probability maps from weighted label counts.

Parameters:
  • pseudo_count (float | None)

  • suff_stat (dict[Any, float] | None)

  • default_value (bool)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

get_prior()[source]

Return the conjugate parameter prior over the category-probability simplex (or None).

Return type:

SequenceEncodableProbabilityDistribution | None

set_prior(prior)[source]

Set the conjugate parameter prior over the category-probability simplex.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

model_log_density(model)[source]

Log-density of the model probability map under the DictDirichlet prior (ELBO global term).

Parameters:

model (CategoricalDistribution)

Return type:

float

accumulator_factory()[source]

Return an accumulator factory matching this estimator.

Return type:

CategoricalAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a CategoricalDistribution from suff_stat value.

If default_value is True, we estimate a default value from the suff_stat counts. Else, it is set to 0.0.

pseudo_count is used to averaged over the number of levels and added to the corresponding counts.

If suff_stat member value is None, estimate for CategoricalDistribution is formed from the suff_stat passed. Otherwise, the suff_stat member value is combined with the suff_stat values passed to estimate.

Parameters:
  • nobs (Optional[float]) – Not used. Kept for consistency with ParameterEstimator.estimate.

  • suff_stat (Dict[Any, float]) – Dict with categories as keys and counts as values from accumulated data.

Returns:

CategoricalDistribution estimated from passed in suff_stat value and sufficient statistic member variable

(if it is not None).

Return type:

CategoricalDistribution

class CategoricalFisherView(dist, keys, probs)[source]

Bases: FixedFisherView

Fisher view for categorical one-hot sufficient statistics.

Parameters:
class CategoricalSampler(dist, seed=None)[source]

Bases: DistributionSampler

Sampler for categorical labels according to the configured probability map.

Parameters:
  • dist (CategoricalDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw iid samples from the categorical distribution.

Parameters:
  • size (int | None) – Number of iid samples to draw. None returns a scalar label. Must be an exact non-negative integer – int() would have read True as one draw, truncated 2.7 to two, and turned a negative count into an empty “successful” sample, which is the contract BackoffSampler.sample already enforces (MXR-080-1845/1904).

  • batched (bool) – Whether to draw the whole batch in one vectorized call (the default) or one draw at a time. Both yield iid samples from the same law and differ only in how the random stream is consumed, so a fixed seed gives different – individually valid – sequences. This argument was previously declared and then ignored entirely: passing batched=False did nothing at all and silently returned the batched result (MXR-080-1904).

Returns:

A scalar label when size is None; otherwise a list of labels.

Return type:

Any | list[Any]

class GeometricAccumulator(name=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted count and sum statistics for Geometric estimation.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Update sufficient statistics for GeometricAccumulator with one weighted observation.

Parameters:
  • x (int) – Positive integer observation of geometric distribution.

  • weight (float) – Weight for observation.

  • estimate (Optional[GeometricDistribution]) – Kept for consistency with SequenceEncodableStatisticAccumulator.

Returns:

None

Return type:

None

seq_update(x, weights, estimate)[source]

Vectorized update of sufficient statistics from encoded sequence x.

sum increased by sum of weighted observations. count increased by sum of weights.

Parameters:
  • x (ndarray) – Numpy array of positive integers.

  • weights (ndarray) – Numpy array of positive floats.

  • estimate (Optional[GeometricDistribution]) – Kept for consistency with SequenceEncodableStatisticAccumulator.

Returns:

None.

Return type:

None

initialize(x, weight, rng)[source]

Initialize sufficient statistics of GeometricAccumulator with weighted observation.

This delegates to update().

Parameters:
  • x (int) – Positive integer observation of geometric distribution.

  • weight (float) – Positive real-valued weight for observation x.

  • rng (Optional[RandomState]) – Kept for consistency with SequenceEncodableStatisticAccumulator.

Returns:

None.

Return type:

None

seq_initialize(x, weights, rng)[source]

Vectorized initialization of GeometricAccumulator sufficient statistics with weighted observations.

This delegates to seq_update().

Parameters:
  • x (ndarray) – Numpy array of positive integers.

  • weights (ndarray) – Numpy array of positive floats.

  • rng (Optional[RandomState]) – Kept for consistency with SequenceEncodableStatisticAccumulator.

Returns:

None.

Return type:

None

combine(suff_stat)[source]

Combine aggregated sufficient statistics with sufficient statistics of GeometricAccumulator instance.

Input suff_stat is Tuple[float, float] with:

suff_stat[0] (float): sum of observation weights, suff_stat[1] (float): weighted sum of observations.

Parameters:

suff_stat (Tuple[float, float]) – See above for details.

Returns:

GeometricAccumulator object.

Return type:

GeometricAccumulator

value()[source]

Returns sufficient statistics Tuple[float, float] of GeometricAccumulator instance.

Return type:

tuple[float, float]

from_value(x)[source]

Sets GeometricAccumulator instance sufficient statistic member variables to x.

Parameters:

x (Tuple[float, float]) – Sum of observations weights and sum of weighted observations.

Returns:

GeometricAccumulator object.

Return type:

GeometricAccumulator

acc_to_encoder()[source]

Return the encoder associated with this accumulator.

Return type:

GeometricDataEncoder

class GeometricAccumulatorFactory(name=None, keys=None)[source]

Bases: StatisticAccumulatorFactory

Create Geometric accumulators with shared name and merge-key metadata.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Return GeometricAccumulator with name and keys passed.

Return type:

GeometricAccumulator

class GeometricDataEncoder[source]

Bases: DataSequenceEncoder

Data encoder for iid positive-integer geometric observations.

seq_encode(x)[source]

Encode iid sequence of geometric observations for vectorized seq_ function calls.

Note: x should be list of numpy array of positive integers.

Parameters:

x (Union[Sequence[int], np.ndarray]) – Positive integer geometric observations.

Returns:

Numpy array of positive integers.

Return type:

ndarray

class GeometricDistribution(p, name=None, keys=None, prior=None)[source]

Bases: CachedParameterLaw, SequenceEncodableProbabilityDistribution

Geometric distribution on {1, 2, ...} with success probability p.

Parameters:
  • p (float)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

classmethod compute_capabilities()[source]

Declare backend support for generated Geometric density kernels.

classmethod compute_declaration()[source]

Return the generated-compute declaration for the Geometric distribution.

static exp_family_legacy_sufficient_statistics(x, params, engine)[source]

Return per-row Geometric sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_sufficient_statistics(x, engine)[source]

Return Geometric sufficient statistic T(x) = (x,) (support x = 1, 2, …).

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return Geometric natural parameter eta = log(1 - p).

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return Geometric log partition A = log(1 - p) - log(p).

Parameters:
Return type:

Any

static exp_family_from_natural(eta)[source]

Return the Geometric with natural parameter eta = log(1 - p).

Parameters:

eta (Any)

Return type:

GeometricDistribution

set_prior(prior)[source]

Attach a Beta parameter prior and precompute conjugate-prior expectations.

With a Beta(a, b) prior on the success probability p this caches the digamma terms (digamma(a), digamma(b), digamma(a+b)) so that expected_log_density evaluates the variational Bayes expectation E_q[log p(x | p)] via E[log p] = digamma(a) - digamma(a+b) and E[log(1-p)] = digamma(b) - digamma(a+b). Any other prior (including None) leaves the distribution a plain point model.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

expected_log_density(x)[source]

Variational expectation E_q[log p(x | p)] under the Beta prior.

Uses the cached digamma expectations of log p and log(1-p); falls back to the plug-in log_density(x) when no conjugate prior is attached.

Parameters:

x (int)

Return type:

float

seq_expected_log_density(x)[source]

Vectorized expected_log_density over sequence-encoded observations.

Parameters:

x (ndarray)

Return type:

ndarray

density(x)[source]

Density of geometric distribution evaluated at x.

P(x=k) = (k-1)*log(1-p) + log(p), for x = 1,2,…, else 0.0.

Parameters:

x (int) – Observed geometric value (1,2,3,….).

Returns:

Density of geometric distribution evaluated at x.

Return type:

float

log_density(x)[source]

Log-density of geometric distribution evaluated at x.

See density() for details.

Parameters:

x (int) – Must be natural number (1,2,3,….).

Returns:

Log-density of geometric distribution evaluated at x.

Return type:

float

seq_log_density(x)[source]

Vectorized log-density evaluated on sequence encoded x.

Parameters:

x (int) – Numpy array of non-negative integers.

Returns:

Numpy array of log-density evaluated at each encoded observation value x.

Return type:

ndarray

static backend_log_density_from_params(x, p, engine)[source]

Engine-neutral geometric log-density from explicit parameters.

Parameters:
Return type:

Any

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked geometric parameters for a homogeneous mixture kernel.

Parameters:
Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of geometric log densities.

Parameters:
Return type:

Any

to_fisher(**kwargs)[source]

Return the Geometric’s count-family Fisher view.

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

cdf(x)[source]

Cumulative distribution function P(X <= x) = 1 - (1-p)^floor(x), support x >= 1.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q), support >= 1 (via scipy geom).

Parameters:

q (float)

Return type:

float

entropy()[source]

Shannon entropy (-(1-p) log(1-p) - p log p) / p (nats).

Return type:

float

mode()[source]

Mode (1 – the minimum of the decreasing pmf).

Return type:

float

sampler(seed=None)[source]

Create a sampler from this geometric distribution.

Parameters:

seed (Optional[int]) – Used to set seed on random number generator.

Returns:

GeometricSampler configured from this distribution.

Return type:

GeometricSampler

estimator(pseudo_count=None)[source]

Create an estimator for a geometric distribution.

Parameters:

pseudo_count (Optional[float]) – Regularize empirical summary statistics.

Returns:

GeometricEstimator configured with this distribution’s prior and name.

Return type:

GeometricEstimator

dist_to_encoder()[source]

Return the encoder for geometric observations.

Return type:

GeometricDataEncoder

enumerator()[source]

Returns GeometricEnumerator iterating the support {1, 2, …} in descending probability order.

Return type:

GeometricEnumerator

quantized_index(max_bits, bin_width_bits=1.0)[source]

Build a bounded bit-quantized index directly from the geometric tail formula.

Parameters:
Return type:

QuantizedEnumerationIndex

quantized_multi_cross_index(others, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view over bounded geometric prefixes.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

quantized_cross_index(other, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view over two bounded geometric prefixes.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

class GeometricEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate geometric support values in descending probability order.

Parameters:

dist (GeometricDistribution)

class GeometricEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]

Bases: ParameterEstimator

Estimate Geometric success probabilities from accumulated sufficient statistics.

Parameters:
  • pseudo_count (float | None)

  • suff_stat (float | None)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

accumulator_factory()[source]

Create a geometric accumulator factory with this estimator’s name and keys.

Return type:

GeometricAccumulatorFactory

model_log_density(model)[source]

Log-density of the model’s success probability under the Beta prior (ELBO global term).

Parameters:

model (GeometricDistribution)

Return type:

float

estimate(nobs, suff_stat)[source]

Estimate a geometric distribution from weighted count and sum statistics.

nobs is accepted for estimator API consistency but is not used. suff_stat is (count, sum). Without a pseudo-count, the estimate is p = count / sum; with a pseudo-count, the empirical statistic is shrunk toward the estimator’s prior statistic when available.

Parameters:
Return type:

GeometricDistribution

class GeometricSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw independent samples from a GeometricDistribution.

Parameters:
  • dist (GeometricDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Generate iid samples from geometric distribution.

Generates a single geometric sample (int) if size is None, else a numpy array of integers of length size, iid samples, from the geometric distribution.

Parameters:
  • size (Optional[int]) – Number of iid samples to draw. If None, assumed to be 1.

  • batched (bool)

Returns:

If size is None, int, else size length numpy array of ints.

Return type:

int | ndarray

class IntegerCategoricalAccumulator(min_val=None, max_val=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulator for weighted counts over a bounded integer support.

Parameters:
  • min_val (int | None)

  • max_val (int | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Update sufficient statistics with one weighted observation.

If the observed value falls outside the current support, the count vector is expanded and existing counts are realigned.

Parameters:
  • x (int) – Integer observation.

  • weight (float) – Observation weight.

  • estimate (IntegerCategoricalDistribution | None) – Accepted for accumulator API consistency.

Return type:

None

initialize(x, weight, rng)[source]

Initialize sufficient statistics with one weighted observation.

Parameters:
  • x (int) – Integer observation.

  • weight (float) – Observation weight.

  • rng (RandomState) – Accepted for accumulator API consistency.

Returns:

None.

Return type:

None

seq_initialize(x, weights, rng)[source]

Vectorized initialization of IntegerCategoricalAccumulator sufficient statistics with weighted observations.

This delegates to seq_update().

Parameters:
  • x (np.ndarray[int]) – Sequence encoded iid observations of integer categorical distribution.

  • weights (ndarray) – Numpy array of positive floats.

  • rng (Optional[RandomState]) – Kept for consistency with SequenceEncodableStatisticAccumulator.

Returns:

None.

Return type:

None

seq_update(x, weights, estimate)[source]
Vectorized update of IntegerCategoricalAccumulator sufficient statistics with sequence encoded iid

observations x.

Note: Determines the range (support) of integer categorical from the sequence encoded data.

Parameters:
  • x (np.ndarray[int]) – Sequence encoded iid observations of integer categorical distribution.

  • weights (ndarray) – Numpy array of positive floats.

  • estimate (Optional[IntegerCategoricalDistribution]) – Previous estimate of IntegerCategoricalDistribution.

Returns:

None.

Return type:

None

seq_update_engine(x, weights, estimate, engine)[source]

Engine-resident accumulation: the weighted value histogram is reduced on the active engine (numpy or torch); the dynamic support range is host bookkeeping. Matches seq_update.

Parameters:
  • x (ndarray)

  • weights (Any)

  • estimate (IntegerCategoricalDistribution | None)

  • engine (Any)

Return type:

None

combine(suff_stat)[source]

Merge another (min_val, count_vec) sufficient statistic.

Supports are aligned before counts are added, so accumulators built on different observed ranges can be combined safely.

Parameters:

suff_stat (tuple[int | None, ndarray | None])

Return type:

IntegerCategoricalAccumulator

value()[source]

Return (min_val, count_vec) sufficient statistics.

Return type:

tuple[int, ndarray]

from_value(x)[source]

Replace accumulator state from a (min_val, count_vec) statistic.

Parameters:

x (tuple[int, ndarray])

Return type:

IntegerCategoricalAccumulator

scale(c)[source]

Scale count vector while preserving integer support metadata.

Parameters:

c (float)

Return type:

IntegerCategoricalAccumulator

acc_to_encoder()[source]

Return the encoder associated with this accumulator.

Return type:

IntegerCategoricalDataEncoder

class IntegerCategoricalAccumulatorFactory(min_val=None, max_val=None, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for integer-categorical count accumulators.

Parameters:
  • min_val (int | None)

  • max_val (int | None)

  • keys (str | None)

make()[source]

Return a fresh integer categorical accumulator with this factory’s bounds and keys.

Return type:

IntegerCategoricalAccumulator

class IntegerCategoricalDataEncoder[source]

Bases: DataSequenceEncoder

Data encoder for iid integer-categorical observations.

seq_encode(x)[source]

Sequence encode iid integer categorical observations for seq_ functions.

Parameters:

x (Union[List[int], np.ndarray]) – Assumed int observations of integer categorical.

Returns:

Numpy array of integers.

Return type:

ndarray

class IntegerCategoricalDistribution(min_val, p_vec=MISSING, name=None, keys=None, prob_vec=MISSING, prior=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Categorical distribution over a bounded integer range.

Parameters:
classmethod compute_capabilities()[source]

Return compute-backend metadata for integer-categorical scoring.

classmethod compute_declaration()[source]

Return the symbolic declaration for bounded integer-categorical probabilities.

static exp_family_sufficient_statistics(x, engine)[source]

Return raw values; category-aware one-hot statistics come from ..._from_params.

Parameters:
Return type:

tuple[Any, …]

static exp_family_sufficient_statistics_from_params(x, params, engine)[source]

Return the one-hot category indicator T(x) of shape (n, K) (zeros off support).

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return the natural parameter eta = log(p_vec) (one entry per category).

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the log partition A = 0 (normalization is carried by eta = log p).

Parameters:
Return type:

Any

static exp_family_base_measure_from_params(x, params, engine)[source]

Return log h(x) = 0 on the support [min_val, min_val+K) and -inf outside it.

Parameters:
Return type:

Any

get_parameters()[source]

Return the probability vector p_vec (lets it be scored by a Dirichlet conjugate prior).

Return type:

ndarray

get_prior()[source]

Return the conjugate parameter prior over the probability vector (or None).

Return type:

SequenceEncodableProbabilityDistribution | None

set_prior(prior)[source]

Attach a parameter prior and precompute conjugate-prior expectations.

With a Dirichlet(alpha) (or SymmetricDirichlet(alpha)) prior over the probability vector this caches the variational expected log-probabilities E[log p_k] = digamma(alpha_k) - digamma(sum_k alpha_k) so that expected_log_density(x) = E[log p_{x - min_val}]. Any other prior (including None) leaves the distribution a plain point model.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

expected_log_density(x)[source]

Variational expectation E_q[log p(x)] under the (symmetric) Dirichlet prior.

Falls back to the plug-in log_density(x) when no conjugate prior is attached.

Parameters:

x (int)

Return type:

float

seq_expected_log_density(x)[source]

Vectorized expected_log_density over sequence-encoded observations.

Parameters:

x (ndarray)

Return type:

ndarray

density(x)[source]

Evaluate the density of the integer categorical at observation x.

p_mat(x_mat=x) = p_vec[x] if x in support [min_val, max_val], else 0.0.

Parameters:

x (int) – Integer value.

Returns:

Density at x.

Return type:

float

log_density(x)[source]

Evaluate the log-density of the integer categorical at observation x.

log_p(x_mat=x) = log_p_vec[x] if x in support [min_val, max_val], else -np.inf.

Parameters:

x (int) – Integer value.

Returns:

Log-density at x.

Return type:

float

seq_log_density(x)[source]

Vectorized evaluation of IntegerCategorical log_density() for sequence encoded iid observations x.

Parameters:

x (np.ndarray[int]) – Sequence encoded iid observation of integer categorical distribution.

Returns:

Numpy array of floats containing log_density() evaluated at each observation in x.

Return type:

ndarray

static backend_log_density_from_params(x, min_val, log_p_vec, engine)[source]

Engine-neutral integer-categorical log-density from explicit parameters.

Parameters:
Return type:

Any

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked integer-categorical parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[IntegerCategoricalDistribution])

  • engine (Any)

Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of integer-categorical log densities.

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]

Return component-stacked legacy (min_val, count_vec) statistics.

Parameters:
Return type:

tuple[Any, Any]

support_size()[source]

Number of integer values in the range.

Return type:

int

to_fisher(**kwargs)[source]

Return the integer-categorical one-hot Fisher view.

sampler(seed=None)[source]

Return a sampler for iid draws from this distribution.

Parameters:

seed (int | None) – Optional random seed.

Return type:

IntegerCategoricalSampler

estimator(pseudo_count=None)[source]

Return an estimator initialized from this distribution.

When pseudo_count is provided, the distribution’s probabilities are used as prior sufficient statistics during estimation.

Parameters:

pseudo_count (float | None) – Weight assigned to the distribution’s current probability vector during estimation.

Return type:

IntegerCategoricalEstimator

dist_to_encoder()[source]

Return the encoder for iid integer categorical observations.

Return type:

IntegerCategoricalDataEncoder

enumerator()[source]

Return IntegerCategoricalEnumerator iterating the support in descending probability order.

Return type:

IntegerCategoricalEnumerator

quantized_index(max_bits, bin_width_bits=1.0)[source]

Build a bounded bit-quantized index directly from the finite integer support.

Parameters:
Return type:

QuantizedEnumerationIndex

quantized_multi_cross_index(others, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view over integer categorical ranges.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

quantized_cross_index(other, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view over two integer categorical ranges.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

class IntegerCategoricalEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerator over bounded integer support in descending probability order.

Parameters:

dist (IntegerCategoricalDistribution)

class IntegerCategoricalEstimator(min_val=None, max_val=None, pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]

Bases: ParameterEstimator

Estimator for bounded integer-categorical probability vectors.

Parameters:
  • min_val (int | None)

  • max_val (int | None)

  • pseudo_count (float | None)

  • suff_stat (tuple[int, ndarray] | None)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

get_prior()[source]

Return the conjugate parameter prior over the probability vector (or None).

Return type:

SequenceEncodableProbabilityDistribution | None

set_prior(prior)[source]

Set the conjugate parameter prior over the probability vector.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

model_log_density(model)[source]

Log-density of the model probability vector under the (symmetric) Dirichlet prior.

Parameters:

model (IntegerCategoricalDistribution)

Return type:

float

accumulator_factory()[source]

Return an accumulator factory configured from this estimator’s support and keys.

Note: If min_val and max_val are BOTH not None, these values are passed to IntegerCategoricalAccumulatorFactory. Else, they are obtained from member variable suff_stat. One of these conditions must be satisfied.

Returns:

Return type:

IntegerCategoricalAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate an integer-categorical distribution from weighted counts.

nobs is accepted for estimator API consistency but is not used. suff_stat is (min_val, count_vec). When pseudo_count and a prior statistic are present, the estimate combines observed counts with the weighted prior probability vector.

Parameters:
Return type:

IntegerCategoricalDistribution

class IntegerCategoricalFisherView(dist)[source]

Bases: CategoricalFisherView

Fisher view for bounded integer-categorical one-hot statistics.

Parameters:

dist (Any)

class IntegerCategoricalSampler(dist, seed=None)[source]

Bases: DistributionSampler

Sampler for bounded integer-categorical values.

Parameters:
  • dist (IntegerCategoricalDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw iid samples from the integer-categorical distribution.

Parameters:
  • size (int | None) – Number of samples. None returns one integer; a positive value returns a list of that length.

  • batched (bool)

Return type:

int | list[int]

class IntegerUniformSpikeAccumulator(min_val, max_val, keys=None, name=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulator for weighted integer counts over a growing range.

Parameters:
  • min_val (int | None)

  • max_val (int | None)

  • keys (str | None)

  • name (str | None)

min_val

Smallest integer observed (or configured) so far.

Type:

Optional[int]

max_val

Largest integer observed (or configured) so far.

Type:

Optional[int]

count_vec

Weighted counts for each integer in [min_val, max_val].

Type:

Optional[np.ndarray]

count

Total weighted observation count.

Type:

float

key

Key for merging sufficient statistics across accumulators.

Type:

Optional[str]

name

Optional accumulator name.

Type:

Optional[str]

update(x, weight, estimate)[source]

Add weight to the count for integer x, growing the count vector if x is out of range.

Parameters:
  • x (int) – Integer observation.

  • weight (float) – Weight on the observation.

  • estimate (Optional[IntegerUniformSpikeDistribution]) – Unused previous estimate.

Return type:

None

initialize(x, weight, rng)[source]

Initialize the accumulator with observation x and weight (delegates to update).

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Vectorized initialization from encoded observations x (delegates to seq_update).

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Vectorized accumulation of weighted counts from encoded observations x.

Parameters:
  • x (np.ndarray) – Sequence encoded integer observations.

  • weights (np.ndarray) – Weights on the observations.

  • estimate (Optional[IntegerUniformSpikeDistribution]) – Unused previous estimate.

Return type:

None

seq_update_engine(x, weights, estimate, engine)[source]

Engine-resident accumulation: the weighted value histogram is reduced on the active engine (numpy or torch); the dynamic support range is host bookkeeping. Matches seq_update.

Parameters:
  • x (ndarray)

  • weights (Any)

  • estimate (IntegerUniformSpikeDistribution | None)

  • engine (Any)

Return type:

None

combine(suff_stat)[source]

Combine sufficient statistics (min_val, count_vec) with this accumulator, aligning ranges.

Parameters:

suff_stat (Tuple[int, np.ndarray]) – Minimum value and count vector of another accumulator.

Returns:

This IntegerUniformSpikeAccumulator.

Return type:

IntegerUniformSpikeAccumulator

value()[source]

Returns sufficient statistics as a tuple (min_val, count_vec).

Return type:

tuple[int, ndarray]

from_value(x)[source]

Set sufficient statistics from a (min_val, count_vec) tuple.

Parameters:

x (Tuple[int, np.ndarray]) – Minimum value and count vector.

Returns:

This IntegerUniformSpikeAccumulator.

Return type:

IntegerUniformSpikeAccumulator

scale(c)[source]

Scale linear counts while preserving the integer support offset.

Parameters:

c (float)

Return type:

IntegerUniformSpikeAccumulator

acc_to_encoder()[source]

Returns an IntegerUniformSpikeDataEncoder for encoding sequences of iid integer observations.

Return type:

IntegerUniformSpikeDataEncoder

class IntegerUniformSpikeAccumulatorFactory(min_val=None, max_val=None, keys=None, name=None)[source]

Bases: StatisticAccumulatorFactory

Factory for integer-uniform-spike accumulators.

Parameters:
  • min_val (Optional[int]) – Smallest integer value in the range, if known.

  • max_val (Optional[int]) – Largest integer value in the range, if known.

  • keys (Optional[str]) – Set key for merging sufficient statistics.

  • name (Optional[str]) – Optional name assigned to created accumulators.

min_val

Smallest integer value in the range, if known.

Type:

Optional[int]

max_val

Largest integer value in the range, if known.

Type:

Optional[int]

keys

Key for merging sufficient statistics.

Type:

Optional[str]

name

Optional name assigned to created accumulators.

Type:

Optional[str]

make()[source]

Return a fresh integer-uniform-spike accumulator.

Return type:

IntegerUniformSpikeAccumulator

class IntegerUniformSpikeDataEncoder[source]

Bases: DataSequenceEncoder

Data encoder for iid integer-uniform-spike observations.

seq_encode(x)[source]

Encode a sequence of iid integer observations as a numpy integer array.

Parameters:

x (Union[List[int], np.ndarray]) – Sequence of iid integer observations.

Returns:

Numpy array of ints.

Return type:

ndarray

class IntegerUniformSpikeDistribution(k, num_vals, p, min_val=0, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Uniform integer distribution with extra probability mass at one value.

Parameters:
classmethod compute_capabilities()[source]

Declare backend support for integer-uniform-spike generated kernels.

classmethod compute_declaration()[source]

Return the generated-compute declaration for the integer uniform spike.

density(x)[source]

Density of the integer uniform spike distribution at observation x.

See log_density() for details.

Parameters:

x (int) – Integer observation.

Returns:

Density at x.

Return type:

float

log_density(x)[source]

Log-density of the integer uniform spike distribution at observation x.

Returns log(p) if x equals the spike value k, log((1-p)/(num_vals-1)) for any other integer in [min_val, max_val], and -inf outside the range.

Parameters:

x (int) – Integer observation.

Returns:

Log-density at observation x.

Return type:

float

seq_log_density(x)[source]

Vectorized evaluation of log-density at sequence encoded input x.

Parameters:

x (np.ndarray) – Numpy array of integer observations.

Returns:

Numpy array of log-density (float) of len(x).

Return type:

ndarray

backend_seq_log_density(x, engine)[source]

Engine-neutral log-density for encoded integer spike observations.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked integer-uniform-spike parameters for a shared support.

Parameters:
  • dists (list[IntegerUniformSpikeDistribution])

  • engine (Any)

Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of integer-uniform-spike log densities.

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]

Return component-stacked legacy (min_val, count_vec) statistics.

Parameters:
Return type:

tuple[Any, Any]

sampler(seed=None)[source]

Create an IntegerUniformSpikeSampler from parameters of this distribution.

Parameters:

seed (Optional[int]) – Used to set seed in random sampler.

Returns:

IntegerUniformSpikeSampler object.

Return type:

IntegerUniformSpikeSampler

estimator(pseudo_count=None)[source]

Create an IntegerUniformSpikeEstimator for the current integer range.

Parameters:

pseudo_count (Optional[float]) – Used to inflate sufficient statistics.

Returns:

IntegerUniformSpikeEstimator object.

Return type:

IntegerUniformSpikeEstimator

dist_to_encoder()[source]

Returns an IntegerUniformSpikeDataEncoder for encoding sequences of iid integer observations.

Return type:

IntegerUniformSpikeDataEncoder

enumerator()[source]

Returns an IntegerUniformSpikeEnumerator iterating the support in descending probability order.

Return type:

IntegerUniformSpikeEnumerator

quantized_index(max_bits, bin_width_bits=1.0)[source]

Build a bounded bit-quantized index directly from the finite integer support.

Parameters:
Return type:

QuantizedEnumerationIndex

quantized_multi_cross_index(others, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view over finite integer spike supports.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

quantized_cross_index(other, max_bits, bin_width_bits=1.0)[source]

Build an exact aligned cross-bin view over two integer spike supports.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

class IntegerUniformSpikeEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerates the support [min_val, max_val] in descending probability order.

The spike value k is yielded first when p >= (1-p)/(num_vals-1), otherwise last; the remaining values share the same probability and are yielded in ascending integer order. Zero-probability values are skipped.

Parameters:

dist (IntegerUniformSpikeDistribution)

class IntegerUniformSpikeEstimator(min_val=None, max_val=None, pseudo_count=None, suff_stat=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Estimator for integer-uniform-spike distributions from weighted counts.

Parameters:
  • min_val (int | None)

  • max_val (int | None)

  • pseudo_count (float | None)

  • suff_stat (tuple[int, float | None] | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Returns an IntegerUniformSpikeAccumulatorFactory consistent with this estimator.

Return type:

IntegerUniformSpikeAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate an IntegerUniformSpikeDistribution by maximizing the spike location and weight.

The spike location k is chosen to maximize the likelihood of the accumulated counts (with optional pseudo_count regularization from the estimator configuration).

Parameters:
  • nobs (Optional[float]) – Weighted number of observations.

  • suff_stat (Tuple[int, np.ndarray]) – Minimum value and count vector.

Returns:

IntegerUniformSpikeDistribution object.

Return type:

IntegerUniformSpikeDistribution

class IntegerUniformSpikeSampler(dist, seed=None)[source]

Bases: DistributionSampler

Sampler for an integer-uniform-spike distribution.

Parameters:
  • dist (IntegerUniformSpikeDistribution)

  • seed (int | None)

dist

Distribution to sample from.

Type:

IntegerUniformSpikeDistribution

rng

Seeded RandomState for sampling.

Type:

RandomState

non_k

Integers of the support excluding the spike value k.

Type:

np.ndarray

sample(size=None, *, batched=True)[source]

Draw iid samples from the integer uniform spike distribution.

Parameters:
  • size (Optional[int]) – Number of iid samples to draw.

  • batched (bool)

Returns:

A single int if size is None, else a numpy array of ints with length size.

Return type:

int | ndarray

class LogSeriesAccumulator(keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted count and sum for log-series estimation.

Parameters:

keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted count and total for one positive integer.

Parameters:
  • x (int)

  • weight (float)

  • estimate (LogSeriesDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate weighted count and total from encoded observations.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded observations.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge another log-series sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float])

Return type:

LogSeriesAccumulator

value()[source]

Return accumulated count and integer total.

Return type:

tuple[float, float]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

x (tuple[float, float])

Return type:

LogSeriesAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

LogSeriesDataEncoder

class LogSeriesAccumulatorFactory(keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for LogSeriesAccumulator.

Parameters:

keys (str | None)

make()[source]

Create a fresh log-series accumulator.

Return type:

LogSeriesAccumulator

class LogSeriesDataEncoder[source]

Bases: DataSequenceEncoder

Encode log-series observations as (k, log k) pairs.

seq_encode(x)[source]

Encode observations as integer values and log-values.

Parameters:

x (Sequence[int])

Return type:

tuple[ndarray, ndarray]

class LogSeriesDistribution(p, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Logarithmic (log-series) distribution on k = 1, 2, … with shape parameter p in (0, 1).

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated log-series kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for log-series distributions.

static backend_legacy_sufficient_statistics(x, params, engine)[source]

Return per-row (count, k) sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_sufficient_statistics(x, engine)[source]

Return the log-series sufficient statistic T(k) = (k,).

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return the log-series natural parameter eta = log(p).

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the log-series log partition A = log(-log(1 - p)).

Parameters:
Return type:

Any

static exp_family_base_measure(x, engine)[source]

Return the log-series base measure log h(k) = -log(k) (independent of p, fixed base).

Parameters:
Return type:

Any

static exp_family_from_natural(eta)[source]

Return the log-series with natural parameter eta = log(p) (so p = exp(eta)).

Parameters:

eta (Any)

Return type:

LogSeriesDistribution

static backend_log_density_from_params(k, log_k, log_p, log_norm, engine)[source]

Engine-neutral log-series log-mass from explicit parameters (linear in k and log k).

Parameters:
Return type:

Any

density(x)[source]

Return the probability mass at a single observation.

Parameters:

x (int)

Return type:

float

log_density(x)[source]

Return the log-mass at a single positive integer (or -inf off support).

Parameters:

x (int)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-mass values for sequence-encoded (k, log k) observations.

Parameters:

x (tuple[ndarray, ndarray])

Return type:

ndarray

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-mass for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked parameters for a homogeneous mixture kernel.

Parameters:
Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of log-series log densities.

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]

Return stacked sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any]

mean()[source]

Mean E[X] = -p / ((1-p) log(1-p)).

Return type:

float

variance()[source]

Variance Var[X] = -p (p + log(1-p)) / ((1-p)^2 log(1-p)^2).

Return type:

float

entropy()[source]

Shannon entropy in nats, by exact summation of the standard series.

The log-series entropy -sum_k p_k log p_k has no closed form (Fisher, Corbet & Williams, 1943). The series is summed from k = 1 up to this distribution’s own quantile at 1 - 1e-16 (plus a safety margin), beyond which the remaining tail mass is far below double rounding.

Return type:

float

cdf(x)[source]

Cumulative distribution function P(X <= x), support x >= 1.

Summed directly in bounded blocks (the series has no closed form); past _SERIES_CAP terms one minus the Euler-Maclaurin tail mass stands in, exact to double rounding by then and never below the partial sum at the cap, so the result is monotone in x and within [0, 1].

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the smallest k with P(X <= k) >= q.

Summed directly in bounded blocks, never through scipy’s generic discrete ppf. That search brackets the answer by doubling an upper bound until cdf(bound) >= q, and the summed CDF can saturate one ULP short of a q this close to one (numpy’s SIMD exp and log round the last bit differently per CPU: the sum reached q = 1 - 1e-16 at k = 5210 on arm64 and emulated x86-64 and never did on AVX-512 hosted CI runners), so the bound doubled without limit and the vectorized CDF sums grew until the 16 GB runner was OOM-killed – through entropy(), which calls this at exactly that q. Here a block whose terms no longer move the running sum, or the term cap, ends the scan, and the Euler-Maclaurin tail mass answers for whatever lies beyond: the smallest k past the scan whose tail mass is at most 1 - q.

Parameters:

q (float)

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

LogSeriesSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

LogSeriesEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution for vectorized methods.

Return type:

LogSeriesDataEncoder

enumerator()[source]

Return an enumerator over k = 1, 2, … in descending probability order.

Return type:

LogSeriesEnumerator

class LogSeriesEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate log-series support values in descending probability order.

The log-series pmf p^k / (k * -log(1 - p)) is strictly decreasing in k (each step multiplies by p * k / (k + 1) < 1), so value order 1, 2, 3, … IS descending-probability order. The iterator is infinite.

Parameters:

dist (LogSeriesDistribution)

class LogSeriesEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Maximum-likelihood estimator for the log-series shape p (inverts the mean -> p relation).

Parameters:
  • pseudo_count (float | None)

  • suff_stat (float | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return an accumulator factory for log-series count statistics.

Return type:

LogSeriesAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate the shape parameter by inverting the weighted mean.

Parameters:
Return type:

LogSeriesDistribution

class LogSeriesSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw iid log-series observations.

Parameters:
  • dist (LogSeriesDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw size iid positive integers (an int when size is None).

Parameters:
Return type:

int | ndarray

class NegativeBinomialAccumulator(name=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted count and sum statistics plus the count histogram.

The dispersion r has no finite-dimensional sufficient statistic: its MLE needs sum_i w_i digamma(x_i + r), which cannot be reduced to count/sum. We therefore accumulate the weighted histogram {x: weight} so NegativeBinomialEstimator.estimate() can solve the score equation for r.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted statistics for one non-negative integer count.

Parameters:
  • x (int)

  • weight (float)

  • estimate (NegativeBinomialDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate weighted statistics from encoded observations.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded observations.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge another negative-binomial sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, dict[int, float]])

Return type:

NegativeBinomialAccumulator

value()[source]

Return count, sum, and histogram statistics.

Return type:

tuple[float, float, dict[int, float]]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

x (tuple[float, float, dict[int, float]])

Return type:

NegativeBinomialAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

NegativeBinomialDataEncoder

class NegativeBinomialAccumulatorFactory(name=None, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for NegativeBinomialAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh negative-binomial accumulator.

Return type:

NegativeBinomialAccumulator

class NegativeBinomialDataEncoder[source]

Bases: DataSequenceEncoder

Encode count observations with precomputed log-factorials.

seq_encode(x)[source]

Encode counts with precomputed log(x!) values.

Parameters:

x (Sequence[int])

Return type:

tuple[ndarray, ndarray]

class NegativeBinomialDistribution(r, p, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Negative binomial distribution over non-negative integer counts.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated negative-binomial kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for negative binomial distributions.

static backend_legacy_sufficient_statistics(x, params, engine)[source]

Return per-row negative-binomial sufficient statistics in accumulator order.

The accumulator’s NegativeBinomialAccumulator.value() returns (count, sum, histogram); the third row stat carries the per-row counts so the declaration’s kind="histogram" reducer can fold them into the weighted count histogram the dispersion (r) solve needs.

Parameters:
Return type:

tuple[Any, …]

static exp_family_sufficient_statistics(x, engine)[source]

Return the NegativeBinomial sufficient statistic T(x) = (x,) (r fixed).

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return the NegativeBinomial natural parameter eta = log(1 - p) (r fixed).

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the NegativeBinomial log partition A = -r * log(p) (r fixed).

Parameters:
Return type:

Any

static exp_family_base_measure_from_params(x, params, engine)[source]

Return the NegativeBinomial base measure log h(x) = lgamma(x+r) - lgamma(r) - log(x!).

The base measure carries the binomial-coefficient term and depends on the fixed shape r; invalid (non-integer / negative) counts are mapped to -inf.

Parameters:
Return type:

Any

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (int)

Return type:

float

log_density(x)[source]

Return the log-density or log-mass at a single observation.

Parameters:

x (int)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-density values for sequence-encoded observations.

Parameters:

x (tuple[ndarray, ndarray])

Return type:

ndarray

static backend_log_density_from_params(vals, log_fact, r, p, engine)[source]

Engine-neutral negative-binomial log-density from explicit parameters.

Parameters:
Return type:

Any

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked negative-binomial parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[NegativeBinomialDistribution])

  • engine (Any)

Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of negative-binomial log densities.

Parameters:
Return type:

Any

to_fisher(**kwargs)[source]

Return the NegativeBinomial’s count-family Fisher view.

mean()[source]

Mean E[X] (failures before r successes): r(1-p)/p.

Return type:

float

variance()[source]

Variance Var[X]: r(1-p)/p^2.

Return type:

float

entropy()[source]

Shannon entropy in nats, by exact summation of the standard series.

The negative-binomial entropy -sum_k p_k log p_k has no closed form (Johnson, Kemp & Kotz, Univariate Discrete Distributions, ch. 5). The series is summed over the support up to this distribution’s own quantile at 1 - 1e-16 (plus a safety margin), beyond which the tail mass is far below double rounding – the same effective-support truncation PoissonDistribution.entropy() uses, but driven by the exact CDF (via betainc) rather than a Gaussian-tail heuristic, since the negative binomial can be heavy-tailed.

Return type:

float

cdf(x)[source]

Cumulative distribution function P(X <= x) = I_p(r, floor(x)+1).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q) (via scipy nbinom).

Parameters:

q (float)

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

NegativeBinomialSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

NegativeBinomialEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution for vectorized methods.

Return type:

NegativeBinomialDataEncoder

enumerator()[source]

Return an enumerator over the distribution support when available.

Return type:

NegativeBinomialEnumerator

class NegativeBinomialEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate the infinite support in descending probability order.

Parameters:

dist (NegativeBinomialDistribution)

class NegativeBinomialEstimator(r=1.0, pseudo_count=None, suff_stat=None, estimate_r=True, threshold=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Estimate r and p for a negative binomial distribution.

By default the dispersion r is recovered by a 1-D solve of the digamma score equation (p profiled out), then p follows in closed form. Pass estimate_r=False to hold r fixed at the constructor value (the historical geometric/fixed-shape M-step). The r argument is the initial value / fallback when estimate_r=True.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for negative-binomial statistics.

Return type:

NegativeBinomialAccumulatorFactory

resident_accumulation_supported()[source]

Dispersion estimation needs the full count histogram, not fixed-width resident stats.

Return type:

bool

static estimate_dispersion(histogram, r_init, threshold)[source]

Solve the negative-binomial dispersion MLE from a weighted count histogram.

With p profiled to its MLE p = r / (r + xbar), the score for r is

g(r) = sum_k h(k) [digamma(k + r) - digamma(r)] - N * log(1 + xbar / r),

which is strictly decreasing and crosses zero exactly when the data are over-dispersed (sample variance > mean). Under equi/under-dispersion the MLE runs off to the Poisson limit, so r is capped at _MAX_NB_SHAPE.

Parameters:
Return type:

float

estimate(nobs, suff_stat)[source]

Estimate r and p from weighted count statistics.

Parameters:
Return type:

NegativeBinomialDistribution

class NegativeBinomialSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw iid negative binomial observations.

Parameters:
  • dist (NegativeBinomialDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one sample or an array of iid samples.

Parameters:
Return type:

int | ndarray

class PointMassAccumulator(value, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulator for a fixed point mass; no parameters are learned.

Parameters:
  • value (Any)

  • keys (str | None)

update(x, weight, estimate)[source]

Ignore one observation because the atom is fixed.

Parameters:
  • x (Any)

  • weight (float)

  • estimate (PointMassDistribution | None)

Return type:

None

seq_update(x, weights, estimate)[source]

Ignore encoded observations because the atom is fixed.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (PointMassDistribution | None)

Return type:

None

seq_update_engine(x, weights, estimate, engine)[source]

Ignore engine-resident observations because the atom is fixed.

Parameters:
  • x (ndarray)

  • weights (Any)

  • estimate (PointMassDistribution | None)

  • engine (Any)

Return type:

None

initialize(x, weight, rng)[source]

Ignore initialization observations because the atom is fixed.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Ignore encoded initialization observations because the atom is fixed.

Parameters:
Return type:

None

combine(suff_stat)[source]

Return this accumulator because fixed atoms have no sufficient statistics.

Parameters:

suff_stat (Any)

Return type:

PointMassAccumulator

value()[source]

Return None because fixed atoms have no sufficient statistics.

Return type:

None

from_value(x)[source]

Return this accumulator because there is no state to restore.

Parameters:

x (Any)

Return type:

PointMassAccumulator

key_merge(stats_dict)[source]

Register the key with empty statistics when configured.

Parameters:

stats_dict (dict[str, Any])

Return type:

None

key_replace(stats_dict)[source]

Ignore keyed replacements because there is no accumulator state.

Parameters:

stats_dict (dict[str, Any])

Return type:

None

acc_to_encoder()[source]

Return the equality-mask encoder for this atom.

Return type:

PointMassDataEncoder

class PointMassAccumulatorFactory(value, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for PointMassAccumulator.

Parameters:
  • value (Any)

  • keys (str | None)

make()[source]

Create an empty point-mass accumulator.

Return type:

PointMassAccumulator

class PointMassDataEncoder(value)[source]

Bases: DataSequenceEncoder

Encode observations as a boolean equality mask against the fixed atom.

Parameters:

value (Any)

seq_encode(x)[source]

Encode observations as booleans indicating equality with the fixed atom.

Parameters:

x (Sequence[Any])

Return type:

ndarray

class PointMassDistribution(value, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Fixed Dirac/point-mass distribution assigning all mass to one value.

Parameters:
  • value (Any)

  • name (str | None)

  • keys (str | None)

classmethod compute_capabilities()[source]

Declare generic NumPy/Torch scoring support for fixed atoms.

classmethod compute_declaration()[source]

Return the declaration for a fixed non-estimated atom.

property value: Any

Return an independent copy so callers cannot mutate the model’s atom.

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (Any)

Return type:

float

log_density(x)[source]

Return the log-density or log-mass at a single observation.

Parameters:

x (Any)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-density values for sequence-encoded observations.

Parameters:

x (ndarray)

Return type:

ndarray

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density from encoded equality flags.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked point-mass parameters for identical fixed atoms.

Parameters:
Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of point-mass log densities.

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]

Return per-component empty statistics for fixed point masses.

Parameters:
Return type:

tuple[None, …]

support_size()[source]

A single atom.

Return type:

int

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

PointMassSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

PointMassEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution for vectorized methods.

Return type:

PointMassDataEncoder

enumerator()[source]

Return an enumerator over the distribution support when available.

Return type:

PointMassEnumerator

quantized_index(max_bits, bin_width_bits=1.0)[source]

Return a bounded quantized support index for this observation.

Parameters:
Return type:

QuantizedEnumerationIndex

class PointMassEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate the single atom of a PointMassDistribution.

Parameters:

dist (PointMassDistribution)

class PointMassEstimator(value, pseudo_count=None, suff_stat=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Estimator that always returns the configured point mass.

Parameters:
  • value (Any)

  • pseudo_count (float | None)

  • suff_stat (Any | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return a factory for point-mass no-op accumulators.

Return type:

PointMassAccumulatorFactory

estimate(nobs, suff_stat=None)[source]

Return the configured point mass unchanged.

Parameters:
  • nobs (float | None)

  • suff_stat (Any | None)

Return type:

PointMassDistribution

class PointMassSampler(dist, seed=None)[source]

Bases: DistributionSampler

Sampler returning the fixed atom.

Parameters:
  • dist (PointMassDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Return the fixed atom once or repeated size times.

Parameters:
Return type:

Any | Sequence[Any]

class PoissonAccumulator(keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted count and sum statistics for Poisson estimation.

Parameters:

keys (str | None)

initialize(x, weight, rng=None)[source]

Initialize sufficient statistics with one weighted observation.

This method delegates to update.

Parameters:
  • x (int) – Observation from a Poisson distribution.

  • weight (float) – Observation weight.

  • rng (RandomState | None) – Unused; accepted for the accumulator interface.

Return type:

None

seq_initialize(x, weights, rng=None)[source]

Vectorized initialization of PoissonAccumulator sufficient statistics with weighted observations.

This delegates to seq_update().

Arg value x (Tuple[np.ndarray[int], np.ndarray[float]]) is seq_encoded Poisson data from PoissonDataEncoder.seq_encode(), containing

x[0] (np.ndarray[int]): Non-negative integer valued Poisson iid observations,
x[1] (np.ndarray[float]): np.log(Gamma(x[0]+1.0)), Gamma is the gamma function.
Parameters:
  • x (tuple[ndarray, ndarray]) – See above for details.

  • weights (ndarray) – Numpy array of positive floats.

  • rng (Optional[RandomState]) – Kept for consistency with SequenceEncodableStatisticAccumulator.

Returns:

None.

Return type:

None

update(x, weight, estimate=None)[source]

Update sufficient statistics for PoissonAccumulator with one weighted observation.

Parameters:
  • x (int) – Observation from Poisson distribution.

  • weight (float) – Weight for observation.

  • estimate (Optional[PoissonDistribution]) – Kept for consistency with SequenceEncodableStatisticAccumulator.

Returns:

None.

Return type:

None

seq_update(x, weights, estimate=None)[source]

Vectorized update of PoissonAccumulator sufficient statistics with weighted observations.

Arg value x (Tuple[np.ndarray[int], np.ndarray[float]]) is seq_encoded Poisson data from PoissonDataEncoder.seq_encode(), containing

x[0] (np.ndarray[int]): Non-negative integer valued Poisson iid observations,
x[1] (np.ndarray[float]): np.log(Gamma(x[0]+1.0)), Gamma is the gamma function.
Parameters:
  • x (tuple[ndarray, ndarray]) – See above for details.

  • weights (ndarray) – Numpy array of positive floats.

  • estimate (Optional[PoissonDistribution]) – Kept for consistency with SequenceEncodableStatisticAccumulator.

Returns:

None.

Return type:

None

combine(suff_stat)[source]

Merge aggregated Poisson sufficient statistics into this accumulator.

The tuple is interpreted as (count, sum).

Parameters:

suff_stat (tuple[float, float]) – Aggregated Poisson sufficient statistics.

Returns:

This accumulator.

Return type:

PoissonAccumulator

value()[source]

Return sufficient statistics as (count, sum).

Return type:

tuple[float, float]

from_value(x)[source]

Replace this accumulator’s sufficient statistics.

Parameters:

x (tuple[float, float]) – Aggregated Poisson sufficient statistics as (count, sum).

Returns:

This accumulator.

Return type:

PoissonAccumulator

acc_to_encoder()[source]

Return an encoder compatible with Poisson observations.

Return type:

PoissonDataEncoder

class PoissonAccumulatorFactory(keys=None)[source]

Bases: StatisticAccumulatorFactory

Create Poisson accumulators with a shared optional merge key.

Parameters:

keys (str | None)

make()[source]

Return a fresh Poisson accumulator.

Return type:

PoissonAccumulator

class PoissonDataEncoder[source]

Bases: DataSequenceEncoder

Encode iid non-negative integer Poisson observations with log-factorials.

seq_encode(x)[source]

Encode iid sequence of Poisson observations for vectorized seq_ function calls.

Data type must be int. Values must be non-negative integers. Returns the integer observations and log(Gamma(x + 1)) values used by the vectorized scorer.

Parameters:

x (Union[np.ndarray, Sequence[int]]) – Sequence of iid non-negative integers valued Poisson observations.

Returns:

Tuple[ndarray[int], ndarray[float]].

Return type:

tuple[ndarray, ndarray]

class PoissonDistribution(lam, name=None, keys=None, prior=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Poisson distribution over non-negative integer counts with rate lam.

Parameters:
  • lam (float)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

classmethod compute_capabilities()[source]

Declare backend support for generated Poisson density kernels.

classmethod compute_declaration()[source]

Return the generated-compute declaration for the Poisson distribution.

static exp_family_sufficient_statistics(x, engine)[source]

Return Poisson sufficient statistics for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_legacy_sufficient_statistics(x, params, engine)[source]

Return per-row Poisson sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return Poisson natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return Poisson log partition for generated scoring.

Parameters:
Return type:

Any

static exp_family_base_measure(x, engine)[source]

Return Poisson base measure for generated scoring.

Parameters:
Return type:

Any

set_prior(prior)[source]

Attach a parameter prior and cache the conjugate Gamma expectations.

With a Gamma(k, theta) prior over the rate lam this caches (k, theta) so that expected_log_density(x) = (psi(k) + ln theta)*x - k*theta - gammaln(x+1) (the VB E-step term using E[ln lam] = psi(k) + ln theta and E[lam] = k*theta). Any other prior (including None) leaves the distribution a plain point model.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

expected_log_density(x)[source]

Variational expectation E_q[log p(x | lam)] under the Gamma prior.

Falls back to the plug-in log_density(x) when no conjugate prior is attached.

Parameters:

x (float)

Return type:

float

seq_expected_log_density(x)[source]

Vectorized expected_log_density over sequence-encoded observations.

Parameters:

x (tuple[ndarray, ndarray])

Return type:

ndarray

density(x)[source]

Evaluate the density of Poisson distribution at observation x.

Calls np.exp(log_density(x)). See log_density() for details.

Parameters:

x (int) – Must be a non-negative integer value (0,1,2,….).

Returns:

Density of Poisson distribution evaluated at x.

Return type:

float

log_density(x)[source]

Log-density of Poisson distribution evaluated at x.

Log-density given by,

log(p_mat(x_mat=x; lam) = x*log(lam) - log(x!) - lam, for x in {0,1,2,…}

and -np.inf else.

Note: log(Gamma(x+1.0)) = log(x!), where Gamma is the gamma function.

Parameters:

x (int) – Must be a non-negative integer value (0,1,2,….).

Returns:

Log-density of Poisson distribution evaluated at x.

Return type:

float

seq_log_density(x)[source]

Vectorized log-density evaluated on sequence encoded x.

Arg value x (Tuple[np.ndarray[int], np.ndarray[float]]) is seq_encoded Poisson data from PoissonDataEncoder.seq_encode(), containing

x[0] (np.ndarray[int]): Non-negative integer valued Poisson iid observations,
x[1] (np.ndarray[float]): np.log(Gamma(x[0]+1.0)), Gamma is the gamma function.
Parameters:

x (tuple[ndarray, ndarray]) – See above for details.

Returns:

Numpy array of log-density evaluated at each encoded observation value x.

Return type:

ndarray

static backend_log_density_from_params(vals, log_fact, lam, engine)[source]

Engine-neutral Poisson log-density from explicit parameters.

Parameters:
Return type:

Any

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked Poisson parameters for a homogeneous mixture kernel.

Parameters:
Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an (n, k) matrix of Poisson log densities.

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]

Return stacked Poisson sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any]

to_fisher(**kwargs)[source]

Return the Poisson’s count-family Fisher view.

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

cdf(x)[source]

Cumulative distribution function P(X <= x) = Q(floor(x)+1, lam).

Parameters:

x (float)

Return type:

float

skewness()[source]

Skewness 1/sqrt(lambda).

Return type:

float

kurtosis()[source]

Excess kurtosis 1/lambda.

Return type:

float

entropy()[source]

Shannon entropy in nats, by exact summation of the standard series.

The Poisson entropy -sum_k p_k log p_k has no closed form; the series is summed over the effective support k <= lam + 40 sqrt(lam) + 40, beyond which the remaining terms are far below double rounding (the tail mass decays super-geometrically).

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q) (via scipy poisson).

Parameters:

q (float)

Return type:

float

mode()[source]

Mode floor(lambda).

Return type:

float

sampler(seed=None)[source]

Return a sampler for iid draws from this distribution.

Parameters:

seed (int | None) – Optional seed for the sampler’s random state.

Returns:

A configured PoissonSampler.

Return type:

PoissonSampler

estimator(pseudo_count=None)[source]

Return an estimator initialized from this distribution’s shape.

Parameters:

pseudo_count (float | None) – Optional smoothing count applied to the current rate.

Returns:

A PoissonEstimator.

Return type:

PoissonEstimator

dist_to_encoder()[source]

Return an encoder for iid Poisson observations.

Return type:

PoissonDataEncoder

enumerator()[source]

Return an enumerator over nonnegative counts in descending probability order.

Return type:

PoissonEnumerator

quantized_index(max_bits, bin_width_bits=1.0)[source]

Build a bounded bit-quantized index by walking the Poisson mode outward.

Parameters:
Return type:

QuantizedEnumerationIndex

quantized_multi_cross_index(others, max_bits, bin_width_bits=1.0)[source]

Build an aligned cross-bin view over bounded Poisson high-mass regions.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

quantized_cross_index(other, max_bits, bin_width_bits=1.0)[source]

Build an aligned cross-bin view over two bounded Poisson high-mass regions.

Parameters:

bin_width_bits (float)

Return type:

QuantizedCrossIndex

class PoissonEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate Poisson support values in descending probability order.

Parameters:

dist (PoissonDistribution)

class PoissonEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]

Bases: ParameterEstimator

Estimate Poisson rate parameters from accumulated sufficient statistics.

Parameters:
  • pseudo_count (float | None)

  • suff_stat (float | None)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

accumulator_factory()[source]

Return an accumulator factory matching this estimator.

Return type:

PoissonAccumulatorFactory

model_log_density(model)[source]

Log-density of the model’s rate under the Gamma prior (ELBO global term).

Parameters:

model (PoissonDistribution)

Return type:

float

estimate(nobs, suff_stat)[source]

Estimate a Poisson distribution from aggregated sufficient statistics.

The tuple is interpreted as (count, sum).

Parameters:
  • nobs (float | None) – Unused; accepted for the ParameterEstimator interface.

  • suff_stat (tuple[float, float]) – Aggregated Poisson sufficient statistics.

Returns:

A fitted Poisson distribution.

Return type:

PoissonDistribution

class PoissonSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw independent samples from a PoissonDistribution.

Parameters:
  • dist (PoissonDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw iid samples from the Poisson distribution.

Parameters:
  • size (int | None) – Number of iid samples to draw. None returns a scalar sample.

  • batched (bool)

Returns:

A scalar draw when size is None; otherwise an array of draws.

Return type:

int | ndarray

class SkellamAccumulator(name=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate the weighted count, sum, and sum-of-squares needed for the moment fit.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate count, sum, and squared sum for one integer observation.

Parameters:
  • x (int)

  • weight (float)

  • estimate (SkellamDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate count, sum, and squared sum from encoded observations.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded observations.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge another Skellam sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

SkellamAccumulator

value()[source]

Return count, sum, and squared sum.

Return type:

tuple[float, float, float]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

x (tuple[float, float, float])

Return type:

SkellamAccumulator

scale(c)[source]

Scale all weight-linear sufficient statistics by c.

Parameters:

c (float)

Return type:

SkellamAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

SkellamDataEncoder

class SkellamAccumulatorFactory(name=None, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for SkellamAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Skellam accumulator.

Return type:

SkellamAccumulator

class SkellamDataEncoder[source]

Bases: DataSequenceEncoder

Encode sequences of iid Skellam observations (integer data type, any sign).

seq_encode(x)[source]

Encode observations as a floating-point integer-valued array.

Parameters:

x (Sequence[int])

Return type:

ndarray

class SkellamDistribution(mu1, mu2, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Skellam distribution: K = N1 - N2 for independent N1 ~ Poisson(mu1), N2 ~ Poisson(mu2).

Parameters:
density(x)[source]

Probability mass at integer x (see log_density).

Parameters:

x (int)

Return type:

float

log_density(x)[source]

Stable Skellam log-mass at integer x (-inf for non-integer input).

Parameters:

x (int)

Return type:

float

seq_log_density(x)[source]

Vectorized Skellam log-mass at sequence-encoded integer counts x.

Parameters:

x (ndarray)

Return type:

ndarray

mean()[source]

Mean E[X] = mu1 - mu2.

Return type:

float

variance()[source]

Variance Var[X] = mu1 + mu2.

Return type:

float

entropy()[source]

Shannon entropy in nats, by exact two-sided summation of the standard series.

The Skellam entropy -sum_k p_k log p_k has no closed form. The sum runs over the support between this distribution’s own quantiles at 1e-16 and 1 - 1e-16 (plus a safety margin on each side), beyond which the remaining tail mass on both sides is far below double rounding. Terms where the scaled Bessel term underflows to exactly zero (mass indistinguishable from 0 at double precision) are dropped, matching the p log p -> 0 limit.

Return type:

float

classmethod compute_capabilities()[source]

Describe backend support for generated Skellam scoring kernels.

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized Skellam log-mass for encoded data (see class backend note).

The series yields the UNSCALED log I_k (not log ive = log I_k - z), so the constant here is -(mu1 + mu2) — the legacy path’s -sqrt_diff_sq plus its implicit -z.

Parameters:
Return type:

Any

cdf(x)[source]

Cumulative distribution function P(X <= x) (via scipy skellam).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q) (via scipy skellam).

Parameters:

q (float)

Return type:

float

sampler(seed=None)[source]

Return a SkellamSampler for this distribution.

Parameters:

seed (int | None)

Return type:

SkellamSampler

estimator(pseudo_count=None)[source]

Return a SkellamEstimator (method of moments).

Parameters:

pseudo_count (float | None)

Return type:

SkellamEstimator

dist_to_encoder()[source]

Return the encoder for Skellam observations.

Return type:

SkellamDataEncoder

enumerator()[source]

Return an enumerator over all integers in descending probability order.

Return type:

SkellamEnumerator

class SkellamEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate the two-sided Skellam support in descending probability order.

The Skellam pmf is log-concave (the difference of two independent Poisson counts, each log-concave on the integers), hence unimodal: enumeration hill-climbs from round(mu1 - mu2) to the mode and walks outward with the standard two-pointer merge over the two tails, emitting the larger side each step. Values whose mass underflows to zero are skipped per the enumerator contract, so the iterator ends when both tails are exhausted at float precision.

Parameters:

dist (SkellamDistribution)

class SkellamEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Estimate (mu1, mu2) by the (exact, closed-form) method of moments.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for Skellam moment statistics.

Return type:

SkellamAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a Skellam from the accumulated (count, sum, sum2) via method of moments.

Parameters:
Return type:

SkellamDistribution

class SkellamSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw iid Skellam observations as the difference of two independent Poisson draws.

Parameters:
  • dist (SkellamDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw size iid Skellam samples (a single int if size is None).

Parameters:
Return type:

int | ndarray

Submodules