mixle.stats.multivariate package¶
Public multivariate probability-model namespace.
The same names are available as attributes of mixle.stats. Distribution and
estimator classes form the curated star-import surface there; this focused namespace
also exposes the sampler, encoder, accumulator, receipt, and exact-enumerator types
needed by framework integrations.
- closure(x, total=1.0)[source]
Normalize strictly positive finite rows to a positive finite total.
- clr(x)[source]
Return centered logratios for strictly positive finite compositions.
- clr_inv(y)[source]
Map finite clr-coordinate rows to the unit simplex.
- ilr(x, basis=None)[source]
Map strictly positive
D-part rows toD-1ilr coordinates.
- ilr_inv(y, basis=None)[source]
Map finite
D-1ilr rows to strictly positive unit compositions.
- ilr_basis(d)[source]
Return the Helmert
(D, D-1)orthonormal contrast basis.
- class AitchisonNormalDistribution(mean, cov, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLogratio-normal density on ordinary unit-simplex coordinates.
- property mean: ndarray
Return the Gaussian mean in ilr coordinates.
- property cov: ndarray
Return the Gaussian covariance in ilr coordinates.
- density(x)[source]
Return ordinary-coordinate simplex density.
- log_density(x)[source]
Return density relative to the first
D-1simplex coordinates.
- seq_log_density(x)[source]
Score an encoded
(ilr coordinates, log Jacobian)payload.
- sampler(seed=None)[source]
Return a push-forward sampler from the ilr Gaussian.
- Parameters:
seed (int | None)
- Return type:
AitchisonNormalSampler
- estimator(pseudo_count=None)[source]
Return an estimator preserving keys and optional current-model smoothing.
- Parameters:
pseudo_count (float | None)
- Return type:
AitchisonNormalEstimator
- dist_to_encoder()[source]
Return a fixed-width composition encoder.
- Return type:
AitchisonNormalDataEncoder
- class AitchisonNormalSampler(dist, seed=None)[source]
Bases:
DistributionSamplerSample compositions by inverting Gaussian ilr draws.
- Parameters:
dist (AitchisonNormalDistribution)
seed (int | None)
- class AitchisonNormalDataEncoder(gaussian_encoder, n_parts)[source]
Bases:
DataSequenceEncoderEncode simplex rows as ilr coordinates plus their log Jacobians.
- Parameters:
gaussian_encoder (DataSequenceEncoder)
n_parts (int)
- seq_encode(x)[source]
Validate unit-simplex rows and encode coordinates with Jacobians.
- class AitchisonNormalEstimator(dim=None, pseudo_count=None, suff_stat=(None, None), name=None, keys=None)[source]
Bases:
ParameterEstimatorFit a Gaussian in ilr coordinates with explicit smoothing and keys.
- Parameters:
- accumulator_factory()[source]
Return a keyed accumulator factory delegated to the Gaussian estimator.
- Return type:
StatisticAccumulatorFactory
- class AitchisonNormalAccumulator(gaussian_acc, n_parts, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorDelegate ilr-coordinate moments while preserving wrapper key semantics.
- update(x, weight, estimate)[source]
Update delegated Gaussian statistics from one raw composition.
- initialize(x, weight, rng)[source]
Initialize delegated statistics from one raw composition.
- seq_update(x, weights, estimate)[source]
Update delegated moments from encoded ilr coordinates.
- seq_initialize(x, weights, rng)[source]
Initialize delegated moments from encoded ilr coordinates.
- combine(suff_stat)[source]
Merge delegated Gaussian sufficient statistics.
- Parameters:
suff_stat (Any)
- Return type:
AitchisonNormalAccumulator
- from_value(x)[source]
Restore delegated Gaussian sufficient statistics.
- Parameters:
x (Any)
- Return type:
AitchisonNormalAccumulator
- acc_to_encoder()[source]
Return an encoder compatible with accumulated ilr dimension.
- Return type:
AitchisonNormalDataEncoder
- class MultinomialDistribution(dist, len_dist=NullDistribution(), len_normalized=False, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultinomial distribution over count vectors.
- Parameters:
- compute_capabilities()[source]
Declare generated-compute support inherited from value and length children.
- compute_declaration()[source]
Return the generated-compute declaration for the categorical multinomial.
- to_exponential_family(engine=None)[source]
Return the multinomial exponential-family view, or
None.A multinomial over an exponential-family element is itself an exponential family with the shared element
etaand the count-weighted sufficient statisticT(x) = sum_j c_j T_0(v_j). This holds only when the trial count is not separately modeled (len_distis Null) and the density is not length-normalized (those break the single-exp-family form); it also requires the value element to be an exponential family. Otherwise returnsNone.- Parameters:
engine (Any)
- density(x)[source]
Returns the density of multinomial evaluated at observation x.
See log_density() for details.
- log_density(x)[source]
Returns the log-density of multinomial evaluated at observation x.
Let P_dist(V_k) be a distribution for a countable set of discrete observations of values V_k of type T. Denote
p_k = P_dist(V_k),
as the probability of success for value V_k. Then sum_{k=0}^{inf} p_k = 1. Let x = (x_0, x_1,….,x_{n-1}) be a multinomial observation for ‘n’ trials, where each x_i = (V_j, n_j) for some value V_j in the observation space and n_j is the associated number of success for the value. (note: sum n_j = n). Then, denoting p_j = p_mat(V_j), the normalized count-vector log mass is:
log(p_mat(x)) = log(n!) - sum_j log(n_j!) + sum_j n_j * log(p_j) + log(P_len(n)),
where P_len(n) is a distribution for the number of trials in the multinomial having support on the non-negative integers.
- seq_log_density(x)[source]
Vectorized evaluated of log-density for an encoded sequence of iid multinomial observations.
See log_density() for details on the log-density function for MultinomialDistribution.
- Arg ‘x’ is a tuple of size 7 containing:
x[0] (ndarray[int]): Observation index of sequence values. x[1] (ndarray[float]): Trial size for each observation. x[2] (ndarray[float]): Non-zero trial size indices. x[3] (T1): Sequence encoded flattened list of values from x. x[4] (Optional[T2]): Sequence encoded flatted list of trial sizes. x[5] (np.ndarray[float]): Flattened array of counts for values. x[6] (ndarray[float]): Flattened array of trial sizes.
- Parameters:
x – See above for details.
- Returns:
Numpy array of the log-density at each encoded observation of x.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded count-vector observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child routes for homogeneous multinomial mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of multinomial log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy multinomial sufficient statistics.
- to_fisher(**kwargs)[source]
Structural Fisher view for the multinomial bag.
- sampler(seed=None)[source]
Return a sampler for iid multinomial bags.
- Parameters:
seed (int | None) – Optional random seed.
- Returns:
A configured
MultinomialSampler.- Return type:
MultinomialSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from the value and length models.
- Parameters:
pseudo_count (float | None) – Optional smoothing count for child estimators.
- Returns:
A configured
MultinomialEstimator.- Return type:
MultinomialEstimator
- dist_to_encoder()[source]
Return an encoder for sparse multinomial observations.
- Return type:
MultinomialDataEncoder
- enumerator()[source]
Returns MultinomialEnumerator iterating (value, count)-pair lists in descending probability order.
- Return type:
MultinomialEnumerator
- class MultinomialSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw sparse value-count observations from a categorical multinomial.
- Parameters:
dist (MultinomialDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw samples from multinomial distribution.
Note: If len_sampler can draw n=0, an empty list is returned for that sample.
- class MultinomialEstimator(estimator, len_estimator=NullEstimator(), len_dist=None, len_normalized=False, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate a categorical multinomial from value and length sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
MultinomialAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a multinomial distribution from aggregated sufficient statistics.
- class MultinomialDataEncoder(encoder, len_encoder, len_normalized=False)[source]
Bases:
DataSequenceEncoderEncode sparse categorical multinomial observations for vectorized scoring.
- Parameters:
encoder (DataSequenceEncoder)
len_encoder (DataSequenceEncoder)
len_normalized (bool)
- seq_encode(x)[source]
Encode iid multinomial observations for vectorized
seq_*methods.- The returned tuple contains:
rv1 (ndarray[int]): Observation index of sequence values. rv2 (ndarray[float]): Trial size for each observation. rv3 (ndarray[float]): Non-zero trial size indices. rv4 (T1): Sequence encoded flattened list of values from x. rv5 (Optional[T2]): Sequence encoded flatted list of trial sizes. rv6 (np.ndarray[float]): Flattened array of counts for values. rv7 (ndarray[float]): Flattened array of trial sizes.
- Parameters:
x (Sequence[Sequence[Tuple[T, float]]]) – Sequence of iid observations of multinomial distributions.
- Returns:
See above.
- class MultinomialEncodedData(indices, inverse_totals, nonzero_totals, encoded_values, encoded_lengths, counts, totals, len_normalized)[source]
Bases:
objectValidated sparse multinomial batch representation.
- class MultinomialEnumerator(dist)[source]
Bases:
DistributionEnumeratorReserved exact enumerator for categorical multinomials.
Construction currently fails closed because arbitrary category distributions do not expose the finite, unique support manifest required to enumerate normalized count-vector probabilities.
- Parameters:
dist (MultinomialDistribution)
- class MultinomialAccumulator(accumulator, len_normalized, len_accumulator=NullAccumulator(), keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate value and trial-count statistics for categorical multinomial data.
- Parameters:
- update(x, weight, estimate)[source]
Update sufficient statistics from one weighted sparse multinomial observation.
- initialize(x, weight, rng)[source]
- Parameters:
- Return type:
None
Returns:
- seq_update(x, weights, estimate)[source]
Vectorized update of encoded sequence of iid observations from multinomial distribution.
- Arg ‘x’ is a tuple of size 7 containing:
x[0] (ndarray[int]): Observation index of sequence values. x[1] (ndarray[float]): Trial size for each observation. x[2] (ndarray[float]): Non-zero trial size indices. x[3] (T1): Sequence encoded flattened list of values from x. x[4] (Optional[T2]): Sequence encoded flatted list of trial sizes. x[5] (np.ndarray[float]): Flattened array of counts for values. x[6] (ndarray[float]): Flattened array of trial sizes.
- Parameters:
x – See above for details.
weights (np.ndarray) – Array of observation weights.
estimate (Optional[MultinomialDistribution]) – Optional previous estimate for multinomial distribution.
- Returns:
None.
- Return type:
None
- seq_update_engine(x, weights, estimate, engine)[source]
Engine-resident E-step: the per-value and per-length weights are formed on the active engine and the value/length accumulators are routed through the engine. Matches seq_update.
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of of sufficient statistics for an encoded sequence of observations.
- Arg ‘x’ is a tuple of size 7 containing:
x[0] (ndarray[int]): Observation index of sequence values. x[1] (ndarray[float]): Trial size for each observation. x[2] (ndarray[float]): Non-zero trial size indices. x[3] (T1): Sequence encoded flattened list of values from x. x[4] (Optional[T2]): Sequence encoded flatted list of trial sizes. x[5] (np.ndarray[float]): Flattened array of counts for values. x[6] (ndarray[float]): Flattened array of trial sizes.
- Parameters:
x – See above for details.
weights (np.ndarray) – Numpy array of observation weights.
rng (RandomState) – Random state for initialization.
- Returns:
None.
- Return type:
None
- combine(suff_stat)[source]
Merge aggregated multinomial sufficient statistics into this accumulator.
- Parameters:
suff_stat (tuple[SS1, SS2 | None]) – Tuple containing value-model and length-model sufficient statistics.
- Returns:
This accumulator.
- Return type:
MultinomialAccumulator
- value()[source]
Return sufficient statistics as
(value_stats, length_stats).
- from_value(x)[source]
Replace this accumulator’s sufficient statistics.
- Parameters:
x (tuple[SS1, SS2 | None]) – Tuple containing value-model and length-model sufficient statistics.
- Returns:
This accumulator.
- Return type:
MultinomialAccumulator
- scale(c)[source]
Scale value and length sufficient statistics through their accumulators.
- Parameters:
c (float)
- Return type:
MultinomialAccumulator
- key_merge(stats_dict)[source]
Merge this accumulator into
stats_dictunder configured keys.
- key_replace(stats_dict)[source]
Replace sufficient statistics from matching keys in
stats_dict.
- acc_to_encoder()[source]
Return an encoder compatible with sparse multinomial observations.
- Return type:
MultinomialDataEncoder
- class MultinomialAccumulatorFactory(est_factory, len_normalized, len_factory=NullAccumulatorFactory(), keys=None)[source]
Bases:
StatisticAccumulatorFactoryCreate categorical multinomial accumulators and child accumulators.
- Parameters:
- make()[source]
Return a fresh multinomial accumulator.
- Return type:
MultinomialAccumulator
- class MultinomialFisherView(dist)[source]
Bases:
SequenceFisherViewFisher view for bag/count observations with a count-weighted child model.
The model Fisher uses the canonical multinomial/count sufficient-statistic moments that match estimation. The multinomial coefficient is a base-measure term, not an accumulator statistic.
- Parameters:
dist (Any)
- class IntegerMultinomialDistribution(min_val=0, p_vec=None, len_dist=NullDistribution(), name=None, keys=None, prob_vec=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultinomial distribution over integer-keyed count maps.
- Parameters:
- compute_capabilities()[source]
Declare generated-compute support inherited from the trial-count distribution.
- compute_declaration()[source]
Return the generated-compute declaration for the integer multinomial.
- static exp_family_sufficient_statistics(x, engine)[source]
Return a shape-only fallback; category-aware count vectors come from
..._from_params.
- static exp_family_sufficient_statistics_from_params(x, params, engine)[source]
Return the per-category count vector
T(x)of shape(sz, K)(counts of in-support values).
- static exp_family_natural_parameters(params, engine)[source]
Return the natural parameter
eta = log(p_vec)(one entry per category).
- static exp_family_log_partition(params, engine)[source]
Return the log partition
A = 0(normalization is carried byeta = log p).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return the multinomial log coefficient in support and
-infoutside support.
- density(x)[source]
Evaluate the density of IntegerMultinomialDistribution at observed value x.
- log_density(x)[source]
Evaluate the log-density of IntegerMultinomialDistribution at observed value x.
Normalized conditional count-vector log-mass given by
log(p_mat(x)) = log(n!) - sum_k log(x_k!) + sum_k x_k*log(p_k) + log(p_mat(n)), for x having k integer categories and n the total trial count.
Note: x has k integer values and p_k denotes the probability of success for integer-category x_k. The
len_distdefaults toNullDistribution, whose log-density is zero for any input; this gives a conditional count-vector mass at each observed total, while a real length law makes it a joint mass.
- seq_log_density(x)[source]
- Vectorized evaluation of log-density for an encoded sequence of iid observations from integer multinomial
distribution.
Arg ‘x’ is a Tuple of length 5 containing:
sz (int): Total number of observed integermultinomial samples. idx (ndarray): Numpy index array for each Tuple[value, count] in flattened x. cnt (ndarray): Number of successes for each value in flattened x. val (ndarray): Integer-category value array in flattened x. tcnt (Optional[T1]): Sequence encoded number of trials for each sequence (length sz), with type T if length DataSequenceEncoder is not NullDataEncoder and returns type T. Else None.
- Parameters:
x (See above for details) – Sequence encoding of iid integer multinomial observation.
- Returns:
Numpy array of log-density evaluated at each observation in encoding.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded integer count vectors.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer-count-vector parameters for homogeneous mixture kernels.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer-multinomial log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy
(min_val, count_vec, length_stat)statistics.
- sampler(seed=None)[source]
Create a sampler for this integer multinomial distribution.
- Parameters:
seed (Optional[int]) – Set seed on random number generator used in sampling.
- Returns:
Sampler bound to this distribution.
- Return type:
IntegerMultinomialSampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this distribution.
- Parameters:
pseudo_count (Optional[float]) – Optional prior mass assigned to this distribution’s current category probabilities during estimation.
- Returns:
Estimator configured with the same support, name, and length estimator.
- Return type:
IntegerMultinomialEstimator
- dist_to_encoder()[source]
Return a data encoder using the encoder supplied by
len_dist.- Return type:
IntegerMultinomialDataEncoder
- class IntegerMultinomialSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw sparse integer-category count vectors from an integer multinomial.
- Parameters:
dist (IntegerMultinomialDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw independent samples from an integer multinomial distribution.
- class IntegerMultinomialEstimator(min_val=None, max_val=None, len_estimator=NullEstimator(), len_dist=None, name=None, pseudo_count=None, suff_stat=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate integer-category multinomial probabilities from count statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
IntegerMultinomialAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a distribution from aggregated sufficient statistics.
If
pseudo_countis not set, prior sufficient statistics are ignored during estimation.suff_statcontains:suff_stat[0] (int): Minimum integer category represented by the count vector. suff_stat[1] (np.ndarray): Weighted counts for consecutive integer categories. suff_stat[2] (Optional[SS0]): Sufficient statistics for the length estimator.
- class IntegerMultinomialDataEncoder(len_encoder=NullDataEncoder(), min_val=None, max_val=None)[source]
Bases:
DataSequenceEncoderEncode sparse integer multinomial observations for vectorized scoring.
- seq_encode(x)[source]
Encode a sequence of iid integer multinomial observations.
The returned tuple contains:
sz (int): Total number of observed integermultinomial samples. idx (ndarray): Numpy index array for each Tuple[value, count] in flattened x. cnt (ndarray): Number of successes for each value in flattened x. val (ndarray): Integer-category value array in flattened x. tcnt (Optional[E0]): Sequence encoded number of trials for each sequence (length sz), with type E0 if length DataSequenceEncoder is not NullDataEncoder and returns type E0. Else None.
- Parameters:
x (Sequence[Sequence[Tuple[int, float]]]) – A sequence of iid integer multinomial observations in the form of Sequence of Tuple(s) containing integer-category and float valued number of successes.
- Returns:
Tuple[int, ndarray[int], ndarray[float], ndarray[int], Optional[T]. See above for details.
- Return type:
- row_count(x)[source]
Return the number of observations in a payload from
seq_encode().The base implementation infers the count from the payload’s shape, which is wrong for this encoder:
idx/cnt/valare flattened over (observation, category) pairs, so the inference agreed on their common length and reported one row per pair – 5,129 rows for 2,000 observations. That made everyseq_encodeof this family fail the encoded-row conservation check.szis the observation count this encoder already computes.
- class IntegerMultinomialEnumerator(dist, *, max_outcomes_per_length=100_000)[source]
Bases:
DistributionEnumeratorEnumerate normalized integer count-vector masses with a modeled trial-count law.
- Parameters:
dist (IntegerMultinomialDistribution)
max_outcomes_per_length (int)
- class IntegerMultinomialAccumulator(min_val=None, max_val=None, name=None, keys=None, len_accumulator=NullAccumulator(), fixed_support=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate sparse integer-category counts and trial-count child statistics.
- Parameters:
- update(x, weight, estimate)[source]
Update sufficient statistics from single data observation.
- initialize(x, weight, rng)[source]
Initialize IntegerMultinomialAccumulator with single observation x.
Just calls update() method.
- seq_update(x, weights, estimate)[source]
- Vectorized update of IntegerMultinomialAccumulator sufficient statistics for encoded sequence of
independent observations x.
Encoded sequence ‘x’ is a Tuple of length 5 containing:
sz (int): Total number of observed integermultinomial samples. idx (ndarray): Numpy index array for each Tuple[value, count] in flattened x. cnt (ndarray): Number of successes for each value in flattened x. val (ndarray): Integer-category value array in flattened x. tcnt (Optional[E0]): Sequence encoded number of trials for each sequence (length sz), with type E0 if length DataSequenceEncoder is not NullDataEncoder and returns type E0.
- Parameters:
x (See above) – Encoded sequence of iid observations of integer multinomial distribution.
weights (ndarray) – Weights for observations in encoded sequence.
estimate (Optional[IntegerMultinomialDistribution]) – Optional previous estimate of integer multinomial distribution.
- Returns:
None.
- Return type:
None
- seq_update_engine(x, weights, estimate, engine)[source]
Engine-resident accumulation of integer-multinomial count statistics (numpy or torch).
The weighted category histogram is reduced on the active engine; the dynamic support range is host bookkeeping. The length child is routed through the engine via child_seq_update. Matches seq_update.
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of sufficient statistics from encoded sequence of iid observations ‘x’.
This delegates to
seq_update().Encoded sequence ‘x’ is a Tuple of length 5 containing:
sz (int): Total number of observed integermultinomial samples. idx (ndarray): Numpy index array for each Tuple[value, count] in flattened x. cnt (ndarray): Number of successes for each value in flattened x. val (ndarray): Integer-category value array in flattened x. tcnt (Optional[T1]): Sequence encoded number of trials for each sequence (length sz), with type E0 if length DataSequenceEncoder is not NullDataEncoder and returns type E0. Else None.
- Parameters:
x (See above) – Encoded sequence of iid observations of integer multinomial distribution.
weights (ndarray) – Weights for observations in encoded sequence.
rng (Optional[RandomState]) – Optional random state for consistency with SequenceEncodableStatisticAccumulator class.
- Returns:
None.
- Return type:
None
- combine(suff_stat)[source]
Combine another integer multinomial sufficient-statistics tuple into this accumulator.
- Arg ‘suff_stat’ contains:
suff_stat[0] (int): A minimum value for aggregated counts. suff_stat[1] (np.ndarray): Numpy array of aggregated counts. suff_stat[2] (Optional[SS0]): Optional sufficient statistics for the length accumulator with type SS0.
- value()[source]
Return accumulated sufficient statistics.
- The returned tuple contains:
suff_stat[0] (int): Minimum integer category represented by the count vector. suff_stat[1] (np.ndarray): Weighted counts for consecutive integer categories. suff_stat[2] (Optional[SS0]): Sufficient statistics from the length accumulator.
- from_value(x)[source]
Restore accumulator state from sufficient statistics.
- The input tuple contains:
x[0] (int): Minimum integer category represented by the count vector. x[1] (np.ndarray): Weighted counts for consecutive integer categories. x[2] (Optional[SS0]): Sufficient statistics for the length accumulator.
- Parameters:
x (See above for details)
- Returns:
This accumulator after restoration.
- Return type:
IntegerMultinomialAccumulator
- key_merge(stats_dict)[source]
Merge this accumulator into
stats_dictwhen it has a matching key.- Parameters:
stats_dict (Dict[str, Any]) – Mapping from statistic keys to accumulators.
- Returns:
None.
- Return type:
None
- key_replace(stats_dict)[source]
Replace this accumulator’s statistics from
stats_dictwhen its key is present.- Parameters:
stats_dict (Dict[str, Any]) – Mapping from statistic keys to accumulators.
- Returns:
None.
- Return type:
None
- acc_to_encoder()[source]
Return a data encoder using the encoder supplied by the length accumulator.
- Return type:
IntegerMultinomialDataEncoder
- class IntegerMultinomialAccumulatorFactory(min_val=None, max_val=None, name=None, keys=None, len_factory=NullAccumulatorFactory(), fixed_support=None)[source]
Bases:
StatisticAccumulatorFactoryCreate integer multinomial accumulators with optional length accumulators.
- Parameters:
- make()[source]
Return a new integer multinomial accumulator.
- Return type:
IntegerMultinomialAccumulator
- class DirichletMultinomialDistribution(alpha, n, name=None, keys=None, *, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS, max_frontier_entries=_DEFAULT_MAX_FRONTIER_ENTRIES)[source]
Bases:
SequenceEncodableProbabilityDistributionDirichlet-multinomial over
K-category count vectors summing ton(concentrationalpha).- Parameters:
- density(x)[source]
Return the probability mass at a single count vector
x.
- log_density(x)[source]
Return the log-mass at
x(-infif any count is negative, non-integer, or the total is notn– a fractional category count is not a valid Dirichlet-multinomial outcome even when the (real-valued) total happens to sum ton).
- seq_log_density(x)[source]
Vectorized log-mass for a stack of count vectors, shape
(N, K)(-infrows where any count is negative, non-integer, or the row total is notn).
- sampler(seed=None)[source]
Return a sampler for drawing count vectors from this distribution.
- Parameters:
seed (int | None)
- Return type:
DirichletMultinomialSampler
- estimator(pseudo_count=None)[source]
Return a Minka fixed-point MLE estimator for
alphaat the fixed number of trialsn.- Parameters:
pseudo_count (float | None)
- Return type:
DirichletMultinomialEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
DirichletMultinomialDataEncoder
- class DirichletMultinomialSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw counts as
p ~ Dirichlet(alpha)thenx ~ Multinomial(n, p).- Parameters:
dist (DirichletMultinomialDistribution)
seed (int | None)
- class DirichletMultinomialEstimator(dim, n, max_iter=500, tol=1.0e-9, pseudo_count=None, name=None, keys=None, min_alpha=_DEFAULT_MIN_ALPHA, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS, max_frontier_entries=_DEFAULT_MAX_FRONTIER_ENTRIES)[source]
Bases:
ParameterEstimatorMinka fixed-point maximum-likelihood estimator for the Dirichlet-multinomial concentration.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Dirichlet-multinomial statistics.
- Return type:
DirichletMultinomialAccumulatorFactory
- class DirichletMultinomialDataEncoder(dim, n)[source]
Bases:
DataSequenceEncoderEncode a sequence of
K-category count vectors as an(N, K)array.
- class DirichletMultinomialEnumerator(dist, *, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS, max_frontier_entries=_DEFAULT_MAX_FRONTIER_ENTRIES)[source]
Bases:
DistributionEnumeratorEnumerate Dirichlet-multinomial count vectors in descending probability order, lazily (A* best-first).
The log-mass separates per category:
log P(x) = log_const + sum_k f_k(x_k)withf_k(c) = gammaln(c + alpha_k) - gammaln(alpha_k) - gammaln(c + 1), and eachf_kis monotone inc(increasing foralpha_k > 1, decreasing foralpha_k < 1), so a prefix assignment(x_1..x_j)withmtrials left admits the admissible completion boundsum_{k>j} max(f_k(0), f_k(m)). A* on the exact prefix score plus that bound streams count vectors in exact descending order without materializing theC(n+K-1, K-1)support.
- class DirichletMultinomialAccumulator(dim, n, name=None, keys=None, *, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate cumulative counts
c[k, j] = sum_i w_i 1{x_ik > j}(the Minka digamma-recurrence stat).- update(x, weight, estimate)[source]
Accumulate Minka recurrence statistics for one count vector.
- initialize(x, weight, rng)[source]
Initialize statistics from one count vector.
- Parameters:
x (ndarray)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate Minka recurrence statistics from encoded count vectors.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded count vectors.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another Dirichlet-multinomial sufficient-statistic tuple.
- value()[source]
Return cumulative recurrence counts, total weight, and logical trial count.
- from_value(x)[source]
Replace accumulator contents from recurrence statistics.
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
DirichletMultinomialDataEncoder
- class DirichletMultinomialAccumulatorFactory(dim, n, name=None, keys=None, *, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS)[source]
Bases:
StatisticAccumulatorFactoryFactory for DirichletMultinomialAccumulator.
- make()[source]
Create a fresh Dirichlet-multinomial accumulator.
- Return type:
DirichletMultinomialAccumulator
- class DirichletMultinomialFitReceipt(algorithm, converged, identifiable, iterations, objective_history, max_delta, regularized_categories, concentration_floor)[source]
Bases:
objectMachine-readable evidence about a concentration fixed-point fit.
- exception DirichletMultinomialResourceError[source]
Bases:
RuntimeErrorRaised before a configured enumeration or fitting resource budget is exceeded.
- class DiagonalGaussianDistribution(mu, covar=MISSING, name=None, keys=None, covariance=MISSING, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultivariate Gaussian distribution with independent components (diagonal covariance matrix).
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for diagonal Gaussian generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the diagonal Gaussian.
- static exp_family_sufficient_statistics(x, engine)[source]
Return vector sufficient statistics for generated diagonal-Gaussian scoring.
- static exp_family_natural_parameters(params, engine)[source]
Return vector natural parameters for generated diagonal-Gaussian scoring.
- static exp_family_log_partition(params, engine)[source]
Return the diagonal-Gaussian log partition for generated scoring.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return row-wise legacy accumulator statistics for generated resident reductions.
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a MultivariateNormalGamma(mu0, lam, a, b) prior over (mu, tau=1/covar) this caches the expected natural parameters [ea, eb, e1, e2] with e1 = E[mu*tau] and e2 = -0.5*E[tau] per component (ea, eb scalars summed over components), so that
expected_log_density(x) = x.e1 + (x*x).e2 - ea + eb. 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 prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.- Return type:
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density at observation x.
See log_density() for details.
- Parameters:
x (Union[Sequence[float], np.ndarray]) – Length-dim observation vector.
- Returns:
Density at x.
- log_density(x)[source]
Evaluate the log-density at observation x.
The log-density is given by
log(p(x)) = -0.5*sum_{i=1}^{n} (x_i-m_i)^2 / s2_i - 0.5*log(s2_i) - (n/2)*log(2*pi).
Computed in the CENTERED form the formula above states,
-0.5*sum (x-mu)^2/covar, not in the algebraically equal expanded formx^2*ca + x*cb + cc. The expanded form is three terms of sizeO(|x|^2/covar)summing to anO(1)answer, so at|x| ~ 1e9with unit variance it cancels away every significant digit: the scorer returned round-number garbage (measured: log-likelihoods of exactly 66560.0 and -135168.0 on unit-variance data at offset 1.7e9), and because EM selects the model with the best objective, anoptimize/fitrun at that offset returned the WORSE of its own iterates.x - muis exact for operands of the same magnitude, so the centered form is accurate at any offset; it is also one gemv instead of two. The full-covariance estimator’s scorer always used the centered form – this is the diagonal one catching up, and it makes the documented formula true (T1-F1). The expanded coefficients remain available asca/cb/ccfor the fused kernels.- Parameters:
x (Union[Sequence[float], np.ndarray]) – Length-dim observation vector.
- Returns:
Log-density at x.
- condition(observed)[source]
Return the conditional over the unobserved dimensions given
observed.A diagonal Gaussian has independent coordinates, so conditioning on some of them leaves the rest unchanged: the result is just
DiagonalGaussian(mu[unobserved], covar[unobserved])(the observed values do not shift the unobserved mean or variance). Provided so diagonal-covariance Gaussian mixtures supportMixtureDistribution.conditional()– there the responsibilities still update from how well each component explains the observed coordinates, even though the within-component coordinates are independent. Raises if no dimension is left unobserved.
- marginal(keep)[source]
Return the marginal over the dimensions
keep:DiagonalGaussian(mu[keep], covar[keep]).Marginalizing a diagonal Gaussian simply drops the other independent coordinates (order kept).
- density_cumulative(x)[source]
Exact probability-ordered cumulative
G(x) = P(p(Y) >= p(x))– the highest-density-region mass throughx(multivariate analogue of a CDF). For a diagonal Gaussian the squared Mahalanobis distancesum_i (x_i-mu_i)^2/var_iis chi-square(dim), soG = chi2.cdf(maha2, dim). Used bymixle.enumeration.density_rank.density_rank()to return an EXACT cumulative.
- density_quantile(q)[source]
Inverse of
density_cumulative(): a representative point at cumulative-density indexq.qis the highest-density-region mass, whose boundary is the squared-Mahalanobis levelchi2.ppf(q, dim); a representative point on that contour offsets the first coordinate bysqrt(level * var_0)(Mahalanobis distance exactly the level). Sweepingqenumerates the support in descending density.
- seq_log_density(x)[source]
Vectorized evaluation of the log-density at a sequence-encoded input x.
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim) from DiagonalGaussianDataEncoder.seq_encode().
- Returns:
Numpy array of length sz containing the log-density of each encoded observation.
- Return type:
- static backend_log_density_from_params(x, mu, covar, engine)[source]
Engine-neutral diagonal 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 diagonal-Gaussian parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of diagonal-Gaussian log densities.
- 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
DiagonalGaussianSampler.- Return type:
DiagonalGaussianSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s shape.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to mean and variance estimates.
- Returns:
A
DiagonalGaussianEstimator.- Return type:
DiagonalGaussianEstimator
- dist_to_encoder()[source]
Return an encoder for iid diagonal Gaussian observations.
- Return type:
DiagonalGaussianDataEncoder
- class DiagonalGaussianSampler(dist, seed=None)[source]
Bases:
DistributionSamplerSampler for iid diagonal Gaussian observations.
- Parameters:
dist (DiagonalGaussianDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw iid samples from the diagonal Gaussian distribution.
- class DiagonalGaussianEstimator(dim=None, pseudo_count=(None, None), suff_stat=(None, None), name=None, keys=None, prior=None, min_covar=None, ridge=None)[source]
Bases:
ParameterEstimatorEstimator for diagonal Gaussian distributions.
The fit is SHIFT-EQUIVARIANT:
fit(x + c)returns the variances ofx + cto within about1e-7relative for any constantcthe data can carry, epoch seconds (~1.7e9) included. That is not free from the declared(sum, sum2, count)statistics – their variance is the cancellation-proneE[x^2] - mu^2, which at offset 1e7 was tens of percent wrong and at 1.7e9 thousands-fold wrong or collapsed onto the floor – soDiagonalGaussianAccumulatorcarries a conditioning-gated shift-anchored moment track and this estimator reads it. Statistics that arrive already reduced and WITHOUT that track (an engine kernel’s stacked moments, a hand-built tuple) cannot be corrected here and take the historical path; when they are too ill-conditioned for it,estimatewarns rather than returning variances it cannot stand behind.The
1e-7is a measured relative bound, not a figure of speech, and the error is NOT uniform across the offset range. Once the anchored track engages, the variances are exact to a few ulps (~1e-14 relative, and unchanged from offset 1.7e9 to 1e10). The bound is set by the band just BELOW the conditioning gate, where the rawE[x^2] - mu^2form is still in use because it is accurate enough to be worth its single pass: atmean^2/variancejust under the gate’s4e6the worst case measured over seeds, sample sizes and scales is3.1e-8relative. An earlier revision of this docstring promised “a few ulps” everywhere, which overstated that band by roughly eight orders of magnitude (T1-07).VARIANCE FLOOR. The fitted variances are the exact per-coordinate maximum-likelihood ones whenever every coordinate has a positive variance of its own. The M-step floors each coordinate at
ridge * var_i(defaultridge=1e-6) – RELATIVE to that coordinate’s own variance, so the safeguard is equivariant under any per-coordinate change of units and, sitting strictly below the variance it guards, never binds on such a coordinate. It is not priced offmean(var)across coordinates: that coupled columns a diagonal covariance exists to keep independent, and inflated the smallest variance of a plain probability/dollars/count table 3.03x (T1-03).A coordinate with no positive variance of its own – a constant column, an EM component holding a single point – still has to be lifted, because a zero variance is an infinite density. It gets
ridge * mean(var over the coordinates that have one), the same manufactured jitter the full covariance estimator uses for a degenerate direction. The absolutemin_covar(default1e-8) is the last resort when nothing carries a scale at all (every coordinate non-positive, orridge=0.0), and becomes a hard per-coordinate lower bound as soon as it is passed explicitly – which is howmixle.taskregularizes its diagonal Gaussians.A floor that actually lifted a coordinate is recorded on the fitted distribution as a
variance-floored(...)entry innumerical_repairs()– and therefore infit_provenance().repairs– naming the coordinate and how far it moved. Manufactured jitter is always reported; an explicitmin_covardominating a positive variance is reported once it exceeds_FLOOR_MATERIAL_RATIOof it. An ordinary fit lifts nothing and records nothing. Because the default floor never binds on a coordinate with its own variance,ridge=0.0is not the route to the maximum-likelihood fit here – it removes the only scale the degenerate-column jitter can be priced from and hands those coordinates to the absolutemin_covarinstead.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
DiagonalGaussianAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model parameters under the MultivariateNormalGamma prior (ELBO global term).
The prior is over (mu, tau=1/covar), so the model’s covariance is inverted before scoring.
- Parameters:
model (DiagonalGaussianDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a diagonal Gaussian distribution from aggregated sufficient statistics.
- Suff_stat is a Tuple of size 3 containing:
suff_stat[0] (np.ndarray): Component-wise sum of weighted observation values. suff_stat[1] (np.ndarray): Component-wise sum of weighted squared observation values. suff_stat[2] (float): Sum of weights for each observation.
- class DiagonalGaussianDataEncoder(dim=None)[source]
Bases:
DataSequenceEncoderEncoder for iid diagonal Gaussian observations.
- Parameters:
dim (int | None)
- class DiagonalGaussianAccumulator(dim=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulator for diagonal Gaussian sufficient statistics.
Alongside the declared raw moments
(sum, sum2, count)this keeps a SHIFT-ANCHORED moment track, for the reason the univariateGaussianAccumulatorkeeps one: the variance computed from raw reduced moments is the classic cancellation-proneE[x^2] - mu^2form, which loses ~2*log2(abs(mean)/sd) bits, so unit-spread data at offset 1e7 fits variances tens of percent wrong and data at offset 1.7e9 fits variances thousands of times too large (or collapsed onto the floor – the sign of the garbage is data-dependent), on data whose variance a two-pass computation returns exactly. Epoch seconds are ~1.7e9. Anchoring at the first value seen keeps every term of the scatter O(count * spread^2), making the M-step variances shift-invariant. The track is CONDITIONING-GATED (see_needs_anchor()): a chunk the raw form handles to ~1e-9 relative error 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 a variance.- update(x, weight, estimate)[source]
Update sufficient statistics with a single weighted observation.
- initialize(x, weight, rng)[source]
Initialize the accumulator with a weighted observation. Calls update().
- seq_update(x, weights, estimate)[source]
Vectorized update of sufficient statistics with an encoded sequence of observations.
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim).
weights (np.ndarray) – Numpy array of sz observation weights.
estimate (Optional[DiagonalGaussianDistribution]) – Kept for consistency (not used).
- Returns:
None.
- Return type:
None
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of the accumulator. Calls seq_update().
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim).
weights (np.ndarray) – Numpy array of sz observation weights.
rng (RandomState) – Kept for consistency with SequenceEncodableStatisticAccumulator.
- Returns:
None.
- Return type:
None
- combine(suff_stat)[source]
Merge sufficient statistics into this accumulator.
- Parameters:
suff_stat (Tuple[np.ndarray, np.ndarray, float]) – Tuple of (weighted sum of observations, weighted sum of squared observations, sum of weights).
- Returns:
This accumulator.
- Return type:
DiagonalGaussianAccumulator
- value()[source]
Return
(sum, sum_squares, count)sufficient statistics.Once the shift-anchored moment track is live the returned value is a
DiagonalGaussianSuffStat– a drop-in 3-tuple (indexing/unpacking/iteration all behave identically) that additionally carries those moments in itsanchoredattribute, socombine()can fold them in andDiagonalGaussianEstimator.estimate()can compute shift-invariant variances. Well-conditioned data never activates the track and gets the historical plain tuple.
- from_value(x)[source]
Replace this accumulator’s sufficient statistics.
- Parameters:
x (Tuple[np.ndarray, np.ndarray, float]) – Tuple of (weighted sum of observations, weighted sum of squared observations, sum of weights).
- Returns:
This accumulator.
- Return type:
DiagonalGaussianAccumulator
- scale(c)[source]
Scale the accumulated statistics in-place by
c, anchored track included.The structural default routes through
from_value(scale_suff_stat(self.value(), c)), which rebuilds from a PLAIN tuple and would therefore drop the anchored payload – turning a scaled large-offset accumulator back into a cancellation-prone one. Scaling every weight bycscales both anchored moments bycand leaves the anchor (a data value) alone.- Parameters:
c (float)
- Return type:
DiagonalGaussianAccumulator
- acc_to_encoder()[source]
Return an encoder compatible with this accumulator’s dimension.
- Return type:
DiagonalGaussianDataEncoder
- class DiagonalGaussianAccumulatorFactory(dim=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for diagonal Gaussian accumulators.
- make()[source]
Return a fresh accumulator with the factory configuration.
- Return type:
DiagonalGaussianAccumulator
- class DiagonalGaussianFisherView(dist)[source]
Bases:
FixedFisherViewFisher view over per-dimension first and second moments for a diagonal Gaussian.
- Parameters:
dist (Any)
- class MultivariateGaussianDistribution(mu, covar=MISSING, name=None, keys=None, covariance=MISSING, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultivariate normal distribution with mean vector mu and full covariance matrix covar.
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for multivariate Gaussian generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the multivariate Gaussian.
- static exp_family_sufficient_statistics(x, engine)[source]
Return vector/matrix sufficient statistics for generated MVN scoring.
- static exp_family_natural_parameters(params, engine)[source]
Return natural parameters for generated MVN scoring.
- static exp_family_log_partition(params, engine)[source]
Return the full-covariance Gaussian log partition.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return row-wise legacy accumulator statistics for generated resident reductions.
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a NormalWishart(m0, kappa, W, nu) prior over (mu, Lambda=covar^-1) this caches the prior parameters and E[ln|Lambda|], the quantities needed by
expected_log_density. 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, Lambda)] under the NormalWishart prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.- Return type:
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density at x.
- Parameters:
x (np.ndarray) – Observation from multivariate Gaussian distribution.
- Returns:
Density at x.
- Return type:
- log_density(x)[source]
Evaluate the log-density at x.
The log-density is given by
log(p(x)) = -0.5*k*log(2*pi) - 0.5*log|covar| - 0.5*(x-mu)’ covar^{-1} (x-mu).
- Parameters:
x (np.ndarray) – Observation from multivariate Gaussian distribution.
- Returns:
Log-density at x.
- Return type:
- density_cumulative(x)[source]
Exact probability-ordered cumulative
G(x) = P(p(Y) >= p(x))– the highest-density-region mass whose boundary passes throughx(the multivariate analogue of a CDF; a coordinate-wise CDF is undefined without a total order on R^d).For a multivariate Gaussian
p(y) >= p(x)iff the squared Mahalanobis distance is no larger, and that distance is chi-square withdimdegrees of freedom, soG(x) = chi2.cdf(maha2, dim). Used bymixle.enumeration.density_rank.density_rank()to return an EXACT cumulative for the MVN.
- density_quantile(q)[source]
Inverse of
density_cumulative(): a representative point at cumulative-density indexq.The multivariate analogue of a quantile / inverse-CDF: a coordinate-wise quantile is undefined without a total order on R^d, but the density ordering gives one.
qis the highest-density region mass, so the boundary is the squared-Mahalanobis levelchi2.ppf(q, dim); we return a representative point on that contour,mu + sqrt(level) * L[:, 0]wherecovar = L L^T(so its Mahalanobis distance is exactly the level). Sweepingqenumerates the support in descending density.
- seq_log_density(x)[source]
Vectorized evaluation of the log-density at a sequence-encoded input x.
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim) from MultivariateGaussianDataEncoder.seq_encode().
- Returns:
Numpy array of length sz containing the log-density of each encoded observation.
- Return type:
- static backend_log_density_from_params(x, mu, inv_covar, log_det, engine)[source]
Engine-neutral multivariate Gaussian log-density from inverse covariance.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked full-covariance Gaussian parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of full-covariance Gaussian log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy sufficient statistics on the active engine.
The weighted second moment
sum_n w[n,k] x_n x_n^Tis accumulated per component as a gemm(x * w[:, k]).T @ xinstead of reducing a per-sample, per-component(n, k, dim, dim)outer-product tensor. That intermediate isN*K*dim*dim(~20 GB at n=2e4, k=8, dim=128 — it OOMs a GPU); the per-component gemm holds only an(n, dim)temporary and hands the reduction to BLAS/cuBLAS. The first moment is likewisew.T @ xrather than a reduced(n, k, dim)tensor.
- 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
MultivariateGaussianSampler.
- condition(observed)[source]
Return the conditional distribution over the unobserved dimensions given
observed.observedmaps dimension index to its fixed value; the result is the closed-form Gaussian conditional over the remaining dimensions (in increasing index order):mu_{u|o} = mu_u + Sigma_uo Sigma_oo^{-1} (x_o - mu_o), Sigma_{u|o} = Sigma_uu - Sigma_uo Sigma_oo^{-1} Sigma_ou.
Sampling the result is
given=-style conditional sampling (draw the unobserved coordinates consistent with the observed ones). Raises if no dimension is left unobserved.
- marginal(keep)[source]
Return the marginal Gaussian over dimensions
keep.N(mu, Sigma)marginalized to index setkeepisN(mu[keep], Sigma[keep, keep]). The order ofkeepis preserved, so the result’s dimensions follow the given order.
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s shape.
If pseudo_count is passed, the current mean and covariance are used to regularize the estimate.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to mean and covariance estimates.
- Returns:
A
MultivariateGaussianEstimator.
- dist_to_encoder()[source]
Return an encoder for iid multivariate Gaussian observations.
- Return type:
MultivariateGaussianDataEncoder
- class MultivariateGaussianSampler(dist, seed=None)[source]
Bases:
DistributionSamplerSampler for iid multivariate Gaussian observations.
- Parameters:
dist (MultivariateGaussianDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw iid samples from the multivariate Gaussian distribution.
- class MultivariateGaussianEstimator(dim=None, pseudo_count=(None, None), suff_stat=(None, None), name=None, keys=None, prior=None, min_covar=None, ridge=None, track_conditioning=False, degenerate_ratio=1.0e-6)[source]
Bases:
ParameterEstimatorEstimator for multivariate Gaussian distributions.
The fitted covariance is NOT the raw maximum-likelihood estimate unless
ridge=0.0is passed: by default the M-step regularizes each diagonal entry of the empirical covariance ascov_ii + eps_iwitheps_i = ridge * cov_ii(defaultridge=1e-6) so a singular empirical covariance – e.g. an EM component holding fewer thandpoints – remains factorizable. Eacheps_iis RELATIVE to its own coordinate’s variance, so the ridge is a negligible ~1e-6 relative perturbation whatever the units, per column: the fit is equivariant under any per-coordinate change of units, and heterogeneous-unit data is no longer penalized (the former trace-scaled ridge priced a microscale column’s jitter off the macroscale columns, inflating the smallest variances – and with them the log-likelihood and AIC – by up to ~5 orders of magnitude, T1-05). A coordinate with no positive variance of its own gets its jitter from the mean of the coordinates that have one; the absolutemin_covar(default1e-8) is the last resort for a covariance with no scale at all (all-zero diagonal, orridge=0.0) and becomes a hard per-coordinate floor as soon as it is passed explicitly.A materially binding ridge is recorded on the fitted distribution as a
covariance-ridged(...)entry innumerical_repairs()– and therefore infit_provenance().repairs. “Materially” means the jitter exceeded_RIDGE_MATERIAL_RATIOof the smallest raw variance (an explicitmin_covardominating a small variance, or manufactured jitter on a variance-free coordinate – never the default per-coordinate ridge on a full-rank fit), or the raw covariance was not positive-definite on its own and the ridge is what makes it factorable – the rank-deficient case this ridge exists for. Passridge=0.0to recover the exact MLE up to themin_covarabsolute jitter floor.The fit is SHIFT-EQUIVARIANT:
fit(x + c)returns the covariance ofx + cto within a few ulps for any constantcthe data can carry, epoch seconds (~1.7e9) included. That is not free from the declared(sum, sum2, count)statistics – their covariance is the cancellation-proneE[xx^T] - mu mu^T, which at offset 1e7 fitted a visibly wrong correlation and at 1e8 a matrix so far from positive-definite that the constructor refused it – soMultivariateGaussianAccumulatorcarries a conditioning-gated shift-anchored moment track and this estimator reads it. Statistics that arrive already reduced and WITHOUT that track (an engine kernel’s stacked moments, a hand-built tuple) cannot be corrected here and take the historical path; when they are too ill-conditioned for it,estimatewarns rather than returning a covariance it cannot stand behind.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
MultivariateGaussianAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model parameters under the NormalWishart prior (ELBO global term).
The prior is over (mu, Lambda=covar^-1), so the model’s covariance is inverted before scoring.
- Parameters:
model (MultivariateGaussianDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a multivariate normal distribution with from aggregated sufficient statistics.
- Suff_stat is a Tuple of size 3 containing:
suff_stat[0] (np.ndarray): Component-wise sum of weighted observation values. suff_stat[1] (np.ndarray): Component-wise sum of weighted squared observation values. suff_stat[2] (float): Sum of weights for each observation.
- class MultivariateGaussianDataEncoder(dim=None)[source]
Bases:
DataSequenceEncoderEncoder for iid multivariate Gaussian observations.
- Parameters:
dim (int | None)
- class MultivariateGaussianAccumulator(dim=None, keys=None, name=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulator for multivariate Gaussian sufficient statistics.
Alongside the declared raw moments
(sum, sum2, count)this keeps a SHIFT-ANCHORED moment track, for the reason the univariateGaussianAccumulatorkeeps one: the covariance computed from raw reduced moments is the classic cancellation-proneE[xx^T] - mu mu^Tform, which loses ~2*log2(abs(mean)/sd) bits, so data with unit spread at offset 1e7 fits a visibly wrong correlation and data at offset 1e8 fits a matrix so far from positive-definite that_robust_cho_factorrefuses it – on data whose covariance a two-pass computation returns exactly (epoch seconds are ~1.7e9). Anchoring at the first value seen keeps every term of the scatter O(count * spread^2), making the M-step covariance shift-invariant. The track is CONDITIONING-GATED (see_needs_anchor()): a chunk the raw form handles to ~1e-9 relative error 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 covariance.- update(x, weight, estimate)[source]
Update sufficient statistics with a single weighted observation.
- Parameters:
x (np.ndarray) – Length-dim observation vector.
weight (float) – Weight for the observation.
estimate (Optional[MultivariateGaussianDistribution]) – Kept for consistency with SequenceEncodableStatisticAccumulator (not used).
- Returns:
None.
- Return type:
None
- initialize(x, weight, rng)[source]
Initialize the accumulator with a weighted observation. Calls update().
- Parameters:
x (np.ndarray) – Length-dim observation vector.
weight (float) – Weight for the observation.
rng (Optional[RandomState]) – Kept for consistency with SequenceEncodableStatisticAccumulator.
- Returns:
None.
- Return type:
None
- seq_update(x, weights, estimate)[source]
Vectorized update of sufficient statistics with an encoded sequence of observations.
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim).
weights (np.ndarray) – Numpy array of sz observation weights.
estimate (Optional[MultivariateGaussianDistribution]) – Kept for consistency (not used).
- Returns:
None.
- Return type:
None
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of the accumulator. Calls seq_update().
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim).
weights (np.ndarray) – Numpy array of sz observation weights.
rng (Optional[RandomState]) – Kept for consistency with SequenceEncodableStatisticAccumulator.
- Returns:
None.
- Return type:
None
- combine(suff_stat)[source]
Merge sufficient statistics into this accumulator.
- Parameters:
suff_stat (Tuple[np.ndarray, np.ndarray, float]) – Tuple of (weighted sum of observations, weighted sum of outer products, sum of weights).
- Returns:
This accumulator.
- Return type:
MultivariateGaussianAccumulator
- value()[source]
Return
(sum, sum_outer, count)sufficient statistics.Once the shift-anchored moment track is live the returned value is a
MultivariateGaussianSuffStat– a drop-in 3-tuple (indexing/unpacking/iteration all behave identically) that additionally carries those moments in itsanchoredattribute, socombine()can fold them in andMultivariateGaussianEstimator.estimate()can compute a shift-invariant covariance. Well-conditioned data never activates the track and gets the historical plain tuple.
- from_value(x)[source]
Replace this accumulator’s sufficient statistics.
- Parameters:
x (Tuple[np.ndarray, np.ndarray, float]) – Tuple of (weighted sum of observations, weighted sum of outer products, sum of weights).
- Returns:
This accumulator.
- Return type:
MultivariateGaussianAccumulator
- scale(c)[source]
Scale the accumulated statistics in-place by
c, anchored track included.The structural default routes through
from_value(scale_suff_stat(self.value(), c)), which rebuilds from a PLAIN tuple and would therefore drop the anchored payload – turning a scaled large-offset accumulator back into a cancellation-prone one. Scaling every weight bycscales both anchored moments bycand leaves the anchor (a data value) alone.- Parameters:
c (float)
- Return type:
MultivariateGaussianAccumulator
- acc_to_encoder()[source]
Return an encoder compatible with this accumulator’s dimension.
- Return type:
MultivariateGaussianDataEncoder
- class MultivariateGaussianAccumulatorFactory(dim, keys=None, name=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for multivariate Gaussian accumulators.
- make()[source]
Return a fresh accumulator with the factory configuration.
- Return type:
MultivariateGaussianAccumulator
- class MultivariateGaussianFisherView(dist)[source]
Bases:
FixedFisherViewFisher view over first and upper-triangular second moments for a full Gaussian.
- Parameters:
dist (Any)
- class MultivariateStudentTDistribution(dof, loc, shape, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultivariate Student’s t distribution with degrees of freedom dof, location mu, and scale Sigma.
- Parameters:
- classmethod compute_capabilities()[source]
Describe backend support for generated multivariate Student-t kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for multivariate Student-t distributions.
- static backend_log_density_from_params(x, mu, inv_shape, log_const, dof, dim, engine)[source]
Engine-neutral multivariate Student’s t log-density from fitted parameters.
- condition(observed)[source]
Return the conditional distribution over the unobserved dimensions given
observed.The conditional of a multivariate Student-t is again a multivariate Student-t. With observed dimensions
o(Mahalanobisd_o) and unobservedu:dof' = dof + |o|, mu' = mu_u + S_uo S_oo^{-1} (x_o - mu_o), shape' = (dof + d_o)/(dof + |o|) * (S_uu - S_uo S_oo^{-1} S_ou),
i.e. the location shifts like the Gaussian conditional but the scale is inflated by how far the observed coordinates fall in the tails (
given=-style conditional sampling). Raises if no dimension is left unobserved.
- marginal(keep)[source]
Return the marginal over the dimensions
keep:MVT(dof, mu[keep], shape[keep, keep]).A multivariate Student-t marginal keeps the same degrees of freedom and simply restricts the location and shape to the kept coordinates (order preserved).
- 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 parameters for equal-dimensional multivariate Student’s t mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of multivariate Student’s t component log densities.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
MultivariateStudentTSampler
- estimator(pseudo_count=None)[source]
Return an EM estimator that keeps dof fixed at this distribution’s value.
- Parameters:
pseudo_count (float | None)
- Return type:
MultivariateStudentTEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
MultivariateStudentTDataEncoder
- class MultivariateStudentTSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid multivariate Student’s t observations as mu + Z * sqrt(nu / G).
- Parameters:
dist (MultivariateStudentTDistribution)
seed (int | None)
- class MultivariateStudentTEstimator(dof=5.0, dim=None, pseudo_count=None, min_ridge=_MIN_RIDGE, name=None, keys=None)[source]
Bases:
ParameterEstimatorFixed-dof EM estimator for the multivariate Student’s t location and scale matrix.
The scale matrix is formed from shift-anchored statistics whenever the accumulated sufficient statistics carry that payload (see
MultivariateStudentTAccumulator), which makes the fit SHIFT-EQUIVARIANT: estimating onx + creturnsloc + cwith the scale matrix unchanged, 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 matrix it cannot stand behind.Residual limit, and it is representational rather than algorithmic. One M-step is shift-equivariant to ~1e-15, but a full EM run is not exactly so: the latent reweighting
u_i = (nu + p)/(nu + delta_i)is a function ofx_i - mu, andmuis a float64 at the data’s own magnitude, so it can only be placed on that grid – 1.2e-4 apart at offset 1e12. Snapping the un-shifted fit’smuonto exactly that grid reproduces the shifted fit to 3e-14, which is what identifies the mechanism. The effect on the fitted scale matrix is bounded by roughlyulp(abs(mu)) / spreadper iteration: 4e-8 at epoch seconds, 1e-7 at 2**31, 7e-5 at 1e12. Every consumer of a fitted location faces the same granularity, so there is no more precise answer to return; subtract a constant origin before fitting if a tighter one is needed.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for fixed-dof Student-t EM statistics.
- Return type:
MultivariateStudentTAccumulatorFactory
- class MultivariateStudentTDataEncoder(dim=None)[source]
Bases:
DataSequenceEncoderEncode a sequence of length-p real vectors into an (n, p) float array.
- Parameters:
dim (int | None)
- class MultivariateStudentTAccumulator(dof, dim=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate the EM/IRLS sufficient statistics for multivariate Student’s t estimation.
The reweighting u_i = (nu + p)/(nu + delta_i) is computed from the previous
estimate; with no estimate (initialization) every u_i = 1, which seeds the fit with the Gaussian moment statistics.Alongside those raw moments the accumulator keeps a CONDITIONING-GATED shift-anchored track. The M-step forms
sum_uxx - mu sum_ux' - sum_ux mu' + sum_u mu mu', which loses ~``2*log2(abs(mean)/sd)`` bits to cancellation, so sd ~2 data at the Unix-epoch offset fitted a scale matrix collapsed to ~1e-6 (and a ValueError at 1e10) with no warning at all. Anchoring at a data value keeps every term of the scatterO(sum_u * spread^2), which makes the scale matrix shift-invariant. The track is gated: a chunk whoseabs(mean)/spreadratio the raw form handles to ~1e-9 relative error (seeneeds_vector_anchor()) accumulates exactly the historical single-pass way – bit-identical statistics, no second pass. The raw moments remain the exchange format, so the anchored track rides along as a payload onMultivariateStudentTSuffStat.- update(x, weight, estimate)[source]
Accumulate one EM reweighted vector observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one vector observation.
- Parameters:
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate EM reweighted statistics from encoded vectors.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded vectors.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another multivariate Student-t sufficient-statistic tuple.
- value()[source]
Return count, latent-weight total, weighted sum, and weighted second moment.
A plain 4-tuple for every consumer that treats it as one –
student_t_momentsincluded; once the shift-anchored track is live it is aMultivariateStudentTSuffStatthat additionally carries those moments in itsanchoredattribute, socombine()can fold them in andMultivariateStudentTEstimator.estimate()can form a shift-invariant scale matrix.
- from_value(x)[source]
Replace accumulator contents from sufficient statistics.
- 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. Scaling every weight bycscales both anchored moments bycand leaves the anchor (a data value, not a statistic) alone.- Parameters:
c (float)
- Return type:
MultivariateStudentTAccumulator
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
MultivariateStudentTDataEncoder
- class MultivariateStudentTAccumulatorFactory(dof, dim=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for MultivariateStudentTAccumulator.
- make()[source]
Create a fresh multivariate Student-t accumulator.
- Return type:
MultivariateStudentTAccumulator
- class GaussianCopulaDistribution(corr, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGaussian copula on
(0,1)^dwith dependence given by a correlation matrix.- property corr: ndarray
Return an owned copy so cached scoring state cannot be desynchronized.
- density(x)[source]
Return the copula density at a single point
uin(0,1)^d.
- log_density(x)[source]
Return the log copula density at a single point
uin(0,1)^d.
- seq_log_density(x)[source]
Vectorized log copula density for sequence-encoded observations (
z = Phi^{-1}(u)rows).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this copula.
- Parameters:
seed (int | None)
- Return type:
GaussianCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator that fits the correlation matrix by the inversion estimator.
- Parameters:
pseudo_count (float | None)
- Return type:
GaussianCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder (stores the normal-score transform
z = Phi^{-1}(u)).- Return type:
GaussianCopulaDataEncoder
- class GaussianCopulaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw
uby samplingz ~ N(0, R)and mapping through the standard-normal CDF.- Parameters:
dist (GaussianCopulaDistribution)
seed (int | None)
- class GaussianCopulaEstimator(dim, min_eig=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorInversion estimator: the correlation of the normal scores
z = Phi^{-1}(u).- accumulator_factory()[source]
Return a factory for Gaussian copula sufficient-statistic accumulators.
- Return type:
GaussianCopulaAccumulatorFactory
- class GaussianCopulaDataEncoder(dim)[source]
Bases:
DataSequenceEncoderEncode each
urow as its normal scorez = Phi^{-1}(u).- Parameters:
dim (int)
- class GaussianCopulaAccumulator(dim, name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate the weighted first and second moments of the normal scores
z.- update(x, weight, estimate)[source]
Accumulate weighted normal-score moments for one copula observation.
- initialize(x, weight, rng)[source]
Initialize the sufficient statistics with one weighted observation.
- Parameters:
x (ndarray)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted moments from encoded normal-score 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 normal-score moments into this accumulator.
- value()[source]
Return the weighted first moments, second moments, and total weight.
- from_value(x)[source]
Restore the accumulator from serialized normal-score moments.
- acc_to_encoder()[source]
Return an encoder that produces normal-score observations.
- Return type:
GaussianCopulaDataEncoder
- class GaussianCopulaAccumulatorFactory(dim, name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for GaussianCopulaAccumulator.
- make()[source]
Create an empty Gaussian copula accumulator.
- Return type:
GaussianCopulaAccumulator
- class ClaytonCopulaDistribution(dim, theta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionClayton copula on
(0,1)^dwiththeta >= 0; zero is independence.- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
ClaytonCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
ClaytonCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class ClaytonCopulaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerMarshall-Olkin frailty: draw
V ~ Gamma(1/theta, 1),E_i ~ Exp(1),u_i = (1 + E_i/V)^{-1/theta}.- Parameters:
dist (ClaytonCopulaDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw observations.
Combinator samplers (mixture/sequence/…) accept
batched. Withbatched=True(the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independentRandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path.batched=Falseforces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.
- class ClaytonCopulaEstimator(dim, name=None, keys=None)[source]
Bases:
ParameterEstimatorKendall’s-tau inversion:
theta = 2*tau / (1 - tau)(pair-averaged ford > 2).- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class FrankCopulaDistribution(dim, theta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionFrank copula on
(0,1)^2with dependence parametertheta(any sign; 0 = independence).- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
FrankCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
FrankCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class FrankCopulaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerConditional inversion: draw
u1,wuniform, solvevfrom the conditionalC(v | u1) = w.- Parameters:
dist (FrankCopulaDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw observations.
Combinator samplers (mixture/sequence/…) accept
batched. Withbatched=True(the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independentRandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path.batched=Falseforces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.
- class FrankCopulaEstimator(name=None, keys=None)[source]
Bases:
ParameterEstimator1-D maximum likelihood on
thetaover[-40, 40](golden section on the copula log-likelihood).- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class GumbelCopulaDistribution(dim, theta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGumbel copula on
(0,1)^2with upper-tail dependence parametertheta >= 1.- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
GumbelCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
GumbelCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class GumbelCopulaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerPositive-stable frailty: draw
M ~ Stable(1/theta),E_i ~ Exp(1),u_i = exp(-(E_i / M)^{1/theta}).- Parameters:
dist (GumbelCopulaDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw observations.
Combinator samplers (mixture/sequence/…) accept
batched. Withbatched=True(the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independentRandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path.batched=Falseforces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.
- class GumbelCopulaEstimator(name=None, keys=None)[source]
Bases:
ParameterEstimatorKendall’s-tau inversion:
theta = 1 / (1 - tau)(clamped totheta >= 1).- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class StudentTCopulaDistribution(corr, df, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionStudent-t copula on
(0,1)^dwith correlationcorrand degrees of freedomdf.- property corr: ndarray
Return an owned copy so cached scoring state cannot be desynchronized.
- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
StudentTCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
StudentTCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class StudentTCopulaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw
z ~ mvt(R, nu)(Gaussian scaled by a chi-square) then map through the univariatet_nuCDF.- Parameters:
dist (StudentTCopulaDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw observations.
Combinator samplers (mixture/sequence/…) accept
batched. Withbatched=True(the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independentRandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path.batched=Falseforces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.
- class StudentTCopulaEstimator(dim, min_eig=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorInversion for
R(correlation of thet-scores) + profile likelihood overnuon a grid.- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- exception VinePairFitError[source]
Bases:
RuntimeErrorRaised when no requested pair-copula family can be fitted on an edge.
- class PairCandidateEvidence(family, parameter_count, weighted_log_likelihood, aic, fit_error)[source]
Bases:
objectOne candidate’s training evidence and complexity-adjusted AIC value.
- class PairSelectionReceipt(schema_version, criterion, edge_context, selected_family, total_weight, evidence)[source]
Bases:
objectAuditable per-edge model-selection receipt.
- class CVineCopulaDistribution(dim, pairs, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA canonical-vine (C-vine) copula on
(0,1)^d:d(d-1)/2bivariate pair copulas in a tree cascade.pairsmaps(tree, position)-> a fitted pair copula,treein1..d-1andpositionin1..d-tree(tree 1 links the root variable to each other; deeper trees link conditionally). Build one by hand, or fit withCVineCopulaEstimator(which selects a family per edge).- Parameters:
- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
CVineCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
CVineCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class CVineCopulaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerInverse C-vine sampling (Aas et al. 2009, Algorithm 2): invert independent uniforms through the h-inverses.
- Parameters:
dist (CVineCopulaDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw observations.
Combinator samplers (mixture/sequence/…) accept
batched. Withbatched=True(the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independentRandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path.batched=Falseforces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.
- class CVineCopulaEstimator(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
ParameterEstimatorSequential (stepwise) MLE: fit tree by tree on conditional pseudo-observations, best family per edge.
- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class DVineCopulaDistribution(dim, pairs, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA drawable-vine (D-vine) copula on
(0,1)^d: the second canonical vine, a PATH of pair copulas.Where a C-vine has a star at each tree (one root linked to all), a D-vine has a path: tree 1 couples consecutive variables
(1,2),(2,3),...,(d-1,d); deeper trees couple(i, i+j)given the variables between them. Samed(d-1)/2pair copulas indexed(tree, position); different (path vs star) tree topology. Like the C-vine it is a drop-in dependence core forCopulaDistribution.- Parameters:
- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
DVineCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
DVineCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class DVineCopulaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerInverse D-vine sampling (Aas et al. 2009, Algorithm 5): invert independent uniforms tree by tree.
- Parameters:
dist (DVineCopulaDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw observations.
Combinator samplers (mixture/sequence/…) accept
batched. Withbatched=True(the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independentRandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path.batched=Falseforces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.
- class DVineCopulaEstimator(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
ParameterEstimatorSequential (stepwise) MLE for a D-vine: fit tree by tree on conditional pseudo-obs, best family per edge.
- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class RVineCopulaDistribution(dim, trees, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA regular-vine copula on
(0,1)^d: an arbitrary tree sequence of bivariate pair copulas.Construct with
RVineCopulaEstimator(Dißmann selection), which picks the tree structure AND a pair-copula family per edge from data.treesis the fitted structure (a list of trees, each a list of_Edge);dimthe number of variables.- Parameters:
- classmethod independence(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Construct an explicit, structurally complete independence R-vine.
- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
RVineCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
RVineCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class RVineCopulaSampler(dist, seed=None)[source]
Bases:
DistributionSamplerSample exactly by the inverse Rosenblatt transform encoded by the validated vine.
- Parameters:
dist (RVineCopulaDistribution)
seed (int | None)
- sample(size=None, *, batched=True)[source]
Draw observations.
Combinator samplers (mixture/sequence/…) accept
batched. Withbatched=True(the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independentRandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path.batched=Falseforces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.
- class RVineCopulaEstimator(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
ParameterEstimatorDißmann selection + sequential MLE: choose the tree structure and per-edge family from data.
- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
Submodules¶
- mixle.stats.multivariate.categorical_multinomial module
- mixle.stats.multivariate.clayton_copula module
- mixle.stats.multivariate.composition module
- mixle.stats.multivariate.diagonal_gaussian module
- mixle.stats.multivariate.dirichlet_multinomial module
- mixle.stats.multivariate.frank_copula module
- mixle.stats.multivariate.gaussian_copula module
- mixle.stats.multivariate.gumbel_copula module
- mixle.stats.multivariate.integer_multinomial module
- mixle.stats.multivariate.multivariate_gaussian module
- mixle.stats.multivariate.multivariate_student_t module
- mixle.stats.multivariate.rvine_copula module
- mixle.stats.multivariate.student_t_copula module
- mixle.stats.multivariate.vine_copula module