mixle.stats.univariate.continuous package

Continuous univariate distribution namespace.

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

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

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

Submodules