mixle.stats.univariate package¶
mixle.stats.univariate – univariate distributions, split into continuous/ and discrete/.
Both subpackages re-export every class they implement, and this package re-exports both, so the
namespace exposes the API it actually contains (MXR-080-1231). Previously each level advertised
only its submodule names, so from mixle.stats.univariate import GaussianDistribution failed
while from mixle.stats import GaussianDistribution worked.
mixle.stats remains the consolidated public API and re-exports these same objects.
- class BetaAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate sufficient statistics for beta estimation.
- update(x, weight, estimate)[source]
Accumulate weighted statistics for one observation in
(0, 1).
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted statistics from encoded observations.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- combine(suff_stat)[source]
Merge another Beta sufficient-statistic tuple.
- value()[source]
Return the accumulated Beta sufficient statistics.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
BetaDataEncoder
- class BetaAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for BetaAccumulator.
- make()[source]
Create a fresh Beta accumulator.
- Return type:
BetaAccumulator
- class BetaDataEncoder[source]
Bases:
DataSequenceEncoderEncode beta observations with log x and log(1-x) columns.
- class BetaDistribution(a, b, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBeta distribution with positive shape parameters a and b.
- 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_xandlog1m_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 frombackend_log_density_from_params; indexing the leading two works for both arities.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Beta sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Beta natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Beta log partition for generated scoring.
- 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.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(log_x, log1m_x, a, b, engine)[source]
Engine-neutral Beta log-density from encoded logs and parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Beta parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Beta log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- entropy()[source]
Differential entropy ln B(a,b) - (a-1)psi(a) - (b-1)psi(b) + (a+b-2)psi(a+b).
- Return type:
- 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:
ParameterEstimatorEstimate beta shape parameters from weighted log-moment statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Beta sufficient statistics.
- Return type:
BetaAccumulatorFactory
- class BetaFisherView(dist)[source]
Bases:
FixedFisherViewFisher view for Beta sufficient statistics.
- Parameters:
dist (Any)
- class BetaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid beta observations.
- Parameters:
dist (BetaDistribution)
seed (int | None)
- class ExponentialAccumulator(keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate 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.
- 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
- initialize(x, weight, rng)[source]
Initialize sufficient statistics of ExponentialAccumulator with weighted observation.
This delegates to
update().
- 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.
- from_value(x)[source]
Sets sufficient statistics (count and sum) of ExponentialAccumulator to x.
- acc_to_encoder()[source]
Return the encoder associated with this accumulator.
- Return type:
ExponentialDataEncoder
- class ExponentialAccumulatorFactory(keys=None)[source]
Bases:
StatisticAccumulatorFactoryCreate 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:
DataSequenceEncoderData 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.
- class ExponentialDistribution(beta, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionExponential distribution on non-negative real values with scale
beta.- Parameters:
- 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.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Exponential sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Exponential natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Exponential log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return Exponential support base measure for generated scoring.
- 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 thatexpected_log_density(x) = e1*x - eawhere the natural parameter iseta = -rate,E[eta] = -k*thetaandE[-log(-eta)] = psi(k) + ln theta(mapping the prior’s(k, theta)to the bstats[a, b] = [k, 1/theta]form). Any other prior (includingNone) 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.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density of exponential distribution with scale beta.
See log_density() for details.
- 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.
- 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:
- static backend_log_density_from_params(x, beta, engine)[source]
Engine-neutral exponential log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Exponential parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Exponential log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Exponential sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return the Exponential’s count-family Fisher view.
- 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:
ParameterEstimatorEstimate Exponential scale parameters from accumulated sufficient statistics.
- Parameters:
- 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:
- 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.
- class ExponentialSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw independent samples from an
ExponentialDistribution.- Parameters:
dist (ExponentialDistribution)
seed (int | None)
- class ExponentiallyModifiedGaussianAccumulator(keys=None, name=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted central moments for method-of-moments EMG estimation.
- update(x, weight, estimate)[source]
Update weighted central moments from one observation.
- initialize(x, weight, rng)[source]
Initialize weighted central moments from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_initialize(x, weights, rng)[source]
Initialize weighted central moments from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- 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]^2cancellation, but a SINGLE centering pass does not remove all of it: the computedmeancarries the rounding of a large-magnitude sum, and that residue enters the third moment linearly – which is the momentlamis inverted from, so the fitted rate drifted at large data offsets. The second pass incentered_batch_moments()computes the residue at spread scale, where it is exact, and makes the fit shift-equivariant.
- combine(suff_stat)[source]
Merge another accumulator’s central-moment summary.
- value()[source]
Return count, mean, second central moment, and third central moment.
- from_value(x)[source]
Restore count and central-moment state from
valueoutput.
- 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:
StatisticAccumulatorFactoryCreate EMG central-moment accumulators.
- make()[source]
Create an empty EMG accumulator.
- Return type:
ExponentiallyModifiedGaussianAccumulator
- class ExponentiallyModifiedGaussianDataEncoder[source]
Bases:
DataSequenceEncoderEncode sequences of iid EMG observations (data type float).
- class ExponentiallyModifiedGaussianDistribution(mu, sigma2, lam, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionExponentially-modified Gaussian:
X = N(mu, sigma2) + Exp(rate=lam).- density(x)[source]
Density of the EMG at observation
x(seelog_density).
- 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)withu = (x - mu)/sigmaandz = (lam*sigma - u)/sqrt(2).
- seq_ld_lambda()[source]
Return vectorized log-density callables for encoded data.
- seq_log_density(x)[source]
Vectorized EMG log-density at sequence-encoded input
x.
- 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.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact, via scipy’s exponnorm).
- 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:
ParameterEstimatorEstimate EMG parameters from weighted central moments.
The fit is SHIFT-EQUIVARIANT: estimating on
x + creturnsmu + cwithsigma2andlamunchanged, for any constantcthe data can carry – epoch seconds (~1.7e9), 2**31 and 1e12 included. The moments come fromExponentiallyModifiedGaussianAccumulator, which centers each batch twice for exactly this reason; a single centering pass moved the fit by 1.3e-4 at 1e12, silently.- accumulator_factory()[source]
Return a factory for EMG central-moment accumulators.
- Return type:
ExponentiallyModifiedGaussianAccumulatorFactory
- class ExponentiallyModifiedGaussianSampler(dist, seed=None)[source]
Bases:
DistributionSamplerSample an EMG by adding independent Gaussian and exponential draws.
- Parameters:
dist (ExponentiallyModifiedGaussianDistribution)
seed (int | None)
- class GammaAccumulator(keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate 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().
- 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.
- 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.
- value()[source]
Return
(count, sum, sum_of_logs)sufficient statistics.
- from_value(x)[source]
Sets sufficient statistics GammaAccumulator to x.
- acc_to_encoder()[source]
Return an encoder compatible with Gamma observations.
- Return type:
GammaDataEncoder
- class GammaAccumulatorFactory(keys=None)[source]
Bases:
StatisticAccumulatorFactoryCreate 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:
DataSequenceEncoderEncoder 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 tok = 1silently. NaN is rejected as missing data, by name.
- class GammaDistribution(k, theta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGamma distribution parameterized by shape and scale.
- 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.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Gamma sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Gamma natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Gamma log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return Gamma support base measure for generated scoring.
- 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.
- 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:
- density(x)[source]
Density of gamma distribution evaluated at x.
See log_density() for details.
- 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
- 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:
- static backend_log_density_from_params(vals, log_vals, k, theta, engine)[source]
Engine-neutral gamma log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Gamma parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Gamma log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Gamma sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- 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:
ParameterEstimatorEstimate 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).
- static estimate_shape(avg_sum, avg_sum_of_logs, threshold)[source]
Estimates the shape parameter of GammaDistribution.
- class GammaFisherView(dist)[source]
Bases:
FixedFisherViewExpose Gamma sufficient statistics for Fisher-information utilities.
- Parameters:
dist (Any)
- class GammaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw independent samples from a
GammaDistribution.- Parameters:
dist (GammaDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw iid observations from the Gamma distribution.
- class GaussianAccumulator(keys=None, name=None, compensated=False)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted first and second moments for Gaussian estimation.
- update(x, weight, estimate)[source]
Update sufficient statistics for GaussianAccumulator with one weighted observation.
- initialize(x, weight, rng)[source]
Initialize with a weighted observation.
- 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
compensatedandsuff_statcarries a numerics-error receipt (seevalue()/GaussianSuffStat), its float64 magnitude and exact term-count fields are folded in too.
- scale(c)[source]
Scale the accumulated statistics in place by
c, anchored track included.The structural default round-trips through
value()andfrom_value(), andscale_suff_statrebuilds the payload as a PLAIN tuple – which drops theanchoredattribute, sofrom_valuesees 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_updatethenscale(0.37)fitted sigma2 = 1e+22 where the same weights passed toseq_updatedirectly fitted 0.24625. Scaling every weight bycis 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.Nonewhen this accumulator was not constructed withcompensated=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.
- 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 aGaussianSuffStat– a drop-in 4-tuple (indexing/unpacking/iteration all behave identically) that additionally carries the numerics-error receipt in its.receiptattribute and the anchored moments in its.anchoredattribute, socombine()can fold them in andGaussianEstimator.estimate()can compute a shift-invariant variance.
- 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).
- 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- make()[source]
Return a GaussianAccumulator object with name and keys passed.
- Return type:
GaussianAccumulator
- class GaussianDataEncoder[source]
Bases:
DataSequenceEncoderEncoder for iid scalar Gaussian observations.
- class GaussianDistribution(mu, sigma2, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionUnivariate Gaussian distribution.
- Parameters:
- 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.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Gaussian sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Gaussian natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Gaussian log partition for generated scoring.
- 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 (includingNone) 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.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Density of Gaussian distribution at observation x.
See log_density() for details.
- 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.
- seq_ld_lambda()[source]
Return vectorized log-density callables for encoded data.
- 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:
- static backend_log_density_from_params(x, mu, sigma2, engine)[source]
Engine-neutral Gaussian log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- gradient_log_prior(priors, prior_strength, torch, engine)[source]
Distribution-owned MAP prior contribution for Gaussian parameters.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Gaussian parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Gaussian log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Gaussian sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return the Gaussian’s own Fisher view.
- 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:
ParameterEstimatorEstimate 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, sooptimize(x + 1.7e9, GaussianEstimator(), engine=NUMPY_ENGINE)on sd ~2 data returned a variance 7.9e9 times too large.estimatenow WARNS in that case rather than returning it silently; the remedy is to accumulate throughGaussianAccumulator(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 siblingDiagonalGaussianEstimatoruses a flat1e-8regardless 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 passmin_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:
- 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.
- class GaussianFisherView(dist)[source]
Bases:
FixedFisherViewFisher view over the Gaussian’s (sum, sum2, count, count2) sufficient statistics.
- Parameters:
dist (Any)
- class GaussianSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw independent samples from a
GaussianDistribution.- Parameters:
dist (GaussianDistribution)
seed (int | None)
- class GaussianSuffStat(sum_, sum2_, count_, count2_, receipt=None)[source]
Bases:
tupleA
(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);
receiptis extra payload thatGaussianAccumulator.combine()reads to fold the Kahan round-off bookkeeping (abs_total,nforsumandsum2) into the receiving accumulator when both sides arecompensated, andanchoredis 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 (seeGaussianAccumulator). Code that doesn’t know about either payload (genericscale_suff_stat, engine kernels, …) sees an ordinary tuple.
- class GeneralizedExtremeValueAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate 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 != 0is 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)^kfork = 1..3about 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 scatterO(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)/spreadratio 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 onGeneralizedExtremeValueSuffStat; a consumer that drops the payload simply gets the historical raw estimate back.- update(x, weight, estimate)[source]
Accumulate weighted first three raw moments and the observed range for one observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted first three raw moments and the observed range from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another GEV sufficient-statistic tuple.
- 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
.anchoredattribute, socombine()can fold them in andGeneralizedExtremeValueEstimator.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.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- 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:
StatisticAccumulatorFactoryFactory for GeneralizedExtremeValueAccumulator.
- make()[source]
Create a fresh GEV accumulator.
- Return type:
GeneralizedExtremeValueAccumulator
- class GeneralizedExtremeValueDataEncoder[source]
Bases:
DataSequenceEncoderEncode GEV observations as a float array.
- class GeneralizedExtremeValueDistribution(loc, scale, shape, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGeneralized Extreme Value distribution with location
loc, scale> 0and shapexi.- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (
-infoutside the support).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- 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, ignoringStatisticSpec.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 handestimatea summed min and max. GEV therefore accumulates through the hostseq_update, which is three dot products for a univariate leaf; engine-resident scoring viabackend_seq_log_densityis unaffected. Reinstate this hook once the generated path honours non-additive support bounds.
- static backend_log_density_from_params(x, loc, scale, shape, engine)[source]
Engine-neutral GEV log-density; the
abs(xi) < tolGumbel limit is selected per element.s^{-1/xi}is computed asexp(-log(s)/xi)so the whole expression stays on engine ops.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked GEV parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of GEV log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact).
- mean()[source]
Mean: loc + scale*(Gamma(1-xi)-1)/xi (loc+scale*euler_gamma at xi=0); inf for xi>=1.
- Return type:
- 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:
- entropy()[source]
Differential entropy log(scale) + euler_gamma * xi + euler_gamma + 1.
- Return type:
- 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,scaleandshape.- 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:
ParameterEstimatorMethod-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-
xirelation, 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 innumerical_repairs()sofit_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:estimateonx + creturnsloc + cwithscaleandshapeunchanged. 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
- class GeneralizedExtremeValueSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid GEV observations by inverse-CDF transform.
- Parameters:
dist (GeneralizedExtremeValueDistribution)
seed (int | None)
- class GeneralizedGaussianAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate 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)^kfork = 1..4about 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 roughly4*log2(abs(mean)/sd)bits, so data with sd ~0.7 at offset 1.7e9 has no correct digits left inm4and the fit collapses onto the shape bound with a scale two orders of magnitude too small – silently. Anchoring keeps every term of the scatterO(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)/spreadratio 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 onGeneralizedGaussianSuffStat; a consumer that drops the payload simply gets the historical raw estimate back.- update(x, weight, estimate)[source]
Accumulate weighted raw moments up to order four for one observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted raw moments up to order four from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another generalized-Gaussian sufficient-statistic tuple.
- 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
.anchoredattribute, socombine()can fold them in andGeneralizedGaussianEstimator.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.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- 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:
StatisticAccumulatorFactoryFactory for GeneralizedGaussianAccumulator.
- make()[source]
Create a fresh generalized-Gaussian accumulator.
- Return type:
GeneralizedGaussianAccumulator
- class GeneralizedGaussianDataEncoder[source]
Bases:
DataSequenceEncoderEncode observations as a float array.
- class GeneralizedGaussianDistribution(mu, alpha, beta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGeneralized Gaussian (exponential power) with location
mu, scalealphaand shapebeta.- 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.
- seq_log_density(x)[source]
Return vectorized log-density for a sequence-encoded array of observations.
- kurtosis()[source]
Excess kurtosis Gamma(5/beta)Gamma(1/beta)/Gamma(3/beta)^2 - 3.
- Return type:
- entropy()[source]
Differential entropy 1/beta - log(beta / (2 alpha Gamma(1/beta))).
- Return type:
- 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:
ParameterEstimatorMethod-of-moments estimator:
mu= mean,betafrom excess kurtosis,alphafrom 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:estimateonx + creturnsmu + cwithalphaandbetaunchanged. 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
- class GeneralizedGaussianSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw
x = mu + sign * alpha * Gamma(1/beta)**(1/beta).- Parameters:
dist (GeneralizedGaussianDistribution)
seed (int | None)
- class GeneralizedParetoAccumulator(loc=0.0, name=None, keys=None, has_prior=False)[source]
Bases:
AnchoredMomentTrack,SequenceEncodableStatisticAccumulatorAccumulate weighted first and second moments for GPD estimation.
Alongside the raw
(sum, sum2, count)the accumulator keeps the conditioning-gated shift-anchored moment track ofAnchoredMomentTrack. Peaks-over-threshold data is the case that needs it most: BOTH moments the inversion uses are differences taken at data magnitude – the exceedance meansum_x/count - locand the varianceE[x^2]-E[x]^2– so a threshold at epoch seconds turned a shape of+0.16into a flat0and the exponential limit, silently. Well-conditioned data never activates the track and accumulates bit-identically to the historical single-pass path.- update(x, weight, estimate)[source]
Accumulate weighted first and second moments for one observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted first and second moments from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another generalized-Pareto sufficient-statistic tuple.
- 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
GeneralizedParetoSuffStatadditionally carrying the anchored moments in its.anchoredattribute and/or the max in.max_x, socombine()can fold them in andGeneralizedParetoEstimator.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 fromestimate, that case is still reported as aGeneralizedParetoSuffStatwithmax_x=Noneandmax_unverified=True, soestimatecan disclose the ambiguity instead of reproducing the T1-01 crash class with zero signal (T1-02).
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- scale(c)[source]
Scale the accumulated statistics in place by
c, anchored track included.The structural default round-trips through
value()/from_value()andscale_suff_statrebuilds a PLAIN tuple, which would drop the payload and undo the repair;locis 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:
StatisticAccumulatorFactoryFactory for GeneralizedParetoAccumulator.
- make()[source]
Create a fresh generalized-Pareto accumulator.
- Return type:
GeneralizedParetoAccumulator
- class GeneralizedParetoDataEncoder(loc=0.0, scale=None, shape=None)[source]
Bases:
DataSequenceEncoderEncode GPD observations as a float array.
- class GeneralizedParetoDistribution(scale, shape, loc=0.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGeneralized Pareto distribution with threshold
loc, scale> 0and shapexi.- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (
-infoutside the support).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- 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).
- static backend_log_density_from_params(x, scale, shape, loc, engine)[source]
Engine-neutral GPD log-density; the
abs(xi) < tolexponential limit is selected per element.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked GPD parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of GPD log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Stacked GPD moment sums
(sum, sum2, count)using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact).
- 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
scaleandshapeat the fixed thresholdloc.- 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:
ParameterEstimatorMethod-of-moments estimator for GPD scale and shape at a fixed threshold
loc.Both inverted moments – the exceedance mean
sum_x/count - locand the varianceE[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 fittedshape=0(the exponential limit) instead of+0.16, silently. Whenever the accumulated statistics carry the shift-anchored payload (seeGeneralizedParetoAccumulator) both moments are formed about a data anchor instead, which makes the fit THRESHOLD-EQUIVARIANT: estimating onx + cwith the threshold atloc + creturns the samescaleandshape, for any constantcthe 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, andestimatewarns rather than returning moments it cannot stand behind.The
pseudo_countprior is carried as the raw pairsuff_stat = (mean0, second0); a plain 2-tuple has its variance and exceedance-mean offset recovered by differencing (second0 - mean0**2andmean0 - locrespectively), 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 withGeneralizedParetoDistribution.estimator(), which carries both exactly (seeGeneralizedParetoPriorMoments).locis 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 apseudo_countprior 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 wrongloc(T1-01).- Parameters:
- property loc: float
The fixed threshold
muobservations are exceedances over.
- accumulator_factory()[source]
Return an accumulator factory for generalized-Pareto moments.
- Return type:
GeneralizedParetoAccumulatorFactory
- class GeneralizedParetoSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid GPD observations by inverse-CDF transform.
- Parameters:
dist (GeneralizedParetoDistribution)
seed (int | None)
- class GumbelAccumulator(keys=None)[source]
Bases:
AnchoredMomentTrack,SequenceEncodableStatisticAccumulatorAccumulate weighted first and second moments for Gumbel estimation.
Alongside the raw
(sum, sum2, count)the accumulator keeps the conditioning-gated shift-anchored moment track ofAnchoredMomentTrack: the naiveE[x^2]-E[x]^2form 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 ontomin_scaleat 2**31 – silently, with an emptynumerical_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.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted first and second moments from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another Gumbel sufficient-statistic tuple.
- 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
GumbelSuffStatadditionally carrying the anchored moments in its.anchoredattribute, socombine()can fold them in andGumbelEstimator.estimate()can invert a shift-invariant variance.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- 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:
StatisticAccumulatorFactoryFactory for GumbelAccumulator.
- Parameters:
keys (str | None)
- make()[source]
Create a fresh Gumbel accumulator.
- Return type:
GumbelAccumulator
- class GumbelDataEncoder[source]
Bases:
DataSequenceEncoderEncode Gumbel observations as a float array.
- class GumbelDistribution(loc=0.0, scale=1.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGumbel (extreme value type I) distribution with location loc and scale beta > 0.
- 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.
- static backend_log_density_from_params(x, loc, scale, engine)[source]
Engine-neutral Gumbel log-density from explicit parameters.
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Gumbel parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Gumbel log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Gumbel sufficient statistics using engine-resident arrays.
- 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:
ParameterEstimatorMoment estimator for the Gumbel location and scale.
Inverts the Gumbel moments:
beta = sqrt(6 * var) / piandloc = mean - beta * gammawhere 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 onx + creturnsloc + cwithscaleunchanged, for any constantcthe 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, andestimatewarns rather than returning a scale it cannot stand behind.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Gumbel moment statistics.
- Return type:
GumbelAccumulatorFactory
- class GumbelSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid Gumbel observations.
- Parameters:
dist (GumbelDistribution)
seed (int | None)
- class HalfNormalAccumulator(keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate 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.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted squared observations from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another half-normal sufficient-statistic tuple.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
HalfNormalDataEncoder
- class HalfNormalAccumulatorFactory(keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for HalfNormalAccumulator.
- Parameters:
keys (str | None)
- make()[source]
Create a fresh half-normal accumulator.
- Return type:
HalfNormalAccumulator
- class HalfNormalDataEncoder[source]
Bases:
DataSequenceEncoderEncode half-normal observations as x and x**2.
- class HalfNormalDistribution(sigma, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionHalf-normal distribution with scale sigma > 0 on x >= 0.
- 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.
- static exp_family_natural_parameters(params, engine)[source]
Return the (-1/(2*sigma^2),) natural parameter for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return the half-normal log partition log(sigma).
- static exp_family_base_measure(x, engine)[source]
Return the support base measure 0.5*log(2/pi) (or -inf off support x >= 0).
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row (count, x**2) sufficient statistics in accumulator order.
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (or -inf off support).
- 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:
- static backend_log_density_from_params(vals, sq_vals, sigma, engine)[source]
Engine-neutral half-normal log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of half-normal log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function P(X <= x) (0 for x < 0).
- 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:
ParameterEstimatorMaximum-likelihood estimator for the half-normal scale: sigma = sqrt(mean(x**2)).
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for half-normal statistics.
- Return type:
HalfNormalAccumulatorFactory
- class HalfNormalSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid half-normal observations as
|N(0, sigma**2)|.- Parameters:
dist (HalfNormalDistribution)
seed (int | None)
- class InverseGammaAccumulator(keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate 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.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate transformed sufficient statistics from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another inverse-gamma sufficient-statistic tuple.
- value()[source]
Return count, reciprocal sum, and negative-log sum.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
InverseGammaDataEncoder
- class InverseGammaAccumulatorFactory(keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for InverseGammaAccumulator.
- Parameters:
keys (str | None)
- make()[source]
Create a fresh inverse-gamma accumulator.
- Return type:
InverseGammaAccumulator
- class InverseGammaDataEncoder[source]
Bases:
DataSequenceEncoderEncode inverse-gamma observations as (log x, 1/x) pairs.
- class InverseGammaDistribution(alpha, beta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionInverse-gamma distribution with shape alpha > 0 and rate beta > 0 on x > 0.
- 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.
- static exp_family_sufficient_statistics(x, engine)[source]
Return inverse-gamma sufficient statistics
T(x) = (log x, 1/x).
- static exp_family_natural_parameters(params, engine)[source]
Return inverse-gamma natural parameters
eta = (-(alpha + 1), -beta).
- static exp_family_log_partition(params, engine)[source]
Return inverse-gamma log partition
A = lgamma(alpha) - alpha * log(beta).
- 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).
- get_parameters()[source]
Return the (shape alpha, rate beta) pair (so this can serve as a conjugate prior).
- cross_entropy(dist)[source]
Cross entropy -E_self[log dist(x)] for an inverse-gamma argument (closed form).
- Parameters:
dist (InverseGammaDistribution)
- Return type:
- mean()[source]
Mean E[X] = beta / (alpha - 1) for alpha > 1, else inf (the mean integral diverges).
- Return type:
- variance()[source]
Variance beta^2 / ((alpha-1)^2 (alpha-2)) for alpha > 2, else inf.
- Return type:
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (or -inf off support).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded (log x, 1/x) observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of inverse-gamma log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function P(X <= x) = Q(alpha, beta/x) (0 for x <= 0).
- 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:
ParameterEstimatorMaximum-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
- class InverseGammaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid inverse-gamma observations as 1 / Gamma(alpha, 1/beta).
- Parameters:
dist (InverseGammaDistribution)
seed (int | None)
- class InverseGaussianAccumulator(keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate 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.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate transformed sufficient statistics from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- combine(suff_stat)[source]
Merge another inverse-Gaussian sufficient-statistic tuple.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
InverseGaussianDataEncoder
- class InverseGaussianAccumulatorFactory(keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for InverseGaussianAccumulator.
- Parameters:
keys (str | None)
- make()[source]
Create a fresh inverse-Gaussian accumulator.
- Return type:
InverseGaussianAccumulator
- class InverseGaussianDataEncoder[source]
Bases:
DataSequenceEncoderEncode inverse Gaussian observations as x, 1/x, and log(x).
- class InverseGaussianDistribution(mu, lam, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionInverse Gaussian (Wald) distribution with mean mu > 0 and shape lam > 0 on x > 0.
- 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.
- static exp_family_natural_parameters(params, engine)[source]
Return the (-lam/(2*mu^2), -lam/2) natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return the inverse Gaussian log partition -0.5*log(lam) - lam/mu.
- 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).
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row (count, x, 1/x) sufficient statistics in accumulator order.
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (or -inf off support).
- 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:
- static backend_log_density_from_params(vals, inv_vals, log_vals, mu, lam, engine)[source]
Engine-neutral inverse Gaussian log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of inverse Gaussian log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function P(X <= x) (Wald, via scipy invgauss).
- 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 sinceE[(X - mu)^2 / X] = mu^2 / lam), withE[log X] = log(mu) - e^{2z} E_1(2z)atz = lam / mu– the order-derivative identity for the BesselK_{1/2}under the GIG representation,E_1the exponential integral. The scaled producte^x E_1(x)switches to its asymptotic series whereexpoverflows.- Return type:
- 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:
ParameterEstimatorMaximum-likelihood estimator for the inverse Gaussian mean and shape.
The MLE is closed form:
mu = mean(x)and1/lam = mean(1/x) - 1/mu.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for inverse-Gaussian statistics.
- Return type:
InverseGaussianAccumulatorFactory
- class InverseGaussianSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid inverse Gaussian (Wald) observations.
- Parameters:
dist (InverseGaussianDistribution)
seed (int | None)
- class LaplaceAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted observations for exact weighted-median M-step.
- update(x, weight, estimate)[source]
Store one positively weighted observation for the weighted-median M-step.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Store positively weighted encoded observations for estimation.
- 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.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge raw weighted observations from another accumulator.
- from_value(x)[source]
Replace accumulator contents from raw observations and weights.
- 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:
StatisticAccumulatorFactoryFactory for LaplaceAccumulator.
- make()[source]
Create a fresh Laplace accumulator.
- Return type:
LaplaceAccumulator
- class LaplaceDataEncoder[source]
Bases:
DataSequenceEncoderEncode Laplace observations as a float array.
- class LaplaceDistribution(mu, b, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLaplace distribution with location mu and scale b > 0.
- 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.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, mu, b, engine)[source]
Engine-neutral Laplace log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Laplace parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Laplace log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return per-component raw weighted observations using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- 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:
ParameterEstimatorExact weighted-MLE estimator for Laplace location and scale.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Laplace raw-observation statistics.
- Return type:
LaplaceAccumulatorFactory
- class LaplaceSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid Laplace observations.
- Parameters:
dist (LaplaceDistribution)
seed (int | None)
- class LogGaussianAccumulator(keys=None, name=None)[source]
Bases:
AnchoredMomentTrack,SequenceEncodableStatisticAccumulatorAccumulate 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 boundsabs(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 onlog(x): values around 1e6 with a 0.2% spread lost 1.4e-7 of the fittedsigma2, 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 tolog_sum/log_sum2. Aliases rather than a rename because(log_sum, log_sum2, count, count2)is the released attribute spelling.- 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.
- initialize(x, weight, rng)[source]
Initialize sufficient statistics with one weighted observation.
- 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
- 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).
- 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
LogGaussianSuffStatadditionally carrying the anchored log moments in itsanchoredattribute.
- 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).
- scale(c)[source]
Scale the accumulated statistics in place by
c, anchored track included.The structural default round-trips through
value()/from_value(), andscale_suff_statrebuilds 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:
StatisticAccumulatorFactoryCreate log-Gaussian accumulators with shared name and merge-key metadata.
- make()[source]
Return a fresh log-Gaussian accumulator with this factory’s name and keys.
- Return type:
LogGaussianAccumulator
- class LogGaussianDataEncoder[source]
Bases:
DataSequenceEncoderData encoder for iid positive log-Gaussian observations.
- class LogGaussianDistribution(mu, sigma2, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLog-normal distribution where
log(X)is Gaussian with meanmuand variancesigma2.- Parameters:
- 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.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row log-Gaussian sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return log-Gaussian natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return log-Gaussian log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return log-Gaussian base measure for generated scoring.
- 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 - ywith y = log(x). Any other prior (includingNone) 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).
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded (logged) observations.
- density(x)[source]
Density of Log-Gaussian distribution at observation x.
See log_density() for details.
- 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.
- seq_ld_lambda()[source]
Return vectorized log-density callables for fast scoring.
- 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:
- static backend_log_density_from_params(x, mu, sigma2, engine)[source]
Engine-neutral log-Gaussian log-density on log-encoded data.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for log-encoded data.
- gradient_log_prior(priors, prior_strength, torch, engine)[source]
Distribution-owned MAP prior contribution for log-Gaussian parameters.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked log-Gaussian parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of log-Gaussian log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked log-Gaussian sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- 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:
ParameterEstimatorEstimate 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 ona * xreturnsmu + log(a)withsigma2unchanged, for any positiveathe data can carry. A large multiplicative scale is a large additive offset onlog(x), which is the same cancellation the sibling location-scale families repaired; here it costs ~1.4e-7 ofsigma2on 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, andestimatewarns 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:
- estimate(nobs, suff_stat)[source]
Estimate a log-Gaussian distribution from accumulated log moments.
suff_statis(sum_log_x, sum_log_x2, count, count2).nobsis accepted for estimator API consistency but is not used.
- class LogGaussianFisherView(dist)[source]
Bases:
FixedFisherViewExpose log-Gaussian sufficient statistics for Fisher-information utilities.
- Parameters:
dist (Any)
- class LogGaussianSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw 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.
Nonereturns a single float. A positivesizereturns a NumPy array of that many samples on the original positive scale.
- class LogisticAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate 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 naiveE[x^2]-E[x]^2form 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)/spreadratio 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 scalarupdate) would corrupt the variance. The raw moments remain the exchange format –(sum, sum2, count)is the declaredStatisticSpectuple consumed by engine kernels – so the anchored track rides along as a payload onLogisticSuffStat.- update(x, weight, estimate)[source]
Accumulate weighted first and second moments for one observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted first and second moments from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another logistic sufficient-statistic tuple.
- 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
LogisticSuffStatthat additionally carries the anchored moments in its.anchoredattribute, socombine()can fold them in andLogisticEstimator.estimate()can compute a shift-invariant variance.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- scale(c)[source]
Scale the accumulated statistics in place by
c, anchored track included.The structural default round-trips through
value()andfrom_value(), andscale_suff_statrebuilds the payload as a PLAIN tuple – which drops theanchoredattribute, sofrom_valuesees 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:
StatisticAccumulatorFactoryFactory for LogisticAccumulator.
- make()[source]
Create a fresh logistic accumulator.
- Return type:
LogisticAccumulator
- class LogisticDataEncoder[source]
Bases:
DataSequenceEncoderEncode logistic observations as a float array.
- class LogisticDistribution(loc=0.0, scale=1.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLogistic distribution with location loc and scale > 0.
- 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.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, loc, scale, engine)[source]
Engine-neutral logistic log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked logistic parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of logistic log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- 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:
ParameterEstimatorMoment 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 onx + creturnsloc + cwithscaleunchanged. 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
- class LogisticSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid logistic observations.
- Parameters:
dist (LogisticDistribution)
seed (int | None)
- class NakagamiAccumulator(name=None, keys=None)[source]
Bases:
SquaredPowerSumTrack,SequenceEncodableStatisticAccumulatorAccumulate 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 ony = 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.- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
NakagamiDataEncoder
- class NakagamiAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for NakagamiAccumulator.
- make()[source]
Create a fresh Nakagami accumulator.
- Return type:
NakagamiAccumulator
- class NakagamiDataEncoder[source]
Bases:
DataSequenceEncoderEncode observations as a float array.
- class NakagamiDistribution(m, omega, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionNakagami distribution with shape
m >= 1/2and spreadomega = E[X^2] > 0.- log_density(x)[source]
Return the log-density at
x, including the exact limit at zero.
- seq_log_density(x)[source]
Return vectorized log-density for a sequence-encoded array of observations.
- 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).
- static backend_log_density_from_params(x, m, omega, engine)[source]
Engine-neutral Nakagami log-density with the exact limit at zero.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked Nakagami parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Nakagami log densities.
- 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.
- cdf(x)[source]
Cumulative distribution function P(X <= x) = P(m, m x^2 / omega) (0 for x <= 0).
- 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)withY = X^2 ~ Gamma(m, omega/m)(Nakagami, ‘The m-distribution’, 1960), soh(X) = h(Y) - log(2) - E[log X] = h(Y) - log(2) - (1/2)(E[log Y])and bothh(Y)andE[log Y]are standard Gamma-distribution identities. Reduces exactly to the Rayleigh entropy atm = 1.- Return type:
- 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:
ParameterEstimatorMethod-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 (seeNakagamiAccumulator). The shape is the reciprocal of the relative spread ofX^2, so the rawE[X^4] - E[X^2]^2form loses abouteps * 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, andestimatewarns 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
- class NakagamiSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw
X = sqrt(G)withG ~ Gamma(shape=m, scale=omega/m)(soX^2 ~ Gamma(m, omega/m)).- Parameters:
dist (NakagamiDistribution)
seed (int | None)
- class ParetoAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted support minimum and log-sum statistics.
- update(x, weight, estimate)[source]
Accumulate weighted log and support-minimum statistics for one sample.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted log and support-minimum statistics from encoded data.
- seq_update_engine(x, weights, estimate, engine)[source]
Engine-resident accumulation of the count and log-sum statistics (numpy or torch).
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another Pareto sufficient-statistic tuple.
- value()[source]
Return count, weighted log-sum, and observed support minimum.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- 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:
StatisticAccumulatorFactoryFactory for ParetoAccumulator.
- make()[source]
Create a fresh Pareto accumulator.
- Return type:
ParetoAccumulator
- class ParetoDataEncoder[source]
Bases:
DataSequenceEncoderEncode Pareto observations with x and log(x).
- class ParetoDistribution(xm, alpha, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionPareto type-I distribution with scale xm > 0 and shape alpha > 0.
- 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,)(scalexmfixed).
- static exp_family_natural_parameters(params, engine)[source]
Return the Pareto natural parameter
eta = -alpha(scalexmfixed).
- static exp_family_log_partition(params, engine)[source]
Return the Pareto log partition
A = -log(alpha) - alpha * log(xm).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return the Pareto base measure
log h(x) = -log(x)on[xm, inf)(-infbelowxm).
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(vals, log_vals, xm, alpha, engine)[source]
Engine-neutral Pareto log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Pareto parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Pareto log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Pareto sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- variance()[source]
Variance xm^2 alpha / ((alpha-1)^2 (alpha-2)) for alpha > 2, else inf.
- Return type:
- 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:
ParameterEstimatorMLE estimator for Pareto scale and shape.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Pareto sufficient statistics.
- Return type:
ParetoAccumulatorFactory
- class ParetoSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid Pareto observations.
- Parameters:
dist (ParetoDistribution)
seed (int | None)
- class RayleighAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted squared observations.
- update(x, weight, estimate)[source]
Accumulate weighted squared observations for one sample.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted squared observations from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- combine(suff_stat)[source]
Merge another Rayleigh sufficient-statistic tuple.
- value()[source]
Return accumulated count and squared-observation sum.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
RayleighDataEncoder
- class RayleighAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for RayleighAccumulator.
- make()[source]
Create a fresh Rayleigh accumulator.
- Return type:
RayleighAccumulator
- class RayleighDataEncoder[source]
Bases:
DataSequenceEncoderEncode Rayleigh observations with x, x**2, and log(x).
- class RayleighDistribution(sigma, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionRayleigh distribution with scale sigma > 0.
- 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.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Rayleigh sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Rayleigh natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Rayleigh log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return Rayleigh support/base measure for generated scoring.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(vals, vals2, log_vals, sigma, engine)[source]
Engine-neutral Rayleigh log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Rayleigh parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Rayleigh log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- 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:
ParameterEstimatorClosed-form MLE estimator for Rayleigh scale.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Rayleigh sufficient statistics.
- Return type:
RayleighAccumulatorFactory
- class RayleighSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid Rayleigh observations.
- Parameters:
dist (RayleighDistribution)
seed (int | None)
- class RicianAccumulator(name=None, keys=None)[source]
Bases:
SquaredPowerSumTrack,SequenceEncodableStatisticAccumulatorAccumulate 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 ony = 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.- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
RicianDataEncoder
- class RicianAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for RicianAccumulator.
- make()[source]
Create a fresh Rician accumulator.
- Return type:
RicianAccumulator
- class RicianDataEncoder[source]
Bases:
DataSequenceEncoderEncode observations as a float array.
- class RicianDistribution(nu, sigma, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionRician distribution with non-centrality
nu >= 0and scalesigma > 0.- log_density(x)[source]
Return the log-density at
x(-inf for x <= 0).
- seq_log_density(x)[source]
Return vectorized log-density for a sequence-encoded array of observations.
- 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).
- static backend_log_density_from_params(x, nu, sigma, engine)[source]
Engine-neutral Rician log-density (
-infforx <= 0).
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked Rician parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Rician log densities.
- 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.
- cdf(x)[source]
Cumulative distribution function P(X <= x) (Marcum-Q, via scipy rice).
- quantile(q)[source]
Inverse CDF F^{-1}(q) (via scipy rice).
- mean()[source]
Mean sigma sqrt(pi/2) L_{1/2}(-nu^2/(2 sigma^2)) (stable via the scaled Bessel ive).
- Return type:
- entropy()[source]
Differential entropy in nats, by adaptive quadrature of -f(x) log f(x) over x > 0.
At
nu = 0the Rician is exactly the Rayleigh, whose entropy is the closed form1 + log(sigma / sqrt(2)) + euler_gamma / 2. Fornu > 0the density’slog 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:
- 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:
ParameterEstimatorMethod-of-moments estimator from
E[X^2]andE[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 (seeRicianAccumulator). 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 anynu/sigma: measured against exact rational arithmetic on the same 2000-point samples, the historical form lost 5.4e-9 relative atnu/sigma1e4, 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, andestimatewarns 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
- class RicianSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw
X = sqrt((nu + sigma Z1)^2 + (sigma Z2)^2)forZ1, Z2 ~ N(0, 1).- Parameters:
dist (RicianDistribution)
seed (int | None)
- class SkewNormalAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted central moments for skew-normal estimation.
The sufficient statistic is stored as
(count, mean, M2, M3)whereM2 = sum_i w_i (x_i - mean)^2andM3 = sum_i w_i (x_i - mean)^3are the weighted central moments. This is mathematically equivalent to the raw power sums(sum x, sum x^2, sum x^3)but avoids the catastrophicE[x^2] - E[x]^2cancellation whenabs(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.- update(x, weight, estimate)[source]
Accumulate a single weighted observation into central moments.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- 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]^2cancellation, but a SINGLE centering pass does not remove all of it: the computedmeancarries 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 incentered_batch_moments()computes the residue at spread scale, where it is exact, and makes the fit shift-equivariant.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another central-moment statistic tuple.
- value()[source]
Return count, mean, second central moment sum, and third central moment sum.
- from_value(x)[source]
Replace accumulator contents from a central-moment statistic tuple.
- 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:
StatisticAccumulatorFactoryFactory for SkewNormalAccumulator.
- make()[source]
Create a fresh skew-normal accumulator.
- Return type:
SkewNormalAccumulator
- class SkewNormalDataEncoder[source]
Bases:
DataSequenceEncoderEncode skew-normal observations as a float array.
- class SkewNormalDistribution(loc, scale, shape, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionSkew-normal distribution with location
loc, scale> 0and shapealpha.- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- 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.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact).
- mean()[source]
Mean E[X] = loc + scale * delta * sqrt(2/pi), delta = shape / sqrt(1 + shape^2).
- Return type:
- variance()[source]
Variance Var[X] = scale^2 (1 - 2 delta^2 / pi), delta = shape / sqrt(1 + shape^2).
- Return type:
- entropy()[source]
Differential entropy log(scale) + 0.5 log(2 pi e) - log(2) - E[log Phi(alpha Y)].
Yis the standard skew-normal(alpha);E[Y^2] = 1for every alpha (a property of the two-Gaussian stochastic representation) collapses the Gaussian part of the log-density to a closed form, leavingE[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:
- 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,scaleandshape.- 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:
ParameterEstimatorMethod-of-moments estimator for skew-normal location, scale and shape.
The fit is SHIFT-EQUIVARIANT: estimating on
x + creturnsloc + cwithscaleandshapeunchanged, for any constantcthe data can carry – epoch seconds (~1.7e9), 2**31 and 1e12 included. The moments come fromSkewNormalAccumulator, 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
- class SkewNormalSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw observations as
xi + omega (delta * abs(Z0) + sqrt(1-delta^2) Z1)withZ0, Z1standard normal.- Parameters:
dist (SkewNormalDistribution)
seed (int | None)
- class StudentTAccumulator(name=None, keys=None)[source]
Bases:
AnchoredMomentTrack,SequenceEncodableStatisticAccumulatorAccumulate 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 ofAnchoredMomentTrack: the naiveE[x^2]-E[x]^2form 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 ontomin_scale– 1.6e8x too small, -86.6 nats per observation, reported withconverged=Trueand an emptynumerical_repairs(). Well-conditioned data never activates the track and accumulates bit-identically to the historical single-pass path.- update(x, weight, estimate)[source]
Accumulate weighted first and second moments for one observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted first and second moments from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another Student-t sufficient-statistic tuple.
- 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
StudentTSuffStatadditionally carrying the anchored moments in its.anchoredattribute, socombine()can fold them in andStudentTEstimator.estimate()can compute a shift-invariant scale.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- 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:
StatisticAccumulatorFactoryFactory for StudentTAccumulator.
- make()[source]
Create a fresh Student-t accumulator.
- Return type:
StudentTAccumulator
- class StudentTDataEncoder[source]
Bases:
DataSequenceEncoderEncode Student’s t observations as a float array.
- class StudentTDistribution(df, loc=0.0, scale=1.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionStudent’s t distribution with degrees of freedom df, location loc, and scale > 0.
- 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.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, df, loc, scale, engine)[source]
Engine-neutral Student-t log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Student-t parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Student-t log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- 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:
- 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:
ParameterEstimatorMoment-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_mapcan 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 onx + creturnsloc + cwithscaleunchanged, for any constantcthe 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, andestimatewarns rather than returning a scale it cannot stand behind.min_scale(default 1e-8) is an absolute floor on the returnedscale; 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
- class StudentTSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid Student’s t observations.
- Parameters:
dist (StudentTDistribution)
seed (int | None)
- class TweedieAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate the weighted count, sum, and sum-of-squares for the moment fit.
- update(x, weight, estimate)[source]
Accumulate weighted count, sum, and second moment for one observation.
- initialize(x, weight, rng)[source]
Initialize the sufficient statistics with one weighted observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted count, sum, and second moment from encoded observations.
- seq_initialize(x, weights, rng)[source]
Initialize the sufficient statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge serialized moment statistics into this accumulator.
- value()[source]
Return the total weight, weighted sum, and weighted second moment.
- from_value(x)[source]
Restore the accumulator from serialized moment statistics.
- 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:
StatisticAccumulatorFactoryFactory for TweedieAccumulator.
- make()[source]
Create an empty Tweedie accumulator.
- Return type:
TweedieAccumulator
- class TweedieDataEncoder[source]
Bases:
DataSequenceEncoderEncode sequences of iid Tweedie observations (non-negative float data type).
- 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:
SequenceEncodableProbabilityDistributionTweedie (compound Poisson-Gamma) distribution on
[0, inf)with fixed powerp in (1, 2).- Parameters:
- density(x)[source]
Probability density (or the point mass at 0) at
x(seelog_density).
- log_density(x)[source]
Tweedie log-density:
log P(Y=0) = -lamat 0, the series forx > 0,-infforx < 0.
- seq_log_density(x)[source]
Vectorized Tweedie log-density at sequence-encoded non-negative observations
x.
- 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).
- 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:
ParameterEstimatorEstimate
(mu, phi)at fixed powerpby the (exact) method of moments.- Parameters:
- accumulator_factory()[source]
Return a factory for Tweedie moment accumulators.
- Return type:
TweedieAccumulatorFactory
- class TweedieSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid Tweedie observations exactly as a compound Poisson-Gamma sum.
- Parameters:
dist (TweedieDistribution)
seed (int | None)
- exception TweedieSeriesResourceError(*, required_terms, rows, max_terms, max_work)[source]
Bases:
RuntimeErrorA Tweedie density series exceeded its declared term or work budget.
- class UniformAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted min/max support statistics.
- update(x, weight, estimate)[source]
Accumulate support bounds and count from one weighted observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate support bounds and count from encoded observations.
- 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.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another uniform sufficient-statistic tuple.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- 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:
StatisticAccumulatorFactoryFactory for UniformAccumulator.
- make()[source]
Create a fresh uniform accumulator.
- Return type:
UniformAccumulator
- class UniformDataEncoder[source]
Bases:
DataSequenceEncoderEncode uniform observations as a float array.
- class UniformDistribution(low, high, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionContinuous uniform distribution on [low, high].
- 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.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, low, high, engine)[source]
Engine-neutral uniform log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked uniform parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of uniform log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Uniform sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- 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:
ParameterEstimatorMLE estimator for uniform support endpoints.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for uniform support statistics.
- Return type:
UniformAccumulatorFactory
- class UniformSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid uniform observations.
- Parameters:
dist (UniformDistribution)
seed (int | None)
- class WeibullAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted first and second moments for Weibull estimation.
- update(x, weight, estimate)[source]
Accumulate weighted first and second moments for one observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted first and second moments from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another Weibull sufficient-statistic tuple.
- value()[source]
Return accumulated sum, second moment sum, and count.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
WeibullDataEncoder
- class WeibullAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for WeibullAccumulator.
- make()[source]
Create a fresh Weibull accumulator.
- Return type:
WeibullAccumulator
- class WeibullDataEncoder[source]
Bases:
DataSequenceEncoderEncode Weibull observations with x and log(x).
- class WeibullDistribution(shape, scale, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionWeibull distribution with shape > 0 and scale > 0 on x >= 0.
- 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.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(vals, log_vals, shape, scale, engine)[source]
Engine-neutral Weibull log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Weibull parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Weibull log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- entropy()[source]
Differential entropy gamma*(1 - 1/shape) + log(scale/shape) + 1.
- Return type:
- 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:
ParameterEstimatorMoment estimator for Weibull shape and scale.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Weibull moment statistics.
- Return type:
WeibullAccumulatorFactory
- class WeibullSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid Weibull observations.
- Parameters:
dist (WeibullDistribution)
seed (int | None)
- class BernoulliAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted success and observation counts.
- update(x, weight, estimate)[source]
Accumulate weighted success and count statistics for one observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted statistics from encoded observations.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another Bernoulli sufficient-statistic tuple.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
BernoulliDataEncoder
- class BernoulliAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for BernoulliAccumulator.
- make()[source]
Create a fresh Bernoulli accumulator.
- Return type:
BernoulliAccumulator
- class BernoulliDataEncoder[source]
Bases:
DataSequenceEncoderEncode Bernoulli observations as a boolean numpy array.
- class BernoulliDistribution(p, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBernoulli distribution over {False, True} with success probability p.
- Parameters:
- classmethod compute_capabilities()[source]
Describe backend support for generated Bernoulli kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Bernoulli distributions.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Bernoulli sufficient statistics for generated scoring.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Bernoulli sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Bernoulli natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Bernoulli log partition for generated scoring.
- set_prior(prior)[source]
Attach a Beta parameter prior and precompute conjugate-prior expectations.
With a Beta(a, b) prior on the success probability
pthis caches the digamma terms so thatexpected_log_densityevaluates the variational Bayes expectationE_q[log p(x | p)]viaE[log p] = digamma(a) - digamma(a+b)andE[log(1-p)] = digamma(b) - digamma(a+b). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation
E_q[log p(x | p)]under the Beta prior.Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, p, engine)[source]
Engine-neutral Bernoulli log-mass from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Bernoulli parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Bernoulli log masses.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Bernoulli sufficient statistics using engine-resident arrays.
- to_fisher(**kwargs)[source]
Return the Bernoulli’s count-family Fisher view.
- cdf(x)[source]
Cumulative distribution function P(X <= x) over {0, 1}.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
BernoulliSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
BernoulliEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
BernoulliDataEncoder
- enumerator()[source]
Return an enumerator over the distribution support when available.
- Return type:
BernoulliEnumerator
- class BernoulliEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate False/True in descending probability order.
- Parameters:
dist (BernoulliDistribution)
- class BernoulliEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate a Bernoulli distribution from weighted success counts.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Bernoulli sufficient statistics.
- Return type:
BernoulliAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s success probability under the Beta prior (ELBO global term).
- Parameters:
model (BernoulliDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate the Bernoulli success probability from weighted counts.
The distribution is defined on the open interval (0, 1), so a sample that is all successes or all failures – whose maximum-likelihood
pis exactly 1 or 0 – is clamped_P_BOUNDARY(1e-12) away from the endpoint. When that clamp binds it is reported on the returned model throughnumerical_repairs()asbernoulli-p-clamped(...), and so throughfit_provenance().repairs; an ordinary fit whosepis already interior records nothing.
- class BernoulliSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid Bernoulli observations.
- Parameters:
dist (BernoulliDistribution)
seed (int | None)
- class BetaBinomialAccumulator(n, name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted first and second moments for beta-binomial estimation.
- update(x, weight, estimate)[source]
Accumulate weighted first and second moments for one count.
- initialize(x, weight, rng)[source]
Initialize statistics from one count.
- Parameters:
x (int)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted moments from encoded counts.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded counts.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another beta-binomial sufficient-statistic tuple.
- value()[source]
Return accumulated sum, second moment sum, and count.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
BetaBinomialDataEncoder
- class BetaBinomialAccumulatorFactory(n, name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for BetaBinomialAccumulator.
- make()[source]
Create a fresh beta-binomial accumulator.
- Return type:
BetaBinomialAccumulator
- class BetaBinomialDataEncoder(n)[source]
Bases:
DataSequenceEncoderEncode beta-binomial counts as a float array.
- Parameters:
n (int)
- class BetaBinomialDistribution(n, a, b, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBeta-binomial distribution over
{0, ..., n}with shape parametersa, b > 0.- density(x)[source]
Return the probability mass at a single count
x.
- log_density(x)[source]
Return the log probability mass at
x(-infoutside{0, ..., n}or non-integer – a fractional count is not a valid beta-binomial outcome).
- seq_log_density(x)[source]
Return vectorized log-mass for an array of counts (
-infoutside{0, ..., n}or non-integer – a fractional count is not a valid beta-binomial outcome).
- cdf(x)[source]
Cumulative distribution function P(X <= x): a log-space partial sum of the pmf over {0..n}.
- quantile(q)[source]
Inverse CDF F^{-1}(q) over {0..n}: the smallest count whose cdf reaches
q(search on the cdf).
- enumerator()[source]
Returns BetaBinomialEnumerator iterating the support in descending probability order.
- Return type:
BetaBinomialEnumerator
- sampler(seed=None)[source]
Return a sampler for drawing counts from this distribution.
- Parameters:
seed (int | None)
- Return type:
BetaBinomialSampler
- estimator(pseudo_count=None)[source]
Return a method-of-moments estimator for
a, bat the fixed number of trialsn.- Parameters:
pseudo_count (float | None)
- Return type:
BetaBinomialEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
BetaBinomialDataEncoder
- class BetaBinomialEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate the bounded beta-binomial support {0, …, n} in descending probability order.
Unlike the binomial, the beta-binomial pmf is not always unimodal (it is U-shaped for
a < 1, b < 1), so a two-pointer walk from a mode is not safe here; the finite support is materialized and sorted instead (the CategoricalEnumerator pattern), with value-order tie-breaks.- Parameters:
dist (BetaBinomialDistribution)
- class BetaBinomialEstimator(n, pseudo_count=None, suff_stat=None, min_conc=1.0e-6, max_conc=1.0e8, name=None, keys=None)[source]
Bases:
ParameterEstimatorMethod-of-moments estimator for the beta-binomial shape parameters.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for beta-binomial moments.
- Return type:
BetaBinomialAccumulatorFactory
- class BetaBinomialSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw counts as
p ~ Beta(a, b)thenk ~ Binomial(n, p).- Parameters:
dist (BetaBinomialDistribution)
seed (int | None)
- class BinomialAccumulator(max_val=None, min_val=None, name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted Binomial count, sum, and observed support bounds.
- update(x, weight, estimate)[source]
Accumulates Binomial sufficient statistics for weighted single observation.
Add x*weight to attribute sum, and increase the count by weight.
- initialize(x, weight, rng)[source]
Initialize BinomialAccumulator sufficient statistics for one weighted observation.
- seq_update(x, weights, estimate)[source]
Accumulates Binomial sufficient statistics for encoded sequence.
- Parameters:
x (E) – Encoded sequence of observations.
weights (np.ndarray) – Numpy array of floats for weighting each observation.
estimate (Optional[BinomialDistribution]) – Previous estimate of BinomialDistribution obtained from prior data.:
- Returns:
None
- Return type:
None
- seq_update_engine(x, weights, estimate, engine)[source]
Engine-resident accumulation of count/sum statistics (numpy or torch).
The weighted sum and count reductions run on the active engine; the scalar min/max support bounds remain host bookkeeping. Matches seq_update.
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of BinomialAccumulator sufficient statistics with weights.
Calls seq_update().
- Parameters:
x (E) – Encoded sequence of observations.
weights (np.ndarray) – Numpy array of floats for weighting each observation.
rng (Optional[RandomState]) – RandomState not needed. No randomness in initialization.
- Returns:
None
- Return type:
None
- combine(suff_stat)[source]
Combine the sufficient statistics of BinomialAccumulator with suff_stat.
- value()[source]
Returns the sufficient statistics, and member variables min_val and max_val.
- from_value(x)[source]
Set BinomialAccumulator suff stats and member variables from suff_stat tuple defined in value().
Takes tuple of (count, sum, min_val, max_val) for setting values of BinomialAccumulator.
- scale(c)[source]
Scale linear count/sum statistics while preserving support bounds.
- Parameters:
c (float)
- Return type:
BinomialAccumulator
- acc_to_encoder()[source]
Create the encoder for binomial observations.
Note: Used for seq_initialize.
- Returns:
BinomialDataEncoder()
- Return type:
BinomialDataEncoder
- class BinomialAccumulatorFactory(max_val=None, min_val=0, name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryCreate Binomial accumulators with configured support-bound metadata.
- make()[source]
Create a fresh binomial accumulator.
- Returns:
BinomialAccumulator.
- Return type:
BinomialAccumulator
- class BinomialDataEncoder(min_val=None, max_val=None)[source]
Bases:
DataSequenceEncoderData encoder for iid integer binomial observations.
- encoding_signature()[source]
The part of this encoder’s identity that determines the encoded column layout: none of it.
min_val/max_valare acceptance bounds –seq_encode()passes them toexact_integer_observationsasminimum/maximumand nothing else. The columns it emits carry the observed range of the data itself, not the encoder’s bounds, so twoBinomialDataEncoders differing only in bounds encode any mutually-acceptable data identically.That distinction matters to consumers that hold an already-encoded batch and need to know whether a different encoder instance describes the same layout – the compiled fused-kernel path being the one in tree. Judging that by
__eq__rejected an ordinary EM step, becauseBinomialEstimator’s M-step re-derives(n, min_val)from the data and so legitimately produces an encoder with different bounds each iteration.__eq__stays strict, since “same encoder” is a different (and still useful) question from “same encoding”.- Return type:
- row_count(x)[source]
Return the number of observations represented by the indexed payload.
- seq_encode(x)[source]
Encode List[int] for vectorized seq calls in Accumulator and Distribution.
- class BinomialDistribution(p, n, min_val=None, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBinomial distribution over
min_val + {0, ..., n}with success probabilityp.- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for generated Binomial density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Binomial distribution.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Binomial sufficient statistics from encoded observations.
The parameter-dependent support shift is handled by
exp_family_sufficient_statistics_from_paramswhen generated scoring supplies the declaration-stacked parameter bundle.
- static exp_family_sufficient_statistics_from_params(x, params, engine)[source]
Return Binomial sufficient statistics for generated scoring.
- static exp_family_natural_parameters(params, engine)[source]
Return Binomial natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Binomial log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return the observation-only Binomial base measure.
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return Binomial support/base measure for generated scoring.
- set_prior(prior)[source]
Attach a Beta parameter prior and precompute conjugate-prior expectations.
With a Beta(a, b) prior on the success probability
pthis caches(E[log p], E[log(1-p)]) = (digamma(a) - digamma(a+b), digamma(b) - digamma(a+b))so thatexpected_log_densityevaluates the variational Bayes expectationE_q[log p(x | p)]. Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation
E_q[log p(x | p)]under the Beta prior.Uses the cached digamma expectations of
log pandlog(1-p); falls back to the plug-inlog_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Returns the probability mass of integer value x.
If x is not an integer between [0,n) or [min_val, n-1-min_val), density is 0.0.
- log_density(x)[source]
Returns the log-probability mass of integer value x.
If x is not an integer between [0,n) or [min_val, n-1-min_val), log-density is -inf.
- seq_log_density(x)[source]
Vectorized evaluation of log-density for sequence encoded data.
Input value x must be obtained from a call to BinomialDataEncoder.seq_encode(data). Returns numpy array of log-density evaluated at all observations contained in encoded data x.
- static backend_log_density_from_params(vals, n, p, min_val, engine)[source]
Engine-neutral binomial log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked binomial parameters for a homogeneous mixture kernel.
A stacked binomial mixture requires components to share the same trial count and shifted support. Mixtures with heterogeneous supports fall back to the generic kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of binomial log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return stacked Binomial sufficient statistics using estimator-owned support bounds.
- to_fisher(**kwargs)[source]
Return the Binomial’s count-family Fisher view.
- cdf(x)[source]
Cumulative distribution function P(X <= x) over min_val + {0..n}.
- quantile(q)[source]
Inverse CDF F^{-1}(q) over min_val + {0..n} (via scipy binom).
- sampler(seed=None)[source]
Returns BinomialSampler for generating samples from BinomialDistribution(n,p,min_val).
- Parameters:
Optional[int] (seed) – Used to set seed on random number generator for sampling.
seed (int | None)
- Returns:
BinomialSampler for BinomialDistribution with seed.
- Return type:
BinomialSampler
- estimator(pseudo_count=None)[source]
Creates a BinomialEstimator for estimating parameters of BinomialDistribution.
- Parameters:
pseudo_count (Optional[float]) – If set, inflates counts for currently set sufficient statistic (p).
- Returns:
BinomialEstimator object.
- Return type:
BinomialEstimator
- dist_to_encoder()[source]
Create the encoder for sequence-encoded binomial observations.
- Returns:
BinomialDataEncoder object.
- Return type:
BinomialDataEncoder
- enumerator()[source]
Returns BinomialEnumerator iterating the support in descending probability order.
- Return type:
BinomialEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index by walking the binomial mode outward.
- class BinomialEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate bounded Binomial support values in descending probability order.
- Parameters:
dist (BinomialDistribution)
- class BinomialEstimator(max_val=None, min_val=0, pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate Binomial probability and support parameters from sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Create a BinomialAccumulatorFactory from estimator member variables.
- Returns:
BinomialAccumulatorFactory
- Return type:
BinomialAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s success probability under the Beta prior (ELBO global term).
- Parameters:
model (BinomialDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a binomial distribution from accumulated sufficient statistics.
nobsis accepted for estimator API consistency but is not used. The sufficient statistic is(count, sum, min_val, max_val). When a prior statistic andpseudo_countare present, they shrink the empirical success probability toward the estimator’s prior probability.
- class BinomialSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw independent samples from a
BinomialDistribution.- Parameters:
dist (BinomialDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw samples from BinomialSampler.
- class CategoricalAccumulator(keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulator for weighted categorical label counts.
- Parameters:
keys (str | None)
- update(x, weight, estimate)[source]
Adds weight to the category_count for category x.
If x is new Category label, a new key in the dict count_map is created and the count is incremented by weight.
- Parameters:
x (Any) – Category label.
weight (float) – Weight for the observation x.
estimate (Optional['CategoricalDistribution']) – Kept for consistency with update method in SequenceEncodableStatisticAccumulator.
- Returns:
None, updates sufficient_stat of Accumulator, count_map.
- Return type:
None
- initialize(x, weight, rng)[source]
Initializes the CategoricalAccumulator sufficient statistics one observation at a time.
This delegates to
update(), since initialization has no random component.- Parameters:
x (Any) – Category label.
weight (float) – Weight incrementing suff stat count_map counts for the observation x.
rng (Optional[RandomState]) – Kept for consistency with update method in SequenceEncodableStatisticAccumulator.
- Returns:
None, initializes sufficient_stat of Accumulator, count_map.
- Return type:
None
- get_seq_lambda()[source]
Return the sequence-update kernel used by generated accumulation code.
- seq_update(x, weights, estimate)[source]
Vectorized accumulation of Categorical sufficient statistics from encoded sequence of data.
Requires data as encoded sequence from CategoricalDataEncoder.seq_encode(data).
- Parameters:
x (Tuple[np.ndarray,np.ndarray]) – Tuple of numpy indices for unique categories, and numpy array unique objects that index xs maps to.
weights (np.ndarray) – weights for each observation in encoded data set.
estimate (Optional['CategoricalDistribution']) – Kept for consistency with update method in SequenceEncodableStatisticAccumulator.
- Returns:
None
- Return type:
None
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of Categorical sufficient statistics from encoded sequence of data.
Requires data as encoded sequence from CategoricalDataEncoder.seq_encode(data). This delegates to
seq_update(), since initialization has no random component.- Parameters:
x (Tuple[np.ndarray,np.ndarray]) – Tuple of numpy indices for unique categories, and numpy array unique objects that index xs maps to.
weights (np.ndarray) – weights for each observation in encoded data set.
rng (Optional[RandomState]) – Kept for consistency with update method in SequenceEncodableStatisticAccumulator.
- Returns:
None
- Return type:
None
- combine(suff_stat)[source]
Combine the sufficient statistics of CategoricalAccumulator with suff_stat.
- Parameters:
suff_stat (Dict[Any, float]) – Prior data observations aggregated into dictionary with category levels as keys and counts as values.
- Returns:
None, updates the count_map of CategoricalAccumulator.
- Return type:
CategoricalAccumulator
- value()[source]
Returns sufficient statistic of CategoricalAccumulator.
Sufficient statistic value is a dictionary with category as keys and counts of categories as values.
- from_value(x)[source]
Set CategoricalAccumulator sufficient statistics and member variables from suff_stat dict defined in value().
Takes sufficient statistic value from dictionary with category as keys and counts of categories as values. Sets count_map to the passed value x.
- Parameters:
x (Dict[Any, float]) – Dictionary with category as keys and counts of categories as values
- Returns:
CategoricalAccumulator with member variable sufficient statistics set to x.
- Return type:
CategoricalAccumulator
- acc_to_encoder()[source]
Return an encoder compatible with categorical observations.
- Return type:
CategoricalDataEncoder
- class CategoricalAccumulatorFactory(keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for categorical count accumulators.
- Parameters:
keys (str | None)
- make()[source]
Return a fresh categorical accumulator.
- Return type:
CategoricalAccumulator
- class CategoricalDataEncoder[source]
Bases:
DataSequenceEncoderSequence encoder for categorical observations used by vectorized
seq_*methods.- seq_encode(x)[source]
Encode a list of category labels for vectorized
seq_*methods.
- class CategoricalDistribution(pmap=MISSING, default_value=0.0, name=None, keys=None, prob_map=MISSING, prior=None, scoring_only=False)[source]
Bases:
SequenceEncodableProbabilityDistributionCategorical distribution over hashable labels.
- Parameters:
- classmethod compute_capabilities()[source]
Return compute-backend metadata for categorical scoring.
- classmethod compute_declaration()[source]
Return the symbolic declaration for categorical probability maps.
- static exp_family_sufficient_statistics(x, engine)[source]
Return a shape-only fallback; category-aware statistics come from
..._from_params.
- static exp_family_sufficient_statistics_from_params(x, params, engine)[source]
Return the one-hot label indicator
T(x)of shape(n, K)(zeros for off-support labels).Categories are ordered canonically by
sorted(pmap, key=repr)so the columns line up withexp_family_natural_parameters().
- static exp_family_natural_parameters(params, engine)[source]
Return the natural parameter
eta = log(pmap)over categories in canonical key order.
- static exp_family_log_partition(params, engine)[source]
Return the log partition
A = 0(normalization is carried byeta = log p).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return
log h(x) = 0on the support (a key ofpmap) and-inffor off-support labels.
- get_prior()[source]
Return the conjugate parameter prior over the category-probability simplex (or None).
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a DictDirichlet(alpha) prior over the category probabilities this caches the variational expected log-probabilities E[log p_k] = digamma(alpha_k) - digamma(sum_k alpha_k) for each key of
pmapso thatexpected_log_density(x) = E[log p_x] - log(1 + default_value). A scalar alpha is treated as a symmetric Dirichlet of dimensionlen(pmap). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x)] under the DictDirichlet prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Density evaluation of CategoricalDistribution.
p_mat(x) = p_i, if x in pmap.keys(), else p_mat(x) = default_value.
With
default_value > 0and apmapthat does not cover the full label space, this is a smoothed scoring function, not a normalized probability measure – see thedefault_valuenote on__init__().- Parameters:
x (Any) – Evaluate CategoricalDistribution density value at x.
- Returns:
float density value at x
- Return type:
- density_semantics()[source]
Report what
log_densityactually returns, derived from the parameters.This keys off
is_normalized_probability, so an object whose numbers do not describe a law does not claim to be one (MXR-080-1841). Three shapes reportLIKELIHOOD_FACTOR:scoring_only, the author’s declaration that this is an evaluation-only factor,default_value != 0open-world smoothing, which spreads mass over every unseen label and so has no finite total,a pmap that does not sum to one – including the empty pmap, whose total is zero.
An earlier revision returned
EXACTfor the last two, because_owned_generative_componentsrefusesLIKELIHOOD_FACTORand mixtures, HMMs and segment models in this repository are all built from categoricals of exactly those shapes: a component that won zero responsibility this iteration, the explicit no-evidence state fitted on all-empty sequences, and deliberately unnormalized components. Labelling them honestly made them non-composable, so the label was bent instead. That was the wrong half to bend: composition inconvenience cannot turn a non-law into an exact law.The composition layer now decides admissibility for itself, by asking a factor whether it differs from a law only by scale (see
composable_as_componentand_owned_generative_components), so both questions get a truthful answer.
- composable_as_component()[source]
Whether a latent model may use this factor as a component (MXR-080-1841).
A mixture, HMM or segment model normalizes responsibilities across components, so a component that differs from a law by a positive constant scale is absorbed into its own mixing weight and leaves the E-step unchanged; a zero-mass component simply wins no responsibility. A categorical is a lookup over a discrete support, so an unnormalized or empty pmap is exactly such a scaled law and stays admissible.
scoring_onlyis not: it is an author’s declaration that the object is not generative at all, and a declaration is not something the composition layer may reason its way around.- Return type:
- log_density(x)[source]
Log-Density evaluation of CategoricalDistribution.
log(p_mat(x)) = log(p_i), if x in pmap.keys(), else log(p_mat(x)) = log(default_value).
With
default_value > 0and apmapthat does not cover the full label space, this is a smoothed scoring function, not a normalized probability measure – see thedefault_valuenote on__init__().- Parameters:
x (Any) – Evaluate CategoricalDistribution density value at x.
- Returns:
Log-density of Categorical distribution evaluated at x.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of log-density for sequence encoded data.
Input value x must be obtained from a call to CategoricalDataEncoder.seq_encode(data). Returns numpy array of log-density evaluated at all observations contained in encoded data x.
- backend_seq_log_density(x, engine)[source]
Engine-neutral log-density for encoded object categories.
The object-to-index lookup remains Python-side at the encoding boundary; the selected log-probability vector is an engine tensor, so simplex-map parameters can still participate in autograd.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked categorical probabilities for shared finite supports.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of categorical log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return per-component legacy count maps from engine-resident posterior weights.
- to_fisher(**kwargs)[source]
Return the categorical’s one-hot Fisher view (generic fallback for default-augmented maps).
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional random seed.
- Returns:
A configured
CategoricalSampler.- Return type:
CategoricalSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s support.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to current probabilities.
- Returns:
A
CategoricalEstimator.- Return type:
CategoricalEstimator
- dist_to_encoder()[source]
Return an encoder for categorical observations.
- Return type:
CategoricalDataEncoder
- enumerator()[source]
Return an enumerator over support labels in descending probability order.
- Return type:
CategoricalEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index directly from the finite support map.
- class CategoricalEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerator over finite categorical support in descending probability order.
- Parameters:
dist (CategoricalDistribution)
- class CategoricalEstimator(pseudo_count=None, suff_stat=None, default_value=False, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimator for categorical probability maps from weighted label counts.
- Parameters:
- get_prior()[source]
Return the conjugate parameter prior over the category-probability simplex (or None).
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Set the conjugate parameter prior over the category-probability simplex.
- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- model_log_density(model)[source]
Log-density of the model probability map under the DictDirichlet prior (ELBO global term).
- Parameters:
model (CategoricalDistribution)
- Return type:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
CategoricalAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a CategoricalDistribution from suff_stat value.
If default_value is True, we estimate a default value from the suff_stat counts. Else, it is set to 0.0.
pseudo_count is used to averaged over the number of levels and added to the corresponding counts.
If suff_stat member value is None, estimate for CategoricalDistribution is formed from the suff_stat passed. Otherwise, the suff_stat member value is combined with the suff_stat values passed to estimate.
- Parameters:
- Returns:
- CategoricalDistribution estimated from passed in suff_stat value and sufficient statistic member variable
(if it is not None).
- Return type:
CategoricalDistribution
- class CategoricalFisherView(dist, keys, probs)[source]
Bases:
FixedFisherViewFisher view for categorical one-hot sufficient statistics.
- class CategoricalSampler(dist, seed=None)[source]
Bases:
DistributionSamplerSampler for categorical labels according to the configured probability map.
- Parameters:
dist (CategoricalDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw iid samples from the categorical distribution.
- Parameters:
size (int | None) – Number of iid samples to draw.
Nonereturns a scalar label. Must be an exact non-negative integer –int()would have readTrueas one draw, truncated2.7to two, and turned a negative count into an empty “successful” sample, which is the contractBackoffSampler.samplealready enforces (MXR-080-1845/1904).batched (bool) – Whether to draw the whole batch in one vectorized call (the default) or one draw at a time. Both yield iid samples from the same law and differ only in how the random stream is consumed, so a fixed seed gives different – individually valid – sequences. This argument was previously declared and then ignored entirely: passing
batched=Falsedid nothing at all and silently returned the batched result (MXR-080-1904).
- Returns:
A scalar label when
sizeisNone; otherwise a list of labels.- Return type:
- class GeometricAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted count and sum statistics for Geometric estimation.
- update(x, weight, estimate)[source]
Update sufficient statistics for GeometricAccumulator with one weighted observation.
- seq_update(x, weights, estimate)[source]
Vectorized update of sufficient statistics from encoded sequence x.
sum increased by sum of weighted observations. count increased by sum of weights.
- Parameters:
x (ndarray) – Numpy array of positive integers.
weights (ndarray) – Numpy array of positive floats.
estimate (Optional[GeometricDistribution]) – Kept for consistency with SequenceEncodableStatisticAccumulator.
- Returns:
None.
- Return type:
None
- initialize(x, weight, rng)[source]
Initialize sufficient statistics of GeometricAccumulator with weighted observation.
This delegates to
update().
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of GeometricAccumulator sufficient statistics with weighted observations.
This delegates to
seq_update().- Parameters:
x (ndarray) – Numpy array of positive integers.
weights (ndarray) – Numpy array of positive floats.
rng (Optional[RandomState]) – Kept for consistency with SequenceEncodableStatisticAccumulator.
- Returns:
None.
- Return type:
None
- combine(suff_stat)[source]
Combine aggregated sufficient statistics with sufficient statistics of GeometricAccumulator instance.
- Input suff_stat is Tuple[float, float] with:
suff_stat[0] (float): sum of observation weights, suff_stat[1] (float): weighted sum of observations.
- value()[source]
Returns sufficient statistics Tuple[float, float] of GeometricAccumulator instance.
- from_value(x)[source]
Sets GeometricAccumulator instance sufficient statistic member variables to x.
- acc_to_encoder()[source]
Return the encoder associated with this accumulator.
- Return type:
GeometricDataEncoder
- class GeometricAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryCreate Geometric accumulators with shared name and merge-key metadata.
- make()[source]
Return GeometricAccumulator with name and keys passed.
- Return type:
GeometricAccumulator
- class GeometricDataEncoder[source]
Bases:
DataSequenceEncoderData encoder for iid positive-integer geometric observations.
- seq_encode(x)[source]
Encode iid sequence of geometric observations for vectorized
seq_function calls.Note: x should be list of numpy array of positive integers.
- class GeometricDistribution(p, name=None, keys=None, prior=None)[source]
Bases:
CachedParameterLaw,SequenceEncodableProbabilityDistributionGeometric distribution on
{1, 2, ...}with success probabilityp.- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for generated Geometric density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Geometric distribution.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Geometric sufficient statistics in accumulator order.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Geometric sufficient statistic
T(x) = (x,)(support x = 1, 2, …).
- static exp_family_natural_parameters(params, engine)[source]
Return Geometric natural parameter
eta = log(1 - p).
- static exp_family_log_partition(params, engine)[source]
Return Geometric log partition
A = log(1 - p) - log(p).
- static exp_family_from_natural(eta)[source]
Return the Geometric with natural parameter
eta = log(1 - p).- Parameters:
eta (Any)
- Return type:
GeometricDistribution
- set_prior(prior)[source]
Attach a Beta parameter prior and precompute conjugate-prior expectations.
With a Beta(a, b) prior on the success probability
pthis caches the digamma terms(digamma(a), digamma(b), digamma(a+b))so thatexpected_log_densityevaluates the variational Bayes expectationE_q[log p(x | p)]viaE[log p] = digamma(a) - digamma(a+b)andE[log(1-p)] = digamma(b) - digamma(a+b). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation
E_q[log p(x | p)]under the Beta prior.Uses the cached digamma expectations of
log pandlog(1-p); falls back to the plug-inlog_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Density of geometric distribution evaluated at x.
P(x=k) = (k-1)*log(1-p) + log(p), for x = 1,2,…, else 0.0.
- log_density(x)[source]
Log-density of geometric distribution evaluated at x.
See density() for details.
- seq_log_density(x)[source]
Vectorized log-density evaluated on sequence encoded x.
- static backend_log_density_from_params(x, p, engine)[source]
Engine-neutral geometric log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked geometric parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of geometric log densities.
- to_fisher(**kwargs)[source]
Return the Geometric’s count-family Fisher view.
- cdf(x)[source]
Cumulative distribution function P(X <= x) = 1 - (1-p)^floor(x), support x >= 1.
- quantile(q)[source]
Inverse CDF F^{-1}(q), support >= 1 (via scipy geom).
- sampler(seed=None)[source]
Create a sampler from this geometric distribution.
- Parameters:
seed (Optional[int]) – Used to set seed on random number generator.
- Returns:
GeometricSampler configured from this distribution.
- Return type:
GeometricSampler
- estimator(pseudo_count=None)[source]
Create an estimator for a geometric distribution.
- Parameters:
pseudo_count (Optional[float]) – Regularize empirical summary statistics.
- Returns:
GeometricEstimator configured with this distribution’s prior and name.
- Return type:
GeometricEstimator
- dist_to_encoder()[source]
Return the encoder for geometric observations.
- Return type:
GeometricDataEncoder
- enumerator()[source]
Returns GeometricEnumerator iterating the support {1, 2, …} in descending probability order.
- Return type:
GeometricEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index directly from the geometric tail formula.
- class GeometricEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate geometric support values in descending probability order.
- Parameters:
dist (GeometricDistribution)
- class GeometricEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate Geometric success probabilities from accumulated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Create a geometric accumulator factory with this estimator’s name and keys.
- Return type:
GeometricAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s success probability under the Beta prior (ELBO global term).
- Parameters:
model (GeometricDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a geometric distribution from weighted count and sum statistics.
nobsis accepted for estimator API consistency but is not used.suff_statis(count, sum). Without a pseudo-count, the estimate isp = count / sum; with a pseudo-count, the empirical statistic is shrunk toward the estimator’s prior statistic when available.
- class GeometricSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw independent samples from a
GeometricDistribution.- Parameters:
dist (GeometricDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Generate iid samples from geometric distribution.
Generates a single geometric sample (int) if size is None, else a numpy array of integers of length size, iid samples, from the geometric distribution.
- class IntegerCategoricalAccumulator(min_val=None, max_val=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulator for weighted counts over a bounded integer support.
- update(x, weight, estimate)[source]
Update sufficient statistics with one weighted observation.
If the observed value falls outside the current support, the count vector is expanded and existing counts are realigned.
- initialize(x, weight, rng)[source]
Initialize sufficient statistics with one weighted observation.
- Parameters:
x (int) – Integer observation.
weight (float) – Observation weight.
rng (RandomState) – Accepted for accumulator API consistency.
- Returns:
None.
- Return type:
None
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of IntegerCategoricalAccumulator sufficient statistics with weighted observations.
This delegates to
seq_update().- Parameters:
x (np.ndarray[int]) – Sequence encoded iid observations of integer categorical distribution.
weights (ndarray) – Numpy array of positive floats.
rng (Optional[RandomState]) – Kept for consistency with SequenceEncodableStatisticAccumulator.
- Returns:
None.
- Return type:
None
- seq_update(x, weights, estimate)[source]
- Vectorized update of IntegerCategoricalAccumulator sufficient statistics with sequence encoded iid
observations x.
Note: Determines the range (support) of integer categorical from the sequence encoded data.
- Parameters:
x (np.ndarray[int]) – Sequence encoded iid observations of integer categorical distribution.
weights (ndarray) – Numpy array of positive floats.
estimate (Optional[IntegerCategoricalDistribution]) – Previous estimate of IntegerCategoricalDistribution.
- Returns:
None.
- Return type:
None
- seq_update_engine(x, weights, estimate, engine)[source]
Engine-resident accumulation: the weighted value histogram is reduced on the active engine (numpy or torch); the dynamic support range is host bookkeeping. Matches seq_update.
- combine(suff_stat)[source]
Merge another
(min_val, count_vec)sufficient statistic.Supports are aligned before counts are added, so accumulators built on different observed ranges can be combined safely.
- from_value(x)[source]
Replace accumulator state from a
(min_val, count_vec)statistic.
- scale(c)[source]
Scale count vector while preserving integer support metadata.
- Parameters:
c (float)
- Return type:
IntegerCategoricalAccumulator
- acc_to_encoder()[source]
Return the encoder associated with this accumulator.
- Return type:
IntegerCategoricalDataEncoder
- class IntegerCategoricalAccumulatorFactory(min_val=None, max_val=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for integer-categorical count accumulators.
- make()[source]
Return a fresh integer categorical accumulator with this factory’s bounds and keys.
- Return type:
IntegerCategoricalAccumulator
- class IntegerCategoricalDataEncoder[source]
Bases:
DataSequenceEncoderData encoder for iid integer-categorical observations.
- class IntegerCategoricalDistribution(min_val, p_vec=MISSING, name=None, keys=None, prob_vec=MISSING, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionCategorical distribution over a bounded integer range.
- Parameters:
- classmethod compute_capabilities()[source]
Return compute-backend metadata for integer-categorical scoring.
- classmethod compute_declaration()[source]
Return the symbolic declaration for bounded integer-categorical probabilities.
- static exp_family_sufficient_statistics(x, engine)[source]
Return raw values; category-aware one-hot statistics come from
..._from_params.
- static exp_family_sufficient_statistics_from_params(x, params, engine)[source]
Return the one-hot category indicator
T(x)of shape(n, K)(zeros off support).
- static exp_family_natural_parameters(params, engine)[source]
Return the natural parameter
eta = log(p_vec)(one entry per category).
- static exp_family_log_partition(params, engine)[source]
Return the log partition
A = 0(normalization is carried byeta = log p).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return
log h(x) = 0on the support[min_val, min_val+K)and-infoutside it.
- get_parameters()[source]
Return the probability vector p_vec (lets it be scored by a Dirichlet conjugate prior).
- Return type:
- get_prior()[source]
Return the conjugate parameter prior over the probability vector (or None).
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a Dirichlet(alpha) (or SymmetricDirichlet(alpha)) prior over the probability vector this caches the variational expected log-probabilities E[log p_k] = digamma(alpha_k) - digamma(sum_k alpha_k) so that
expected_log_density(x) = E[log p_{x - min_val}]. Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x)] under the (symmetric) Dirichlet prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density of the integer categorical at observation x.
p_mat(x_mat=x) = p_vec[x] if x in support [min_val, max_val], else 0.0.
- log_density(x)[source]
Evaluate the log-density of the integer categorical at observation x.
log_p(x_mat=x) = log_p_vec[x] if x in support [min_val, max_val], else -np.inf.
- seq_log_density(x)[source]
Vectorized evaluation of IntegerCategorical log_density() for sequence encoded iid observations x.
- static backend_log_density_from_params(x, min_val, log_p_vec, engine)[source]
Engine-neutral integer-categorical log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer-categorical parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer-categorical log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy
(min_val, count_vec)statistics.
- to_fisher(**kwargs)[source]
Return the integer-categorical one-hot Fisher view.
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional random seed.
- Return type:
IntegerCategoricalSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution.
When
pseudo_countis provided, the distribution’s probabilities are used as prior sufficient statistics during estimation.- Parameters:
pseudo_count (float | None) – Weight assigned to the distribution’s current probability vector during estimation.
- Return type:
IntegerCategoricalEstimator
- dist_to_encoder()[source]
Return the encoder for iid integer categorical observations.
- Return type:
IntegerCategoricalDataEncoder
- enumerator()[source]
Return IntegerCategoricalEnumerator iterating the support in descending probability order.
- Return type:
IntegerCategoricalEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index directly from the finite integer support.
- class IntegerCategoricalEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerator over bounded integer support in descending probability order.
- Parameters:
dist (IntegerCategoricalDistribution)
- class IntegerCategoricalEstimator(min_val=None, max_val=None, pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimator for bounded integer-categorical probability vectors.
- Parameters:
- get_prior()[source]
Return the conjugate parameter prior over the probability vector (or None).
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Set the conjugate parameter prior over the probability vector.
- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- model_log_density(model)[source]
Log-density of the model probability vector under the (symmetric) Dirichlet prior.
- Parameters:
model (IntegerCategoricalDistribution)
- Return type:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator’s support and keys.
Note: If min_val and max_val are BOTH not None, these values are passed to IntegerCategoricalAccumulatorFactory. Else, they are obtained from member variable suff_stat. One of these conditions must be satisfied.
Returns:
- Return type:
IntegerCategoricalAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an integer-categorical distribution from weighted counts.
nobsis accepted for estimator API consistency but is not used.suff_statis(min_val, count_vec). Whenpseudo_countand a prior statistic are present, the estimate combines observed counts with the weighted prior probability vector.
- class IntegerCategoricalFisherView(dist)[source]
Bases:
CategoricalFisherViewFisher view for bounded integer-categorical one-hot statistics.
- Parameters:
dist (Any)
- class IntegerCategoricalSampler(dist, seed=None)[source]
Bases:
DistributionSamplerSampler for bounded integer-categorical values.
- Parameters:
dist (IntegerCategoricalDistribution)
seed (int | None)
- class IntegerUniformSpikeAccumulator(min_val, max_val, keys=None, name=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulator for weighted integer counts over a growing range.
- min_val
Smallest integer observed (or configured) so far.
- Type:
Optional[int]
- max_val
Largest integer observed (or configured) so far.
- Type:
Optional[int]
- count_vec
Weighted counts for each integer in [min_val, max_val].
- Type:
Optional[np.ndarray]
- count
Total weighted observation count.
- Type:
- key
Key for merging sufficient statistics across accumulators.
- Type:
Optional[str]
- name
Optional accumulator name.
- Type:
Optional[str]
- update(x, weight, estimate)[source]
Add weight to the count for integer x, growing the count vector if x is out of range.
- initialize(x, weight, rng)[source]
Initialize the accumulator with observation x and weight (delegates to update).
- Parameters:
x (int)
weight (float)
rng (RandomState)
- Return type:
None
- seq_initialize(x, weights, rng)[source]
Vectorized initialization from encoded observations x (delegates to seq_update).
- seq_update(x, weights, estimate)[source]
Vectorized accumulation of weighted counts from encoded observations x.
- Parameters:
x (np.ndarray) – Sequence encoded integer observations.
weights (np.ndarray) – Weights on the observations.
estimate (Optional[IntegerUniformSpikeDistribution]) – Unused previous estimate.
- Return type:
None
- seq_update_engine(x, weights, estimate, engine)[source]
Engine-resident accumulation: the weighted value histogram is reduced on the active engine (numpy or torch); the dynamic support range is host bookkeeping. Matches seq_update.
- combine(suff_stat)[source]
Combine sufficient statistics (min_val, count_vec) with this accumulator, aligning ranges.
- Parameters:
suff_stat (Tuple[int, np.ndarray]) – Minimum value and count vector of another accumulator.
- Returns:
This IntegerUniformSpikeAccumulator.
- Return type:
IntegerUniformSpikeAccumulator
- value()[source]
Returns sufficient statistics as a tuple (min_val, count_vec).
- from_value(x)[source]
Set sufficient statistics from a (min_val, count_vec) tuple.
- Parameters:
x (Tuple[int, np.ndarray]) – Minimum value and count vector.
- Returns:
This IntegerUniformSpikeAccumulator.
- Return type:
IntegerUniformSpikeAccumulator
- scale(c)[source]
Scale linear counts while preserving the integer support offset.
- Parameters:
c (float)
- Return type:
IntegerUniformSpikeAccumulator
- acc_to_encoder()[source]
Returns an IntegerUniformSpikeDataEncoder for encoding sequences of iid integer observations.
- Return type:
IntegerUniformSpikeDataEncoder
- class IntegerUniformSpikeAccumulatorFactory(min_val=None, max_val=None, keys=None, name=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for integer-uniform-spike accumulators.
- Parameters:
- min_val
Smallest integer value in the range, if known.
- Type:
Optional[int]
- max_val
Largest integer value in the range, if known.
- Type:
Optional[int]
- keys
Key for merging sufficient statistics.
- Type:
Optional[str]
- name
Optional name assigned to created accumulators.
- Type:
Optional[str]
- make()[source]
Return a fresh integer-uniform-spike accumulator.
- Return type:
IntegerUniformSpikeAccumulator
- class IntegerUniformSpikeDataEncoder[source]
Bases:
DataSequenceEncoderData encoder for iid integer-uniform-spike observations.
- class IntegerUniformSpikeDistribution(k, num_vals, p, min_val=0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionUniform integer distribution with extra probability mass at one value.
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for integer-uniform-spike generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the integer uniform spike.
- density(x)[source]
Density of the integer uniform spike distribution at observation x.
See log_density() for details.
- log_density(x)[source]
Log-density of the integer uniform spike distribution at observation x.
Returns log(p) if x equals the spike value k, log((1-p)/(num_vals-1)) for any other integer in [min_val, max_val], and -inf outside the range.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- Parameters:
x (np.ndarray) – Numpy array of integer observations.
- Returns:
Numpy array of log-density (float) of len(x).
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral log-density for encoded integer spike observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer-uniform-spike parameters for a shared support.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer-uniform-spike log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy
(min_val, count_vec)statistics.
- sampler(seed=None)[source]
Create an IntegerUniformSpikeSampler from parameters of this distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
IntegerUniformSpikeSampler object.
- Return type:
IntegerUniformSpikeSampler
- estimator(pseudo_count=None)[source]
Create an IntegerUniformSpikeEstimator for the current integer range.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics.
- Returns:
IntegerUniformSpikeEstimator object.
- Return type:
IntegerUniformSpikeEstimator
- dist_to_encoder()[source]
Returns an IntegerUniformSpikeDataEncoder for encoding sequences of iid integer observations.
- Return type:
IntegerUniformSpikeDataEncoder
- enumerator()[source]
Returns an IntegerUniformSpikeEnumerator iterating the support in descending probability order.
- Return type:
IntegerUniformSpikeEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index directly from the finite integer support.
- class IntegerUniformSpikeEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates the support [min_val, max_val] in descending probability order.
The spike value k is yielded first when p >= (1-p)/(num_vals-1), otherwise last; the remaining values share the same probability and are yielded in ascending integer order. Zero-probability values are skipped.
- Parameters:
dist (IntegerUniformSpikeDistribution)
- class IntegerUniformSpikeEstimator(min_val=None, max_val=None, pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator for integer-uniform-spike distributions from weighted counts.
- Parameters:
- accumulator_factory()[source]
Returns an IntegerUniformSpikeAccumulatorFactory consistent with this estimator.
- Return type:
IntegerUniformSpikeAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an IntegerUniformSpikeDistribution by maximizing the spike location and weight.
The spike location k is chosen to maximize the likelihood of the accumulated counts (with optional pseudo_count regularization from the estimator configuration).
- class IntegerUniformSpikeSampler(dist, seed=None)[source]
Bases:
DistributionSamplerSampler for an integer-uniform-spike distribution.
- Parameters:
dist (IntegerUniformSpikeDistribution)
seed (int | None)
- dist
Distribution to sample from.
- Type:
IntegerUniformSpikeDistribution
- rng
Seeded RandomState for sampling.
- Type:
RandomState
- non_k
Integers of the support excluding the spike value k.
- Type:
np.ndarray
- class LogSeriesAccumulator(keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted count and sum for log-series estimation.
- Parameters:
keys (str | None)
- update(x, weight, estimate)[source]
Accumulate weighted count and total for one positive integer.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (int)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted count and total from encoded observations.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another log-series sufficient-statistic tuple.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
LogSeriesDataEncoder
- class LogSeriesAccumulatorFactory(keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for LogSeriesAccumulator.
- Parameters:
keys (str | None)
- make()[source]
Create a fresh log-series accumulator.
- Return type:
LogSeriesAccumulator
- class LogSeriesDataEncoder[source]
Bases:
DataSequenceEncoderEncode log-series observations as (k, log k) pairs.
- class LogSeriesDistribution(p, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLogarithmic (log-series) distribution on k = 1, 2, … with shape parameter p in (0, 1).
- classmethod compute_capabilities()[source]
Describe backend support for generated log-series kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for log-series distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row (count, k) sufficient statistics in accumulator order.
- static exp_family_sufficient_statistics(x, engine)[source]
Return the log-series sufficient statistic
T(k) = (k,).
- static exp_family_natural_parameters(params, engine)[source]
Return the log-series natural parameter
eta = log(p).
- static exp_family_log_partition(params, engine)[source]
Return the log-series log partition
A = log(-log(1 - p)).
- static exp_family_base_measure(x, engine)[source]
Return the log-series base measure
log h(k) = -log(k)(independent of p, fixed base).
- static exp_family_from_natural(eta)[source]
Return the log-series with natural parameter
eta = log(p)(sop = exp(eta)).- Parameters:
eta (Any)
- Return type:
LogSeriesDistribution
- static backend_log_density_from_params(k, log_k, log_p, log_norm, engine)[source]
Engine-neutral log-series log-mass from explicit parameters (linear in k and log k).
- density(x)[source]
Return the probability mass at a single observation.
- log_density(x)[source]
Return the log-mass at a single positive integer (or -inf off support).
- seq_log_density(x)[source]
Return vectorized log-mass values for sequence-encoded (k, log k) observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-mass for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of log-series log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked sufficient statistics using engine-resident arrays.
- entropy()[source]
Shannon entropy in nats, by exact summation of the standard series.
The log-series entropy
-sum_k p_k log p_khas no closed form (Fisher, Corbet & Williams, 1943). The series is summed fromk = 1up to this distribution’s own quantile at1 - 1e-16(plus a safety margin), beyond which the remaining tail mass is far below double rounding.- Return type:
- cdf(x)[source]
Cumulative distribution function
P(X <= x), supportx >= 1.Summed directly in bounded blocks (the series has no closed form); past
_SERIES_CAPterms one minus the Euler-Maclaurin tail mass stands in, exact to double rounding by then and never below the partial sum at the cap, so the result is monotone inxand within[0, 1].
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the smallestkwithP(X <= k) >= q.Summed directly in bounded blocks, never through scipy’s generic discrete
ppf. That search brackets the answer by doubling an upper bound untilcdf(bound) >= q, and the summed CDF can saturate one ULP short of aqthis close to one (numpy’s SIMDexpandloground the last bit differently per CPU: the sum reachedq = 1 - 1e-16atk = 5210on arm64 and emulated x86-64 and never did on AVX-512 hosted CI runners), so the bound doubled without limit and the vectorized CDF sums grew until the 16 GB runner was OOM-killed – throughentropy(), which calls this at exactly thatq. Here a block whose terms no longer move the running sum, or the term cap, ends the scan, and the Euler-Maclaurin tail mass answers for whatever lies beyond: the smallestkpast the scan whose tail mass is at most1 - q.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
LogSeriesSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
LogSeriesEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
LogSeriesDataEncoder
- enumerator()[source]
Return an enumerator over k = 1, 2, … in descending probability order.
- Return type:
LogSeriesEnumerator
- class LogSeriesEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate log-series support values in descending probability order.
The log-series pmf
p^k / (k * -log(1 - p))is strictly decreasing ink(each step multiplies byp * k / (k + 1) < 1), so value order 1, 2, 3, … IS descending-probability order. The iterator is infinite.- Parameters:
dist (LogSeriesDistribution)
- class LogSeriesEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the log-series shape p (inverts the mean -> p relation).
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for log-series count statistics.
- Return type:
LogSeriesAccumulatorFactory
- class LogSeriesSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid log-series observations.
- Parameters:
dist (LogSeriesDistribution)
seed (int | None)
- class NegativeBinomialAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted count and sum statistics plus the count histogram.
The dispersion
rhas no finite-dimensional sufficient statistic: its MLE needssum_i w_i digamma(x_i + r), which cannot be reduced to count/sum. We therefore accumulate the weighted histogram{x: weight}soNegativeBinomialEstimator.estimate()can solve the score equation forr.- update(x, weight, estimate)[source]
Accumulate weighted statistics for one non-negative integer count.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (int)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted statistics from encoded observations.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another negative-binomial sufficient-statistic tuple.
- value()[source]
Return count, sum, and histogram statistics.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
NegativeBinomialDataEncoder
- class NegativeBinomialAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for NegativeBinomialAccumulator.
- make()[source]
Create a fresh negative-binomial accumulator.
- Return type:
NegativeBinomialAccumulator
- class NegativeBinomialDataEncoder[source]
Bases:
DataSequenceEncoderEncode count observations with precomputed log-factorials.
- class NegativeBinomialDistribution(r, p, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionNegative binomial distribution over non-negative integer counts.
- classmethod compute_capabilities()[source]
Describe backend support for generated negative-binomial kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for negative binomial distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row negative-binomial sufficient statistics in accumulator order.
The accumulator’s
NegativeBinomialAccumulator.value()returns(count, sum, histogram); the third row stat carries the per-row counts so the declaration’skind="histogram"reducer can fold them into the weighted count histogram the dispersion (r) solve needs.
- static exp_family_sufficient_statistics(x, engine)[source]
Return the NegativeBinomial sufficient statistic
T(x) = (x,)(rfixed).
- static exp_family_natural_parameters(params, engine)[source]
Return the NegativeBinomial natural parameter
eta = log(1 - p)(rfixed).
- static exp_family_log_partition(params, engine)[source]
Return the NegativeBinomial log partition
A = -r * log(p)(rfixed).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return the NegativeBinomial base measure
log h(x) = lgamma(x+r) - lgamma(r) - log(x!).The base measure carries the binomial-coefficient term and depends on the fixed shape
r; invalid (non-integer / negative) counts are mapped to-inf.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(vals, log_fact, r, p, engine)[source]
Engine-neutral negative-binomial log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked negative-binomial parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of negative-binomial log densities.
- to_fisher(**kwargs)[source]
Return the NegativeBinomial’s count-family Fisher view.
- entropy()[source]
Shannon entropy in nats, by exact summation of the standard series.
The negative-binomial entropy
-sum_k p_k log p_khas no closed form (Johnson, Kemp & Kotz, Univariate Discrete Distributions, ch. 5). The series is summed over the support up to this distribution’s own quantile at1 - 1e-16(plus a safety margin), beyond which the tail mass is far below double rounding – the same effective-support truncation PoissonDistribution.entropy() uses, but driven by the exact CDF (viabetainc) rather than a Gaussian-tail heuristic, since the negative binomial can be heavy-tailed.- Return type:
- cdf(x)[source]
Cumulative distribution function P(X <= x) = I_p(r, floor(x)+1).
- quantile(q)[source]
Inverse CDF F^{-1}(q) (via scipy nbinom).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
NegativeBinomialSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
NegativeBinomialEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
NegativeBinomialDataEncoder
- enumerator()[source]
Return an enumerator over the distribution support when available.
- Return type:
NegativeBinomialEnumerator
- class NegativeBinomialEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate the infinite support in descending probability order.
- Parameters:
dist (NegativeBinomialDistribution)
- class NegativeBinomialEstimator(r=1.0, pseudo_count=None, suff_stat=None, estimate_r=True, threshold=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate
randpfor a negative binomial distribution.By default the dispersion
ris recovered by a 1-D solve of the digamma score equation (pprofiled out), thenpfollows in closed form. Passestimate_r=Falseto holdrfixed at the constructor value (the historical geometric/fixed-shape M-step). Therargument is the initial value / fallback whenestimate_r=True.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for negative-binomial statistics.
- Return type:
NegativeBinomialAccumulatorFactory
- resident_accumulation_supported()[source]
Dispersion estimation needs the full count histogram, not fixed-width resident stats.
- Return type:
- static estimate_dispersion(histogram, r_init, threshold)[source]
Solve the negative-binomial dispersion MLE from a weighted count histogram.
With
pprofiled to its MLEp = r / (r + xbar), the score forrisg(r) = sum_k h(k) [digamma(k + r) - digamma(r)] - N * log(1 + xbar / r),
which is strictly decreasing and crosses zero exactly when the data are over-dispersed (sample variance > mean). Under equi/under-dispersion the MLE runs off to the Poisson limit, so
ris capped at_MAX_NB_SHAPE.
- class NegativeBinomialSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid negative binomial observations.
- Parameters:
dist (NegativeBinomialDistribution)
seed (int | None)
- class PointMassAccumulator(value, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulator for a fixed point mass; no parameters are learned.
- update(x, weight, estimate)[source]
Ignore one observation because the atom is fixed.
- seq_update(x, weights, estimate)[source]
Ignore encoded observations because the atom is fixed.
- seq_update_engine(x, weights, estimate, engine)[source]
Ignore engine-resident observations because the atom is fixed.
- initialize(x, weight, rng)[source]
Ignore initialization observations because the atom is fixed.
- Parameters:
x (Any)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_initialize(x, weights, rng)[source]
Ignore encoded initialization observations because the atom is fixed.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Return this accumulator because fixed atoms have no sufficient statistics.
- Parameters:
suff_stat (Any)
- Return type:
PointMassAccumulator
- value()[source]
Return
Nonebecause fixed atoms have no sufficient statistics.- Return type:
None
- from_value(x)[source]
Return this accumulator because there is no state to restore.
- Parameters:
x (Any)
- Return type:
PointMassAccumulator
- key_merge(stats_dict)[source]
Register the key with empty statistics when configured.
- key_replace(stats_dict)[source]
Ignore keyed replacements because there is no accumulator state.
- acc_to_encoder()[source]
Return the equality-mask encoder for this atom.
- Return type:
PointMassDataEncoder
- class PointMassAccumulatorFactory(value, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for PointMassAccumulator.
- make()[source]
Create an empty point-mass accumulator.
- Return type:
PointMassAccumulator
- class PointMassDataEncoder(value)[source]
Bases:
DataSequenceEncoderEncode observations as a boolean equality mask against the fixed atom.
- Parameters:
value (Any)
- class PointMassDistribution(value, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionFixed Dirac/point-mass distribution assigning all mass to one value.
- classmethod compute_capabilities()[source]
Declare generic NumPy/Torch scoring support for fixed atoms.
- classmethod compute_declaration()[source]
Return the declaration for a fixed non-estimated atom.
- property value: Any
Return an independent copy so callers cannot mutate the model’s atom.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density from encoded equality flags.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked point-mass parameters for identical fixed atoms.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of point-mass log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return per-component empty statistics for fixed point masses.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
PointMassSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
PointMassEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
PointMassDataEncoder
- enumerator()[source]
Return an enumerator over the distribution support when available.
- Return type:
PointMassEnumerator
- class PointMassEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate the single atom of a PointMassDistribution.
- Parameters:
dist (PointMassDistribution)
- class PointMassEstimator(value, pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator that always returns the configured point mass.
- Parameters:
- accumulator_factory()[source]
Return a factory for point-mass no-op accumulators.
- Return type:
PointMassAccumulatorFactory
- class PointMassSampler(dist, seed=None)[source]
Bases:
DistributionSamplerSampler returning the fixed atom.
- Parameters:
dist (PointMassDistribution)
seed (int | None)
- class PoissonAccumulator(keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted count and sum statistics for Poisson estimation.
- Parameters:
keys (str | None)
- initialize(x, weight, rng=None)[source]
Initialize sufficient statistics with one weighted observation.
This method delegates to
update.- Parameters:
x (int) – Observation from a Poisson distribution.
weight (float) – Observation weight.
rng (RandomState | None) – Unused; accepted for the accumulator interface.
- Return type:
None
- seq_initialize(x, weights, rng=None)[source]
Vectorized initialization of PoissonAccumulator sufficient statistics with weighted observations.
This delegates to
seq_update().Arg value x (Tuple[np.ndarray[int], np.ndarray[float]]) is seq_encoded Poisson data from PoissonDataEncoder.seq_encode(), containing
x[0] (np.ndarray[int]): Non-negative integer valued Poisson iid observations, x[1] (np.ndarray[float]): np.log(Gamma(x[0]+1.0)), Gamma is the gamma function.
- update(x, weight, estimate=None)[source]
Update sufficient statistics for PoissonAccumulator with one weighted observation.
- seq_update(x, weights, estimate=None)[source]
Vectorized update of PoissonAccumulator sufficient statistics with weighted observations.
Arg value x (Tuple[np.ndarray[int], np.ndarray[float]]) is seq_encoded Poisson data from PoissonDataEncoder.seq_encode(), containing
x[0] (np.ndarray[int]): Non-negative integer valued Poisson iid observations, x[1] (np.ndarray[float]): np.log(Gamma(x[0]+1.0)), Gamma is the gamma function.
- combine(suff_stat)[source]
Merge aggregated Poisson sufficient statistics into this accumulator.
The tuple is interpreted as
(count, sum).
- from_value(x)[source]
Replace this accumulator’s sufficient statistics.
- acc_to_encoder()[source]
Return an encoder compatible with Poisson observations.
- Return type:
PoissonDataEncoder
- class PoissonAccumulatorFactory(keys=None)[source]
Bases:
StatisticAccumulatorFactoryCreate Poisson accumulators with a shared optional merge key.
- Parameters:
keys (str | None)
- make()[source]
Return a fresh Poisson accumulator.
- Return type:
PoissonAccumulator
- class PoissonDataEncoder[source]
Bases:
DataSequenceEncoderEncode iid non-negative integer Poisson observations with log-factorials.
- seq_encode(x)[source]
Encode iid sequence of Poisson observations for vectorized
seq_function calls.Data type must be int. Values must be non-negative integers. Returns the integer observations and
log(Gamma(x + 1))values used by the vectorized scorer.
- class PoissonDistribution(lam, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionPoisson distribution over non-negative integer counts with rate
lam.- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for generated Poisson density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Poisson distribution.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Poisson sufficient statistics for generated scoring.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Poisson sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Poisson natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Poisson log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return Poisson base measure for generated scoring.
- set_prior(prior)[source]
Attach a parameter prior and cache the conjugate Gamma expectations.
With a Gamma(k, theta) prior over the rate
lamthis caches (k, theta) so thatexpected_log_density(x) = (psi(k) + ln theta)*x - k*theta - gammaln(x+1)(the VB E-step term using E[ln lam] = psi(k) + ln theta and E[lam] = k*theta). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x | lam)] under the Gamma prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density of Poisson distribution at observation x.
Calls np.exp(log_density(x)). See log_density() for details.
- log_density(x)[source]
Log-density of Poisson distribution evaluated at x.
Log-density given by,
log(p_mat(x_mat=x; lam) = x*log(lam) - log(x!) - lam, for x in {0,1,2,…}
and -np.inf else.
Note: log(Gamma(x+1.0)) = log(x!), where Gamma is the gamma function.
- seq_log_density(x)[source]
Vectorized log-density evaluated on sequence encoded x.
Arg value x (Tuple[np.ndarray[int], np.ndarray[float]]) is seq_encoded Poisson data from PoissonDataEncoder.seq_encode(), containing
x[0] (np.ndarray[int]): Non-negative integer valued Poisson iid observations, x[1] (np.ndarray[float]): np.log(Gamma(x[0]+1.0)), Gamma is the gamma function.
- static backend_log_density_from_params(vals, log_fact, lam, engine)[source]
Engine-neutral Poisson log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Poisson parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Poisson log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Poisson sufficient statistics using engine-resident arrays.
- to_fisher(**kwargs)[source]
Return the Poisson’s count-family Fisher view.
- cdf(x)[source]
Cumulative distribution function P(X <= x) = Q(floor(x)+1, lam).
- entropy()[source]
Shannon entropy in nats, by exact summation of the standard series.
The Poisson entropy
-sum_k p_k log p_khas no closed form; the series is summed over the effective supportk <= lam + 40 sqrt(lam) + 40, beyond which the remaining terms are far below double rounding (the tail mass decays super-geometrically).- Return type:
- quantile(q)[source]
Inverse CDF F^{-1}(q) (via scipy poisson).
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional seed for the sampler’s random state.
- Returns:
A configured
PoissonSampler.- Return type:
PoissonSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s shape.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to the current rate.
- Returns:
A
PoissonEstimator.- Return type:
PoissonEstimator
- dist_to_encoder()[source]
Return an encoder for iid Poisson observations.
- Return type:
PoissonDataEncoder
- enumerator()[source]
Return an enumerator over nonnegative counts in descending probability order.
- Return type:
PoissonEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index by walking the Poisson mode outward.
- class PoissonEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate Poisson support values in descending probability order.
- Parameters:
dist (PoissonDistribution)
- class PoissonEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate Poisson rate parameters from accumulated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
PoissonAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s rate under the Gamma prior (ELBO global term).
- Parameters:
model (PoissonDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a Poisson distribution from aggregated sufficient statistics.
The tuple is interpreted as
(count, sum).
- class PoissonSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw independent samples from a
PoissonDistribution.- Parameters:
dist (PoissonDistribution)
seed (int | None)
- class SkellamAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate the weighted count, sum, and sum-of-squares needed for the moment fit.
- update(x, weight, estimate)[source]
Accumulate count, sum, and squared sum for one integer observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (int)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate count, sum, and squared sum from encoded observations.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another Skellam sufficient-statistic tuple.
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- scale(c)[source]
Scale all weight-linear sufficient statistics by
c.- Parameters:
c (float)
- Return type:
SkellamAccumulator
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
SkellamDataEncoder
- class SkellamAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for SkellamAccumulator.
- make()[source]
Create a fresh Skellam accumulator.
- Return type:
SkellamAccumulator
- class SkellamDataEncoder[source]
Bases:
DataSequenceEncoderEncode sequences of iid Skellam observations (integer data type, any sign).
- class SkellamDistribution(mu1, mu2, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionSkellam distribution:
K = N1 - N2for independentN1 ~ Poisson(mu1),N2 ~ Poisson(mu2).- density(x)[source]
Probability mass at integer
x(seelog_density).
- log_density(x)[source]
Stable Skellam log-mass at integer
x(-inffor non-integer input).
- seq_log_density(x)[source]
Vectorized Skellam log-mass at sequence-encoded integer counts
x.
- entropy()[source]
Shannon entropy in nats, by exact two-sided summation of the standard series.
The Skellam entropy
-sum_k p_k log p_khas no closed form. The sum runs over the support between this distribution’s own quantiles at1e-16and1 - 1e-16(plus a safety margin on each side), beyond which the remaining tail mass on both sides is far below double rounding. Terms where the scaled Bessel term underflows to exactly zero (mass indistinguishable from 0 at double precision) are dropped, matching thep log p -> 0limit.- Return type:
- classmethod compute_capabilities()[source]
Describe backend support for generated Skellam scoring kernels.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized Skellam log-mass for encoded data (see class backend note).
The series yields the UNSCALED
log I_k(notlog ive = log I_k - z), so the constant here is-(mu1 + mu2)— the legacy path’s-sqrt_diff_sqplus its implicit-z.
- cdf(x)[source]
Cumulative distribution function P(X <= x) (via scipy skellam).
- quantile(q)[source]
Inverse CDF F^{-1}(q) (via scipy skellam).
- sampler(seed=None)[source]
Return a SkellamSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
SkellamSampler
- estimator(pseudo_count=None)[source]
Return a SkellamEstimator (method of moments).
- Parameters:
pseudo_count (float | None)
- Return type:
SkellamEstimator
- dist_to_encoder()[source]
Return the encoder for Skellam observations.
- Return type:
SkellamDataEncoder
- enumerator()[source]
Return an enumerator over all integers in descending probability order.
- Return type:
SkellamEnumerator
- class SkellamEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate the two-sided Skellam support in descending probability order.
The Skellam pmf is log-concave (the difference of two independent Poisson counts, each log-concave on the integers), hence unimodal: enumeration hill-climbs from
round(mu1 - mu2)to the mode and walks outward with the standard two-pointer merge over the two tails, emitting the larger side each step. Values whose mass underflows to zero are skipped per the enumerator contract, so the iterator ends when both tails are exhausted at float precision.- Parameters:
dist (SkellamDistribution)
- class SkellamEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate
(mu1, mu2)by the (exact, closed-form) method of moments.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Skellam moment statistics.
- Return type:
SkellamAccumulatorFactory
- class SkellamSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid Skellam observations as the difference of two independent Poisson draws.
- Parameters:
dist (SkellamDistribution)
seed (int | None)
Subpackages¶
- mixle.stats.univariate.continuous package
- Submodules
- mixle.stats.univariate.continuous.beta module
- mixle.stats.univariate.continuous.exgaussian module
- mixle.stats.univariate.continuous.exponential module
- mixle.stats.univariate.continuous.gamma module
- mixle.stats.univariate.continuous.gaussian module
- mixle.stats.univariate.continuous.generalized_extreme_value module
- mixle.stats.univariate.continuous.generalized_gaussian module
- mixle.stats.univariate.continuous.generalized_pareto module
- mixle.stats.univariate.continuous.gumbel module
- mixle.stats.univariate.continuous.half_normal module
- mixle.stats.univariate.continuous.inverse_gamma module
- mixle.stats.univariate.continuous.inverse_gaussian module
- mixle.stats.univariate.continuous.laplace module
- mixle.stats.univariate.continuous.log_gaussian module
- mixle.stats.univariate.continuous.logistic module
- mixle.stats.univariate.continuous.nakagami module
- mixle.stats.univariate.continuous.pareto module
- mixle.stats.univariate.continuous.rayleigh module
- mixle.stats.univariate.continuous.rician module
- mixle.stats.univariate.continuous.skew_normal module
- mixle.stats.univariate.continuous.student_t module
- mixle.stats.univariate.continuous.tweedie module
- mixle.stats.univariate.continuous.uniform module
- mixle.stats.univariate.continuous.weibull module
- Submodules
- mixle.stats.univariate.discrete package
- Submodules
- mixle.stats.univariate.discrete.bernoulli module
- mixle.stats.univariate.discrete.beta_binomial module
- mixle.stats.univariate.discrete.binomial module
- mixle.stats.univariate.discrete.categorical module
- mixle.stats.univariate.discrete.geometric module
- mixle.stats.univariate.discrete.integer_categorical module
- mixle.stats.univariate.discrete.integer_uniform_spike module
- mixle.stats.univariate.discrete.logseries module
- mixle.stats.univariate.discrete.negative_binomial module
- mixle.stats.univariate.discrete.point_mass module
- mixle.stats.univariate.discrete.poisson module
- mixle.stats.univariate.discrete.skellam module
- Submodules