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.

Parameters:
Return type:

ndarray

clr(x)[source]

Return centered logratios for strictly positive finite compositions.

Parameters:

x (ndarray)

Return type:

ndarray

clr_inv(y)[source]

Map finite clr-coordinate rows to the unit simplex.

Parameters:

y (ndarray)

Return type:

ndarray

ilr(x, basis=None)[source]

Map strictly positive D-part rows to D-1 ilr coordinates.

Parameters:
Return type:

ndarray

ilr_inv(y, basis=None)[source]

Map finite D-1 ilr rows to strictly positive unit compositions.

Parameters:
Return type:

ndarray

ilr_basis(d)[source]

Return the Helmert (D, D-1) orthonormal contrast basis.

Parameters:

d (int)

Return type:

ndarray

class AitchisonNormalDistribution(mean, cov, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Logratio-normal density on ordinary unit-simplex coordinates.

Parameters:
  • mean (np.ndarray)

  • cov (np.ndarray)

  • name (str | None)

  • keys (str | None)

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.

Parameters:

x (ndarray)

Return type:

float

log_density(x)[source]

Return density relative to the first D-1 simplex coordinates.

Parameters:

x (ndarray)

Return type:

float

seq_log_density(x)[source]

Score an encoded (ilr coordinates, log Jacobian) payload.

Parameters:

x (tuple[ndarray, ndarray])

Return type:

ndarray

mean_composition()[source]

Return the ilr-mean mapped to the unit simplex.

Return type:

ndarray

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: DistributionSampler

Sample compositions by inverting Gaussian ilr draws.

Parameters:
  • dist (AitchisonNormalDistribution)

  • seed (int | None)

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

Draw one composition or size iid compositions.

Parameters:
Return type:

ndarray

class AitchisonNormalDataEncoder(gaussian_encoder, n_parts)[source]

Bases: DataSequenceEncoder

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

Parameters:

x (Any)

Return type:

tuple[ndarray, ndarray]

row_count(x)[source]

Return the number of aligned encoded rows.

Parameters:

x (tuple[ndarray, ndarray])

Return type:

int

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

Bases: ParameterEstimator

Fit a Gaussian in ilr coordinates with explicit smoothing and keys.

Parameters:
  • dim (int | None)

  • pseudo_count (float | None)

  • suff_stat (tuple[np.ndarray | None, np.ndarray | None])

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return a keyed accumulator factory delegated to the Gaussian estimator.

Return type:

StatisticAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate ilr Gaussian parameters from delegated sufficient statistics.

Parameters:
Return type:

AitchisonNormalDistribution

class AitchisonNormalAccumulator(gaussian_acc, n_parts, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Delegate ilr-coordinate moments while preserving wrapper key semantics.

Parameters:
  • gaussian_acc (Any)

  • n_parts (int | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Update delegated Gaussian statistics from one raw composition.

Parameters:
  • x (ndarray)

  • weight (float)

  • estimate (AitchisonNormalDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize delegated statistics from one raw composition.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update delegated moments from encoded ilr coordinates.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize delegated moments from encoded ilr coordinates.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge delegated Gaussian sufficient statistics.

Parameters:

suff_stat (Any)

Return type:

AitchisonNormalAccumulator

value()[source]

Return delegated Gaussian sufficient statistics.

Return type:

Any

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: SequenceEncodableProbabilityDistribution

Multinomial distribution over count vectors.

Parameters:
  • dist (SequenceEncodableProbabilityDistribution)

  • len_dist (SequenceEncodableProbabilityDistribution | None)

  • len_normalized (bool)

  • name (str | None)

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 eta and the count-weighted sufficient statistic T(x) = sum_j c_j T_0(v_j). This holds only when the trial count is not separately modeled (len_dist is 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 returns None.

Parameters:

engine (Any)

density(x)[source]

Returns the density of multinomial evaluated at observation x.

See log_density() for details.

Parameters:

x (Sequence[Tuple[T, float]]) – Tuples of observed multinomial values and success s.t. success sum to number of trials.

Returns:

Density evaluated at x.

Return type:

float

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.

Parameters:

x (Sequence[Tuple[T, float]]) – Tuples of observed multinomial values and success s.t. success sum to number of trials.

Returns:

Log-density evaluated at x.

Return type:

float

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:

ndarray

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded count-vector observations.

Parameters:

engine (Any)

Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked child routes for homogeneous multinomial mixtures.

Parameters:
  • dists (Sequence[MultinomialDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

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

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]

Return per-component legacy multinomial sufficient statistics.

Parameters:
Return type:

tuple[Any, …]

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: DistributionSampler

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

Parameters:
  • size (Optional[int]) – Number of iid samples to draw from multinomial.

  • batched (bool)

Returns:

Sequence of ‘size’ iid observations if size is not None, else a single multinomial sample.

Return type:

Sequence[Sequence[tuple[Any, float]]] | Sequence[tuple[Any, float]]

class MultinomialEstimator(estimator, len_estimator=NullEstimator(), len_dist=None, len_normalized=False, name=None, keys=None)[source]

Bases: ParameterEstimator

Estimate a categorical multinomial from value and length sufficient statistics.

Parameters:
  • estimator (ParameterEstimator)

  • len_estimator (ParameterEstimator | None)

  • len_dist (SequenceEncodableProbabilityDistribution | None)

  • len_normalized (bool | None)

  • name (str | None)

  • keys (str | None)

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.

Parameters:
  • nobs (float | None) – Number of observations represented by suff_stat.

  • suff_stat (tuple[SS1, SS2 | None]) – Tuple of value-model and trial-count sufficient statistics.

Returns:

A fitted multinomial distribution.

Return type:

MultinomialDistribution

class MultinomialDataEncoder(encoder, len_encoder, len_normalized=False)[source]

Bases: DataSequenceEncoder

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

row_count(x)[source]

Return the number of bag observations in a validated encoding.

Parameters:

x (Any)

Return type:

int

class MultinomialEncodedData(indices, inverse_totals, nonzero_totals, encoded_values, encoded_lengths, counts, totals, len_normalized)[source]

Bases: object

Validated sparse multinomial batch representation.

Parameters:
class MultinomialEnumerator(dist)[source]

Bases: DistributionEnumerator

Reserved 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: SequenceEncodableStatisticAccumulator

Accumulate value and trial-count statistics for categorical multinomial data.

Parameters:
  • accumulator (SequenceEncodableStatisticAccumulator)

  • len_normalized (bool)

  • len_accumulator (SequenceEncodableStatisticAccumulator | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Update sufficient statistics from one weighted sparse multinomial observation.

Parameters:
  • x (Sequence[tuple[T, float]]) – Sparse observation as [(value, count), ...].

  • weight (float) – Observation weight.

  • estimate (MultinomialDistribution | None) – Optional previous multinomial estimate.

Return type:

None

initialize(x, weight, rng)[source]
Parameters:
  • x (Sequence[Tuple[T, float]]) – A single observation of multinomial distribution.

  • weight (float) – Observation weight.

  • rng (Optional[RandomState]) – Random state for initialization.

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.

Parameters:
  • weights (Any)

  • estimate (MultinomialDistribution | None)

  • engine (Any)

Return type:

None

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

Return type:

tuple[Any, Any | None]

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_dict under configured keys.

Parameters:

stats_dict (dict[str, Any]) – Mapping from merge keys to sufficient statistics.

Return type:

None

key_replace(stats_dict)[source]

Replace sufficient statistics from matching keys in stats_dict.

Parameters:

stats_dict (dict[str, Any]) – Mapping from merge keys to sufficient statistics.

Return type:

None

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: StatisticAccumulatorFactory

Create categorical multinomial accumulators and child accumulators.

Parameters:
  • est_factory (StatisticAccumulatorFactory)

  • len_normalized (bool)

  • len_factory (StatisticAccumulatorFactory)

  • keys (str | None)

make()[source]

Return a fresh multinomial accumulator.

Return type:

MultinomialAccumulator

class MultinomialFisherView(dist)[source]

Bases: SequenceFisherView

Fisher 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: SequenceEncodableProbabilityDistribution

Multinomial distribution over integer-keyed count maps.

Parameters:
  • min_val (int)

  • p_vec (list[float])

  • len_dist (SequenceEncodableProbabilityDistribution | None)

  • name (str | None)

  • keys (str | None)

  • prob_vec (list[float])

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.

Parameters:
Return type:

tuple[Any, …]

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

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return the natural parameter eta = log(p_vec) (one entry per category).

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the log partition A = 0 (normalization is carried by eta = log p).

Parameters:
Return type:

Any

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

Return the multinomial log coefficient in support and -inf outside support.

Parameters:
Return type:

Any

density(x)[source]

Evaluate the density of IntegerMultinomialDistribution at observed value x.

Parameters:

x (Sequence[Tuple[int, float]]) – Sequence of Tuple(s) containing the integer category value and number of successes.

Returns:

Density at x.

Return type:

float

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_dist defaults to NullDistribution, 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.

Parameters:

x (Sequence[Tuple[int, float]]) – Sequence of Tuple(s) containing the integer category value and number of successes.

Returns:

Log-density at x.

Return type:

float

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:

ndarray

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded integer count vectors.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked integer-count-vector parameters for homogeneous mixture kernels.

Parameters:
  • dists (Sequence[IntegerMultinomialDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

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

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]

Return per-component legacy (min_val, count_vec, length_stat) statistics.

Parameters:
Return type:

tuple[Any, …]

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

enumerator(*, max_outcomes_per_length=100_000)[source]

Returns IntegerMultinomialEnumerator iterating count vectors in descending log-density order.

Parameters:

max_outcomes_per_length (int)

Return type:

IntegerMultinomialEnumerator

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

Bases: DistributionSampler

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

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

  • batched (bool)

Returns:

List length size containing List[Tuple[int, float]]. If size is None, returns one sample

List[Tuple[int, float]].

Return type:

list[tuple[int, float]] | list[list[tuple[int, float]]]

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: ParameterEstimator

Estimate integer-category multinomial probabilities from count statistics.

Parameters:
  • min_val (int | None)

  • max_val (int | None)

  • len_estimator (ParameterEstimator | None)

  • len_dist (SequenceEncodableProbabilityDistribution | None)

  • name (str | None)

  • pseudo_count (float | None)

  • suff_stat (tuple[int, ndarray] | None)

  • keys (str | None)

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_count is not set, prior sufficient statistics are ignored during estimation.

suff_stat 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 for the length estimator.

Parameters:
  • nobs (Optional[float]) – Number of observations in accumulated data.

  • suff_stat (tuple[int, ndarray, SS0 | None]) – See above for details.

Returns:

Estimated distribution.

Return type:

IntegerMultinomialDistribution

class IntegerMultinomialDataEncoder(len_encoder=NullDataEncoder(), min_val=None, max_val=None)[source]

Bases: DataSequenceEncoder

Encode sparse integer multinomial observations for vectorized scoring.

Parameters:
  • len_encoder (DataSequenceEncoder | None)

  • min_val (int | None)

  • max_val (int | None)

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:

tuple[int, ndarray, ndarray, ndarray, Any | None]

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/val are 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 every seq_encode of this family fail the encoded-row conservation check. sz is the observation count this encoder already computes.

Parameters:

x (tuple[int, ndarray, ndarray, ndarray, Any | None])

Return type:

int

class IntegerMultinomialEnumerator(dist, *, max_outcomes_per_length=100_000)[source]

Bases: DistributionEnumerator

Enumerate 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: SequenceEncodableStatisticAccumulator

Accumulate sparse integer-category counts and trial-count child statistics.

Parameters:
  • min_val (int | None)

  • max_val (int | None)

  • name (str | None)

  • keys (str | None)

  • len_accumulator (SequenceEncodableStatisticAccumulator | None)

  • fixed_support (bool | None)

update(x, weight, estimate)[source]

Update sufficient statistics from single data observation.

Parameters:
  • x (Sequence[Tuple[int, float]]) – Single observation of integer multinomial distribution.

  • weight (float) – Weight for observation.

  • estimate (Optional[IntegerMultinomialDistribution]) – Optional previous estimate of integer multinomial distribution.

Returns:

None.

Return type:

None

initialize(x, weight, rng)[source]

Initialize IntegerMultinomialAccumulator with single observation x.

Just calls update() method.

Parameters:
  • x (Sequence[Tuple[int, float]]) – Single observation of integer multinomial distribution.

  • weight (float) – Weight for observation.

  • rng (Optional[RandomState]) – Optional random state for consistency with SequenceEncodableStatisticAccumulator class.

Returns:

None.

Return type:

None

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.

Parameters:
Return type:

None

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.

Parameters:

suff_stat (tuple[int, ndarray, SS0 | None]) – See above for details.

Returns:

IntegerMultinomialAccumulator object.

Return type:

IntegerMultinomialAccumulator

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.

Returns:

Tuple[int, ndarray, Optional[SS0]].

Return type:

tuple[int, ndarray, Any | None]

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_dict when 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_dict when 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: StatisticAccumulatorFactory

Create integer multinomial accumulators with optional length accumulators.

Parameters:
  • min_val (int | None)

  • max_val (int | None)

  • name (str | None)

  • keys (str | None)

  • len_factory (StatisticAccumulatorFactory | None)

  • fixed_support (bool | None)

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: SequenceEncodableProbabilityDistribution

Dirichlet-multinomial over K-category count vectors summing to n (concentration alpha).

Parameters:
  • alpha (ndarray)

  • n (int)

  • name (str | None)

  • keys (str | None)

  • max_recurrence_cells (int)

  • max_frontier_entries (int)

density(x)[source]

Return the probability mass at a single count vector x.

Parameters:

x (ndarray)

Return type:

float

log_density(x)[source]

Return the log-mass at x (-inf if any count is negative, non-integer, or the total is not n – a fractional category count is not a valid Dirichlet-multinomial outcome even when the (real-valued) total happens to sum to n).

Parameters:

x (ndarray)

Return type:

float

seq_log_density(x)[source]

Vectorized log-mass for a stack of count vectors, shape (N, K) (-inf rows where any count is negative, non-integer, or the row total is not n).

Parameters:

x (ndarray)

Return type:

ndarray

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 alpha at the fixed number of trials n.

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

enumerator(*, max_recurrence_cells=None, max_frontier_entries=None)[source]

Return an enumerator over count vectors summing to n in descending probability order.

Parameters:
  • max_recurrence_cells (int | None)

  • max_frontier_entries (int | None)

Return type:

DirichletMultinomialEnumerator

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

Bases: DistributionSampler

Draw counts as p ~ Dirichlet(alpha) then x ~ Multinomial(n, p).

Parameters:
  • dist (DirichletMultinomialDistribution)

  • seed (int | None)

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

Draw one count vector or a stack of iid count vectors.

Parameters:
Return type:

ndarray

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: ParameterEstimator

Minka fixed-point maximum-likelihood estimator for the Dirichlet-multinomial concentration.

Parameters:
  • dim (int)

  • n (int)

  • max_iter (int)

  • tol (float)

  • pseudo_count (float | None)

  • name (str | None)

  • keys (str | None)

  • min_alpha (float)

  • max_recurrence_cells (int)

  • max_frontier_entries (int)

accumulator_factory()[source]

Return an accumulator factory for Dirichlet-multinomial statistics.

Return type:

DirichletMultinomialAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate concentration parameters by Minka’s fixed-point update.

Parameters:
Return type:

DirichletMultinomialDistribution

class DirichletMultinomialDataEncoder(dim, n)[source]

Bases: DataSequenceEncoder

Encode a sequence of K-category count vectors as an (N, K) array.

Parameters:
seq_encode(x)[source]

Validate and encode count vectors as an integral matrix.

Parameters:

x (Sequence[ndarray])

Return type:

ndarray

class DirichletMultinomialEnumerator(dist, *, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS, max_frontier_entries=_DEFAULT_MAX_FRONTIER_ENTRIES)[source]

Bases: DistributionEnumerator

Enumerate 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) with f_k(c) = gammaln(c + alpha_k) - gammaln(alpha_k) - gammaln(c + 1), and each f_k is monotone in c (increasing for alpha_k > 1, decreasing for alpha_k < 1), so a prefix assignment (x_1..x_j) with m trials left admits the admissible completion bound sum_{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 the C(n+K-1, K-1) support.

Parameters:
  • dist (DirichletMultinomialDistribution)

  • max_recurrence_cells (int)

  • max_frontier_entries (int)

class DirichletMultinomialAccumulator(dim, n, name=None, keys=None, *, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate cumulative counts c[k, j] = sum_i w_i 1{x_ik > j} (the Minka digamma-recurrence stat).

Parameters:
  • dim (int)

  • n (int)

  • name (str | None)

  • keys (str | None)

  • max_recurrence_cells (int)

update(x, weight, estimate)[source]

Accumulate Minka recurrence statistics for one count vector.

Parameters:
  • x (ndarray)

  • weight (float)

  • estimate (DirichletMultinomialDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one count vector.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate Minka recurrence statistics from encoded count vectors.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded count vectors.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge another Dirichlet-multinomial sufficient-statistic tuple.

Parameters:

suff_stat (tuple[ndarray, float, int])

Return type:

DirichletMultinomialAccumulator

value()[source]

Return cumulative recurrence counts, total weight, and logical trial count.

Return type:

tuple[ndarray, float, int]

from_value(x)[source]

Replace accumulator contents from recurrence statistics.

Parameters:

x (tuple[ndarray, float, int])

Return type:

DirichletMultinomialAccumulator

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: StatisticAccumulatorFactory

Factory for DirichletMultinomialAccumulator.

Parameters:
  • dim (int)

  • n (int)

  • name (str | None)

  • keys (str | None)

  • max_recurrence_cells (int)

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: object

Machine-readable evidence about a concentration fixed-point fit.

Parameters:
exception DirichletMultinomialResourceError[source]

Bases: RuntimeError

Raised 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: SequenceEncodableProbabilityDistribution

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

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return vector natural parameters for generated diagonal-Gaussian scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the diagonal-Gaussian log partition for generated scoring.

Parameters:
Return type:

Any

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

Return row-wise legacy accumulator statistics for generated resident reductions.

Parameters:
Return type:

tuple[Any, …]

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 (including None) leaves the distribution a plain point model.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

expected_log_density(x)[source]

Variational expectation E_q[log p(x | mu, tau)] under the prior.

Falls back to the plug-in log_density(x) when no conjugate prior is attached.

Return type:

float

seq_expected_log_density(x)[source]

Vectorized expected_log_density over sequence-encoded observations.

Parameters:

x (ndarray)

Return type:

ndarray

density(x)[source]

Evaluate the density 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 form x^2*ca + x*cb + cc. The expanded form is three terms of size O(|x|^2/covar) summing to an O(1) answer, so at |x| ~ 1e9 with 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, an optimize/fit run at that offset returned the WORSE of its own iterates. x - mu is 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 as ca/cb/cc for 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 support MixtureDistribution.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.

Parameters:

observed (dict[int, float])

Return type:

DiagonalGaussianDistribution

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

Parameters:

keep (Sequence[int])

Return type:

DiagonalGaussianDistribution

density_cumulative(x)[source]

Exact probability-ordered cumulative G(x) = P(p(Y) >= p(x)) – the highest-density-region mass through x (multivariate analogue of a CDF). For a diagonal Gaussian the squared Mahalanobis distance sum_i (x_i-mu_i)^2/var_i is chi-square(dim), so G = chi2.cdf(maha2, dim). Used by mixle.enumeration.density_rank.density_rank() to return an EXACT cumulative.

Parameters:

x (Sequence[float] | ndarray)

Return type:

float

density_quantile(q)[source]

Inverse of density_cumulative(): a representative point at cumulative-density index q.

q is the highest-density-region mass, whose boundary is the squared-Mahalanobis level chi2.ppf(q, dim); a representative point on that contour offsets the first coordinate by sqrt(level * var_0) (Mahalanobis distance exactly the level). Sweeping q enumerates the support in descending density.

Parameters:

q (float)

Return type:

ndarray

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:

ndarray

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

Engine-neutral diagonal Gaussian log-density from explicit parameters.

Parameters:
Return type:

Any

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

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

Parameters:
  • dists (Sequence[DiagonalGaussianDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

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

Parameters:
Return type:

Any

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: DistributionSampler

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

Parameters:
  • size (Optional[int]) – Number of iid samples to draw. If None, a single sample is drawn.

  • batched (bool)

Returns:

Numpy array with shape (dim,) if size is None, else a list of ‘size’ such arrays.

Return type:

Sequence[ndarray] | ndarray

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: ParameterEstimator

Estimator for diagonal Gaussian distributions.

The fit is SHIFT-EQUIVARIANT: fit(x + c) returns the variances of x + c to within about 1e-7 relative for any constant c the data can carry, epoch seconds (~1.7e9) included. That is not free from the declared (sum, sum2, count) statistics – their variance is the cancellation-prone E[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 – so DiagonalGaussianAccumulator carries 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, estimate warns rather than returning variances it cannot stand behind.

The 1e-7 is 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 raw E[x^2] - mu^2 form is still in use because it is accurate enough to be worth its single pass: at mean^2/variance just under the gate’s 4e6 the worst case measured over seeds, sample sizes and scales is 3.1e-8 relative. 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 (default ridge=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 off mean(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 absolute min_covar (default 1e-8) is the last resort when nothing carries a scale at all (every coordinate non-positive, or ridge=0.0), and becomes a hard per-coordinate lower bound as soon as it is passed explicitly – which is how mixle.task regularizes its diagonal Gaussians.

A floor that actually lifted a coordinate is recorded on the fitted distribution as a variance-floored(...) entry in numerical_repairs() – and therefore in fit_provenance().repairs – naming the coordinate and how far it moved. Manufactured jitter is always reported; an explicit min_covar dominating a positive variance is reported once it exceeds _FLOOR_MATERIAL_RATIO of it. An ordinary fit lifts nothing and records nothing. Because the default floor never binds on a coordinate with its own variance, ridge=0.0 is 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 absolute min_covar instead.

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:

float

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.

Parameters:
  • nobs (Optional[float]) – Weighted number of observations used in aggregation of suff stats.

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

Returns:

DiagonalGaussianDistribution object.

Return type:

DiagonalGaussianDistribution

class DiagonalGaussianDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encoder for iid diagonal Gaussian observations.

Parameters:

dim (int | None)

seq_encode(x)[source]

Encode a sequence of iid length-dim observations for vectorized seq_ calls.

Parameters:

x (Sequence[Union[List[float], np.ndarray]]) – Sequence of length-dim observation vectors.

Returns:

Encoded data matrix with shape (len(x), dim).

Return type:

ndarray

class DiagonalGaussianAccumulator(dim=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulator for diagonal Gaussian sufficient statistics.

Alongside the declared raw moments (sum, sum2, count) this keeps a SHIFT-ANCHORED moment track, for the reason the univariate GaussianAccumulator keeps one: the variance computed from raw reduced moments is the classic cancellation-prone E[x^2] - mu^2 form, 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 scalar update) would corrupt a variance.

Parameters:
  • dim (int | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Update sufficient statistics with a single weighted observation.

Parameters:
  • x (Union[Sequence[float], np.ndarray]) – Length-dim observation vector.

  • weight (float) – Weight for the observation.

  • estimate (Optional[DiagonalGaussianDistribution]) – 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 (Union[Sequence[float], np.ndarray]) – Length-dim observation vector.

  • weight (float) – Weight for the observation.

  • rng (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[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 its anchored attribute, so combine() can fold them in and DiagonalGaussianEstimator.estimate() can compute shift-invariant variances. Well-conditioned data never activates the track and gets the historical plain tuple.

Return type:

tuple[ndarray, ndarray, float]

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 by c scales both anchored moments by c and 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: StatisticAccumulatorFactory

Factory for diagonal Gaussian accumulators.

Parameters:
  • dim (int | None)

  • keys (str | None)

make()[source]

Return a fresh accumulator with the factory configuration.

Return type:

DiagonalGaussianAccumulator

class DiagonalGaussianFisherView(dist)[source]

Bases: FixedFisherView

Fisher 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: SequenceEncodableProbabilityDistribution

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

Parameters:
Return type:

tuple[Any, …]

static exp_family_natural_parameters(params, engine)[source]

Return natural parameters for generated MVN scoring.

Parameters:
Return type:

tuple[Any, …]

static exp_family_log_partition(params, engine)[source]

Return the full-covariance Gaussian log partition.

Parameters:
Return type:

Any

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

Return row-wise legacy accumulator statistics for generated resident reductions.

Parameters:
Return type:

tuple[Any, …]

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 (including None) leaves the distribution a plain point model.

Parameters:

prior (SequenceEncodableProbabilityDistribution | None)

Return type:

None

expected_log_density(x)[source]

Variational expectation E_q[log p(x | mu, Lambda)] under the NormalWishart prior.

Falls back to the plug-in log_density(x) when no conjugate prior is attached.

Return type:

float

seq_expected_log_density(x)[source]

Vectorized expected_log_density over sequence-encoded observations.

Parameters:

x (ndarray)

Return type:

ndarray

density(x)[source]

Evaluate the density at x.

Parameters:

x (np.ndarray) – Observation from multivariate Gaussian distribution.

Returns:

Density at x.

Return type:

float

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:

float

density_cumulative(x)[source]

Exact probability-ordered cumulative G(x) = P(p(Y) >= p(x)) – the highest-density-region mass whose boundary passes through x (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 with dim degrees of freedom, so G(x) = chi2.cdf(maha2, dim). Used by mixle.enumeration.density_rank.density_rank() to return an EXACT cumulative for the MVN.

Parameters:

x (ndarray)

Return type:

float

density_quantile(q)[source]

Inverse of density_cumulative(): a representative point at cumulative-density index q.

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. q is the highest-density region mass, so the boundary is the squared-Mahalanobis level chi2.ppf(q, dim); we return a representative point on that contour, mu + sqrt(level) * L[:, 0] where covar = L L^T (so its Mahalanobis distance is exactly the level). Sweeping q enumerates the support in descending density.

Parameters:

q (float)

Return type:

ndarray

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:

ndarray

static backend_log_density_from_params(x, mu, inv_covar, log_det, engine)[source]

Engine-neutral multivariate Gaussian log-density from inverse covariance.

Parameters:
Return type:

Any

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked full-covariance Gaussian parameters for a homogeneous mixture kernel.

Parameters:
  • dists (Sequence[MultivariateGaussianDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

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

Parameters:
Return type:

Any

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^T is accumulated per component as a gemm (x * w[:, k]).T @ x instead of reducing a per-sample, per-component (n, k, dim, dim) outer-product tensor. That intermediate is N*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 likewise w.T @ x rather than a reduced (n, k, dim) tensor.

Parameters:
Return type:

tuple[Any, …]

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.

observed maps 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.

Parameters:

observed (dict[int, float])

Return type:

MultivariateGaussianDistribution

marginal(keep)[source]

Return the marginal Gaussian over dimensions keep.

N(mu, Sigma) marginalized to index set keep is N(mu[keep], Sigma[keep, keep]). The order of keep is preserved, so the result’s dimensions follow the given order.

Parameters:

keep (Sequence[int])

Return type:

MultivariateGaussianDistribution

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: DistributionSampler

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

Parameters:
  • size (Optional[int]) – Number of iid samples to draw. If None, a single sample is drawn.

  • batched (bool)

Returns:

Numpy array with shape (dim,) if size is None, else with shape (size, dim).

Return type:

ndarray

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: ParameterEstimator

Estimator for multivariate Gaussian distributions.

The fitted covariance is NOT the raw maximum-likelihood estimate unless ridge=0.0 is passed: by default the M-step regularizes each diagonal entry of the empirical covariance as cov_ii + eps_i with eps_i = ridge * cov_ii (default ridge=1e-6) so a singular empirical covariance – e.g. an EM component holding fewer than d points – remains factorizable. Each eps_i is 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 absolute min_covar (default 1e-8) is the last resort for a covariance with no scale at all (all-zero diagonal, or ridge=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 in numerical_repairs() – and therefore in fit_provenance().repairs. “Materially” means the jitter exceeded _RIDGE_MATERIAL_RATIO of the smallest raw variance (an explicit min_covar dominating 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. Pass ridge=0.0 to recover the exact MLE up to the min_covar absolute jitter floor.

The fit is SHIFT-EQUIVARIANT: fit(x + c) returns the covariance of x + c to within a few ulps for any constant c the data can carry, epoch seconds (~1.7e9) included. That is not free from the declared (sum, sum2, count) statistics – their covariance is the cancellation-prone E[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 – so MultivariateGaussianAccumulator carries 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, estimate warns 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:

float

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.

Parameters:
  • nobs (Optional[float]) – Weighted number of observations used in aggregation of suff stats.

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

Returns:

MultivariateGaussianDistribution

Return type:

MultivariateGaussianDistribution

class MultivariateGaussianDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encoder for iid multivariate Gaussian observations.

Parameters:

dim (int | None)

seq_encode(x)[source]

Encode a sequence of iid length-dim observations for vectorized seq_ calls.

Parameters:

x (Union[Sequence[List[float]], Sequence[List[np.ndarray]], np.ndarray]) – Sequence of length-dim observation vectors.

Returns:

Encoded data matrix with shape (len(x), dim).

class MultivariateGaussianAccumulator(dim=None, keys=None, name=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulator for multivariate Gaussian sufficient statistics.

Alongside the declared raw moments (sum, sum2, count) this keeps a SHIFT-ANCHORED moment track, for the reason the univariate GaussianAccumulator keeps one: the covariance computed from raw reduced moments is the classic cancellation-prone E[xx^T] - mu mu^T form, 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_factor refuses 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 scalar update) would corrupt the covariance.

Parameters:
  • dim (int | None)

  • keys (str | None)

  • name (str | None)

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 its anchored attribute, so combine() can fold them in and MultivariateGaussianEstimator.estimate() can compute a shift-invariant covariance. Well-conditioned data never activates the track and gets the historical plain tuple.

Return type:

tuple[ndarray, ndarray, float]

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 by c scales both anchored moments by c and 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: StatisticAccumulatorFactory

Factory for multivariate Gaussian accumulators.

Parameters:
  • dim (int | None)

  • keys (str | None)

  • name (str | None)

make()[source]

Return a fresh accumulator with the factory configuration.

Return type:

MultivariateGaussianAccumulator

class MultivariateGaussianFisherView(dist)[source]

Bases: FixedFisherView

Fisher 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: SequenceEncodableProbabilityDistribution

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

Parameters:
Return type:

Any

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 (Mahalanobis d_o) and unobserved u:

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.

Parameters:

observed (dict[int, float])

Return type:

MultivariateStudentTDistribution

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

Parameters:

keep (Sequence[int])

Return type:

MultivariateStudentTDistribution

density(x)[source]

Return the probability density at a single observation.

Parameters:

x (Sequence[float] | ndarray)

Return type:

float

log_density(x)[source]

Return the log-density at a single observation.

Parameters:

x (Sequence[float] | ndarray)

Return type:

float

seq_log_density(x)[source]

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

Parameters:

x (ndarray)

Return type:

ndarray

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized log-density for encoded data.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Return stacked parameters for equal-dimensional multivariate Student’s t mixtures.

Parameters:
  • dists (Sequence[MultivariateStudentTDistribution])

  • engine (Any)

Return type:

dict[str, Any]

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

Return an (n, k) matrix of multivariate Student’s t component log densities.

Parameters:
Return type:

Any

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: DistributionSampler

Draw iid multivariate Student’s t observations as mu + Z * sqrt(nu / G).

Parameters:
  • dist (MultivariateStudentTDistribution)

  • seed (int | None)

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

Draw size iid vectors (shape (p,) when size is None, else (size, p)).

Parameters:
Return type:

ndarray

class MultivariateStudentTEstimator(dof=5.0, dim=None, pseudo_count=None, min_ridge=_MIN_RIDGE, name=None, keys=None)[source]

Bases: ParameterEstimator

Fixed-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 on x + c returns loc + c with the scale matrix unchanged, for any constant c the data can carry – epoch seconds (~1.7e9) and 2**31 included. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, and estimate warns rather than returning a scale 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 of x_i - mu, and mu is 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’s mu onto 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 roughly ulp(abs(mu)) / spread per 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

estimate(nobs, suff_stat)[source]

Estimate location and scale from EM reweighted statistics.

Parameters:
Return type:

MultivariateStudentTDistribution

class MultivariateStudentTDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode a sequence of length-p real vectors into an (n, p) float array.

Parameters:

dim (int | None)

seq_encode(x)[source]

Encode observations as an (n, p) floating-point matrix.

Parameters:

x (Sequence[Sequence[float]] | ndarray)

Return type:

ndarray

class MultivariateStudentTAccumulator(dof, dim=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate 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 scatter O(sum_u * spread^2), which makes the scale matrix shift-invariant. The track is gated: a chunk whose abs(mean)/spread ratio the raw form handles to ~1e-9 relative error (see needs_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 on MultivariateStudentTSuffStat.

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

Accumulate one EM reweighted vector observation.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one vector observation.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate EM reweighted statistics from encoded vectors.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (MultivariateStudentTDistribution | None)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded vectors.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge another multivariate Student-t sufficient-statistic tuple.

Parameters:

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

Return type:

MultivariateStudentTAccumulator

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_moments included; once the shift-anchored track is live it is a MultivariateStudentTSuffStat that additionally carries those moments in its anchored attribute, so combine() can fold them in and MultivariateStudentTEstimator.estimate() can form a shift-invariant scale matrix.

Return type:

tuple[float, float, ndarray | None, ndarray | None]

from_value(x)[source]

Replace accumulator contents from sufficient statistics.

Parameters:

x (tuple[float, float, ndarray | None, ndarray | None])

Return type:

MultivariateStudentTAccumulator

scale(c)[source]

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

The structural default round-trips through value()/from_value(), and scale_suff_stat rebuilds the payload as a PLAIN tuple – which drops the anchored track and undoes the repair. Scaling every weight by c scales both anchored moments by c and 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: StatisticAccumulatorFactory

Factory for MultivariateStudentTAccumulator.

Parameters:
make()[source]

Create a fresh multivariate Student-t accumulator.

Return type:

MultivariateStudentTAccumulator

class GaussianCopulaDistribution(corr, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Gaussian copula on (0,1)^d with dependence given by a correlation matrix.

Parameters:
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 u in (0,1)^d.

Parameters:

x (ndarray)

Return type:

float

log_density(x)[source]

Return the log copula density at a single point u in (0,1)^d.

Parameters:

x (ndarray)

Return type:

float

seq_log_density(x)[source]

Vectorized log copula density for sequence-encoded observations (z = Phi^{-1}(u) rows).

Parameters:

x (ndarray)

Return type:

ndarray

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: DistributionSampler

Draw u by sampling z ~ N(0, R) and mapping through the standard-normal CDF.

Parameters:
  • dist (GaussianCopulaDistribution)

  • seed (int | None)

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

Draw one copula sample or a batch of independent copula samples.

Parameters:
Return type:

ndarray

class GaussianCopulaEstimator(dim, min_eig=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Inversion estimator: the correlation of the normal scores z = Phi^{-1}(u).

Parameters:
accumulator_factory()[source]

Return a factory for Gaussian copula sufficient-statistic accumulators.

Return type:

GaussianCopulaAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate the copula correlation matrix from normal-score moments.

Parameters:
Return type:

GaussianCopulaDistribution

class GaussianCopulaDataEncoder(dim)[source]

Bases: DataSequenceEncoder

Encode each u row as its normal score z = Phi^{-1}(u).

Parameters:

dim (int)

seq_encode(x)[source]

Encode copula observations by clipping and applying the normal quantile.

Parameters:

x (Sequence[ndarray])

Return type:

ndarray

class GaussianCopulaAccumulator(dim, name=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate the weighted first and second moments of the normal scores z.

Parameters:
  • dim (int)

  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Accumulate weighted normal-score moments for one copula observation.

Parameters:
  • x (ndarray)

  • weight (float)

  • estimate (GaussianCopulaDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize the sufficient statistics with one weighted observation.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate weighted moments from encoded normal-score observations.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (GaussianCopulaDistribution | None)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize the sufficient statistics from encoded observations.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge serialized normal-score moments into this accumulator.

Parameters:

suff_stat (tuple[ndarray, ndarray, float])

Return type:

GaussianCopulaAccumulator

value()[source]

Return the weighted first moments, second moments, and total weight.

Return type:

tuple[ndarray, ndarray, float]

from_value(x)[source]

Restore the accumulator from serialized normal-score moments.

Parameters:

x (tuple[ndarray, ndarray, float])

Return type:

GaussianCopulaAccumulator

acc_to_encoder()[source]

Return an encoder that produces normal-score observations.

Return type:

GaussianCopulaDataEncoder

class GaussianCopulaAccumulatorFactory(dim, name=None, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for GaussianCopulaAccumulator.

Parameters:
  • dim (int)

  • name (str | None)

  • keys (str | None)

make()[source]

Create an empty Gaussian copula accumulator.

Return type:

GaussianCopulaAccumulator

class ClaytonCopulaDistribution(dim, theta, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Clayton copula on (0,1)^d with theta >= 0; zero is independence.

Parameters:
log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

float

seq_log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

ndarray

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: DistributionSampler

Marshall-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. With batched=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 independent RandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path. batched=False forces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.

Parameters:
Return type:

ndarray

class ClaytonCopulaEstimator(dim, name=None, keys=None)[source]

Bases: ParameterEstimator

Kendall’s-tau inversion: theta = 2*tau / (1 - tau) (pair-averaged for d > 2).

Parameters:
  • dim (int)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return the accumulator factory used to collect this estimator’s sufficient statistics.

Return type:

BufferedUScoreAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a distribution from accumulated sufficient statistics.

Parameters:
Return type:

ClaytonCopulaDistribution

class FrankCopulaDistribution(dim, theta, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Frank copula on (0,1)^2 with dependence parameter theta (any sign; 0 = independence).

Parameters:
log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

float

seq_log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

ndarray

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: DistributionSampler

Conditional inversion: draw u1, w uniform, solve v from the conditional C(v | u1) = w.

Parameters:
  • dist (FrankCopulaDistribution)

  • seed (int | None)

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

Draw observations.

Combinator samplers (mixture/sequence/…) accept batched. With batched=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 independent RandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path. batched=False forces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.

Parameters:
Return type:

ndarray

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

Bases: ParameterEstimator

1-D maximum likelihood on theta over [-40, 40] (golden section on the copula log-likelihood).

Parameters:
  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return the accumulator factory used to collect this estimator’s sufficient statistics.

Return type:

BufferedUScoreAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a distribution from accumulated sufficient statistics.

Parameters:
Return type:

FrankCopulaDistribution

class GumbelCopulaDistribution(dim, theta, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Gumbel copula on (0,1)^2 with upper-tail dependence parameter theta >= 1.

Parameters:
log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

float

seq_log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

ndarray

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: DistributionSampler

Positive-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. With batched=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 independent RandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path. batched=False forces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.

Parameters:
Return type:

ndarray

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

Bases: ParameterEstimator

Kendall’s-tau inversion: theta = 1 / (1 - tau) (clamped to theta >= 1).

Parameters:
  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return the accumulator factory used to collect this estimator’s sufficient statistics.

Return type:

BufferedUScoreAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a distribution from accumulated sufficient statistics.

Parameters:
Return type:

GumbelCopulaDistribution

class StudentTCopulaDistribution(corr, df, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Student-t copula on (0,1)^d with correlation corr and degrees of freedom df.

Parameters:
  • corr (np.ndarray)

  • df (float)

  • name (str | None)

  • keys (str | None)

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.

Parameters:

u (ndarray)

Return type:

float

seq_log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

ndarray

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: DistributionSampler

Draw z ~ mvt(R, nu) (Gaussian scaled by a chi-square) then map through the univariate t_nu CDF.

Parameters:
  • dist (StudentTCopulaDistribution)

  • seed (int | None)

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

Draw observations.

Combinator samplers (mixture/sequence/…) accept batched. With batched=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 independent RandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path. batched=False forces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.

Parameters:
Return type:

ndarray

class StudentTCopulaEstimator(dim, min_eig=1.0e-8, name=None, keys=None)[source]

Bases: ParameterEstimator

Inversion for R (correlation of the t-scores) + profile likelihood over nu on a grid.

Parameters:
accumulator_factory()[source]

Return the accumulator factory used to collect this estimator’s sufficient statistics.

Return type:

BufferedUScoreAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a distribution from accumulated sufficient statistics.

Parameters:
Return type:

StudentTCopulaDistribution

exception VinePairFitError[source]

Bases: RuntimeError

Raised when no requested pair-copula family can be fitted on an edge.

class PairCandidateEvidence(family: 'str', parameter_count: 'int', weighted_log_likelihood: 'float | None', aic: 'float | None', fit_error: 'str | None')[source]

Bases: object

Parameters:
  • family (str)

  • parameter_count (int)

  • weighted_log_likelihood (float | None)

  • aic (float | None)

  • fit_error (str | None)

class PairSelectionReceipt(schema_version: 'int', criterion: 'str', edge_context: 'str', selected_family: 'str', total_weight: 'float', evidence: 'tuple[PairCandidateEvidence, ...]')[source]

Bases: object

Parameters:
  • schema_version (int)

  • criterion (str)

  • edge_context (str)

  • selected_family (str)

  • total_weight (float)

  • evidence (tuple[PairCandidateEvidence, ...])

class CVineCopulaDistribution(dim, pairs, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

A canonical-vine (C-vine) copula on (0,1)^d: d(d-1)/2 bivariate pair copulas in a tree cascade.

pairs maps (tree, position) -> a fitted pair copula, tree in 1..d-1 and position in 1..d-tree (tree 1 links the root variable to each other; deeper trees link conditionally). Build one by hand, or fit with CVineCopulaEstimator (which selects a family per edge).

Parameters:
log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

float

seq_log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

ndarray

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: DistributionSampler

Inverse 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. With batched=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 independent RandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path. batched=False forces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.

Parameters:
Return type:

ndarray

class CVineCopulaEstimator(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]

Bases: ParameterEstimator

Sequential (stepwise) MLE: fit tree by tree on conditional pseudo-observations, best family per edge.

Parameters:
accumulator_factory()[source]

Return the accumulator factory used to collect this estimator’s sufficient statistics.

Return type:

BufferedUScoreAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a distribution from accumulated sufficient statistics.

Parameters:
Return type:

CVineCopulaDistribution

class DVineCopulaDistribution(dim, pairs, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

A 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. Same d(d-1)/2 pair copulas indexed (tree, position); different (path vs star) tree topology. Like the C-vine it is a drop-in dependence core for CopulaDistribution.

Parameters:
log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

float

seq_log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

ndarray

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: DistributionSampler

Inverse 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. With batched=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 independent RandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path. batched=False forces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.

Parameters:
Return type:

ndarray

class DVineCopulaEstimator(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]

Bases: ParameterEstimator

Sequential (stepwise) MLE for a D-vine: fit tree by tree on conditional pseudo-obs, best family per edge.

Parameters:
accumulator_factory()[source]

Return the accumulator factory used to collect this estimator’s sufficient statistics.

Return type:

BufferedUScoreAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a distribution from accumulated sufficient statistics.

Parameters:
Return type:

DVineCopulaDistribution

class RVineCopulaDistribution(dim, trees, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

A 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. trees is the fitted structure (a list of trees, each a list of _Edge); dim the number of variables.

Parameters:
classmethod independence(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]

Construct an explicit, structurally complete independence R-vine.

Parameters:
Return type:

RVineCopulaDistribution

log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

float

seq_log_density(u)[source]

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

Parameters:

u (ndarray)

Return type:

ndarray

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: DistributionSampler

Sample 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. With batched=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 independent RandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path. batched=False forces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.

Parameters:
Return type:

ndarray

class RVineCopulaEstimator(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]

Bases: ParameterEstimator

Dißmann selection + sequential MLE: choose the tree structure and per-edge family from data.

Parameters:
accumulator_factory()[source]

Return the accumulator factory used to collect this estimator’s sufficient statistics.

Return type:

BufferedUScoreAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a distribution from accumulated sufficient statistics.

Parameters:
Return type:

RVineCopulaDistribution

Submodules