mixle.stats.univariate.continuous package¶
Continuous univariate distribution namespace.
Every class implemented under this package is re-exported here so the namespace exposes the API it
actually contains (MXR-080-1231). Before this, the package exposed only its submodule names, so
from mixle.stats.univariate.continuous import BetaAccumulator failed while from mixle.stats import BetaAccumulator
worked – the subpackage advertised modules and hid the classes inside them.
mixle.stats remains the consolidated public API and re-exports these same objects; this package
is the narrower namespace for callers who want only continuous univariate families.
- class BetaAccumulator(name=None, keys=None)[source]
Bases:
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)
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