mixle.stats.univariate package

mixle.stats.univariate – univariate distributions, split into continuous/ and discrete/.

Both subpackages re-export every class they implement, and this package re-exports both, so the namespace exposes the API it actually contains (MXR-080-1231). Previously each level advertised only its submodule names, so from mixle.stats.univariate import GaussianDistribution failed while from mixle.stats import GaussianDistribution worked.

mixle.stats remains the consolidated public API and re-exports these same objects.

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate sufficient statistics for beta estimation.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted statistics for one observation in (0, 1).

Parameters:
  • x (float)

  • weight (float)

  • estimate (BetaDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and inside the unit interval.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility.

Return type:

ndarray

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 Beta sufficient-statistic tuple.

Parameters:

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

Return type:

BetaAccumulator

value()[source]

Return the accumulated Beta sufficient statistics.

Return type:

tuple[float, float, float, float, float]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

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

Return type:

BetaAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

BetaDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for BetaAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Beta accumulator.

Return type:

BetaAccumulator

class BetaDataEncoder[source]

Bases: DataSequenceEncoder

Encode beta observations with log x and log(1-x) columns.

seq_encode(x)[source]

Encode observations as log and moment arrays for vectorized updates.

Parameters:

x (Sequence[float])

Return type:

tuple[ndarray, ndarray, ndarray, ndarray]

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

Bases: SequenceEncodableProbabilityDistribution

Beta distribution with positive shape parameters a and b.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated Beta kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Beta distributions.

static exp_family_sufficient_statistics(x, engine)[source]

Return Beta sufficient statistics for generated scoring.

Scoring needs only log_x and log1m_x (the two natural-parameter partners). The encoder emits the full (log_x, log1m_x, x, x**2) tuple for the M-step, while the symbolic generator supplies just the two scoring symbols from backend_log_density_from_params; indexing the leading two works for both arities.

Parameters:
Return type:

tuple[Any, …]

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

Return per-row Beta sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return Beta natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return Beta log partition for generated scoring.

Parameters:
Return type:

Any

get_parameters()[source]

Return the (a, b) shape pair.

Lets a BetaDistribution serve as a conjugate prior (on a Bernoulli/Geometric/Binomial success probability) under the unified Bayesian estimation protocol.

Return type:

tuple[float, float]

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

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

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

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

Parameters:

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

Return type:

ndarray

static backend_log_density_from_params(log_x, log1m_x, a, b, engine)[source]

Engine-neutral Beta log-density from encoded logs and 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 Beta 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 Beta log densities.

Parameters:
Return type:

Any

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

to_fisher(**kwargs)[source]

Return this distribution’s own Fisher view.

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Formed in logs: at concentrations near the float floor (a + b) ** 2 underflows to zero and the direct quotient raised ZeroDivisionError where the variance is a perfectly ordinary number (a = b = 1e-300 is the fair coin on {0, 1}, variance 0.25 – P01-F10).

Return type:

float

entropy()[source]

Differential entropy ln B(a,b) - (a-1)psi(a) - (b-1)psi(b) + (a+b-2)psi(a+b).

Return type:

float

mode()[source]

Mode (a-1)/(a+b-2) for a,b>1; boundary otherwise.

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

BetaSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

BetaEstimator

dist_to_encoder()[source]

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

Return type:

BetaDataEncoder

class BetaEstimator(pseudo_count=None, suff_stat=None, delta=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Estimate beta shape parameters from weighted log-moment statistics.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for Beta sufficient statistics.

Return type:

BetaAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate Beta shape parameters from weighted sufficient statistics.

Parameters:
Return type:

BetaDistribution

class BetaFisherView(dist)[source]

Bases: FixedFisherView

Fisher view for Beta sufficient statistics.

Parameters:

dist (Any)

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

Bases: DistributionSampler

Draw iid beta observations.

Parameters:
  • dist (BetaDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

class ExponentialAccumulator(keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted count and sum statistics for Exponential estimation.

Parameters:

keys (str | None)

update(x, weight, estimate)[source]

Update sufficient statistics for ExponentialAccumulator with one weighted observation.

Parameters:
  • x (float) – Observation from exponential distribution.

  • weight (float) – Weight for observation.

  • estimate (Optional['ExponentialDistribution']) – 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 positvie floats.

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

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

Returns:

None.

Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and non-negative.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility.

Return type:

ndarray

initialize(x, weight, rng)[source]

Initialize sufficient statistics of ExponentialAccumulator with weighted observation.

This delegates to update().

Parameters:
  • x (float) – Positive real-valued observation of exponential.

  • 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 ExponentialAccumulator sufficient statistics with weighted observations.

This delegates to seq_update().

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

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

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

Returns:

None.

Return type:

None

combine(suff_stat)[source]

Aggregates sufficient statistics with ExponentialAccumulator member sufficient statistics.

Parameters:

suff_stat (Tuple[float, float]) – Aggregated count and sum.

Returns:

ExponentialAccumulator

Return type:

ExponentialAccumulator

value()[source]

Return (count, sum) sufficient statistics.

Return type:

tuple[float, float]

from_value(x)[source]

Sets sufficient statistics (count and sum) of ExponentialAccumulator to x.

Parameters:

x (Tuple[float, float]) – Sufficient statistics tuple (count, sum).

Returns:

ExponentialAccumulator

Return type:

ExponentialAccumulator

acc_to_encoder()[source]

Return the encoder associated with this accumulator.

Return type:

ExponentialDataEncoder

class ExponentialAccumulatorFactory(keys=None)[source]

Bases: StatisticAccumulatorFactory

Create Exponential accumulators with a shared optional merge key.

Parameters:

keys (str | None)

make()[source]

Create an accumulator with this factory’s merge key.

Return type:

ExponentialAccumulator

class ExponentialDataEncoder[source]

Bases: DataSequenceEncoder

Data encoder for iid non-negative exponential observations.

seq_encode(x)[source]

Encode sequence of iid exponential observations.

Data type must be a float. Data must also be non-negative real-valued numbers.

Parameters:

x (Union[List[float], np.ndarray]) – IID numpy array or list of non-negative real-valued floats.

Returns:

Numpy array of floats.

Return type:

ndarray

class ExponentialDistribution(beta, name=None, keys=None, prior=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Exponential distribution on non-negative real values with scale beta.

Parameters:
  • beta (float)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

classmethod compute_capabilities()[source]

Declare backend support for generated Exponential density kernels.

classmethod compute_declaration()[source]

Return the generated-compute declaration for the Exponential distribution.

static exp_family_sufficient_statistics(x, engine)[source]

Return Exponential sufficient statistics for generated scoring.

Parameters:
Return type:

tuple[Any, …]

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

Return per-row Exponential sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return Exponential natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return Exponential log partition for generated scoring.

Parameters:
Return type:

Any

static exp_family_base_measure(x, engine)[source]

Return Exponential support base measure for generated scoring.

Parameters:
Return type:

Any

set_prior(prior)[source]

Attach a parameter prior and precompute the conjugate Gamma expectations.

The exponential rate is 1/beta; with a Gamma(k, theta) prior on that rate this caches the variational expected natural parameters so that expected_log_density(x) = e1*x - ea where the natural parameter is eta = -rate, E[eta] = -k*theta and E[-log(-eta)] = psi(k) + ln theta (mapping the prior’s (k, theta) to the bstats [a, b] = [k, 1/theta] form). 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 | rate)] 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 (ndarray)

Return type:

ndarray

density(x)[source]

Evaluate the density of exponential distribution with scale beta.

See log_density() for details.

Parameters:

x (float) – Non-negative real-valued number.

Returns:

Density evaluated at x.

Return type:

float

log_density(x)[source]

Evaluate the log-density of exponential distribution with scale beta.

log(f(x;beta)) = -log(beta) - x/beta, for x >= 0, else -np.inf.

Parameters:

x (float) – Non-negative real-valued number.

Returns:

Log-density evaluated at x.

Return type:

float

seq_log_density(x)[source]

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

Vectorized call to log-density on each observation value x.

Parameters:

x (np.ndarray) – Numpy array of floats.

Returns:

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

Return type:

ndarray

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

Engine-neutral exponential 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 Exponential parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[ExponentialDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

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

Parameters:
Return type:

Any

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

Return stacked Exponential sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

to_fisher(**kwargs)[source]

Return the Exponential’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

entropy()[source]

Differential entropy 1 + log(scale).

Return type:

float

skewness()[source]

Skewness (2).

Return type:

float

kurtosis()[source]

Excess kurtosis (6).

Return type:

float

mode()[source]

Mode (0).

Return type:

float

sampler(seed=None)[source]

Create a sampler with scale beta.

Parameters:

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

Returns:

ExponentialSampler object.

Return type:

ExponentialSampler

estimator(pseudo_count=None)[source]

Return an estimator initialized with this distribution’s scale.

Parameters:

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

Returns:

ExponentialEstimator.

Return type:

ExponentialEstimator

dist_to_encoder()[source]

Return the encoder for exponential observations.

Return type:

ExponentialDataEncoder

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

Bases: ParameterEstimator

Estimate Exponential scale 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]

Create an exponential accumulator factory with this estimator’s keys.

Return type:

ExponentialAccumulatorFactory

model_log_density(model)[source]

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

Parameters:

model (ExponentialDistribution)

Return type:

float

estimate(nobs, suff_stat)[source]

Estimate ExponentialDistribution from suff_stat arg.

Estimate ExponentialDistribution from sufficient statistic tuple suff_stat, counting a float value for count and sum. If pseudo_count is set, this is used to re-weight the member value “suff_stat”, which is the scale of ExponentialEstimator object.

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

  • suff_stat (Tuple[float, float]) – Tuple of count and sum. Both are positive real-valued floats.

Returns:

ExponentialDistribution object.

Return type:

ExponentialDistribution

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

Bases: DistributionSampler

Draw independent samples from an ExponentialDistribution.

Parameters:
  • dist (ExponentialDistribution)

  • seed (int | None)

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

Draw iid samples from the exponential distribution.

Parameters:
  • size (Optional[int]) – Number of samples. None returns one float.

  • batched (bool)

Returns:

NumPy array when size is provided; otherwise one sample as a float.

Return type:

float | ndarray

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted central moments for method-of-moments EMG estimation.

Parameters:
  • keys (str | None)

  • name (str | None)

update(x, weight, estimate)[source]

Update weighted central moments from one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (ExponentiallyModifiedGaussianDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize weighted central moments from one observation.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize weighted central moments from encoded observations.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update weighted central moments from encoded observations.

Centering the batch on its own mean removes the E[x^2]-E[x]^2 cancellation, but a SINGLE centering pass does not remove all of it: the computed mean carries the rounding of a large-magnitude sum, and that residue enters the third moment linearly – which is the moment lam is inverted from, so the fitted rate drifted at large data offsets. The second pass in centered_batch_moments() computes the residue at spread scale, where it is exact, and makes the fit shift-equivariant.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (ExponentiallyModifiedGaussianDistribution | None)

Return type:

None

combine(suff_stat)[source]

Merge another accumulator’s central-moment summary.

Parameters:

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

Return type:

ExponentiallyModifiedGaussianAccumulator

value()[source]

Return count, mean, second central moment, and third central moment.

Return type:

tuple[float, float, float, float]

from_value(x)[source]

Restore count and central-moment state from value output.

Parameters:

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

Return type:

ExponentiallyModifiedGaussianAccumulator

scale(c)[source]

Scale the weighted moment summary by a constant.

Parameters:

c (float)

Return type:

ExponentiallyModifiedGaussianAccumulator

acc_to_encoder()[source]

Return the encoder compatible with EMG moment statistics.

Return type:

ExponentiallyModifiedGaussianDataEncoder

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

Bases: StatisticAccumulatorFactory

Create EMG central-moment accumulators.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create an empty EMG accumulator.

Return type:

ExponentiallyModifiedGaussianAccumulator

class ExponentiallyModifiedGaussianDataEncoder[source]

Bases: DataSequenceEncoder

Encode sequences of iid EMG observations (data type float).

seq_encode(x)[source]

Validate and encode EMG observations as a finite float array.

Parameters:

x (list[float] | ndarray)

Return type:

ndarray

class ExponentiallyModifiedGaussianDistribution(mu, sigma2, lam, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Exponentially-modified Gaussian: X = N(mu, sigma2) + Exp(rate=lam).

Parameters:
density(x)[source]

Density of the EMG at observation x (see log_density).

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Stable log-density of the EMG at x.

log f(x) = log(lam/2) - 0.5*u^2 + log_erfcx(z) with u = (x - mu)/sigma and z = (lam*sigma - u)/sqrt(2).

Parameters:

x (float)

Return type:

float

seq_ld_lambda()[source]

Return vectorized log-density callables for encoded data.

Return type:

list[Callable]

seq_log_density(x)[source]

Vectorized EMG log-density at sequence-encoded input x.

Parameters:

x (ndarray)

Return type:

ndarray

classmethod compute_capabilities()[source]

Declare NumPy/Torch scoring capabilities for EMG log-density kernels.

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized EMG log-density for encoded data.

Parameters:
Return type:

Any

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact, via scipy’s exponnorm).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

Parameters:

q (float)

Return type:

float

sampler(seed=None)[source]

Return an ExponentiallyModifiedGaussianSampler for this distribution.

Parameters:

seed (int | None)

Return type:

ExponentiallyModifiedGaussianSampler

estimator(pseudo_count=None)[source]

Return an ExponentiallyModifiedGaussianEstimator (method-of-moments).

Parameters:

pseudo_count (float | None)

Return type:

ExponentiallyModifiedGaussianEstimator

dist_to_encoder()[source]

Return the encoder for exponentially modified Gaussian observations.

Return type:

ExponentiallyModifiedGaussianDataEncoder

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

Bases: ParameterEstimator

Estimate EMG parameters from weighted central moments.

The fit is SHIFT-EQUIVARIANT: estimating on x + c returns mu + c with sigma2 and lam unchanged, for any constant c the data can carry – epoch seconds (~1.7e9), 2**31 and 1e12 included. The moments come from ExponentiallyModifiedGaussianAccumulator, which centers each batch twice for exactly this reason; a single centering pass moved the fit by 1.3e-4 at 1e12, silently.

Parameters:
  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return a factory for EMG central-moment accumulators.

Return type:

ExponentiallyModifiedGaussianAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate an EMG from the accumulated (count, mean, M2, M3) via method of moments.

Parameters:
Return type:

ExponentiallyModifiedGaussianDistribution

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

Bases: DistributionSampler

Sample an EMG by adding independent Gaussian and exponential draws.

Parameters:
  • dist (ExponentiallyModifiedGaussianDistribution)

  • seed (int | None)

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

Draw size iid EMG samples (a single float if size is None).

Parameters:
Return type:

float | ndarray

class GammaAccumulator(keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted count, sum, and log-sum statistics for Gamma estimation.

Parameters:

keys (str | None)

initialize(x, weight, rng)[source]

Initialize sufficient statistics of GammaAccumulator with weighted observation.

This delegates to update().

Parameters:
  • x (float) – Positive real-valued observation of gamma.

  • 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 GammaAccumulator sufficient statistics with weighted observations.

This delegates to seq_update().

Parameters:
  • x (Tuple[ndarray, ndarray]) – Tuple of Numpy array of observations and log(observations).

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

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

Returns:

None.

Return type:

None

update(x, weight, estimate)[source]

Update sufficient statistics for GammaAccumulator with one weighted observation.

Parameters:
  • x (float) – Observation from gamma distribution.

  • weight (float) – Weight for observation.

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

Returns:

None

Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and strictly positive.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility.

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Vectorized update of sufficient statistics from encoded sequence x.

Parameters:
  • x (Tuple[ndarray, ndarray]) – Tuple of Numpy array of observations and log(observations).

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

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

Returns:

None.

Return type:

None

combine(suff_stat)[source]

Aggregates sufficient statistics with GammaAccumulator member sufficient statistics.

Parameters:

suff_stat (Tuple[float, float, float]) – Aggregated count, sum, sum_of_logs.

Returns:

ExponentialAccumulator

Return type:

GammaAccumulator

value()[source]

Return (count, sum, sum_of_logs) sufficient statistics.

Return type:

tuple[float, float, float]

from_value(x)[source]

Sets sufficient statistics GammaAccumulator to x.

Parameters:

x (Tuple[float, float, float]) – Sufficient statistics tuple of length three..

Returns:

ExponentialAccumulator

Return type:

GammaAccumulator

acc_to_encoder()[source]

Return an encoder compatible with Gamma observations.

Return type:

GammaDataEncoder

class GammaAccumulatorFactory(keys=None)[source]

Bases: StatisticAccumulatorFactory

Create Gamma accumulators with a shared optional merge key.

Parameters:

keys (str | None)

make()[source]

Return a fresh Gamma accumulator.

Return type:

GammaAccumulator

class GammaDataEncoder[source]

Bases: DataSequenceEncoder

Encoder for iid positive Gamma observations.

seq_encode(x)[source]

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

Note: Each entry of x must be a non-negative float. Exact zeros encode (density evaluation at the boundary is well-defined in the limit), but ESTIMATION rejects them in the accumulator: the Gamma likelihood is degenerate on zeros (E[log x] diverges), which used to collapse the fitted shape to k = 1 silently. NaN is rejected as missing data, by name.

Parameters:

x (Union[List[float], np.ndarray]) – IID sequence of gamma distributed observations.

Returns:

Tuple of x as numpy array and log(x).

Return type:

tuple[ndarray, ndarray]

class GammaDistribution(k, theta, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Gamma distribution parameterized by shape and scale.

Parameters:
classmethod compute_capabilities()[source]

Declare backend support for generated Gamma density kernels.

classmethod compute_declaration()[source]

Return the generated-compute declaration for the Gamma distribution.

static exp_family_sufficient_statistics(x, engine)[source]

Return Gamma sufficient statistics for generated scoring.

Parameters:
Return type:

tuple[Any, …]

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

Return per-row Gamma sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return Gamma natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return Gamma log partition for generated scoring.

Parameters:
Return type:

Any

static exp_family_base_measure(x, engine)[source]

Return Gamma support base measure for generated scoring.

Parameters:
Return type:

Any

get_parameters()[source]

Return the (shape k, scale theta) pair.

Lets a GammaDistribution serve as a conjugate prior (on a Poisson/Exponential rate, or a Gamma scale) under the unified Bayesian estimation protocol.

Return type:

tuple[float, float]

cross_entropy(dist)[source]

Cross entropy -E_self[log dist(x)] for a Gamma argument (closed form).

Used as the conjugate prior/posterior cross-entropy term in variational Bayes (e.g. the ELBO global term in DPM for Poisson/Exponential-rate components).

Parameters:

dist (GammaDistribution)

Return type:

float

entropy()[source]

Return the differential entropy in nats.

Return type:

float

density(x)[source]

Density of gamma distribution evaluated at x.

See log_density() for details.

Parameters:

x (float) – Positive real-valued number.

Returns:

Density of gamma distribution evaluated at x.

Return type:

float

log_density(x)[source]

Log-density of gamma distribution evaluated at x.

Log-density given by, If x > 0.0,

log(f(x;k,theta)) = -gammaln(k) - k*log(theta) + (k-1) * log(x) - x / theta,

else,

-np.inf

Parameters:

x (float) – Positive real-valued number.

Returns:

Log-density of gamma distribution evaluated at x.

Return type:

float

seq_log_density(x)[source]

Vectorized evaluation of sequence encoded observations from gamma distribution.

Input must be x (Tuple[ndarray, ndarray]):

x[0]: Numpy array of floats containing observations from gamma distribution. x[1]: Numpy array of floats containing log of observation values.

Parameters:

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

Returns:

Numpy array containing log-density evaluated at all observations of encoded sequence x.

Return type:

ndarray

static backend_log_density_from_params(vals, log_vals, k, theta, engine)[source]

Engine-neutral gamma 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 Gamma 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 Gamma log densities.

Parameters:
Return type:

Any

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

Return stacked Gamma sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

to_fisher(**kwargs)[source]

Return this distribution’s own Fisher view.

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

skewness()[source]

Skewness 2/sqrt(k).

Return type:

float

kurtosis()[source]

Excess kurtosis 6/k.

Return type:

float

mode()[source]

Mode (k-1)*theta for k>=1, else 0.

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 GammaSampler.

Return type:

GammaSampler

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 distribution moments.

Returns:

A GammaEstimator.

Return type:

GammaEstimator

dist_to_encoder()[source]

Return an encoder for iid Gamma observations.

Return type:

GammaDataEncoder

class GammaEstimator(pseudo_count=(0.0, 0.0), suff_stat=(1.0, 0.0), threshold=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Estimate Gamma shape and scale parameters from sufficient statistics.

Parameters:
accumulator_factory()[source]

Return an accumulator factory matching this estimator.

Return type:

GammaAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a Gamma distribution from aggregated sufficient statistics.

The tuple is interpreted as (count, sum, sum_of_logs).

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

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

Returns:

A fitted Gamma distribution.

Return type:

GammaDistribution

static estimate_shape(avg_sum, avg_sum_of_logs, threshold)[source]

Estimates the shape parameter of GammaDistribution.

Parameters:
  • avg_sum (float) – Weighted sum of gamma observations.

  • avg_sum_of_logs (float) – Weighted log sum of gamma observations.

  • threshold (float) – Threshold used for assessing convergence of shape estimation.

Returns:

Estimate of shape parameter ‘k’.

Return type:

float

class GammaFisherView(dist)[source]

Bases: FixedFisherView

Expose Gamma sufficient statistics for Fisher-information utilities.

Parameters:

dist (Any)

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

Bases: DistributionSampler

Draw independent samples from a GammaDistribution.

Parameters:
  • dist (GammaDistribution)

  • seed (int | None)

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

Draw iid observations from the Gamma 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:

float | ndarray

class GaussianAccumulator(keys=None, name=None, compensated=False)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted first and second moments for Gaussian estimation.

Parameters:
  • keys (str | None)

  • name (str | None)

  • compensated (bool)

update(x, weight, estimate)[source]

Update sufficient statistics for GaussianAccumulator with one weighted observation.

Parameters:
  • x (float) – Observation from Gaussian distribution.

  • weight (float) – Weight for observation.

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

Returns:

None.

Return type:

None

initialize(x, weight, rng)[source]

Initialize with a weighted observation.

Parameters:
  • x (float) – Observation from Gaussian distribution.

  • weight (float) – Weight for observation.

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

Returns:

None.

Return type:

None

seq_initialize(x, weights, rng)[source]

Vectorized initialization from encoded weighted observations.

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

  • 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 sufficient statistics from encoded sequence x.

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

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

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

Returns:

None.

Return type:

None

combine(suff_stat)[source]

Merge sufficient statistics into this accumulator.

Arg passed suff_stat is tuple of four floats:

suff_stat[0] (float): Sum of weighted observations (sum_i w_i*X_i), suff_stat[1] (float): Sum of weighted observations (sum_i w_i*X_i^2), suff_stat[2] (float): Sum of weighted observations (sum_i w_i), suff_stat[3] (float): Sum of weighted observations (sum_i w_i).

When this accumulator is compensated and suff_stat carries a numerics-error receipt (see value() / GaussianSuffStat), its float64 magnitude and exact term-count fields are folded in too.

Parameters:

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

Returns:

This accumulator.

Return type:

GaussianAccumulator

scale(c)[source]

Scale the accumulated statistics in place by c, anchored track included.

The structural default round-trips through value() and from_value(), and scale_suff_stat rebuilds the payload as a PLAIN tuple – which drops the anchored attribute, so from_value sees raw-only statistics and restarts the track unactivated. The scaled accumulator then estimates through the cancellation-prone raw form and undoes the whole shift-anchored repair: measured on sd-0.5 data at mean 1e15, seq_update then scale(0.37) fitted sigma2 = 1e+22 where the same weights passed to seq_update directly fitted 0.24625. Scaling every weight by c is reachable from ordinary use – HMM/LDA/hierarchical-mixture child accumulators and streaming EM’s batch mixing all do it.

Uniform weight scaling is exactly linear in both anchored moments and leaves the anchor (a data value, not a statistic) alone, so the track scales as the raw moments do.

The moment arithmetic lives in scale_anchored_triple; this method is pure attribute wiring, and its body is byte-identical to the Logistic/Gaussian sibling accumulator’s – flagged by the duplicate-body scanner and accepted in the manifest deliberately, because de-duplicating the wiring itself would mean a mixin coupling both classes’ private attribute names, a bigger structural change than the release stage warrants for zero remaining bug-risk (the shared math is what could drift; this cannot).

Parameters:

c (float)

Return type:

GaussianAccumulator

error_bound()[source]

Return historical round-off diagnostics for sum/sum2.

None when this accumulator was not constructed with compensated=True – the disabled default carries no receipt to report. The compensated values are asymptotic estimates, not certified error bounds; the method name is retained for compatibility.

Return type:

dict[str, float] | None

value()[source]

Returns sufficient statistics of GaussianAccumulator object (Tuple[float, float, float, float]).

When compensated, or once any data has been seen (so the shift-anchored moment track is live), the returned value is a GaussianSuffStat – a drop-in 4-tuple (indexing/unpacking/iteration all behave identically) that additionally carries the numerics-error receipt in its .receipt attribute and the anchored moments in its .anchored attribute, so combine() can fold them in and GaussianEstimator.estimate() can compute a shift-invariant variance.

Return type:

tuple[float, float, float, float]

from_value(x)[source]

Replace this accumulator’s sufficient statistics.

Arg passed x is tuple of four floats:

x[0] (float): Sum of weighted observations (sum_i w_i*X_i), x[1] (float): Sum of weighted observations (sum_i w_i*X_i^2), x[2] (float): Sum of weighted observations (sum_i w_i), x[3] (float): Sum of weighted observations (sum_i w_i).

Parameters:

x (tuple[float, float, float, float]) – Tuple of (sum, sum2, count, count2).

Returns:

This accumulator.

Return type:

GaussianAccumulator

acc_to_encoder()[source]

Return an encoder compatible with Gaussian scalar observations.

Return type:

GaussianDataEncoder

class GaussianAccumulatorFactory(name=None, keys=None, compensated=False)[source]

Bases: StatisticAccumulatorFactory

Parameters:
  • name (str | None)

  • keys (str | None)

  • compensated (bool)

make()[source]

Return a GaussianAccumulator object with name and keys passed.

Return type:

GaussianAccumulator

class GaussianDataEncoder[source]

Bases: DataSequenceEncoder

Encoder for iid scalar Gaussian observations.

seq_encode(x)[source]

Encode sequence of iid Gaussian observations.

Data type must be List[float] or np.ndarray[float].

Parameters:

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

Returns:

A numpy array of floats.

Return type:

ndarray

class GaussianDistribution(mu, sigma2, name=None, keys=None, prior=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Univariate Gaussian distribution.

Parameters:
  • mu (float)

  • sigma2 (float)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

classmethod compute_capabilities()[source]

Declare backend support for generated Gaussian density kernels.

classmethod compute_declaration()[source]

Return the generated-compute declaration for the Gaussian distribution.

static exp_family_sufficient_statistics(x, engine)[source]

Return Gaussian sufficient statistics for generated scoring.

Parameters:
Return type:

tuple[Any, …]

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

Return per-row Gaussian sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return Gaussian natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return Gaussian log partition for generated scoring.

Parameters:
Return type:

Any

set_prior(prior)[source]

Attach a parameter prior and precompute conjugate-prior expectations.

With a NormalGamma(mu0, lam, a, b) prior over (mu, tau=1/sigma2) this caches the variational expected natural parameters [ea, eb, e1, e2] so that expected_log_density(x) = x*(e1 + x*e2) - ea + eb (the VB E-step term). 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 | mu, tau)] under the NormalGamma 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 (ndarray)

Return type:

ndarray

density(x)[source]

Density of Gaussian distribution at observation x.

See log_density() for details.

Parameters:

x (float) – Real-valued observation of Gaussian.

Returns:

Density of Gaussian at x.

Return type:

float

log_density(x)[source]

Log-density of Gaussian distribution at observation x.

Log-density of Gaussian with mean mu and variance sigma2 given by,

log(f(x;mu, sigma2)) = -0.5*log(2*pi*sigma2) - 0.5*(x-mu)^2/sigma2, for real-valued x.

Parameters:

x (float) – Real-valued observation of Gaussian.

Returns:

Log-density at observation x.

Return type:

float

seq_ld_lambda()[source]

Return vectorized log-density callables for encoded data.

Return type:

list[Callable]

seq_log_density(x)[source]

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

Parameters:

x (np.ndarray) – Numpy array of floats.

Returns:

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

Return type:

ndarray

static backend_log_density_from_params(x, mu, sigma2, engine)[source]

Engine-neutral Gaussian 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

gradient_log_prior(priors, prior_strength, torch, engine)[source]

Distribution-owned MAP prior contribution for Gaussian parameters.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked Gaussian 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 Gaussian log densities.

Parameters:
Return type:

Any

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

Return stacked Gaussian sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any, Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

to_fisher(**kwargs)[source]

Return the Gaussian’s own Fisher view.

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

entropy()[source]

Differential entropy 0.5*log(2*pi*e*sigma2).

Return type:

float

skewness()[source]

Skewness (0).

Return type:

float

kurtosis()[source]

Excess kurtosis (0).

Return type:

float

mode()[source]

Mode (= the mean mu).

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 GaussianSampler.

Return type:

GaussianSampler

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 mean and variance.

Returns:

A GaussianEstimator.

Return type:

GaussianEstimator

dist_to_encoder()[source]

Return an encoder for iid scalar Gaussian observations.

Return type:

GaussianDataEncoder

class GaussianEstimator(pseudo_count=(None, None), suff_stat=(None, None), name=None, keys=None, prior=None, min_covar=None, compensated=False)[source]

Bases: ParameterEstimator

Estimate Gaussian mean and variance from accumulated sufficient statistics.

The variance is formed from shift-anchored statistics whenever the accumulated statistics carry that payload (see GaussianAccumulator), which makes the fit shift-equivariant at any data offset. Statistics that arrive WITHOUT that payload cannot be corrected here – the information cancellation destroyed is not in them any more – and that is a reachable state, not a theoretical one: an engine kernel stacks the declared (sum, sum2, count, count2) moments directly, so optimize(x + 1.7e9, GaussianEstimator(), engine=NUMPY_ENGINE) on sd ~2 data returned a variance 7.9e9 times too large. estimate now WARNS in that case rather than returning it silently; the remedy is to accumulate through GaussianAccumulator (which anchors automatically) or to subtract a constant origin from the data before fitting.

ON GENUINELY DEGENERATE (zero-spread) DATA the equivariance guarantee above does not apply, and cannot: the true variance of a point mass is 0 and the true density is a Dirac delta, so the floor returned is a convention, not a measurement, and no offset makes one convention more correct than another. This estimator’s convention is ratio * mu**2 (scale-relative, so it is a UV of noise on 10 uV data and 2.9e10 on data at the Unix epoch); its sibling DiagonalGaussianEstimator uses a flat 1e-8 regardless of magnitude – the two disagree by up to 18 orders of magnitude on identical degenerate input (T1-05, campaign four), and neither is “right”. A caller that needs a specific, fixed value on this exact input – not just a safeguard against it – should pass min_covar=<value> explicitly, which both estimators honor exactly.

Parameters:
accumulator_factory()[source]

Return GaussianAccumulatorFactory with name and keys passed.

Return type:

GaussianAccumulatorFactory

model_log_density(model)[source]

Log-density of the model parameters under the NormalGamma prior (ELBO global term).

The prior is over (mu, tau=1/sigma2), so the model’s (mu, sigma2) is mapped accordingly.

Parameters:

model (GaussianDistribution)

Return type:

float

estimate(nobs, suff_stat)[source]

Estimate a Gaussian distribution from aggregated sufficient statistics.

The tuple is interpreted as (sum_x, sum_x2, count_for_mean, count_for_variance). Optional pseudo-counts smooth the corresponding mean and variance estimates.

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

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

Returns:

A fitted Gaussian distribution.

Return type:

GaussianDistribution

class GaussianFisherView(dist)[source]

Bases: FixedFisherView

Fisher view over the Gaussian’s (sum, sum2, count, count2) sufficient statistics.

Parameters:

dist (Any)

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

Bases: DistributionSampler

Draw independent samples from a GaussianDistribution.

Parameters:
  • dist (GaussianDistribution)

  • seed (int | None)

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

Draw iid samples from the Gaussian 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:

float | ndarray

class GaussianSuffStat(sum_, sum2_, count_, count2_, receipt=None)[source]

Bases: tuple

A (sum, sum2, count, count2) sufficient statistic that also carries side payloads.

Behaves exactly like the plain 4-tuple everywhere it is indexed, unpacked, or iterated (it is one); receipt is extra payload that GaussianAccumulator.combine() reads to fold the Kahan round-off bookkeeping (abs_total, n for sum and sum2) into the receiving accumulator when both sides are compensated, and anchored is the shift-anchored moment payload (anchor, sum_i w_i*(x_i - anchor), sum_i w_i*(x_i - anchor)^2) the accumulator maintains alongside the raw moments so the M-step variance survives large-offset data (see GaussianAccumulator). Code that doesn’t know about either payload (generic scale_suff_stat, engine kernels, …) sees an ordinary tuple.

Parameters:
class GeneralizedExtremeValueAccumulator(name=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted first three moments and the observed range for GEV estimation.

The range is not a moment: it is the support bound the estimate has to respect, since a GEV with xi != 0 is bounded on one side and moment matching alone can place that bound inside the sample. See _shape_covering_range().

Alongside the raw sums the accumulator keeps a CONDITIONING-GATED shift-anchored track, sum_i w_i (x_i - anchor)^k for k = 1..3 about a data anchor. The method of moments needs central moments, and differencing them out of raw power sums is the classic cancellation-prone form: at sd ~0.6 and offset 1.7e9 the raw variance is wrong by a factor of thousands and the raw third moment has no correct digits at all, which drives the shape onto its bound and the scale tens of times too large – silently. Anchoring keeps every term of the scatter O(count * spread^3), making the M-step shift-equivariant.

The gate keeps the historical path bit-identical for well-conditioned data: a chunk whose abs(mean)/spread ratio the raw form handles to ~1e-9 relative (see _needs_anchor()) accumulates exactly the way it always did, with no anchor and no second pass. The raw sums remain the exchange format, so the anchored track rides along as a payload on GeneralizedExtremeValueSuffStat; a consumer that drops the payload simply gets the historical raw estimate back.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted first three raw moments and the observed range for one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (GeneralizedExtremeValueDistribution | 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 first three raw moments and the observed range from encoded data.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (GeneralizedExtremeValueDistribution | 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 GEV sufficient-statistic tuple.

Parameters:

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

Return type:

GeneralizedExtremeValueAccumulator

value()[source]

Return raw moment sums, observation count, and the observed range.

The returned object is a plain 6-tuple for every consumer that treats it as one; once the shift-anchored track is live it additionally carries the anchored moments in its .anchored attribute, so combine() can fold them in and GeneralizedExtremeValueEstimator.estimate() can use them for the reduced moments. The payload is withheld when the track was seeded from raw statistics that had already lost their central moments (see _activate_anchor()), so a pool that cannot honestly claim shift-equivariance reports the historical raw statistics instead of a worse anchored guess.

Return type:

tuple[float, float, float, float, float, float]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

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

Return type:

GeneralizedExtremeValueAccumulator

scale(c)[source]

Scale accumulated evidence while preserving the observed range.

The shift-anchored track scales with the raw sums; leaving it behind would turn a scaled accumulator back into the ill-conditioned raw path.

Parameters:

c (float)

Return type:

GeneralizedExtremeValueAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

GeneralizedExtremeValueDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for GeneralizedExtremeValueAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh GEV accumulator.

Return type:

GeneralizedExtremeValueAccumulator

class GeneralizedExtremeValueDataEncoder[source]

Bases: DataSequenceEncoder

Encode GEV observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array.

Parameters:

x (Sequence[float])

Return type:

ndarray

class GeneralizedExtremeValueDistribution(loc, scale, shape, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Generalized Extreme Value distribution with location loc, scale > 0 and shape xi.

Parameters:
density(x)[source]

Return the probability density at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at a single observation (-inf outside the support).

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

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

Parameters:

x (ndarray)

Return type:

ndarray

classmethod compute_capabilities()[source]

Describe backend support for generated GEV kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for GEV distributions.

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

Per-row GEV moment sums in accumulator order (sum, sum2, sum3, count).

Deliberately not wired into the declaration as legacy_sufficient_statistics. The generated statistic path reduces every declared statistic with a weighted sum, ignoring StatisticSpec.additive, so it cannot produce the observed range the M-step needs to keep the fitted support around the data (see _shape_covering_range()) – it would silently hand estimate a summed min and max. GEV therefore accumulates through the host seq_update, which is three dot products for a univariate leaf; engine-resident scoring via backend_seq_log_density is unaffected. Reinstate this hook once the generated path honours non-additive support bounds.

Parameters:
Return type:

tuple[Any, …]

static backend_log_density_from_params(x, loc, scale, shape, engine)[source]

Engine-neutral GEV log-density; the abs(xi) < tol Gumbel limit is selected per element.

s^{-1/xi} is computed as exp(-log(s)/xi) so the whole expression stays on engine ops.

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]

Stacked GEV parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[GeneralizedExtremeValueDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

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

Parameters:
Return type:

Any

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

Parameters:

q (float)

Return type:

float

mean()[source]

Mean: loc + scale*(Gamma(1-xi)-1)/xi (loc+scale*euler_gamma at xi=0); inf for xi>=1.

Return type:

float

variance()[source]

Variance: scale^2 (Gamma(1-2xi)-Gamma(1-xi)^2)/xi^2 (scale^2 pi^2/6 at xi=0); inf for xi>=1/2.

Return type:

float

entropy()[source]

Differential entropy log(scale) + euler_gamma * xi + euler_gamma + 1.

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

GeneralizedExtremeValueSampler

estimator(pseudo_count=None)[source]

Return a method-of-moments estimator for loc, scale and shape.

Parameters:

pseudo_count (float | None)

Return type:

GeneralizedExtremeValueEstimator

dist_to_encoder()[source]

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

Return type:

GeneralizedExtremeValueDataEncoder

class GeneralizedExtremeValueEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-12, xi_max=1.0 / 3.0 - 1.0e-4, xi_min=-1.0, name=None, keys=None, prior_central=None)[source]

Bases: ParameterEstimator

Method-of-moments estimator for GEV location, scale and shape.

This is a moment estimator, not an MLE: the shape is solved from the skewness-vs-xi relation, and the shape is additionally constrained so the fitted support covers the observed range (see _shape_covering_range()). Whenever that constraint rewrites the shape – or the rewritten shape still scores the extreme observation catastrophically and the estimate falls back to the Gumbel limit – the returned distribution is not the raw moment fit, and the change is recorded in numerical_repairs() so fit_provenance() carries it (MXR-080-1202).

The reduced moments are formed about a reference point rather than about zero whenever the accumulated statistics carry a shift-anchored payload (see GeneralizedExtremeValueAccumulator), which makes the fit shift-equivariant: estimate on x + c returns loc + c with scale and shape unchanged. With a plain raw tuple – statistics restored from an older serialization, or a hand-built one – the historical raw path is used unchanged.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for GEV raw-moment statistics.

Return type:

GeneralizedExtremeValueAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate location, scale, and shape from weighted moments, keeping the data in support.

Parameters:
Return type:

GeneralizedExtremeValueDistribution

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

Bases: DistributionSampler

Draw iid GEV observations by inverse-CDF transform.

Parameters:
  • dist (GeneralizedExtremeValueDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples by inverse CDF.

Parameters:
Return type:

float | ndarray

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate the weighted power sums (count, sum x, sum x^2, sum x^3, sum x^4) for the MoM.

Alongside the raw sums the accumulator keeps a CONDITIONING-GATED shift-anchored track, sum_i w_i (x_i - anchor)^k for k = 1..4 about a data anchor. The method of moments needs central moments, and differencing them out of raw power sums is the classic cancellation-prone form: the fourth reduced moment loses roughly 4*log2(abs(mean)/sd) bits, so data with sd ~0.7 at offset 1.7e9 has no correct digits left in m4 and the fit collapses onto the shape bound with a scale two orders of magnitude too small – silently. Anchoring keeps every term of the scatter O(count * spread^4), making the M-step shift-equivariant.

The gate keeps the historical path bit-identical for well-conditioned data: a chunk whose abs(mean)/spread ratio the raw form handles to ~1e-9 relative (see _needs_anchor()) accumulates exactly the way it always did, with no anchor and no second pass. The raw sums remain the exchange format, so the anchored track rides along as a payload on GeneralizedGaussianSuffStat; a consumer that drops the payload simply gets the historical raw estimate back.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted raw moments up to order four for one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (GeneralizedGaussianDistribution | 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 raw moments up to order four from encoded data.

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 generalized-Gaussian sufficient-statistic tuple.

Parameters:

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

Return type:

GeneralizedGaussianAccumulator

value()[source]

Return count and raw moment sums through order four.

The returned object is a plain 5-tuple for every consumer that treats it as one; once the shift-anchored track is live it additionally carries the anchored moments in its .anchored attribute, so combine() can fold them in and GeneralizedGaussianEstimator.estimate() can use them for the reduced moments. The payload is withheld when the track was seeded from raw statistics that had already lost their central moments (see _activate_anchor()), so a pool that cannot honestly claim shift-equivariance reports the historical raw statistics instead of a worse anchored guess.

Return type:

tuple[float, float, float, float, float]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

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

Return type:

GeneralizedGaussianAccumulator

scale(c)[source]

Scale accumulated evidence, keeping the shift-anchored track in step with the raw sums.

The generic base implementation round-trips through scale_suff_stat/from_value, which sees only a plain tuple and would silently drop the anchored payload – turning a scaled accumulator back into the ill-conditioned raw path.

Parameters:

c (float)

Return type:

GeneralizedGaussianAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

GeneralizedGaussianDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for GeneralizedGaussianAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh generalized-Gaussian accumulator.

Return type:

GeneralizedGaussianAccumulator

class GeneralizedGaussianDataEncoder[source]

Bases: DataSequenceEncoder

Encode observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array.

Parameters:

x (Sequence[float])

Return type:

ndarray

class GeneralizedGaussianDistribution(mu, alpha, beta, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Generalized Gaussian (exponential power) with location mu, scale alpha and shape beta.

Parameters:
classmethod compute_declaration()[source]

Return the structured compute declaration for generalized Gaussian distributions.

static backend_log_density_from_params(x, mu, alpha, beta, engine)[source]

Engine-neutral generalized-Gaussian log-density: log_norm - (abs(x-mu)/alpha)**beta.

Parameters:
Return type:

Any

density(x)[source]

Return the probability density at x.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at x.

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-density for a sequence-encoded array of observations.

Parameters:

x (ndarray)

Return type:

ndarray

cdf(x)[source]

Cumulative distribution function P(X <= x).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

Parameters:

q (float)

Return type:

float

mean()[source]

Mean (the location mu).

Return type:

float

variance()[source]

Variance alpha^2 Gamma(3/beta) / Gamma(1/beta).

Return type:

float

skewness()[source]

Skewness (0 – the law is symmetric).

Return type:

float

kurtosis()[source]

Excess kurtosis Gamma(5/beta)Gamma(1/beta)/Gamma(3/beta)^2 - 3.

Return type:

float

entropy()[source]

Differential entropy 1/beta - log(beta / (2 alpha Gamma(1/beta))).

Return type:

float

sampler(seed=None)[source]

Return a sampler (Gamma magnitude with a random sign).

Parameters:

seed (int | None)

Return type:

GeneralizedGaussianSampler

estimator(pseudo_count=None)[source]

Return a method-of-moments estimator for mu, alpha, beta.

Parameters:

pseudo_count (float | None)

Return type:

GeneralizedGaussianEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution (the raw value).

Return type:

GeneralizedGaussianDataEncoder

class GeneralizedGaussianEstimator(pseudo_count=None, suff_stat=None, beta_bounds=(0.25, 50.0), name=None, keys=None, prior_central=None)[source]

Bases: ParameterEstimator

Method-of-moments estimator: mu = mean, beta from excess kurtosis, alpha from variance.

The reduced moments are formed about a reference point rather than about zero whenever the accumulated statistics carry a shift-anchored payload (see GeneralizedGaussianAccumulator), which makes the fit shift-equivariant: estimate on x + c returns mu + c with alpha and beta unchanged. With a plain raw tuple – statistics restored from an older serialization, or a hand-built one – the historical raw path is used unchanged.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for generalized-Gaussian raw moments.

Return type:

GeneralizedGaussianAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate location, scale, and shape from weighted raw moments.

Parameters:
Return type:

GeneralizedGaussianDistribution

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

Bases: DistributionSampler

Draw x = mu + sign * alpha * Gamma(1/beta)**(1/beta).

Parameters:
  • dist (GeneralizedGaussianDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

class GeneralizedParetoAccumulator(loc=0.0, name=None, keys=None, has_prior=False)[source]

Bases: AnchoredMomentTrack, SequenceEncodableStatisticAccumulator

Accumulate weighted first and second moments for GPD estimation.

Alongside the raw (sum, sum2, count) the accumulator keeps the conditioning-gated shift-anchored moment track of AnchoredMomentTrack. Peaks-over-threshold data is the case that needs it most: BOTH moments the inversion uses are differences taken at data magnitude – the exceedance mean sum_x/count - loc and the variance E[x^2]-E[x]^2 – so a threshold at epoch seconds turned a shape of +0.16 into a flat 0 and the exponential limit, silently. Well-conditioned data never activates the track and accumulates bit-identically to the historical single-pass path.

Parameters:
update(x, weight, estimate)[source]

Accumulate weighted first and second moments for one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (GeneralizedParetoDistribution | 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 first and second moments from encoded data.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (GeneralizedParetoDistribution | None)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded observations.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and at or above the threshold loc.

The encoder admits rows below the threshold so a mixture can encode one batch against every component; this is the predicate a latent model’s initialization consults before handing this component any responsibility (Q01-F02).

Parameters:

x (Any)

Return type:

ndarray

combine(suff_stat)[source]

Merge another generalized-Pareto sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

GeneralizedParetoAccumulator

value()[source]

Return accumulated sum, second moment sum, and count.

A plain 3-tuple for every consumer that treats it as one; once the shift-anchored moment track is live, or a trustworthy observation max is known AND relevant, it is a GeneralizedParetoSuffStat additionally carrying the anchored moments in its .anchored attribute and/or the max in .max_x, so combine() can fold them in and GeneralizedParetoEstimator.estimate() can invert threshold-invariant moments and keep a shape<0 fit’s implied support consistent with the data (T1-01). “Relevant” is always true for a prior-carrying estimator (see _max_x_relevant()); for one without a prior it is the same cheap raw-moment pre-check as before, so ordinary well-conditioned data still returns the historical plain tuple, byte for byte.

For a prior-carrying estimator that protection is supposed to be unconditional, but a foreign (pre-payload) combine() can still leave real observations with no trustworthy max (self._max_tainted); rather than silently degrade to the plain tuple that hides this from estimate, that case is still reported as a GeneralizedParetoSuffStat with max_x=None and max_unverified=True, so estimate can disclose the ambiguity instead of reproducing the T1-01 crash class with zero signal (T1-02).

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:

GeneralizedParetoAccumulator

scale(c)[source]

Scale the accumulated statistics in place by c, anchored track included.

The structural default round-trips through value()/from_value() and scale_suff_stat rebuilds a PLAIN tuple, which would drop the payload and undo the repair; loc is a fixed threshold, not a statistic, and is left alone. The tracked max is likewise left alone: uniform weight scaling reweights the aggregate contribution of the same observations, it does not change which values were actually observed.

Parameters:

c (float)

Return type:

GeneralizedParetoAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

GeneralizedParetoDataEncoder

class GeneralizedParetoAccumulatorFactory(loc=0.0, name=None, keys=None, has_prior=False)[source]

Bases: StatisticAccumulatorFactory

Factory for GeneralizedParetoAccumulator.

Parameters:
make()[source]

Create a fresh generalized-Pareto accumulator.

Return type:

GeneralizedParetoAccumulator

class GeneralizedParetoDataEncoder(loc=0.0, scale=None, shape=None)[source]

Bases: DataSequenceEncoder

Encode GPD observations as a float array.

Parameters:
seq_encode(x)[source]

Encode observations as a floating-point array, admitting finite rows outside the support.

A row below the threshold – or, for a negative shape, above the upper endpoint – is scored -inf by GeneralizedParetoDistribution.seq_log_density(), exactly as the scalar path scores it, so a mixture whose other component owns it can encode the whole batch (P02-F03). Refusing it here made Mixture[Gaussian, GeneralizedPareto] unencodable (Q01-F02). Non-finite values stay refused.

Parameters:

x (Sequence[float])

Return type:

ndarray

class GeneralizedParetoDistribution(scale, shape, loc=0.0, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Generalized Pareto distribution with threshold loc, scale > 0 and shape xi.

Parameters:
density(x)[source]

Return the probability density at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at a single observation (-inf outside the support).

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

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

Parameters:

x (ndarray)

Return type:

ndarray

classmethod compute_capabilities()[source]

Describe backend support for generated generalized-Pareto kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for generalized Pareto distributions.

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

Per-row GPD moment sums in accumulator order (sum, sum2, count).

Parameters:
Return type:

tuple[Any, …]

static backend_log_density_from_params(x, scale, shape, loc, engine)[source]

Engine-neutral GPD log-density; the abs(xi) < tol exponential limit is selected per element.

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]

Stacked GPD parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[GeneralizedParetoDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

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

Parameters:
Return type:

Any

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

Stacked GPD moment sums (sum, sum2, count) using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

Parameters:

q (float)

Return type:

float

mean()[source]

Mean loc + scale/(1-xi) for xi < 1, else inf.

Return type:

float

variance()[source]

Variance scale^2 / ((1-xi)^2 (1-2xi)) for xi < 1/2, else inf.

Return type:

float

entropy()[source]

Differential entropy log(scale) + xi + 1.

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

GeneralizedParetoSampler

estimator(pseudo_count=None)[source]

Return a method-of-moments estimator for scale and shape at the fixed threshold loc.

Parameters:

pseudo_count (float | None)

Return type:

GeneralizedParetoEstimator

dist_to_encoder()[source]

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

Return type:

GeneralizedParetoDataEncoder

class GeneralizedParetoEstimator(loc=0.0, pseudo_count=None, suff_stat=None, min_scale=1.0e-12, xi_max=0.5 - 1.0e-6, xi_min=-10.0, name=None, keys=None)[source]

Bases: ParameterEstimator

Method-of-moments estimator for GPD scale and shape at a fixed threshold loc.

Both inverted moments – the exceedance mean sum_x/count - loc and the variance E[x^2]-E[x]^2 – are differences taken at DATA magnitude, so a threshold far from zero destroys them: peaks over a threshold at epoch seconds fitted shape=0 (the exponential limit) instead of +0.16, silently. Whenever the accumulated statistics carry the shift-anchored payload (see GeneralizedParetoAccumulator) both moments are formed about a data anchor instead, which makes the fit THRESHOLD-EQUIVARIANT: estimating on x + c with the threshold at loc + c returns the same scale and shape, for any constant c the data can carry. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, and estimate warns rather than returning moments it cannot stand behind.

The pseudo_count prior is carried as the raw pair suff_stat = (mean0, second0); a plain 2-tuple has its variance and exceedance-mean offset recovered by differencing (second0 - mean0**2 and mean0 - loc respectively), which is the prior’s own encoding and is unaffected by the anchored track – a prior whose mean sits far from zero loses precision in both reconstructions, so express such a prior in threshold-relative coordinates, or build it with GeneralizedParetoDistribution.estimator(), which carries both exactly (see GeneralizedParetoPriorMoments).

loc is a property, not a bare attribute: reassigning it re-targets this SAME estimator at a new threshold (the “threshold stability” / mean-residual-life re-thresholding workflow) and, when a pseudo_count prior is configured, re-anchors its frozen (mean0, second0) moments to the new origin so the prior keeps meaning what it meant when built instead of being silently reinterpreted relative to the wrong loc (T1-01).

Parameters:
property loc: float

The fixed threshold mu observations are exceedances over.

accumulator_factory()[source]

Return an accumulator factory for generalized-Pareto moments.

Return type:

GeneralizedParetoAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate scale and shape from exceedance moments at the fixed location.

Parameters:
Return type:

GeneralizedParetoDistribution

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

Bases: DistributionSampler

Draw iid GPD observations by inverse-CDF transform.

Parameters:
  • dist (GeneralizedParetoDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples by inverse CDF.

Parameters:
Return type:

float | ndarray

class GumbelAccumulator(keys=None)[source]

Bases: AnchoredMomentTrack, SequenceEncodableStatisticAccumulator

Accumulate weighted first and second moments for Gumbel estimation.

Alongside the raw (sum, sum2, count) the accumulator keeps the conditioning-gated shift-anchored moment track of AnchoredMomentTrack: the naive E[x^2]-E[x]^2 form the moment inversion needs loses ~``2*log2(abs(mean)/sd)`` bits to cancellation, so Gumbel data with sd ~2 fitted a scale 8.8x too large at offset 1.7e9 and collapsed onto min_scale at 2**31 – silently, with an empty numerical_repairs(). Well-conditioned data never activates the track and accumulates bit-identically to the historical single-pass path.

Parameters:

keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted first and second moments for one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (GumbelDistribution | 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 first and second moments from encoded data.

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 Gumbel sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

GumbelAccumulator

value()[source]

Return accumulated sum, second moment sum, and count.

A plain 3-tuple for every consumer that treats it as one; once the shift-anchored moment track is live it is a GumbelSuffStat additionally carrying the anchored moments in its .anchored attribute, so combine() can fold them in and GumbelEstimator.estimate() can invert a shift-invariant variance.

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:

GumbelAccumulator

scale(c)[source]

Scale the accumulated statistics in place by c, anchored track included.

Parameters:

c (float)

Return type:

GumbelAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

GumbelDataEncoder

class GumbelAccumulatorFactory(keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for GumbelAccumulator.

Parameters:

keys (str | None)

make()[source]

Create a fresh Gumbel accumulator.

Return type:

GumbelAccumulator

class GumbelDataEncoder[source]

Bases: DataSequenceEncoder

Encode Gumbel observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array.

Parameters:

x (Sequence[float])

Return type:

ndarray

class GumbelDistribution(loc=0.0, scale=1.0, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Gumbel (extreme value type I) distribution with location loc and scale beta > 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated Gumbel kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Gumbel distributions.

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

Return per-row Gumbel sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static backend_log_density_from_params(x, loc, scale, engine)[source]

Engine-neutral Gumbel log-density from explicit parameters.

Parameters:
Return type:

Any

density(x)[source]

Return the probability density at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at a single observation.

Parameters:

x (float)

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 for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked Gumbel 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 Gumbel log densities.

Parameters:
Return type:

Any

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

Return stacked Gumbel sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

q = 0 and q = 1 return the support’s bounds, -inf and +inf: Gumbel was the one continuous family that raised there, where Gaussian, Laplace and the rest already returned the infinities (P01-F12).

Parameters:

q (float)

Return type:

float

mean()[source]

Mean E[X] = loc + scale * euler_gamma.

Return type:

float

variance()[source]

Variance Var[X] = pi^2 scale^2 / 6.

Return type:

float

entropy()[source]

Differential entropy log(scale) + euler_gamma + 1.

Return type:

float

skewness()[source]

Skewness 12*sqrt(6)*zeta(3)/pi^3.

Return type:

float

kurtosis()[source]

Excess kurtosis (12/5).

Return type:

float

mode()[source]

Mode (= the location loc).

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

GumbelSampler

estimator(pseudo_count=None)[source]

Return a moment estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

GumbelEstimator

dist_to_encoder()[source]

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

Return type:

GumbelDataEncoder

class GumbelEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Moment estimator for the Gumbel location and scale.

Inverts the Gumbel moments: beta = sqrt(6 * var) / pi and loc = mean - beta * gamma where gamma is the Euler-Mascheroni constant.

The variance moment is formed from shift-anchored statistics whenever the accumulated sufficient statistics carry that payload (see GumbelAccumulator), which makes the fit SHIFT-EQUIVARIANT: estimating on x + c returns loc + c with scale unchanged, for any constant c the data can carry – epoch seconds (~1.7e9) and 2**31 included. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, and estimate warns rather than returning a scale it cannot stand behind.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for Gumbel moment statistics.

Return type:

GumbelAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate location and scale from weighted moments.

Parameters:
Return type:

GumbelDistribution

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

Bases: DistributionSampler

Draw iid Gumbel observations.

Parameters:
  • dist (GumbelDistribution)

  • seed (int | None)

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

Draw size iid observations (a float when size is None).

Parameters:
Return type:

float | ndarray

class HalfNormalAccumulator(keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted count and sum of squares for half-normal estimation.

Parameters:

keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted squared observations for one non-negative sample.

Parameters:
  • x (float)

  • weight (float)

  • estimate (HalfNormalDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and non-negative.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility.

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate weighted squared observations from encoded data.

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 half-normal sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float])

Return type:

HalfNormalAccumulator

value()[source]

Return count and squared-observation sum.

Return type:

tuple[float, float]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

x (tuple[float, float])

Return type:

HalfNormalAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

HalfNormalDataEncoder

class HalfNormalAccumulatorFactory(keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for HalfNormalAccumulator.

Parameters:

keys (str | None)

make()[source]

Create a fresh half-normal accumulator.

Return type:

HalfNormalAccumulator

class HalfNormalDataEncoder[source]

Bases: DataSequenceEncoder

Encode half-normal observations as x and x**2.

seq_encode(x)[source]

Encode observations as values and squared values.

Parameters:

x (Sequence[float])

Return type:

tuple[ndarray, ndarray]

class HalfNormalDistribution(sigma, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Half-normal distribution with scale sigma > 0 on x >= 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated half-normal kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for half-normal distributions.

static exp_family_sufficient_statistics(x, engine)[source]

Return the (x**2,) sufficient statistic for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return the (-1/(2*sigma^2),) natural parameter for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the half-normal log partition log(sigma).

Parameters:
Return type:

Any

static exp_family_base_measure(x, engine)[source]

Return the support base measure 0.5*log(2/pi) (or -inf off support x >= 0).

Parameters:
Return type:

Any

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

Return per-row (count, x**2) sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

density(x)[source]

Return the probability density at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at a single observation (or -inf off support).

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

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

Parameters:

x (Tuple[ndarray, ndarray]) – Tuple of observations and squared observations produced by the HalfNormalDataEncoder.

Returns:

Numpy array of log-density values, with -inf entries off the non-negative support.

Return type:

ndarray

static backend_log_density_from_params(vals, sq_vals, sigma, engine)[source]

Engine-neutral half-normal 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 parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[HalfNormalDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

Return an (n, k) matrix of half-normal 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]

cdf(x)[source]

Cumulative distribution function P(X <= x) (0 for x < 0).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

Parameters:

q (float)

Return type:

float

mean()[source]

Mean E[X] = sigma * sqrt(2/pi).

Return type:

float

variance()[source]

Variance Var[X] = sigma^2 (1 - 2/pi).

Return type:

float

entropy()[source]

Differential entropy 0.5*log(pi*sigma^2/2) + 1/2.

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

HalfNormalSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (Optional[float]) – Re-weight the second moment toward this instance’s own E[x**2] = sigma**2 when not None (a simple ridge toward the current parameter).

Returns:

HalfNormalEstimator object.

Return type:

HalfNormalEstimator

dist_to_encoder()[source]

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

Return type:

HalfNormalDataEncoder

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

Bases: ParameterEstimator

Maximum-likelihood estimator for the half-normal scale: sigma = sqrt(mean(x**2)).

Parameters:
  • pseudo_count (float | None)

  • suff_stat (float | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return an accumulator factory for half-normal statistics.

Return type:

HalfNormalAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate the half-normal scale from weighted squared observations.

Parameters:
Return type:

HalfNormalDistribution

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

Bases: DistributionSampler

Draw iid half-normal observations as |N(0, sigma**2)|.

Parameters:
  • dist (HalfNormalDistribution)

  • seed (int | None)

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

Draw size iid observations (a float when size is None).

Parameters:
Return type:

float | ndarray

class InverseGammaAccumulator(keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted count, sum of reciprocals, and sum of negative logs for inverse-gamma estimation.

Parameters:

keys (str | None)

update(x, weight, estimate)[source]

Accumulate reciprocal and negative-log statistics for one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (InverseGammaDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and strictly positive.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility.

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate transformed sufficient statistics from encoded data.

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 inverse-gamma sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

InverseGammaAccumulator

value()[source]

Return count, reciprocal sum, and negative-log 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:

InverseGammaAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

InverseGammaDataEncoder

class InverseGammaAccumulatorFactory(keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for InverseGammaAccumulator.

Parameters:

keys (str | None)

make()[source]

Create a fresh inverse-gamma accumulator.

Return type:

InverseGammaAccumulator

class InverseGammaDataEncoder[source]

Bases: DataSequenceEncoder

Encode inverse-gamma observations as (log x, 1/x) pairs.

seq_encode(x)[source]

Encode observations as log-values and reciprocal values.

Parameters:

x (Sequence[float])

Return type:

tuple[ndarray, ndarray]

class InverseGammaDistribution(alpha, beta, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Inverse-gamma distribution with shape alpha > 0 and rate beta > 0 on x > 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated inverse-gamma kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for inverse-gamma distributions.

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

Return per-row (count, 1/x, -log x) sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_sufficient_statistics(x, engine)[source]

Return inverse-gamma sufficient statistics T(x) = (log x, 1/x).

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return inverse-gamma natural parameters eta = (-(alpha + 1), -beta).

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return inverse-gamma log partition A = lgamma(alpha) - alpha * log(beta).

Parameters:
Return type:

Any

static exp_family_from_natural(eta)[source]

Return the inverse-gamma with natural parameters eta = (-(alpha + 1), -beta).

Parameters:

eta (Any)

Return type:

InverseGammaDistribution

static backend_log_density_from_params(log_x, inv_x, alpha, beta, log_const, engine)[source]

Engine-neutral inverse-gamma log-density from explicit parameters (linear in log x and 1/x).

Parameters:
Return type:

Any

get_parameters()[source]

Return the (shape alpha, rate beta) pair (so this can serve as a conjugate prior).

Return type:

tuple[float, float]

cross_entropy(dist)[source]

Cross entropy -E_self[log dist(x)] for an inverse-gamma argument (closed form).

Parameters:

dist (InverseGammaDistribution)

Return type:

float

entropy()[source]

Returns the differential entropy in nats.

Return type:

float

mean()[source]

Mean E[X] = beta / (alpha - 1) for alpha > 1, else inf (the mean integral diverges).

Return type:

float

variance()[source]

Variance beta^2 / ((alpha-1)^2 (alpha-2)) for alpha > 2, else inf.

Return type:

float

density(x)[source]

Return the probability density at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at a single observation (or -inf off support).

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-density values for sequence-encoded (log x, 1/x) observations.

Parameters:

x (tuple[ndarray, ndarray])

Return type:

ndarray

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 parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[InverseGammaDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

Return an (n, k) matrix of inverse-gamma 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, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) = Q(alpha, beta/x) (0 for x <= 0).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-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:

InverseGammaSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

InverseGammaEstimator

dist_to_encoder()[source]

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

Return type:

InverseGammaDataEncoder

class InverseGammaEstimator(pseudo_count=None, suff_stat=None, threshold=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Maximum-likelihood estimator for the inverse-gamma shape and rate.

Fits the gamma distribution to the reciprocals y = 1/x (y ~ Gamma(alpha, 1/beta)) by the standard log-mean / mean shape equation, then maps back to (alpha, beta) = (k, 1/theta).

Parameters:
accumulator_factory()[source]

Return an accumulator factory for inverse-gamma statistics.

Return type:

InverseGammaAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate shape and rate from reciprocal and log-reciprocal statistics.

Parameters:
Return type:

InverseGammaDistribution

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

Bases: DistributionSampler

Draw iid inverse-gamma observations as 1 / Gamma(alpha, 1/beta).

Parameters:
  • dist (InverseGammaDistribution)

  • seed (int | None)

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

Draw size iid observations (a float when size is None).

Parameters:
Return type:

float | ndarray

class InverseGaussianAccumulator(keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted count, sum, and sum of reciprocals for inverse Gaussian estimation.

Parameters:

keys (str | None)

update(x, weight, estimate)[source]

Accumulate count, sum, and reciprocal sum for one positive observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (InverseGaussianDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and strictly positive.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility.

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate transformed sufficient statistics from encoded data.

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 inverse-Gaussian sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

InverseGaussianAccumulator

value()[source]

Return count, sum, and reciprocal 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:

InverseGaussianAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

InverseGaussianDataEncoder

class InverseGaussianAccumulatorFactory(keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for InverseGaussianAccumulator.

Parameters:

keys (str | None)

make()[source]

Create a fresh inverse-Gaussian accumulator.

Return type:

InverseGaussianAccumulator

class InverseGaussianDataEncoder[source]

Bases: DataSequenceEncoder

Encode inverse Gaussian observations as x, 1/x, and log(x).

seq_encode(x)[source]

Encode observations as values, reciprocal values, and log-values.

Parameters:

x (Sequence[float])

Return type:

tuple[ndarray, ndarray, ndarray]

class InverseGaussianDistribution(mu, lam, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Inverse Gaussian (Wald) distribution with mean mu > 0 and shape lam > 0 on x > 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated inverse-Gaussian kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for inverse Gaussian distributions.

static exp_family_sufficient_statistics(x, engine)[source]

Return the (x, 1/x) sufficient statistics for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return the (-lam/(2*mu^2), -lam/2) natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the inverse Gaussian log partition -0.5*log(lam) - lam/mu.

Parameters:
Return type:

Any

static exp_family_base_measure(x, engine)[source]

Return the support base measure -0.5*log(2*pi) - 1.5*log(x) (or -inf off support).

Parameters:
Return type:

Any

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

Return per-row (count, x, 1/x) sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

density(x)[source]

Return the probability density at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at a single observation (or -inf off support).

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

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

Parameters:

x (Tuple[ndarray, ndarray, ndarray]) – Tuple of observations, reciprocals, and log values produced by the InverseGaussianDataEncoder.

Returns:

Numpy array of log-density values, with -inf entries off the positive support.

Return type:

ndarray

static backend_log_density_from_params(vals, inv_vals, log_vals, mu, lam, engine)[source]

Engine-neutral inverse Gaussian 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 parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[InverseGaussianDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

Return an (n, k) matrix of inverse Gaussian 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, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) (Wald, via scipy invgauss).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

Parameters:

q (float)

Return type:

float

mean()[source]

Mean E[X] = mu.

Return type:

float

variance()[source]

Variance Var[X] = mu^3 / lam.

Return type:

float

entropy()[source]

Differential entropy in nats (closed form).

H = -E[log f(X)] = 1/2 log(2 pi e / lam) + 3/2 E[log X] (the quadratic term integrates to exactly 1/2 since E[(X - mu)^2 / X] = mu^2 / lam), with E[log X] = log(mu) - e^{2z} E_1(2z) at z = lam / mu – the order-derivative identity for the Bessel K_{1/2} under the GIG representation, E_1 the exponential integral. The scaled product e^x E_1(x) switches to its asymptotic series where exp overflows.

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

InverseGaussianSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (Optional[float]) – Re-weight the sufficient statistics of this instance toward its own moments when not None (a simple ridge toward the current parameters).

Returns:

InverseGaussianEstimator object.

Return type:

InverseGaussianEstimator

dist_to_encoder()[source]

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

Return type:

InverseGaussianDataEncoder

class InverseGaussianEstimator(pseudo_count=None, suff_stat=None, min_param=_MIN_IG_PARAM, max_param=_MAX_IG_PARAM, name=None, keys=None)[source]

Bases: ParameterEstimator

Maximum-likelihood estimator for the inverse Gaussian mean and shape.

The MLE is closed form: mu = mean(x) and 1/lam = mean(1/x) - 1/mu.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for inverse-Gaussian statistics.

Return type:

InverseGaussianAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate mean and shape from count, sum, and reciprocal sum.

Parameters:
Return type:

InverseGaussianDistribution

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

Bases: DistributionSampler

Draw iid inverse Gaussian (Wald) observations.

Parameters:
  • dist (InverseGaussianDistribution)

  • seed (int | None)

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

Draw size iid observations (a float when size is None).

Parameters:
Return type:

float | ndarray

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted observations for exact weighted-median M-step.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Store one positively weighted observation for the weighted-median M-step.

Parameters:
  • x (float)

  • weight (float)

  • estimate (LaplaceDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Store positively weighted encoded observations for estimation.

Parameters:
Return type:

None

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

Engine-aware accumulation. Laplace’s MLE is a weighted median, so the sufficient statistic is the (positively weighted) data itself; this path accepts engine (e.g. torch) weights and stores host arrays. Matches seq_update.

Parameters:
  • x (ndarray)

  • weights (Any)

  • estimate (LaplaceDistribution | None)

  • engine (Any)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded observations.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge raw weighted observations from another accumulator.

Parameters:

suff_stat (tuple[ndarray, ndarray])

Return type:

LaplaceAccumulator

value()[source]

Return flattened observations and weights.

Return type:

tuple[ndarray, ndarray]

from_value(x)[source]

Replace accumulator contents from raw observations and weights.

Parameters:

x (tuple[ndarray, ndarray])

Return type:

LaplaceAccumulator

scale(c)[source]

Scale weights while preserving the raw observation payload.

Parameters:

c (float)

Return type:

LaplaceAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

LaplaceDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for LaplaceAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Laplace accumulator.

Return type:

LaplaceAccumulator

class LaplaceDataEncoder[source]

Bases: DataSequenceEncoder

Encode Laplace observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array.

Parameters:

x (Sequence[float])

Return type:

ndarray

class LaplaceDistribution(mu, b, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Laplace distribution with location mu and scale b > 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated Laplace kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Laplace distributions.

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

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

Parameters:

x (float)

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, mu, b, engine)[source]

Engine-neutral Laplace 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 Laplace 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 Laplace log densities.

Parameters:
Return type:

Any

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

Return per-component raw weighted observations using engine-resident arrays.

Parameters:
Return type:

tuple[tuple[Any, Any], …]

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

entropy()[source]

Differential entropy 1 + log(2b).

Return type:

float

skewness()[source]

Skewness (0).

Return type:

float

kurtosis()[source]

Excess kurtosis (3).

Return type:

float

mode()[source]

Mode (= the location mu).

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

LaplaceSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

LaplaceEstimator

dist_to_encoder()[source]

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

Return type:

LaplaceDataEncoder

class LaplaceEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Exact weighted-MLE estimator for Laplace location and scale.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for Laplace raw-observation statistics.

Return type:

LaplaceAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate location and scale by the exact weighted MLE.

Parameters:
Return type:

LaplaceDistribution

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

Bases: DistributionSampler

Draw iid Laplace observations.

Parameters:
  • dist (LaplaceDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

Bases: AnchoredMomentTrack, SequenceEncodableStatisticAccumulator

Accumulate weighted log-scale moments for log-Gaussian estimation.

Alongside the raw log moments the accumulator keeps the conditioning-gated shift-anchored track of AnchoredMomentTrack. The log transform bounds abs(log x) at ~709, so this family cannot reach the epoch-offset regime its siblings do – but it reaches the same defect from the other side, because a large multiplicative scale IS a large additive offset on log(x): values around 1e6 with a 0.2% spread lost 1.4e-7 of the fitted sigma2, and values around 1e20 with a 0.1% spread lost 7.1e-7, silently. Well-conditioned data never activates the track and accumulates bit-identically to the historical single-pass path.

The mixin names the moments it differences sum/sum2; for this family those are the LOG moments, so the two aliases below tie them to log_sum/log_sum2. Aliases rather than a rename because (log_sum, log_sum2, count, count2) is the released attribute spelling.

Parameters:
  • keys (str | None)

  • name (str | None)

property sum: float

Alias of log_sum – the first moment the anchored track and the M-step difference.

property sum2: float

Alias of log_sum2 – the second moment the anchored track and the M-step difference.

update(x, weight, estimate)[source]

Update sufficient statistics for LogGaussianAccumulator with one weighted observation.

Parameters:
  • x (float) – Observation from log-Gaussian distribution.

  • weight (float) – Weight for observation.

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

Returns:

None.

Return type:

None

initialize(x, weight, rng)[source]

Initialize sufficient statistics with one weighted observation.

Parameters:
  • x (float) – Observation from log-Gaussian distribution.

  • weight (float) – Weight for observation.

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

Returns:

None.

Return type:

None

seq_initialize(x, weights, rng)[source]

Vectorized initialization of LogGaussianAccumulator sufficient statistics with weighted observations.

This delegates to seq_update().

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

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

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

Returns:

None.

Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite on the log scale, i.e. strictly positive.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility.

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Vectorized update of sufficient statistics from encoded sequence x.

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

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

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

Returns:

None.

Return type:

None

combine(suff_stat)[source]

Aggregates sufficient statistics with LogGaussianAccumulator member sufficient statistics.

Arg passed suff_stat is tuple of four floats:

suff_stat[0] (float): Sum of weighted observations (sum_i w_i*log(X_i)), suff_stat[1] (float): Sum of weighted observations (sum_i w_i*log(X_i)^2), suff_stat[2] (float): Sum of weighted observations (sum_i w_i), suff_stat[3] (float): Sum of weighted observations (sum_i w_i).

Parameters:

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

Returns:

GaussianAccumulator object.

Return type:

LogGaussianAccumulator

value()[source]

Return sufficient statistics as (log_sum, log_sum2, count, count2).

A plain 4-tuple for every consumer that treats it as one; once the shift-anchored moment track is live it is a LogGaussianSuffStat additionally carrying the anchored log moments in its anchored attribute.

Return type:

tuple[float, float, float, float]

from_value(x)[source]

Assigns sufficient statistics of LogGaussianAccumulator instance to x.

Arg passed x is tuple of four floats:

x[0] (float): Sum of weighted observations (sum_i w_i*log(X_i)), x[1] (float): Sum of weighted observations (sum_i w_i*log(X_i)^2), x[2] (float): Sum of weighted observations (sum_i w_i), x[3] (float): Sum of weighted observations (sum_i w_i).

Parameters:

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

Returns:

LogGaussianAccumulator object.

Return type:

LogGaussianAccumulator

scale(c)[source]

Scale the accumulated statistics in place by c, anchored track included.

The structural default round-trips through value()/from_value(), and scale_suff_stat rebuilds the payload as a PLAIN tuple – which drops the anchored track and undoes the repair. Uniform weight scaling is exactly linear in both anchored moments and leaves the anchor (a log-data value, not a statistic) alone.

Parameters:

c (float)

Return type:

LogGaussianAccumulator

acc_to_encoder()[source]

Return the encoder associated with this accumulator.

Return type:

LogGaussianDataEncoder

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

Bases: StatisticAccumulatorFactory

Create log-Gaussian accumulators with shared name and merge-key metadata.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Return a fresh log-Gaussian accumulator with this factory’s name and keys.

Return type:

LogGaussianAccumulator

class LogGaussianDataEncoder[source]

Bases: DataSequenceEncoder

Data encoder for iid positive log-Gaussian observations.

seq_encode(x)[source]

Encode sequence of iid Log-Gaussian observations.

Data type must be List[float] or np.ndarray[float].

Parameters:

x (Union[List[float], np.ndarray]) – Sequence of iid log-Gaussian observations.

Returns:

A numpy array of floats.

Return type:

ndarray

class LogGaussianDistribution(mu, sigma2, name=None, keys=None, prior=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Log-normal distribution where log(X) is Gaussian with mean mu and variance sigma2.

Parameters:
  • mu (float)

  • sigma2 (float)

  • name (str | None)

  • keys (str | None)

  • prior (SequenceEncodableProbabilityDistribution | None)

classmethod compute_capabilities()[source]

Declare backend support for generated log-Gaussian density kernels.

classmethod compute_declaration()[source]

Return the generated-compute declaration for the log-Gaussian distribution.

static exp_family_sufficient_statistics(x, engine)[source]

Return log-Gaussian sufficient statistics for generated scoring.

Parameters:
Return type:

tuple[Any, …]

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

Return per-row log-Gaussian sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return log-Gaussian natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return log-Gaussian log partition for generated scoring.

Parameters:
Return type:

Any

static exp_family_base_measure(x, engine)[source]

Return log-Gaussian base measure for generated scoring.

Parameters:
Return type:

Any

set_prior(prior)[source]

Attach a parameter prior and precompute conjugate-prior expectations.

With a NormalGamma(mu0, lam, a, b) prior over (mu, tau=1/sigma2) of log(X) this caches the variational expected natural parameters [ea, eb, e1, e2] exactly as in the Gaussian case, so that expected_log_density(x) = y*(e1 + y*e2) - ea + eb - y with y = log(x). 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 | mu, tau)] under the NormalGamma prior.

With a conjugate prior this is the Gaussian VB expected log-likelihood evaluated at log(x), plus the Jacobian term -log(x); without a prior it falls back to log_density(x).

Parameters:

x (float)

Return type:

float

seq_expected_log_density(x)[source]

Vectorized expected_log_density over sequence-encoded (logged) observations.

Parameters:

x (ndarray)

Return type:

ndarray

density(x)[source]

Density of Log-Gaussian distribution at observation x.

See log_density() for details.

Parameters:

x (float) – Positive real-valued number.

Returns:

Density of Log-Gaussian at x.

Return type:

float

log_density(x)[source]

Log-density of log-Gaussian distribution at observation x.

Log-density of log-Gaussian with log-mean mu and log-variance sigma2 given by,

log(f(x;mu, sigma2)) = -0.5*log(2*pi*sigma2) - log(x) - 0.5*(log(x)-mu)^2/sigma2, for positive x.

Parameters:

x (float) – Positive valued observation of log-Gaussian.

Returns:

Log-density at observation x.

Return type:

float

seq_ld_lambda()[source]

Return vectorized log-density callables for fast scoring.

Return type:

list[Callable]

seq_log_density(x)[source]

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

Parameters:

x (np.ndarray) – Numpy array of floats.

Returns:

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

Return type:

ndarray

static backend_log_density_from_params(x, mu, sigma2, engine)[source]

Engine-neutral log-Gaussian log-density on log-encoded data.

Parameters:
Return type:

Any

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for log-encoded data.

Parameters:
Return type:

Any

gradient_log_prior(priors, prior_strength, torch, engine)[source]

Distribution-owned MAP prior contribution for log-Gaussian parameters.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked log-Gaussian parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[LogGaussianDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

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

Parameters:
Return type:

Any

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

Return stacked log-Gaussian sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any, Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

to_fisher(**kwargs)[source]

Return this distribution’s own Fisher view.

mean()[source]

Mean exp(mu + sigma2/2).

Return type:

float

variance()[source]

Variance (exp(sigma2) - 1) * exp(2 mu + sigma2).

Return type:

float

entropy()[source]

Differential entropy mu + 0.5*log(2*pi*e*sigma2).

Return type:

float

sampler(seed=None)[source]

Create a sampler from this log-Gaussian distribution.

Parameters:

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

Returns:

LogGaussianSampler object.

Return type:

LogGaussianSampler

estimator(pseudo_count=None)[source]

Return an estimator initialized from this distribution’s parameters.

Parameters:

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

Returns:

LogGaussianEstimator object.

Return type:

LogGaussianEstimator

dist_to_encoder()[source]

Return the encoder for log-Gaussian observations.

Return type:

LogGaussianDataEncoder

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

Bases: ParameterEstimator

Estimate log-Gaussian location and variance from accumulated log moments.

The variance is formed from shift-anchored log moments whenever the accumulated statistics carry that payload (see LogGaussianAccumulator), which makes the fit SCALE-EQUIVARIANT: estimating on a * x returns mu + log(a) with sigma2 unchanged, for any positive a the data can carry. A large multiplicative scale is a large additive offset on log(x), which is the same cancellation the sibling location-scale families repaired; here it costs ~1.4e-7 of sigma2 on values around 1e6 with a 0.2% spread. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, and estimate warns rather than returning a variance it cannot stand behind.

Parameters:
accumulator_factory()[source]

Return GaussianAccumulatorFactory with name and keys passed.

Return type:

LogGaussianAccumulatorFactory

model_log_density(model)[source]

Log-density of the model parameters under the NormalGamma prior (ELBO global term).

The prior is over (mu, tau=1/sigma2) of log(X), so the model’s (mu, sigma2) is mapped.

Parameters:

model (LogGaussianDistribution)

Return type:

float

estimate(nobs, suff_stat)[source]

Estimate a log-Gaussian distribution from accumulated log moments.

suff_stat is (sum_log_x, sum_log_x2, count, count2). nobs is accepted for estimator API consistency but is not used.

Parameters:
Return type:

LogGaussianDistribution

class LogGaussianFisherView(dist)[source]

Bases: FixedFisherView

Expose log-Gaussian sufficient statistics for Fisher-information utilities.

Parameters:

dist (Any)

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

Bases: DistributionSampler

Draw independent samples from a LogGaussianDistribution.

Parameters:
  • dist (LogGaussianDistribution)

  • seed (int | None)

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

Draw iid samples from the log-Gaussian distribution.

None returns a single float. A positive size returns a NumPy array of that many samples on the original positive scale.

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

  • batched (bool)

Returns:

Log-Gaussian samples.

Return type:

float | ndarray

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted first and second moments for logistic estimation.

Alongside the raw (sum, sum2, count) the accumulator keeps a CONDITIONING-GATED shift-anchored moment track. The naive E[x^2]-E[x]^2 form the M-step needs loses ~2*log2(abs(mean)/sd) bits to cancellation, so data with sd ~0.99 at offset 1.7e9 fits a scale 12.6x too large with no warning. Anchoring at a data value keeps every term of the scatter O(count * spread^2), making the M-step variance shift-invariant.

The track is CONDITIONING-GATED: a chunk whose abs(mean)/spread ratio the raw form handles to ~1e-9 relative error (see _needs_anchor()) accumulates exactly the historical single-pass way – bit-identical statistics, no second pass – and the anchor activates only when a chunk (or a scalar update) would corrupt the variance. The raw moments remain the exchange format – (sum, sum2, count) is the declared StatisticSpec tuple consumed by engine kernels – so the anchored track rides along as a payload on LogisticSuffStat.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted first and second moments for one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (LogisticDistribution | 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 first and second moments from encoded data.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (LogisticDistribution | 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 logistic sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

LogisticAccumulator

value()[source]

Return accumulated sum, second moment sum, and count.

The returned object is a plain 3-tuple for every consumer that treats it as one; once the shift-anchored moment track is live it is a LogisticSuffStat that additionally carries the anchored moments in its .anchored attribute, so combine() can fold them in and LogisticEstimator.estimate() can compute a shift-invariant variance.

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:

LogisticAccumulator

scale(c)[source]

Scale the accumulated statistics in place by c, anchored track included.

The structural default round-trips through value() and from_value(), and scale_suff_stat rebuilds the payload as a PLAIN tuple – which drops the anchored attribute, so from_value sees raw-only statistics and restarts the track unactivated. Uniform weight scaling is exactly linear in both anchored moments and leaves the anchor (a data value, not a statistic) alone, so the track scales as the raw moments do.

The moment arithmetic lives in scale_anchored_triple; this method is pure attribute wiring, and its body is byte-identical to the Logistic/Gaussian sibling accumulator’s – flagged by the duplicate-body scanner and accepted in the manifest deliberately, because de-duplicating the wiring itself would mean a mixin coupling both classes’ private attribute names, a bigger structural change than the release stage warrants for zero remaining bug-risk (the shared math is what could drift; this cannot).

Parameters:

c (float)

Return type:

LogisticAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

LogisticDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for LogisticAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh logistic accumulator.

Return type:

LogisticAccumulator

class LogisticDataEncoder[source]

Bases: DataSequenceEncoder

Encode logistic observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array.

Parameters:

x (Sequence[float])

Return type:

ndarray

class LogisticDistribution(loc=0.0, scale=1.0, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Logistic distribution with location loc and scale > 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated logistic kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for logistic distributions.

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

Return per-row Logistic sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

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

Parameters:

x (float)

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, loc, scale, engine)[source]

Engine-neutral logistic 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 logistic 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 logistic log densities.

Parameters:
Return type:

Any

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

entropy()[source]

Differential entropy log(scale) + 2.

Return type:

float

skewness()[source]

Skewness (0).

Return type:

float

kurtosis()[source]

Excess kurtosis (6/5).

Return type:

float

mode()[source]

Mode (= the location loc).

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

LogisticSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

LogisticEstimator

dist_to_encoder()[source]

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

Return type:

LogisticDataEncoder

class LogisticEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Moment estimator for logistic location and scale.

The likelihood MLE has no closed-form M-step. The EM estimator uses the identities mean=loc and var=pi^2 scale^2 / 3; torch gradient MLE can refine both parameters when exact likelihood optimization is desired.

The variance moment is formed from shift-anchored statistics whenever the accumulated sufficient statistics carry that payload (see LogisticAccumulator), which makes the fit shift-equivariant: estimating on x + c returns loc + c with scale unchanged. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones restored from an older serialization – the historical raw path is used, bit-identically.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for logistic moment statistics.

Return type:

LogisticAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate location and scale from weighted moments.

Parameters:
Return type:

LogisticDistribution

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

Bases: DistributionSampler

Draw iid logistic observations.

Parameters:
  • dist (LogisticDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

Bases: SquaredPowerSumTrack, SequenceEncodableStatisticAccumulator

Accumulate the weighted power sums (count, sum x^2, sum x^4) for the moment fit.

The whole accumulator is SquaredPowerSumTrack – shape, validation and the conditioning-gated shift-anchored track on y = x**2, which is the quantity this family’s M-step differences. It is shared with the Rician family, whose accumulator was character-for- character the same; the duplicate-body gate caught the pair and de-duplicating it is what keeps a fix landing on one from missing the other.

Parameters:
  • name (str | None)

  • keys (str | None)

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

NakagamiDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for NakagamiAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Nakagami accumulator.

Return type:

NakagamiAccumulator

class NakagamiDataEncoder[source]

Bases: DataSequenceEncoder

Encode observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array, admitting finite rows outside the support.

A negative value is scored -inf by NakagamiDistribution.seq_log_density() (and by the scalar path), so a mixture whose other component owns it can encode the whole batch (P02-F03). Refusing it here made Mixture[Gaussian, Nakagami] unencodable (Q01-F02). The accumulator still refuses a negative row that carries weight. Non-finite values stay refused.

Parameters:

x (Sequence[float])

Return type:

ndarray

class NakagamiDistribution(m, omega, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Nakagami distribution with shape m >= 1/2 and spread omega = E[X^2] > 0.

Parameters:
density(x)[source]

Return the probability density at x.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at x, including the exact limit at zero.

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-density for a sequence-encoded array of observations.

Parameters:

x (ndarray)

Return type:

ndarray

classmethod compute_capabilities()[source]

Describe backend support for generated Nakagami kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Nakagami distributions.

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

Per-row Nakagami power sums in accumulator order (count, sum x^2, sum x^4).

Parameters:
Return type:

tuple[Any, …]

static backend_log_density_from_params(x, m, omega, engine)[source]

Engine-neutral Nakagami log-density with the exact limit at zero.

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]

Stacked Nakagami 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 Nakagami log densities.

Parameters:
Return type:

Any

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

Stacked Nakagami power sums (count, sum x^2, sum x^4) using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) = P(m, m x^2 / omega) (0 for x <= 0).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

Parameters:

q (float)

Return type:

float

mean()[source]

Mean (Gamma(m+1/2)/Gamma(m)) sqrt(omega/m).

Return type:

float

variance()[source]

Variance omega - mean^2 (since E[X^2] = omega).

Return type:

float

entropy()[source]

Differential entropy m + lgamma(m) + (1/2 - m) psi(m) + (1/2) log(omega/m) - log(2).

Derived via the entropy of a monotone transform: X = sqrt(Y) with Y = X^2 ~ Gamma(m, omega/m) (Nakagami, ‘The m-distribution’, 1960), so h(X) = h(Y) - log(2) - E[log X] = h(Y) - log(2) - (1/2)(E[log Y]) and both h(Y) and E[log Y] are standard Gamma-distribution identities. Reduces exactly to the Rayleigh entropy at m = 1.

Return type:

float

sampler(seed=None)[source]

Return a sampler (X = sqrt(Gamma(m, omega/m))).

Parameters:

seed (int | None)

Return type:

NakagamiSampler

estimator(pseudo_count=None)[source]

Return a closed-form method-of-moments estimator.

Parameters:

pseudo_count (float | None)

Return type:

NakagamiEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution (the raw value).

Return type:

NakagamiDataEncoder

class NakagamiEstimator(pseudo_count=None, suff_stat=None, m_min=0.5, name=None, keys=None)[source]

Bases: ParameterEstimator

Method-of-moments estimator: omega = E[X^2], m = E[X^2]^2 / Var[X^2] (clamped m >= 1/2).

Var[X^2] comes from the shift-anchored moment track whenever the accumulated statistics carry that payload (see NakagamiAccumulator). The shape is the reciprocal of the relative spread of X^2, so the raw E[X^4] - E[X^2]^2 form loses about eps * m: measured against exact rational arithmetic, 2.0e-10 relative at m=1e6, 2.6e-8 at 1e8 and 2.6e-6 at 1e10, now 2.0e-10, 4.7e-16 and 1.0e-13. With a plain raw tuple the historical path is used bit-identically, and estimate warns rather than returning a shape it cannot stand behind.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for Nakagami power-sum statistics.

Return type:

NakagamiAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate shape and spread from weighted second and fourth moments.

Parameters:
Return type:

NakagamiDistribution

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

Bases: DistributionSampler

Draw X = sqrt(G) with G ~ Gamma(shape=m, scale=omega/m) (so X^2 ~ Gamma(m, omega/m)).

Parameters:
  • dist (NakagamiDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted support minimum and log-sum statistics.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted log and support-minimum statistics for one sample.

Parameters:
  • x (float)

  • weight (float)

  • estimate (ParetoDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and strictly positive.

The encoder admits out-of-support rows so a mixture can encode one batch against every component; this predicate is what keeps them out of the sufficient statistics, and what a latent model’s initialization consults before handing this component any responsibility.

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate weighted log and support-minimum statistics from encoded data.

Parameters:
Return type:

None

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

Engine-resident accumulation of the count and log-sum statistics (numpy or torch).

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 Pareto sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

ParetoAccumulator

value()[source]

Return count, weighted log-sum, and observed support minimum.

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:

ParetoAccumulator

scale(c)[source]

Scale linear count/log-sum statistics while preserving support bound.

Parameters:

c (float)

Return type:

ParetoAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

ParetoDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for ParetoAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Pareto accumulator.

Return type:

ParetoAccumulator

class ParetoDataEncoder[source]

Bases: DataSequenceEncoder

Encode Pareto observations with x and log(x).

seq_encode(x)[source]

Encode observations as values and log-values, admitting rows outside the support.

An encoder admits out-of-support observations so a mixture can encode ONE batch against every component: the component that does not own a value scores it -inf and the E-step gives it no responsibility (P02-F03). This one refused instead, which made any mixture containing a Pareto component unencodable the moment another component owned a non-positive value – optimize on a Gaussian-plus-Pareto mixture died at encode time on data both components can jointly explain, and said so as a type error about disjoint types (Q01-F02).

seq_log_density already scores those rows -inf through its own xx >= xm mask, and the scalar log_density(-1.0) already returned -inf, so the law never disagreed with itself – only the encoder did. NaN stays refused: it marks missing data rather than an observation, which is the rule every sibling family applies.

Parameters:

x (Sequence[float])

Return type:

tuple[ndarray, ndarray]

class ParetoDistribution(xm, alpha, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Pareto type-I distribution with scale xm > 0 and shape alpha > 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated Pareto kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Pareto distributions.

static exp_family_sufficient_statistics(x, engine)[source]

Return the Pareto sufficient statistic T(x) = (log x,) (scale xm fixed).

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return the Pareto natural parameter eta = -alpha (scale xm fixed).

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the Pareto log partition A = -log(alpha) - alpha * log(xm).

Parameters:
Return type:

Any

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

Return the Pareto base measure log h(x) = -log(x) on [xm, inf) (-inf below xm).

Parameters:
Return type:

Any

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

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

Parameters:

x (float)

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_vals, xm, alpha, engine)[source]

Engine-neutral Pareto 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 Pareto 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 Pareto log densities.

Parameters:
Return type:

Any

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

Return stacked Pareto sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

mean()[source]

Mean alpha*xm/(alpha-1) for alpha > 1, else inf.

Return type:

float

variance()[source]

Variance xm^2 alpha / ((alpha-1)^2 (alpha-2)) for alpha > 2, else inf.

Return type:

float

entropy()[source]

Differential entropy log(xm/alpha) + 1/alpha + 1.

Return type:

float

mode()[source]

Mode (the scale xm).

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

ParetoSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

ParetoEstimator

dist_to_encoder()[source]

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

Return type:

ParetoDataEncoder

class ParetoEstimator(pseudo_count=None, suff_stat=None, min_denom=1.0e-12, name=None, keys=None)[source]

Bases: ParameterEstimator

MLE estimator for Pareto scale and shape.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for Pareto sufficient statistics.

Return type:

ParetoAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate Pareto scale and shape from support and log-sum statistics.

Parameters:
Return type:

ParetoDistribution

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

Bases: DistributionSampler

Draw iid Pareto observations.

Parameters:
  • dist (ParetoDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted squared observations.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted squared observations for one sample.

Parameters:
  • x (float)

  • weight (float)

  • estimate (RayleighDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and non-negative.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility.

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate weighted squared observations from encoded data.

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 Rayleigh sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float])

Return type:

RayleighAccumulator

value()[source]

Return accumulated count and squared-observation sum.

Return type:

tuple[float, float]

from_value(x)[source]

Replace accumulator contents from a sufficient-statistic tuple.

Parameters:

x (tuple[float, float])

Return type:

RayleighAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

RayleighDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for RayleighAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Rayleigh accumulator.

Return type:

RayleighAccumulator

class RayleighDataEncoder[source]

Bases: DataSequenceEncoder

Encode Rayleigh observations with x, x**2, and log(x).

seq_encode(x)[source]

Encode observations as values, squared values, and log-values.

Parameters:

x (Sequence[float])

Return type:

tuple[ndarray, ndarray, ndarray]

class RayleighDistribution(sigma, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Rayleigh distribution with scale sigma > 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated Rayleigh kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Rayleigh distributions.

static exp_family_sufficient_statistics(x, engine)[source]

Return Rayleigh sufficient statistics for generated scoring.

Parameters:
Return type:

tuple[Any, …]

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

Return per-row Rayleigh sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return Rayleigh natural parameters for generated scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return Rayleigh log partition for generated scoring.

Parameters:
Return type:

Any

static exp_family_base_measure(x, engine)[source]

Return Rayleigh support/base measure for generated scoring.

Parameters:
Return type:

Any

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

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

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

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

Parameters:

x (tuple[ndarray, ndarray, ndarray])

Return type:

ndarray

static backend_log_density_from_params(vals, vals2, log_vals, sigma, engine)[source]

Engine-neutral Rayleigh 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 Rayleigh 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 Rayleigh log densities.

Parameters:
Return type:

Any

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

entropy()[source]

Differential entropy 1 + log(sigma/sqrt(2)) + gamma/2.

Return type:

float

skewness()[source]

Skewness 2*sqrt(pi)(pi-3)/(4-pi)^1.5.

Return type:

float

kurtosis()[source]

Excess kurtosis -(6pi^2-24pi+16)/(4-pi)^2.

Return type:

float

mode()[source]

Mode (sigma).

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

RayleighSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

RayleighEstimator

dist_to_encoder()[source]

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

Return type:

RayleighDataEncoder

class RayleighEstimator(pseudo_count=None, suff_stat=None, min_sigma=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Closed-form MLE estimator for Rayleigh scale.

Parameters:
  • pseudo_count (float | None)

  • suff_stat (float | None)

  • min_sigma (float)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return an accumulator factory for Rayleigh sufficient statistics.

Return type:

RayleighAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate the Rayleigh scale from weighted squared observations.

Parameters:
Return type:

RayleighDistribution

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

Bases: DistributionSampler

Draw iid Rayleigh observations.

Parameters:
  • dist (RayleighDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

Bases: SquaredPowerSumTrack, SequenceEncodableStatisticAccumulator

Accumulate the weighted power sums (count, sum x^2, sum x^4) for the moment fit.

The whole accumulator is SquaredPowerSumTrack – shape, validation and the conditioning-gated shift-anchored track on y = x**2, which is the quantity this family’s M-step differences. It is shared with the Nakagami family, whose accumulator was character-for- character the same; the duplicate-body gate caught the pair and de-duplicating it is what keeps a fix landing on one from missing the other.

Parameters:
  • name (str | None)

  • keys (str | None)

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

RicianDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for RicianAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Rician accumulator.

Return type:

RicianAccumulator

class RicianDataEncoder[source]

Bases: DataSequenceEncoder

Encode observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array, admitting finite rows outside the support.

A negative value is scored -inf by RicianDistribution.seq_log_density() (and by the scalar path), so a mixture whose other component owns it can encode the whole batch (P02-F03). Refusing it here made Mixture[Gaussian, Rician] unencodable (Q01-F02). The accumulator still refuses a negative row that carries weight. Non-finite values stay refused.

Parameters:

x (Sequence[float])

Return type:

ndarray

class RicianDistribution(nu, sigma, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Rician distribution with non-centrality nu >= 0 and scale sigma > 0.

Parameters:
density(x)[source]

Return the probability density at x.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at x (-inf for x <= 0).

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-density for a sequence-encoded array of observations.

Parameters:

x (ndarray)

Return type:

ndarray

classmethod compute_capabilities()[source]

Describe backend support for generated Rician kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Rician distributions.

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

Per-row Rician power sums in accumulator order (count, sum x^2, sum x^4).

Parameters:
Return type:

tuple[Any, …]

static backend_log_density_from_params(x, nu, sigma, engine)[source]

Engine-neutral Rician log-density (-inf for x <= 0).

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]

Stacked Rician 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 Rician log densities.

Parameters:
Return type:

Any

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

Stacked Rician power sums (count, sum x^2, sum x^4) using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) (Marcum-Q, via scipy rice).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

Parameters:

q (float)

Return type:

float

mean()[source]

Mean sigma sqrt(pi/2) L_{1/2}(-nu^2/(2 sigma^2)) (stable via the scaled Bessel ive).

Return type:

float

variance()[source]

Variance E[X^2] - mean^2 with E[X^2] = nu^2 + 2 sigma^2.

Return type:

float

entropy()[source]

Differential entropy in nats, by adaptive quadrature of -f(x) log f(x) over x > 0.

At nu = 0 the Rician is exactly the Rayleigh, whose entropy is the closed form 1 + log(sigma / sqrt(2)) + euler_gamma / 2. For nu > 0 the density’s log I0(x nu / sigma^2) term has no closed-form expectation (Rice, ‘Mathematical analysis of random noise’, 1944/1945), so the integral is evaluated numerically against the exact log-density.

Return type:

float

sampler(seed=None)[source]

Return a sampler (the envelope of a 2-D Gaussian offset by nu).

Parameters:

seed (int | None)

Return type:

RicianSampler

estimator(pseudo_count=None)[source]

Return a closed-form method-of-moments estimator.

Parameters:

pseudo_count (float | None)

Return type:

RicianEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution (the raw value).

Return type:

RicianDataEncoder

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

Bases: ParameterEstimator

Method-of-moments estimator from E[X^2] and E[X^4] (closed-form quadratic in sigma^2).

The quadratic is solved in its RATIONALIZED form, sigma^2 = Var(X^2) / (2 (E[X^2] + sqrt(E[X^2]^2 - Var(X^2)))), whenever the accumulated statistics carry the shift-anchored payload (see RicianAccumulator). Algebraically it is the same root as (m2 - sqrt(2 m2^2 - m4)) / 2, but it differences raw moments once instead of twice, and the one difference it needs is supplied exactly by the anchored track. That makes the fit accurate at any nu/sigma: measured against exact rational arithmetic on the same 2000-point samples, the historical form lost 5.4e-9 relative at nu/sigma 1e4, 4.1e-5 at 1e6 and 44% at 1e8, and now measures 3.5e-15, 7.1e-13 and 3.5e-11. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical path is used bit-identically, and estimate warns rather than returning a scale it cannot stand behind.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for Rician power-sum statistics.

Return type:

RicianAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate Rician noncentrality and scale from second and fourth moments.

Parameters:
Return type:

RicianDistribution

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

Bases: DistributionSampler

Draw X = sqrt((nu + sigma Z1)^2 + (sigma Z2)^2) for Z1, Z2 ~ N(0, 1).

Parameters:
  • dist (RicianDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted central moments for skew-normal estimation.

The sufficient statistic is stored as (count, mean, M2, M3) where M2 = sum_i w_i (x_i - mean)^2 and M3 = sum_i w_i (x_i - mean)^3 are the weighted central moments. This is mathematically equivalent to the raw power sums (sum x, sum x^2, sum x^3) but avoids the catastrophic E[x^2] - E[x]^2 cancellation when abs(mean) is large relative to the spread: each batch is centered on its own mean before squaring/cubing, and batches merge through the Pébay/West parallel-moment formulas (exact for real weights). SkewNormal is a host-only leaf (no exponential-family / engine-resident path), so changing the accumulator representation has no engine-swap parity implications.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate a single weighted observation into central moments.

Parameters:
  • x (float)

  • weight (float)

  • estimate (SkewNormalDistribution | 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 central moments from encoded observations.

Centering the batch on its own mean removes the E[x^2]-E[x]^2 cancellation, but a SINGLE centering pass does not remove all of it: the computed mean carries the rounding of a large-magnitude sum, and that residue enters the third moment linearly, which left the fitted shape 1.1e-3 off at offset 1e12 and 5e-7 off at the Unix-epoch offset. The second pass in centered_batch_moments() computes the residue at spread scale, where it is exact, and makes the fit shift-equivariant.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (SkewNormalDistribution | 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 central-moment statistic tuple.

Parameters:

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

Return type:

SkewNormalAccumulator

value()[source]

Return count, mean, second central moment sum, and third central moment sum.

Return type:

tuple[float, float, float, float]

from_value(x)[source]

Replace accumulator contents from a central-moment statistic tuple.

Parameters:

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

Return type:

SkewNormalAccumulator

scale(c)[source]

Scale weight-linear statistics while preserving the weighted mean.

Parameters:

c (float)

Return type:

SkewNormalAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

SkewNormalDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for SkewNormalAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh skew-normal accumulator.

Return type:

SkewNormalAccumulator

class SkewNormalDataEncoder[source]

Bases: DataSequenceEncoder

Encode skew-normal observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array.

Parameters:

x (Sequence[float])

Return type:

ndarray

class SkewNormalDistribution(loc, scale, shape, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Skew-normal distribution with location loc, scale > 0 and shape alpha.

Parameters:
density(x)[source]

Return the probability density at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Return the log-density at a single observation.

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

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

Parameters:

x (ndarray)

Return type:

ndarray

classmethod compute_capabilities()[source]

Describe backend support for generated skew-normal scoring kernels.

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized skew-normal log-density for encoded data.

Parameters:
Return type:

Any

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact).

Parameters:

x (float)

Return type:

float

quantile(q)[source]

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

Parameters:

q (float)

Return type:

float

mean()[source]

Mean E[X] = loc + scale * delta * sqrt(2/pi), delta = shape / sqrt(1 + shape^2).

Return type:

float

variance()[source]

Variance Var[X] = scale^2 (1 - 2 delta^2 / pi), delta = shape / sqrt(1 + shape^2).

Return type:

float

entropy()[source]

Differential entropy log(scale) + 0.5 log(2 pi e) - log(2) - E[log Phi(alpha Y)].

Y is the standard skew-normal(alpha); E[Y^2] = 1 for every alpha (a property of the two-Gaussian stochastic representation) collapses the Gaussian part of the log-density to a closed form, leaving E[log Phi(alpha Y)]. That term has no closed form for general alpha (Arellano-Valle, Contreras-Reyes & Genton, ‘Shannon entropy and mutual information for multivariate skew-elliptical distributions’, Scand. J. Statist. 40 (2013)), so it is evaluated by adaptive quadrature against the standard skew-normal density itself.

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

SkewNormalSampler

estimator(pseudo_count=None)[source]

Return a method-of-moments estimator for loc, scale and shape.

Parameters:

pseudo_count (float | None)

Return type:

SkewNormalEstimator

dist_to_encoder()[source]

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

Return type:

SkewNormalDataEncoder

class SkewNormalEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-12, name=None, keys=None)[source]

Bases: ParameterEstimator

Method-of-moments estimator for skew-normal location, scale and shape.

The fit is SHIFT-EQUIVARIANT: estimating on x + c returns loc + c with scale and shape unchanged, for any constant c the data can carry – epoch seconds (~1.7e9), 2**31 and 1e12 included. The moments come from SkewNormalAccumulator, which centers each batch twice for exactly this reason; a single centering pass left the fitted shape 1.1e-3 off at 1e12, silently.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for skew-normal moment statistics.

Return type:

SkewNormalAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate location, scale, and shape from weighted central moments.

Parameters:
Return type:

SkewNormalDistribution

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

Bases: DistributionSampler

Draw observations as xi + omega (delta * abs(Z0) + sqrt(1-delta^2) Z1) with Z0, Z1 standard normal.

Parameters:
  • dist (SkewNormalDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

Bases: AnchoredMomentTrack, SequenceEncodableStatisticAccumulator

Accumulate weighted first and second moments for fixed-df t estimation.

Alongside the raw (sum, sum2, count) the accumulator keeps the conditioning-gated shift-anchored moment track of AnchoredMomentTrack: the naive E[x^2]-E[x]^2 form the moment M-step needs loses ~``2*log2(abs(mean)/sd)`` bits to cancellation, so sd ~2 data at the Unix-epoch offset 1.7e9 collapsed the fitted scale onto min_scale – 1.6e8x too small, -86.6 nats per observation, reported with converged=True and an empty numerical_repairs(). Well-conditioned data never activates the track and accumulates bit-identically to the historical single-pass path.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted first and second moments for one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (StudentTDistribution | 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 first and second moments from encoded data.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (StudentTDistribution | 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 Student-t sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

StudentTAccumulator

value()[source]

Return accumulated sum, second moment sum, and count.

A plain 3-tuple for every consumer that treats it as one; once the shift-anchored moment track is live it is a StudentTSuffStat additionally carrying the anchored moments in its .anchored attribute, so combine() can fold them in and StudentTEstimator.estimate() can compute a shift-invariant scale.

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:

StudentTAccumulator

scale(c)[source]

Scale the accumulated statistics in place by c, anchored track included.

Parameters:

c (float)

Return type:

StudentTAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

StudentTDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for StudentTAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Student-t accumulator.

Return type:

StudentTAccumulator

class StudentTDataEncoder[source]

Bases: DataSequenceEncoder

Encode Student’s t observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array.

Parameters:

x (Sequence[float])

Return type:

ndarray

class StudentTDistribution(df, loc=0.0, scale=1.0, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Student’s t distribution with degrees of freedom df, location loc, and scale > 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated Student-t kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Student-t distributions.

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

Return per-row Student-t sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

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

Parameters:

x (float)

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, df, loc, scale, engine)[source]

Engine-neutral Student-t 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 Student-t 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 Student-t log densities.

Parameters:
Return type:

Any

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

mean()[source]

Mean (loc) for df > 1, else inf (undefined).

Return type:

float

variance()[source]

Variance scale^2 * df/(df-2) for df > 2, else inf.

Return type:

float

entropy()[source]

Differential entropy log(scale) + (df+1)/2 [psi((df+1)/2) - psi(df/2)] + log(sqrt(df) B(df/2, 1/2)).

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

StudentTSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

StudentTEstimator

dist_to_encoder()[source]

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

Return type:

StudentTDataEncoder

class StudentTEstimator(df=5.0, pseudo_count=None, suff_stat=None, min_scale=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Moment-style fixed-df estimator for Student’s t location and scale.

The exact MLE has no simple closed-form update. This estimator keeps df fixed and uses weighted moments, while generic gradient optimizers such as mixle.inference.gradient_fit.fit_mle / fit_map can fit all three parameters through distribution-owned backend math.

The variance moment is formed from shift-anchored statistics whenever the accumulated sufficient statistics carry that payload (see StudentTAccumulator), which makes the fit SHIFT-EQUIVARIANT: estimating on x + c returns loc + c with scale unchanged, for any constant c the data can carry – epoch seconds (~1.7e9) and 2**31 included. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, and estimate warns rather than returning a scale it cannot stand behind.

min_scale (default 1e-8) is an absolute floor on the returned scale; it exists for genuinely constant data, and a fit that lands on it is reporting no resolvable spread.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for fixed-df Student-t moments.

Return type:

StudentTAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate location and scale while keeping degrees of freedom fixed.

Parameters:
Return type:

StudentTDistribution

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

Bases: DistributionSampler

Draw iid Student’s t observations.

Parameters:
  • dist (StudentTDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

Bases: SequenceEncodableStatisticAccumulator

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

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted count, sum, and second moment for one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (TweedieDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize the sufficient statistics with one weighted observation.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and non-negative.

The encoder admits a negative observation so a mixture can encode one batch against every component (P02-F03); this is the predicate that keeps it out of the moments and the one a latent model’s initialization consults before handing this component any responsibility.

Parameters:

x (Any)

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate weighted count, sum, and second moment from encoded observations.

The encoder admits negative rows for scoring, so this is where they are refused – the moment sums below would otherwise take a negative value as silently as a positive one.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize the sufficient statistics from encoded observations.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge serialized moment statistics into this accumulator.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

TweedieAccumulator

value()[source]

Return the total weight, weighted sum, and weighted second moment.

Return type:

tuple[float, float, float]

from_value(x)[source]

Restore the accumulator from serialized moment statistics.

Parameters:

x (tuple[float, float, float])

Return type:

TweedieAccumulator

scale(c)[source]

Scale accumulated moment statistics by a constant.

Parameters:

c (float)

Return type:

TweedieAccumulator

acc_to_encoder()[source]

Return an encoder for non-negative Tweedie observations.

Return type:

TweedieDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for TweedieAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create an empty Tweedie accumulator.

Return type:

TweedieAccumulator

class TweedieDataEncoder[source]

Bases: DataSequenceEncoder

Encode sequences of iid Tweedie observations (non-negative float data type).

seq_encode(x)[source]

Validate and encode observations as a float array, admitting negative finite rows.

A negative value is scored -inf by TweedieDistribution.seq_log_density(), exactly as the scalar path scores it, so a mixture whose other component owns it can encode the whole batch (P02-F03). Refusing it here made Mixture[Gaussian, Tweedie] unencodable (Q01-F02); the accumulator still refuses a negative row that carries weight. Non-finite values stay refused.

Parameters:

x (Sequence[float])

Return type:

ndarray

class TweedieDistribution(mu, phi, p=1.5, name=None, keys=None, *, max_series_terms=_DEFAULT_MAX_SERIES_TERMS, max_series_work=_DEFAULT_MAX_SERIES_WORK, series_tolerance=_DEFAULT_SERIES_TOLERANCE)[source]

Bases: SequenceEncodableProbabilityDistribution

Tweedie (compound Poisson-Gamma) distribution on [0, inf) with fixed power p in (1, 2).

Parameters:
density(x)[source]

Probability density (or the point mass at 0) at x (see log_density).

Parameters:

x (float)

Return type:

float

log_density(x)[source]

Tweedie log-density: log P(Y=0) = -lam at 0, the series for x > 0, -inf for x < 0.

Parameters:

x (float)

Return type:

float

seq_log_density(x)[source]

Vectorized Tweedie log-density at sequence-encoded non-negative observations x.

Parameters:

x (ndarray)

Return type:

ndarray

classmethod compute_capabilities()[source]

Return compute-backend metadata for Tweedie scoring.

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized Tweedie log-density for encoded data (see class backend note).

Parameters:
Return type:

Any

sampler(seed=None)[source]

Return a TweedieSampler for this distribution.

Parameters:

seed (int | None)

Return type:

TweedieSampler

estimator(pseudo_count=None)[source]

Return a TweedieEstimator (method of moments at the fixed power p).

Parameters:

pseudo_count (float | None)

Return type:

TweedieEstimator

dist_to_encoder()[source]

Return the encoder for Tweedie observations.

Return type:

TweedieDataEncoder

class TweedieEstimator(p=1.5, pseudo_count=None, suff_stat=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Estimate (mu, phi) at fixed power p by the (exact) method of moments.

Parameters:
accumulator_factory()[source]

Return a factory for Tweedie moment accumulators.

Return type:

TweedieAccumulatorFactory

estimate(nobs, suff_stat)[source]

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

Parameters:
Return type:

TweedieDistribution

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

Bases: DistributionSampler

Draw iid Tweedie observations exactly as a compound Poisson-Gamma sum.

Parameters:
  • dist (TweedieDistribution)

  • seed (int | None)

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

Draw size iid Tweedie samples (a single float if size is None).

Y | N is a sum of N iid Gamma(shape, scale), which is Gamma(N*shape, scale); N = 0 yields an exact zero.

Parameters:
Return type:

float | ndarray

exception TweedieSeriesResourceError(*, required_terms, rows, max_terms, max_work)[source]

Bases: RuntimeError

A Tweedie density series exceeded its declared term or work budget.

Parameters:
  • required_terms (int)

  • rows (int)

  • max_terms (int)

  • max_work (int)

Return type:

None

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted min/max support statistics.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate support bounds and count from one weighted observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (UniformDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility. Without it the initializer could not tell that this component does not own a row, seeded it from one anyway, and the refusal below then blamed the DATA for a mixture the model can express – a Poisson-plus-Geometric fit on counts with zeros was refused outright (Q01-F02/Q02-F02).

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate support bounds and count from encoded observations.

Parameters:
Return type:

None

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

Engine-resident accumulation of the weighted count (numpy or torch).

The support min/max are host scalar bookkeeping over the observed values.

Parameters:
  • x (ndarray)

  • weights (Any)

  • estimate (UniformDistribution | None)

  • engine (Any)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded observations.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge another uniform sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

UniformAccumulator

value()[source]

Return count and observed support bounds.

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:

UniformAccumulator

scale(c)[source]

Scale observation count while preserving support bounds.

Parameters:

c (float)

Return type:

UniformAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

UniformDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for UniformAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh uniform accumulator.

Return type:

UniformAccumulator

class UniformDataEncoder[source]

Bases: DataSequenceEncoder

Encode uniform observations as a float array.

seq_encode(x)[source]

Encode observations as a floating-point array.

Parameters:

x (Sequence[float])

Return type:

ndarray

class UniformDistribution(low, high, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Continuous uniform distribution on [low, high].

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated uniform kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for uniform distributions.

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

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

Parameters:

x (float)

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, low, high, engine)[source]

Engine-neutral uniform 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 uniform 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 uniform log densities.

Parameters:
Return type:

Any

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

Return stacked Uniform sufficient statistics using engine-resident arrays.

Parameters:
Return type:

tuple[Any, Any, Any]

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

mean()[source]

Mean E[X] of the distribution.

Return type:

float

variance()[source]

Variance Var[X] of the distribution.

Return type:

float

entropy()[source]

Differential entropy log(high - low).

Return type:

float

skewness()[source]

Skewness (0).

Return type:

float

kurtosis()[source]

Excess kurtosis (-6/5).

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

UniformSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

UniformEstimator

dist_to_encoder()[source]

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

Return type:

UniformDataEncoder

class UniformEstimator(pseudo_count=None, suff_stat=None, min_width=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

MLE estimator for uniform support endpoints.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for uniform support statistics.

Return type:

UniformAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate support endpoints from observed weighted bounds.

Parameters:
Return type:

UniformDistribution

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

Bases: DistributionSampler

Draw iid uniform observations.

Parameters:
  • dist (UniformDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted first and second moments for Weibull estimation.

Parameters:
  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted first and second moments for one observation.

Parameters:
  • x (float)

  • weight (float)

  • estimate (WeibullDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one observation.

Parameters:
Return type:

None

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and non-negative.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility.

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate weighted first and second moments from encoded data.

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 Weibull sufficient-statistic tuple.

Parameters:

suff_stat (tuple[float, float, float])

Return type:

WeibullAccumulator

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:

WeibullAccumulator

acc_to_encoder()[source]

Return the encoder used by this accumulator.

Return type:

WeibullDataEncoder

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

Bases: StatisticAccumulatorFactory

Factory for WeibullAccumulator.

Parameters:
  • name (str | None)

  • keys (str | None)

make()[source]

Create a fresh Weibull accumulator.

Return type:

WeibullAccumulator

class WeibullDataEncoder[source]

Bases: DataSequenceEncoder

Encode Weibull observations with x and log(x).

seq_encode(x)[source]

Encode observations as values and log-values.

Parameters:

x (Sequence[float])

Return type:

tuple[ndarray, ndarray]

class WeibullDistribution(shape, scale, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Weibull distribution with shape > 0 and scale > 0 on x >= 0.

Parameters:
classmethod compute_capabilities()[source]

Describe backend support for generated Weibull kernels.

classmethod compute_declaration()[source]

Return the structured compute declaration for Weibull distributions.

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

Return per-row Weibull sufficient statistics in accumulator order.

Parameters:
Return type:

tuple[Any, …]

density(x)[source]

Return the probability density or mass at a single observation.

Parameters:

x (float)

Return type:

float

log_density(x)[source]

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

Parameters:

x (float)

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_vals, shape, scale, engine)[source]

Engine-neutral Weibull 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 Weibull 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 Weibull log densities.

Parameters:
Return type:

Any

cdf(x)[source]

Cumulative distribution function P(X <= x) (exact). The continuous ‘index of’ a value.

Parameters:

x (float)

Return type:

float

quantile(q)[source]

Inverse CDF F^{-1}(q): the value at cumulative-probability index q (continuous unranking).

Parameters:

q (float)

Return type:

float

mean()[source]

Mean scale * Gamma(1 + 1/shape).

Gamma(1 + 1/shape) diverges as the shape goes to zero, where math.gamma raises an OverflowError rather than returning the limit scipy reports (P01-F10). Summed in logs so the divergence arrives as inf.

Return type:

float

variance()[source]

Variance scale^2 * (Gamma(1+2/shape) - Gamma(1+1/shape)^2).

Both gamma terms diverge together as the shape goes to zero; the difference diverges with them, so the limit is inf rather than an OverflowError (P01-F10).

Return type:

float

entropy()[source]

Differential entropy gamma*(1 - 1/shape) + log(scale/shape) + 1.

Return type:

float

mode()[source]

Mode scale*((k-1)/k)^(1/k) for shape k>1, else 0.

Return type:

float

sampler(seed=None)[source]

Return a sampler for drawing observations from this distribution.

Parameters:

seed (int | None)

Return type:

WeibullSampler

estimator(pseudo_count=None)[source]

Return an estimator for fitting this distribution from data.

Parameters:

pseudo_count (float | None)

Return type:

WeibullEstimator

dist_to_encoder()[source]

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

Return type:

WeibullDataEncoder

class WeibullEstimator(pseudo_count=None, suff_stat=None, min_shape=1.0e-3, max_shape=1.0e3, min_scale=1.0e-12, name=None, keys=None)[source]

Bases: ParameterEstimator

Moment estimator for Weibull shape and scale.

Parameters:
accumulator_factory()[source]

Return an accumulator factory for Weibull moment statistics.

Return type:

WeibullAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate shape and scale by matching weighted moments.

Parameters:
Return type:

WeibullDistribution

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

Bases: DistributionSampler

Draw iid Weibull observations.

Parameters:
  • dist (WeibullDistribution)

  • seed (int | None)

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

Draw one sample or an array of iid samples.

Parameters:
Return type:

float | ndarray

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

supported_rows(x)[source]

Encoded rows this law can be fitted on: outcomes in {0, 1}.

The encoder admits an integer outside {0, 1} so a mixture can encode one batch against every component (P02-F03); this is the predicate a latent model’s initialization consults before handing this component any responsibility. The encoder used to refuse such a count, so an integer-categorical-plus-Bernoulli mixture could not be encoded at all (Q01-F02).

Parameters:

x (ndarray)

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate weighted statistics from encoded observations.

A count outside {0, 1} carrying weight is refused; with zero weight it contributes nothing. Before the encoder admitted such counts this summed the raw value, which never mattered because none could arrive.

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, or as integers when a count lies off {0, 1}.

An integer outside {0, 1} is an outcome this law gives probability zero – a probability question the scorer answers -inf – so it is admitted, and a mixture whose other component owns it can encode the whole batch (P02-F03, Q01-F02). Such a batch keeps its integers, since a boolean cast would turn 2 into a success. Anything that is not an integer stays refused.

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_base_measure(x, engine)[source]

Return the Bernoulli base measure: 0 on {0, 1}, -inf for any other count.

The generated engine kernels score x log p + (1 - x) log(1 - p) with no support of their own, so once the encoder admitted a count outside {0, 1} (Q01-F02) the numba-generated kernel scored -1 as a POSITIVE log-probability, and an engine fit reported a finite validation objective the default route refuses (V01-F04). The support lives in the base measure, as the Poisson family’s already does.

Parameters:
Return type:

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.

A boolean encoding holds only valid outcomes. An integer encoding is what the encoder emits when the batch also holds a count outside {0, 1}, which this law gives probability zero: it scores -inf, as the scalar path does (P02-F03, Q01-F02).

Parameters:

x (ndarray)

Return type:

ndarray

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

Engine-neutral Bernoulli log-mass from explicit parameters (-inf outside {0, 1}).

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

supported_rows(x)[source]

Encoded rows this law can be fitted on: counts in {0, ..., n}.

The encoder admits a count outside that range so a mixture can encode one batch against every component (P02-F03); this is the predicate that keeps it out of the moments and the one a latent model’s initialization consults before handing this component any responsibility (Q01-F02).

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate weighted moments from encoded counts.

A count outside {0, ..., n} carrying weight is refused; with zero weight it contributes nothing.

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, admitting counts outside the support {0, ..., n}.

Being an exact integer is a type contract and stays enforced; being inside {0, ..., n} is a probability question the scorer answers -inf, so a mixture whose other component owns such a count can encode the whole batch (P02-F03, Q01-F02).

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

supported_rows(x)[source]

Encoded rows this accumulator can be fitted on: counts inside its DECLARED bounds.

The encoder admits counts outside [min_val, max_val] so a mixture can encode one batch against every component, and seq_update refuses such a count only when it carries weight. Initialization draws responsibilities before any model exists, so without this predicate a mixture handed this component a share of the rows its bounds exclude and the refusal blamed the data – an integer-categorical-plus-binomial fit failed with “observations with positive weight must be at most 10” (Q01-F02). The bounds are the declared ones, never the observed running range, for the reason __init__ records.

Parameters:

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

Return type:

ndarray

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).

The endpoints are the support’s own bounds – min_val at q = 0 and min_val + n at q = 1 – rather than scipy’s -1, which is outside the support this law scores (P01-F12).

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

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and at least one.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility. Without it the initializer could not tell that this component does not own a row, seeded it from one anyway, and the refusal below then blamed the DATA for a mixture the model can express – a Poisson-plus-Geometric fit on counts with zeros was refused outright (Q01-F02/Q02-F02).

Return type:

ndarray

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_base_measure(x, engine)[source]

Return the Geometric base measure: 0 for x >= 1, -inf below.

Without it the generated engine kernels scored an admitted zero or negative count with the closed form log p + (x - 1) log(1 - p) – a finite log-probability for an impossible value, where every numpy route returns -inf (V01-F04). The encoder guarantees integers.

Parameters:
Return type:

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 k >= 1 (via scipy geom).

The endpoints are the support’s own bounds – 1 at q = 0 and inf at q = 1; scipy’s 0 at q = 0 is outside the support this law scores (P01-F12).

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

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and at least one.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility. Without it the initializer could not tell that this component does not own a row, seeded it from one anyway, and the refusal below then blamed the DATA for a mixture the model can express – a Poisson-plus-Geometric fit on counts with zeros was refused outright (Q01-F02/Q02-F02).

Return type:

ndarray

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) for k >= 1, and -inf below.

-log(k) alone is +inf at an admitted k = 0 and NaN at a negative count, so the generated engine kernels returned +inf and NaN where every numpy route returns -inf (V01-F04). The encoder guarantees integers.

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 (-inf for k < 1).

Linear in k and log k, which is +inf at an admitted k = 0 and NaN at a negative count, so the torch kernel returned both where the numpy scorer returns -inf (V01-F04).

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

supported_rows(x)[source]

Encoded rows this law can be fitted on: non-negative counts.

The encoder admits a negative count so a mixture can encode one batch against every component (P02-F03); this is the predicate that keeps it out of the statistics and the one a latent model’s initialization consults before handing this component any responsibility. The encoder used to refuse it outright, so an integer-categorical-plus-negative-binomial mixture could not be encoded on data the categorical owns (Q01-F02).

Return type:

ndarray

seq_update(x, weights, estimate)[source]

Accumulate weighted statistics from encoded observations.

A negative count carrying weight is refused. One with zero weight – a row EM gave another component – contributes nothing and is kept out of the histogram, whose keys the dispersion solve reads.

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, admitting negative counts.

Being an exact integer is a type contract and stays enforced; being non-negative is a probability question, answered -inf by the scorer, so a negative count is admitted and a mixture whose other component owns it can encode the whole batch (P02-F03, Q01-F02).

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 (-inf off support).

The encoder admits a negative count so a mixture can encode one batch against every component (P02-F03); the scalar path already scored it -inf, and so does the engine path below.

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 summation of the standard series in bounded memory.

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 – driven by the exact CDF (via betainc) rather than a Gaussian-tail heuristic, since the negative binomial can be heavy-tailed. The sum is taken one bounded block at a time and, once the support is wider than ENTROPY_TERM_CAP counts, the remainder is the Euler-Maclaurin integral of the smooth extension: r = 1e8 used to allocate a single 3.2 GB array here (P01-F02), and the quantile that bounded the scan is itself NaN at extreme parameters (P01-F11), which the tail branch now absorbs instead of propagating.

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).

The endpoints are the support’s own bounds – 0 at q = 0 and inf at q = 1 – rather than scipy’s -1, which is outside the support this law scores (P01-F12).

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

supported_rows(x)[source]

Encoded rows this law can be fitted on: finite and non-negative.

The encoder admits out-of-support observations so that a mixture can encode a whole batch against every component (P02-F03); this is the predicate that keeps them out of the sufficient statistics, and the one a latent model’s initialization consults before it hands this component any responsibility. Without it the initializer could not tell that this component does not own a row, seeded it from one anyway, and the refusal below then blamed the DATA for a mixture the model can express – a Poisson-plus-Geometric fit on counts with zeros was refused outright (Q01-F02/Q02-F02).

Return type:

ndarray

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 summation of the standard series in bounded memory.

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). The sum is taken one bounded block at a time, and from lam = 1e3 upward the classical asymptotic series stands in for it exactly: lam = 1e8 used to allocate a single 3.2 GB array here and lam = 1e15 a 7 PiB one (P01-F02).

Return type:

float

quantile(q)[source]

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

The endpoints are the support’s own bounds – 0 at q = 0 and inf at q = 1 – rather than scipy’s -1, which is outside the support this law scores (P01-F12). Past lam ~ 1e12 scipy’s generic discrete ppf returns NaN for mid-range q while the CDF keeps working; there the answer is bracketed from the normal approximation and bisected on this law’s own CDF (P01-F11).

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

Subpackages