mixle.dist module¶
mixle.dist — the distribution families.
The objects: the leaf distributions, multivariate families, combinators, latent-variable models and
priors. A friendly namespace alias of mixle.stats during the concern-oriented reorg
(docs/ARCHITECTURE.md) — a re-export, so every mixle.stats import keeps working. The
cross-cutting concerns live in mixle.enumeration, mixle.inference,
and mixle.ops (sampling is intrinsic behavior, not a concern: mixle.stats.sample).
Naming note (T2-06): the log-normal family is named LogGaussian in this catalog
(LogGaussianDistribution / LogGaussianEstimator) but LogNormal in the
mixle.ppl dialect (mixle.ppl.LogNormal(), with mixle.ppl.LogGaussian() as its
alias). So that a search under either name finds the family on either surface, this module also
exports LogNormalDistribution / LogNormalEstimator as aliases of the LogGaussian
classes — the same objects, not subclasses.
Parameterization note (T2-05): mixle.ppl constructors use the conventional textbook
parameterizations, which for a few families differ from the catalog classes here. Measured
divergences (all other shared families agree argument-for-argument):
family |
ppl constructor |
catalog class (this module) |
conversion |
|---|---|---|---|
Normal |
|
|
|
LogNormal |
|
|
|
EMG |
|
|
|
Gamma |
|
|
|
Exponential |
|
|
|
Binomial |
|
|
same meanings, positional order swapped |
Example — the same model written on both surfaces:
from mixle.ppl import Normal # ppl dialect: standard deviation
from mixle.dist import GaussianDistribution # catalog: variance
Normal(0.0, 2.0) # sd = 2.0 ...
GaussianDistribution(0.0, 4.0) # ... is sigma2 = 2.0**2 = 4.0 here
The full dialect-side table lives in mixle.ppl.distributions.
- conjugate_posterior(dist, data, prior=None, weights=None)[source]
Closed-form conjugate posterior over the parameters of
distgivendata.Every supported family returns an exact closed-form parameter posterior: exact parameter samples, marginal likelihood, and posterior mean / point estimate. A posterior predictive is exact where its compound law is implemented; otherwise the returned distribution carries
is_exact_posterior_predictive=Falseand a machine-readableapproximation_receipt. For families with a multi-parameter likelihood whose conjugate is conditional (Gamma, InverseGamma, InverseGaussian, Pareto, NegativeBinomial, vonMises), the non-target parameter (shape / location / scale / number-of-trials / concentration) is taken as known fromdist– exactly as a Binomial’s number of trials is. Families with no closed-form conjugate (full Beta, full Gamma, LogSeries, …) raise a clear error rather than returning a partial answer.- Parameters:
dist – A mixle likelihood distribution instance whose type selects the conjugate family.
data – A sequence of observations of the kind
distscores.prior (dict | None) – Optional dict of conjugate-prior hyperparameters (family specific).
Noneuses a weak proper prior.weights (ndarray | None) – Optional per-observation weights (e.g. EM responsibilities).
- Returns:
A
ConjugatePosteriorexposingmean,sample,point_estimate,log_marginal_likelihood,posterior_predictiveandsummary.- Return type:
ConjugatePosterior
- class ConjugatePosterior[source]
Bases:
objectBase class for a closed-form conjugate posterior over a likelihood’s parameters.
Subclasses provide the family-specific hyperparameters and the four capabilities:
mean(the posterior mean of the parameters),sample(exact draws of the parameters),point_estimate(a fitted distribution at the posterior mean),log_marginal_likelihood(the evidence of the observed data under the prior), andposterior_predictive(the distribution of a new draw).- mean()[source]
Return posterior mean parameters as a family-specific dictionary.
- sample(n=1, rng=None)[source]
Draw
nexact parameter samples from the posterior.- Parameters:
n (int)
rng (RandomState | None)
- Return type:
- sampler(seed=None)[source]
Return a sampler exposing the standard
obj.sampler(seed).sample(size)API.Mirrors the distribution sampling convention so conjugate posteriors read the same way as every other mixle object; here each draw is a parameter set from the posterior.
size=Nonereturns one parameter set (scalars),size=na dict of length-narrays. The explicit-rng formsample(n, rng)remains available.- Parameters:
seed (int | None)
- Return type:
ConjugatePosteriorSampler
- point_estimate()[source]
Return a likelihood distribution built from a representative posterior parameter value.
- log_marginal_likelihood()[source]
Return the closed-form log evidence of the observed data.
- Return type:
- posterior_predictive()[source]
Return the posterior predictive distribution for a new observation.
- summary()[source]
Return a compact summary of the posterior family, mean, and hyperparameters.
- mixture_conjugate_posterior(dist, data, priors, prior_weights=None, weights=None)[source]
Posterior under a prior that is a mixture of conjugate priors (Diaconis-Ylvisaker).
- Parameters:
dist – The likelihood distribution (must map to a closed-form conjugate realiser, since the reweighting needs each component’s marginal likelihood).
data – The observations.
priors (list[dict]) – One hyperparameter dict per mixture component (same keys
conjugate_posterior()accepts for this family).prior_weights (ndarray | None) – Prior mixing weights
w_m(default uniform); normalised internally.weights (ndarray | None) – Optional per-observation weights.
- Returns:
the exact posterior, again a mixture of conjugate posteriors with weights
w'_m proportional to w_m * Z_m.- Return type:
A
MixtureConjugatePosterior
- class MixtureConjugatePosterior(components, post_weights, prior_weights, comp_log_evidence)[source]
Bases:
ConjugatePosteriorPosterior under a prior that is itself a mixture of conjugate priors.
Diaconis-Ylvisaker (1979): if the prior is
sum_m w_m * pi_m(theta)with eachpi_mconjugate to the likelihood, the posterior is again a mixture of the component conjugate posteriors,sum_m w'_m * pi_m^post(theta), with the mixing weights reweighted by each component’s marginal likelihoodZ_m:w’_m proportional to w_m * Z_m.
Everything stays closed-form, so a prior can be multimodal (e.g. “the rate is near 1 OR near 10”) or robust (a heavy-tailed prior as a mixture of conjugates) without losing exact inference.
- mean()[source]
Return the posterior-weighted mean of component posterior means.
- sample(n=1, rng=None)[source]
Draw parameter samples from the posterior mixture.
- Parameters:
n (int)
rng (RandomState | None)
- Return type:
- point_estimate()[source]
The maximum-a-posteriori component’s point estimate (the dominant conjugate mode).
- posterior_predictive()[source]
A mixle MixtureDistribution of the component predictives, weighted by the posterior weights.
- log_marginal_likelihood()[source]
Return the mixture-prior log evidence by log-summing component evidences.
- Return type:
- mixture_prior(weight_prior, component_priors)[source]
Build the joint mixture prior: a weight prior plus one prior per component.
- Parameters:
weight_prior (SequenceEncodableProbabilityDistribution) – Prior on the mixture weights (a
DirichletDistributionorSymmetricDirichletDistribution).component_priors (Sequence[SequenceEncodableProbabilityDistribution]) – Sequence of one conjugate prior per component.
- Returns:
A
(weight_prior, tuple(component_priors))pair consumed byMixtureDistribution/MixtureEstimatorset_prior.- Return type:
tuple[SequenceEncodableProbabilityDistribution, tuple[SequenceEncodableProbabilityDistribution, …]]
- class DictDirichletDistribution(alpha, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionDirichlet distribution over probability maps keyed by arbitrary values; a scalar alpha denotes a symmetric Dirichlet of unspecified dimension.
- get_parameters()[source]
Returns the concentration parameters (dict, or scalar if unbounded).
- set_parameters(params)[source]
Set the concentration parameters.
- density(x)[source]
Density at the probability map x (exp of log_density).
- log_density(x)[source]
Log-density of the Dirichlet at the probability map x.
With scalar alpha the dimension is len(x); with dict alpha the observation is scored with the concentration entries matching its keys.
- seq_log_density(x)[source]
Vectorized log-density at a sequence of probability maps.
- cross_entropy(dist)[source]
Cross entropy -E_self[log dist(x)] for a DictDirichlet argument.
- Parameters:
dist (DictDirichletDistribution)
- Return type:
- sampler(seed=None)[source]
Returns a DictDirichletSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
DictDirichletSampler
- estimator(pseudo_count=None)[source]
DictDirichlet is a parameter prior and is not fit from data by EM.
- Parameters:
pseudo_count (float | None)
- Return type:
ParameterEstimator
- dist_to_encoder()[source]
Returns a DictDirichletDataEncoder for encoding probability maps.
- Return type:
DictDirichletDataEncoder
- class SymmetricDirichletDistribution(alpha, dim=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionSymmetric Dirichlet distribution with shared concentration alpha; the dimension is inferred from each observation (or fixed with dim for sampling).
- set_parameters(params)[source]
Set the shared concentration parameter alpha.
- Parameters:
params (float)
- Return type:
None
- density(x)[source]
Density at the probability vector x (exp of log_density).
- log_density(x)[source]
Log-density of the symmetric Dirichlet at the probability vector x (
-infoff the simplex: a negative or non-finite entry, or a vector that doesn’t sum to one).
- seq_log_density(x)[source]
Vectorized log-density at a sequence-encoded (m, n) array of probability vectors (
-infrows that are off the simplex: a negative or non-finite entry, or a row that doesn’t sum to one).
- sampler(seed=None)[source]
Returns a SymmetricDirichletSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
SymmetricDirichletSampler
- estimator(pseudo_count=None)[source]
SymmetricDirichlet is a parameter prior and is not fit from data by EM.
- Parameters:
pseudo_count (float | None)
- Return type:
ParameterEstimator
- dist_to_encoder()[source]
Returns a SymmetricDirichletDataEncoder for encoding probability vectors.
- Return type:
SymmetricDirichletDataEncoder
- class NormalGammaDistribution(mu, lam, a, b, name=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionNormal-Gamma distribution over (mu, tau); conjugate prior for the univariate Gaussian.
- Parameters:
- get_parameters()[source]
Returns the parameter tuple (mu, lam, a, b).
- set_parameters(params)[source]
Set the parameters from a tuple (mu, lam, a, b).
- cross_entropy(dist)[source]
Cross-entropy H(self, dist) = -E_self[log dist].
Closed form for a NormalGamma argument; numerical double integration otherwise.
- Parameters:
dist (NormalGammaDistribution)
- Return type:
- entropy()[source]
Returns the entropy of the Normal-Gamma distribution (in nats).
- Return type:
- density(x)[source]
Density at x = (mu, tau); see log_density().
- log_density(x)[source]
Log-density at x = (mu, tau) with tau > 0.
- seq_log_density(x)[source]
Vectorized log-density at sequence-encoded (n, 2) array of (mu, tau) rows.
- sampler(seed=None)[source]
Create a NormalGammaSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
NormalGammaSampler
- estimator(pseudo_count=None)[source]
NormalGamma is a parameter prior and is not fit from data by EM.
- Parameters:
pseudo_count (float | None)
- Return type:
ParameterEstimator
- dist_to_encoder()[source]
Return the encoder for
(mu, tau)normal-gamma observations.- Return type:
NormalGammaDataEncoder
- class NormalWishartDistribution(mu, kappa, w_mat, nu, name=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionNormal-Wishart distribution over (mu, Lambda); conjugate prior for the multivariate Gaussian with unknown mean and precision matrix.
- Parameters:
- get_parameters()[source]
Returns the parameter tuple (mu, kappa, w_mat, nu).
- set_parameters(params)[source]
Set the parameters and refresh the cached Wishart log-normalizer.
- Parameters:
params – Tuple (mu, kappa, w_mat, nu) with w_mat positive definite and nu > d - 1.
- Return type:
None
- log_density(x)[source]
Log density at x = (mu, Lambda) with Lambda a precision matrix.
Returns -inf when Lambda is not positive definite.
- Return type:
- cross_entropy(dist)[source]
H(self, dist) = -E_self[log dist] for a NormalWishart argument.
- Parameters:
dist (NormalWishartDistribution)
- Return type:
- entropy()[source]
Returns the entropy of the Normal-Wishart distribution (in nats).
- Return type:
- seq_log_density(x)[source]
Vectorized log-density over a sequence of (mu, Lambda) pairs.
- Return type:
- sampler(seed=None)[source]
Create a NormalWishartSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
NormalWishartSampler
- estimator(pseudo_count=None)[source]
NormalWishart is a parameter prior and is not fit from data by EM.
- Parameters:
pseudo_count (float | None)
- Return type:
ParameterEstimator
- dist_to_encoder()[source]
Return the encoder for
(mu, Lambda)normal-Wishart observations.- Return type:
NormalWishartDataEncoder
- class MultivariateNormalGammaDistribution(mu, lam, a, b, name=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionVector of independent NormalGamma distributions over per-component (mu_i, tau_i) pairs; conjugate prior for diagonal Gaussians.
- Parameters:
- get_parameters()[source]
Returns the parameter tuple (mu, lam, a, b) of vectors.
- set_parameters(value)[source]
Set the parameters from a tuple of vectors.
- Parameters:
value – Tuple (mu, lam, a, b) of length-d arrays.
- Return type:
None
- cross_entropy(dist)[source]
Cross-entropy H(self, dist) = -E_self[log dist], summed over components, for a MultivariateNormalGamma argument.
- Parameters:
dist (MultivariateNormalGammaDistribution)
- Return type:
- density(x)[source]
Density at x = (mu, tau); see log_density().
- log_density(x)[source]
Log-density at x = (mu, tau), summed over the d components.
- Parameters:
x (FlexDatumType) – Tuple (mu, tau) of length-d vectors with tau_i > 0.
- Returns:
Log-density at x.
- Return type:
- seq_log_density(x)[source]
Vectorized log-density over a sequence of (mu, tau) pairs.
- Return type:
- sampler(seed=None)[source]
Create a MultivariateNormalGammaSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
MultivariateNormalGammaSampler
- estimator(pseudo_count=None)[source]
MultivariateNormalGamma is a parameter prior; not fit from data by EM.
- Parameters:
pseudo_count (float | None)
- Return type:
ParameterEstimator
- dist_to_encoder()[source]
Returns a MultivariateNormalGammaDataEncoder for encoding (mu, tau) pairs.
- Return type:
MultivariateNormalGammaDataEncoder
- class DirichletProcessMixtureDistribution(components, w, a, g, component_priors, name=None, prior=default_prior)[source]
Bases:
SequenceEncodableProbabilityDistributionTruncated Dirichlet process mixture with stick-breaking weights w over K component distributions, carrying the variational Beta posteriors.
- Parameters:
- get_prior()[source]
Return the Gamma hyper-posterior on the concentration alpha.
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Set the Gamma hyper-prior (or hyper-posterior) on alpha.
- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- get_parameters()[source]
Return concentration, weights, and independent component snapshots.
- set_parameters(params)[source]
Atomically set concentration, weights, and component snapshots.
- density(x)[source]
Density of the mixture at observation x; see log_density().
- log_density(x)[source]
Mixture log-density log sum_k w_k p(x | theta_k) at observation x.
- expected_log_density(x)[source]
Mixture log-density with each component’s plug-in log-density replaced by its variational expectation E_q[log p(x | theta_k)].
- seq_log_density(x)[source]
Vectorized log-density at sequence-encoded input x.
- posterior(x)[source]
Return the component posterior
p(z = k | x)at a single observation.This is the plug-in mixture posterior consistent with
log_density():softmax_k( log p(x | theta_k) + log w_k ). An observation with no support under any component returns an all-zero responsibility vector. Returns a length-K array summing to one for possible evidence and zero otherwise.
- seq_posterior(x)[source]
Vectorized component posterior over a sequence-encoded input.
Returns an
(sz, K)array whose rowiis the plug-in posteriorp(z = k | x_i)(seeposterior()); rows for observations with no support under any component receive zero responsibility.
- seq_local_elbo(x)[source]
Per-observation local ELBO contributions.
For each observation i this returns
sum_k phi_ik * ( E_q[log p(z_i = k | v)] + E_q[log p(x_i | theta_k)] - log phi_ik )
where phi_i is the optimal variational assignment for x_i. The global (data-independent) ELBO terms are returned by
DirichletProcessMixtureEstimator.model_log_density.
- seq_expected_log_density(x)[source]
Vectorized expected_log_density() at sequence-encoded input x.
- latent_posterior(x)[source]
Return a typed latent posterior or reject zero-probability evidence.
- density_semantics()[source]
Return exact-or-approximate density semantics joined from component models.
- sampler(seed=None)[source]
Create a DirichletProcessMixtureSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
DirichletProcessMixtureSampler
- estimator(pseudo_count=None)[source]
Create a DirichletProcessMixtureEstimator from this distribution’s components.
- Parameters:
pseudo_count (float | None)
- Return type:
DirichletProcessMixtureEstimator
- dist_to_encoder()[source]
Returns a DirichletProcessMixtureDataEncoder delegating to the components.
- Return type:
DirichletProcessMixtureDataEncoder
- class DirichletProcessMixtureEstimator(estimators, name=None, prior=default_prior, pseudo_count=None, keys=(None, None))[source]
Bases:
ParameterEstimatorEstimates a DirichletProcessMixtureDistribution by mean-field variational Bayes from accumulated assignment statistics.
- Parameters:
- accumulator_factory()[source]
Returns a DirichletProcessMixtureAccumulatorFactory for this estimator.
- Return type:
DirichletProcessMixtureAccumulatorFactory
- get_prior()[source]
Return the Gamma hyper-prior on the concentration alpha.
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Set the Gamma hyper-prior on the concentration alpha.
- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- model_log_density(model)[source]
Data-independent ELBO terms of the variational approximation.
Combines the cross-entropies of the stick-fraction prior and the component priors against their variational posteriors with the entropies of those posteriors. Together with
DirichletProcessMixtureDistribution.seq_local_elbothis forms the full ELBO maximized by the fit driver.- Parameters:
model (DirichletProcessMixtureDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a DirichletProcessMixtureDistribution by one VB M-step.
Re-estimates each component (whose conjugate update carries its posterior forward as its prior), re-sorts components by expected count, updates the variational Beta posteriors gamma_k on the stick fractions, updates the Gamma hyper-posterior on the concentration alpha (carried as the returned distribution’s prior), and converts the expected log stick fractions into the mixture weights w.
- Parameters:
- Returns:
Fitted Dirichlet-process mixture approximation.
- Return type:
DirichletProcessMixtureDistribution
- class HierarchicalDirichletProcessMixtureDistribution(components, beta, alpha, gamma, group_weights=None, name=None, len_dist=None, group_ids=None)[source]
Bases:
SequenceEncodableProbabilityDistributionTruncated hierarchical DP mixture over K shared atoms with global weights beta and (optionally) fitted per-group weights.
- Parameters:
- get_parameters()[source]
Return beta, concentrations, and independent component snapshots.
- set_parameters(params)[source]
Atomically replace beta, concentrations, and complete component snapshots.
- group_weight(group)[source]
Return the fitted row for
group, or global beta for an unseen group.
- density_semantics()[source]
Return density semantics for the expected-weight HDP mixture approximation.
- log_density(x)[source]
Score a group with the global weights beta (expected weights of a new group).
- seq_encode(x)[source]
Encode groups into a flat component encoding with offsets.
- Parameters:
x (Sequence[Sequence]) – Iterable of groups (sequences of observations).
- Returns:
Tuple
(group_ids, lengths, offsets, flat_enc, len_enc)consumed by vectorizedseq_*methods.- Return type:
- seq_log_density(x)[source]
Vectorized log_density() at sequence-encoded input x (each group scored with the global weights beta).
- seq_local_elbo(x)[source]
Per-group data term of the penalized objective: training groups are scored with their own fitted weights. Falls back to beta when the group count does not match the fit.
- group_posteriors(x)[source]
Posterior atom-usage (mean responsibility) per group.
Groups are scored with their fitted weights when available (else with the global weights beta).
- sampler(seed=None)[source]
Create a HierarchicalDirichletProcessMixtureSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
HierarchicalDirichletProcessMixtureSampler
- estimator(pseudo_count=None)[source]
Create a HierarchicalDirichletProcessMixtureEstimator from this distribution’s components, concentrations, and length estimator.
- Parameters:
pseudo_count (float | None)
- Return type:
HierarchicalDirichletProcessMixtureEstimator
- dist_to_encoder()[source]
Returns a HierarchicalDirichletProcessMixtureDataEncoder for this distribution.
- Return type:
HierarchicalDirichletProcessMixtureDataEncoder
- class HierarchicalDirichletProcessMixtureEstimator(estimators, gamma=1.0, alpha=1.0, name=None, keys=None, len_estimator=None)[source]
Bases:
ParameterEstimatorEstimates a HierarchicalDirichletProcessMixtureDistribution from accumulated group counts via the direct-assignment truncation updates.
- Parameters:
- accumulator_factory()[source]
Returns a HierarchicalDirichletProcessMixtureAccumulatorFactory for this estimator.
- Return type:
HierarchicalDirichletProcessMixtureAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model parameters under the HDP priors.
Sums the Dirichlet(gamma/K) log-density of the global weights beta, the Dirichlet(alpha*beta) log-density of each fitted group’s weights on the exact active global support, and each atom estimator’s model_log_density of its atom. Together with seq_local_elbo this forms the penalized objective maximized by the fit driver.
- Parameters:
model (HierarchicalDirichletProcessMixtureDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a HierarchicalDirichletProcessMixtureDistribution.
Re-estimates each atom (whose conjugate update carries its posterior forward as its prior), updates the global weights beta via the expected-table-count approximation followed by the Dirichlet(gamma/K +
m_.k) posterior mean, and sets each group’s weights to the Dirichlet(alpha*beta) posterior mean (deliberately the mean, not the MAP, which degenerates when alpha*beta_k < 1).- Parameters:
- Returns:
Fitted hierarchical Dirichlet-process mixture approximation.
- Return type:
HierarchicalDirichletProcessMixtureDistribution
- class HDPGroup(group_id, values)[source]
Bases:
objectA grouped observation with a stable user-supplied identity.
- class PitmanYorProcessDistribution(alpha=1.0, discount=0.0, num_elements=None, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionPitman-Yor process over set partitions with concentration alpha and discount in [0, 1).
Data type: List[int] (a cluster-label vector partitioning n elements). discount = 0 is the Dirichlet process / Chinese Restaurant Process.
- Parameters:
- classmethod compute_capabilities()[source]
Return compute-backend metadata for Pitman-Yor EPPF evaluation.
- density(x)[source]
Return the probability of a partition (cluster-label vector) x.
- log_density(x)[source]
Return the log-probability of a partition (cluster-label vector) x.
- seq_log_density(x)[source]
Return vectorized log-probabilities for a sequence of block-size arrays.
- sampler(seed=None)[source]
Return a sampler for drawing partitions from this distribution.
- Parameters:
seed (int | None)
- Return type:
PitmanYorProcessSampler
- estimator(pseudo_count=None)[source]
Return an estimator that fits alpha (and optionally the discount).
- Parameters:
pseudo_count (float | None)
- Return type:
PitmanYorProcessEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
PitmanYorProcessDataEncoder
- class PitmanYorProcessEstimator(discount=0.0, estimate_discount=False, max_alpha=1.0e6, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the Pitman-Yor concentration alpha and (optionally) discount.
- Parameters:
- accumulator_factory()[source]
Return a factory for Pitman-Yor sufficient-statistic accumulators.
- Return type:
PitmanYorProcessAccumulatorFactory
- sample(model, size=None, *, seed=None, rng=None, **kwargs)[source]
Draw sample(s) from any samplable mixle object.
- Parameters:
model (Any) – a distribution, conjugate posterior,
Relation,FieldPosteriororLatentPosterior.size (int | None) –
Nonereturns a single draw in the object’s natural type; a non-negative integer returns a collection (an array for homogeneous leaves, a list / dict-of-arrays for structured draws). Zero returns an empty collection in that natural collection type.seed (int | None) – scalar seed for the draw. Mutually exclusive with
rng.rng (RandomState | None) – a shared
RandomStatefor reproducible, composable streams. Mutually exclusive withseed.**kwargs (Any) – forwarded to the underlying sampler – e.g.
temperature/k/uniformfor a relation,nodesfor a field posterior,batchedfor a distribution.
- Returns:
A single draw (
size=None) or a collection ofsizedraws.- Raises:
TypeError – if
modelis not a recognized samplable object, ifsizeis not an integer orNone, or if bothseedandrngare supplied (two randomness sources are ambiguous – the same double-supply policy as the constructor keyword aliases).ValueError – if
sizeis negative.
- Return type:
- seq_encode(data, encoder=None, estimator=None, model=None, num_chunks=1, chunk_size=None)[source]
Sequence encode a sequence of iid observations from a distribution corresponding to ‘encoder’.
Takes data of type Union[Sequence[T], pyspark.rdd.RDD], where the data type of the DataSequenceEncoder object’s corresponding distribution is type T.
If not RDD, returns a List[Tuple[int, T1]], with each list entry being a tuple containing the number of observations in the sequence (chunk_size), and an encoded sequence of the observations having type T1. The list has length num_chunks.
RDD version with receive the Tuple of chunk_size and encoded data of type T1 for each corresponding node.
- Parameters:
data (Union[Sequence[T], pyspark.rdd.RDD]) – Sequence of iid observations of data type consistent with ‘encoder’.
encoder (Optional[DataSequenceEncoder]) – A DataSequenceEncoder object for sequence encoding iid sequences.
estimator (Optional[ParameterEstimator]) – An estimator to create DataSequenceEncoder from.
model (Optional[SequenceEncodableProbabilityDistribution]) – A distribution to create DataSequenceEncoder from.
num_chunks (int) – Number of chunks to split the data into. Useful for distributed data sets.
chunk_size (Optional[int]) – Approximate size of chunks to determine num_chunks above.
- Returns:
Encoded data ready for vectorized
seq_*methods.- Return type:
- seq_log_density(enc_data, estimate)[source]
Vectorized evaluation of ‘estimate’ log-density for each observation in enc_data.
If ‘estimate’ is input as a List of numpy arrays. Each list entry corresponds to the seq_log_density calls of all the encoded data for each List entry of estimate.
If ‘estimate’ is a single SequenceEncodableProbabilityDistribution instance. The log_density of every observation in the ‘enc_data’ data set is returned as a list.
- Parameters:
enc_data (Union[List[Tuple[int, T]], 'pyspark.rdd.RDD']) – Sequence encoded data of format matching output of seq_encode() function.
estimate (SequenceEncodableProbabilityDistribution) – Distribution to use for log_density evaluations. Must be consistent with enc_data.
- Returns:
List[np.ndarray[float]] or List[float] depending on input.
- Return type:
list[np.ndarray]
- seq_log_density_sum(enc_data, estimate)[source]
Vectorized evaluation of total count and total log-density over encoded data.
The returned pair contains the observation count represented by
enc_dataand the sum oflog_densityover those encoded observations.- Parameters:
enc_data (Union[List[Tuple[int, T]], 'pyspark.rdd.RDD']) – Sequence encoded data of format matching output of seq_encode() function.
estimate (SequenceEncodableProbabilityDistribution) – Distribution to use for log_density evaluations. Must be consistent with enc_data.
- Returns:
Tuple of sum of total obs, and sum of log_density of estimate at all encoded data observations.
- Return type:
- log_density(data, model)[source]
Per-observation log-density of ‘model’ over raw (unencoded) ‘data’.
Convenience wrapper that encodes ‘data’ with the model’s own encoder, evaluates the vectorized seq_log_density, and returns a single flat numpy array aligned to the input order – the common need that otherwise requires the seq_encode / seq_log_density / np.concatenate boilerplate. For a distributed RDD the densities are collected to the driver in partition order.
- Parameters:
data (Union[Sequence[T], pyspark.rdd.RDD]) – Raw iid observations of data type consistent with ‘model’.
model (SequenceEncodableProbabilityDistribution) – Distribution to score the observations under.
- Returns:
np.ndarray of per-observation log-densities.
- Return type:
np.ndarray
- density(data, model)[source]
Per-observation density of ‘model’ over raw (unencoded) ‘data’.
Exponentiated companion to log_density(); returns a flat numpy array of densities aligned to the input order.
- Parameters:
data (Union[Sequence[T], pyspark.rdd.RDD]) – Raw iid observations of data type consistent with ‘model’.
model (SequenceEncodableProbabilityDistribution) – Distribution to score the observations under.
- Returns:
np.ndarray of per-observation densities.
- Return type:
np.ndarray
- load_models(x)[source]
Reconstruct a model or collection of models from dump_models() JSON.
- Parameters:
x (str)
- dump_models(x, *, verify=True)[source]
Serialize a stats model or collection of models to safe strict JSON.
The JSON is read back through
load_models()before it is returned, and a failure is raised here rather than handed to whoever later tries to load it. Encoding on its own does not establish that: the encoder accepts any registered class’s__dict__, while the decoder also requires that state to reconstruct through the class’s own constructor. Families whose estimator pins a fit annotation onto the fitted object, and families whose state names a parameter differently from the constructor’s, encode cleanly and then refuse to load – so without this checkdump_modelsreturns text thatload_modelscannot read, and the bill arrives in another process on another day.mixle.propose()(andmixle.Model) return aModelwrapper, not a stats model: passmodel.fitted, the fitted distribution it wraps, rather than the wrapper itself, which is not registered for serialization and is refused with aSerializationErrornamingregister_serializable_callable(a detour meant for user callables, not for this).Pass
verify=Falsefor text wanted to inspect rather than to reload; the JSON is byte-identical either way and only the read back is skipped. It is the way to get at the parameters of a model whose family has no working decoder yet, since the written state is complete even when the reader refuses it.
- class DistributionEnumerator(dist)[source]
Bases:
ABCLazy iterator over the support of dist in non-increasing probability order.
- Yields (value, log_prob) pairs, possibly infinitely many. Contract:
Each support value is yielded exactly once (deduplication is the enumerator’s responsibility).
log_prob equals dist.log_density(value) up to float round-off (~1e-10), and the sequence of log_probs is non-increasing up to the same tolerance.
Values with zero probability are skipped, never yielded.
Ties are broken deterministically by insertion order; no further guarantee.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
- top_k(k)[source]
Return the k most probable (value, log_prob) pairs (fewer if the support is smaller).
- top_p(p, max_items=None)[source]
Return the smallest descending-probability prefix whose total probability reaches
p.The nucleus / minimal high-probability set: because values are yielded in non-increasing probability order, the returned prefix is a minimum-size set of outcomes whose summed mass is
>= p(e.g.p=0.95gives a 95%-coverage support set – the discrete analogue of nucleus sampling). Accumulation stops as soon as the cumulative probability reachesp.max_itemscaps how many values are pulled so an infinite or heavy-tailed support cannot run away. A cap is mandatory when the support has no known finite cardinality. The returned list-compatibleNucleusResultreports whether the target was reached, the accumulated mass, and whether a cap stopped the search.
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Precompute a bounded bit-quantized index over this enumeration.
The index groups values by floor((-log2 p(x)) / bin_width_bits), includes only values with -log2 p(x) <= max_bits, and returns exact log probabilities for indexed values. Building the index consumes this enumerator.
- rank(value)[source]
Rank and cumulative probability of
valuein the descending-probability order.Returns a
DensityRankResultwith.rank(0-based count of strictly-more-probable outcomes;Noneif only the sampling estimate was used) and.cumulative_probability(G(value) = P(p(Y) >= p(value))). Exact head enumeration where the support is countable, with a Monte-Carlo fallback for the deep tail.- Parameters:
value (Any)
- seek(index)[source]
The value at descending-probability
index(0-based) – the inverse ofrank().Returns a
CountDPSeekResultcarrying the value and a provable[rank_lower, rank_upper]bracket. Uses the structural count-DP for decomposable families, so arbitrarily deep indices are reachable without enumerating the prefix.- Parameters:
index (int)
- seek_certified(index)[source]
The value at descending
indexwith a GUARANTEED bracket on its TRUE marginal rank.Unlike
seek()– whose bracket bounds only the tropical rank for a marginal family (mixture/HMM) – this widens the rank window by the family’stropical_displacement_bitsand divides out the component over-count, so the returnedMarginalSeekResult[true_rank_lower, true_rank_upper]provably contains#{u : log p(u) > log p(value)}. It pins the rank exactly (.exact) for decomposable / provably-disjoint families and for shallow indices, and otherwise returns the certified provable envelope. For a decomposable family it agrees withseek().- Parameters:
index (int)
- cumulative(value)[source]
G(value) = P(p(Y) >= p(value))– total mass of outcomes at least as probable asvalue.Returns a
CumulativeProbabilityResultwith.probabilityplus explicit certification (.exact,.dropped_upper) of what that figure rests on.- Parameters:
value (Any)
- nucleus_size(p)[source]
Size of
top_p()(the minimal>= p-mass set) WITHOUT materializing it.Returns a
CountDPTopPResultwith a provable size bracket, from the structural count-DP – usable when the nucleus is far too large to list.- Parameters:
p (float)
- from_index(start, stop=None)[source]
Iterate
(value, log_prob)in descending-probability order starting at structuralstart.Yields the same stream as iterating a fresh enumerator but beginning at index
start(and ending beforestopif given). A fresh underlying enumeration is used, so this does not consumeself. (Decomposable families admit a direct structural jump via the count-budget index; the current implementation skips the best-first prefix – the structural fast path is a WS-3 performance follow-up.)
- exception EnumerationError(dist, path='', reason='')[source]
Bases:
NotImplementedErrorRaised when a distribution (or a child of a combinator) cannot enumerate its support.
The path argument identifies the offending child within a combinator, e.g. ‘CompositeDistribution.dists[1]’.
- class NucleusResult(items, *, target_probability, cumulative_probability, reached_target, capped, exhausted)[source]
Bases:
list[tuple[Any,float]]List-compatible nucleus prefix with explicit termination provenance.
- exception KeyValidationError[source]
Bases:
ValueErrorRaised when keyed sufficient-statistic sites are incompatible.
A key denotes an equality constraint across model sites. Sites sharing a key must therefore have the same accumulator family and compatible estimator settings before their sufficient statistics are pooled.
- validate_estimator_keys(estimator)[source]
Validate keyed estimator and accumulator sites before EM folds stats.
The validator catches the classic keying footgun: two different families, or two sites with incompatible estimator settings, accidentally sharing the same key string. Validation is intentionally protocol-level and best-effort; a family can still perform stricter checks in its own factory if needed.
- Parameters:
estimator (ParameterEstimator)
- Return type:
None
- encoded_nbytes(x)[source]
Return an approximate byte size for nested encoded array payloads.
Encoders mostly return arrays or tuples/lists/dicts of arrays. The helper keeps accounting structural and deterministic; Python object overhead is included only for scalar leaves where no array-native byte count exists.
- scale_suff_stat(x, c)[source]
Return
xwith numeric sufficient-statistic leaves multiplied byc.
- class EncodedData(count, payload, engine, nbytes, encoder=None)[source]
Bases:
objectA one-chunk encoded payload with planner-visible metadata.
- Parameters:
- classmethod from_payload(payload, count, encoder=None, engine=None)[source]
Wrap an already encoded payload with count, engine, and byte metadata.
- class ResidentEncodedPayload(host_payload, engine_payload)[source]
Bases:
objectPair a host encoding with a resident engine encoding for one chunk.
- as_encoded_data(payload, count, encoder=None, engine=None)[source]
Wrap an existing encoded payload with count, engine, and byte metadata.
- move_encoded_payload(payload, engine)[source]
Move numeric encoded arrays into
enginewhile preserving object fields.Encoders remain backend-agnostic and produce their historical Python/NumPy payloads. Orchestrators can call this exactly once after encoding a shard so scoring kernels see resident engine arrays. Object/string arrays and non-array Python metadata stay on the host because many distribution encodings intentionally carry labels, maps, or structural metadata.
- class DistributionCapabilities(engine_ready=('numpy',), kernel_status='generic', numpy_only_reason=None)[source]
Bases:
objectRuntime capability metadata for a distribution family.
- supports_engine(engine)[source]
Return whether this metadata allows execution on
engine.
- property is_permanently_numpy_only: bool
Return true for families intentionally excluded from tensor engines.
- capabilities_for(x)[source]
Return registered capabilities for a distribution instance or class.
- Parameters:
x (Any)
- Return type:
DistributionCapabilities
- numpy_only_distribution_types()[source]
Return families intentionally kept on the NumPy execution path.
This excludes transitional
legacy_numpyfamilies: those may gain backend declarations later. The returned families have permanent distribution-owned reasons explaining why generic tensor engines are not a good fit.
- register_capabilities(dist_type, capabilities)[source]
Register capability metadata for a class, rejecting accidental replacement.
- registered_capability_types()[source]
Return distribution classes with explicitly registered capabilities.
- supported_engines(x)[source]
Return engine names supported by a distribution instance or class.
- class DistributionDeclaration(name, distribution_type, parameters, statistics, support, children=(), child_roles=(), differentiable=True, exponential_family=None, legacy_sufficient_statistics=None)[source]
Bases:
objectMetadata needed by generated kernels and future autograd paths.
- Parameters:
name (str)
parameters (tuple[ParameterSpec, ...])
statistics (tuple[StatisticSpec, ...])
support (str)
children (tuple[DistributionDeclaration, ...])
differentiable (bool)
exponential_family (ExponentialFamilySpec | None)
legacy_sufficient_statistics (Callable[[Any, dict[str, Any], Any], tuple[Any, ...]] | None)
- parameter_values(dist)[source]
Extract declared parameter values from a distribution instance.
- statistic_values(suff_stat)[source]
Map a legacy accumulator value into declared statistic names.
- property statistic_names: tuple[str, ...]
Return declared sufficient-statistic names in accumulator order.
- property has_exponential_family: bool
Return whether generated exponential-family scoring is available.
- class ExponentialFamilySpec(sufficient_statistics, natural_parameters, log_partition, base_measure=None, sufficient_statistics_from_params=None, base_measure_from_params=None, legacy_sufficient_statistics=None, analytic_mean_parameters=None, log_partition_from_natural=None, fixed_base=True, runtime_scoring=True)[source]
Bases:
objectConditional exponential-family pieces for generated scalar scoring.
- Parameters:
sufficient_statistics (Callable[[Any, Any], tuple[Any, ...]])
natural_parameters (Callable[[dict[str, Any], Any], tuple[Any, ...]])
sufficient_statistics_from_params (Callable[[Any, dict[str, Any], Any], tuple[Any, ...]] | None)
base_measure_from_params (Callable[[Any, dict[str, Any], Any], Any] | None)
legacy_sufficient_statistics (Callable[[Any, dict[str, Any], Any], tuple[Any, ...]] | None)
analytic_mean_parameters (Callable[[dict[str, Any], Any], Any] | None)
log_partition_from_natural (Callable[[Any, Any], Any] | None)
fixed_base (bool)
runtime_scoring (bool)
- runtime_scoring: bool = True
Whether the generated exp-family form may drive runtime scoring (scalar + stacked + numba).
Set
Falsewhen the canonical<eta, T(x)>dot form is numerically unsafe as a runtime scorer even though the family is a valid exponential family. The motivating case is the categorical:eta = log(p)has-infentries for zero-probability categories, so the generic dot product hits0 * -inf = NaNfor observations of other categories (its ownseq_log_densityavoids this by indexing). Withruntime_scoring=Falsethe family keeps itsbackend_*scoring path whileto_exponential_familystill exposes the canonical map (valid wherep > 0).
- class ParameterSpec(name, constraint='real', differentiable=True)[source]
Bases:
objectA fitted distribution parameter used by scoring.
Constraints are interpreted by generic generated/scoring utilities. In addition to scalar constraints such as
positiveand vector/matrix constraints such assimplex_vector,row_simplex_matrix, andcolumn_simplex_matrix,greater_than:<parameter>marks a coupled ordered bound.
- class StatisticSpec(name, kind='moment', additive=True, scales=True)[source]
Bases:
objectA sufficient-statistic entry produced by accumulation.
- exception BackendCapabilityUnavailableError[source]
Bases:
BackendScoringErrorRaised only when neither a backend hook nor generated scorer exists.
- exception BackendScoringError[source]
Bases:
NotImplementedErrorCompatibility base for an explicit backend-scoring capability decline.
- backend_log_density_sum(dist, enc, engine=NUMPY_ENGINE)[source]
Return the total log likelihood for one encoded payload.
- backend_seq_component_log_density(dist, enc, engine=NUMPY_ENGINE)[source]
Return component log densities when a distribution exposes them.
- backend_seq_log_density(dist, enc, engine=NUMPY_ENGINE)[source]
Return per-row log densities using
engineand distribution-local math.
- declaration_issues(x)[source]
Return structural issues in a distribution declaration.
This is intentionally schema-level validation: it checks names, constraints, child roles, and callable exponential-family pieces without importing or special-casing concrete distribution implementations.
- declaration_for(x)[source]
Return a declaration for a distribution instance or class, if present.
- Parameters:
x (Any)
- Return type:
DistributionDeclaration | None
- declared_distribution_types()[source]
Return classes that currently have declarations.
- exception GeneratedKernelCompilationError[source]
Bases:
RuntimeErrorA declared generated kernel failed to trace or compile unexpectedly.
- generated_log_density_diagnostics(x, encoded_symbols=None)[source]
Trace a generated scalar log-density formula with the symbolic engine.
The returned dictionary contains the symbolic expression string, referenced data/parameter symbols, operation counts, and expression depth. This is an author-facing inspection tool for declaration-generated kernels; it does not select or execute a runtime backend.
- generated_log_density(dist, enc, engine)[source]
Return per-row log densities from declaration-owned scoring metadata.
This is the single-distribution counterpart of
generated_stacked_log_density. It gives generic kernels an engine-aware fallback before they drop to legacy NumPyseq_log_densitymethods, and it stays fully metadata-driven: no caller imports or switches on concrete distribution implementations.
- generated_stacked_available(dist_type)[source]
Return true when declarations can generate stacked leaf scoring.
- generated_stacked_log_density(enc, params, engine)[source]
Return an
(n, k)log-density matrix from declaration-stacked params.
- generated_stacked_params(dists, engine)[source]
Stack declared distribution parameters for generated homogeneous-mixture scoring.
The generated path is intentionally conservative: it supports scalar, vector, or matrix per-component parameters that can be broadcast over per-row encoded fields. Non-differentiable support metadata such as integer bounds must still be shared across components unless a family keeps an explicit
backend_stacked_*route.
- generated_stacked_preferred(dist_type)[source]
Return true when a family explicitly opts into declaration-generated scoring.
- generated_stacked_strategy(dist_type)[source]
Describe the declaration-generated stacked scoring route for a family.
- generated_sufficient_statistics(dist, enc, weights, engine)[source]
Return legacy sufficient statistics from declaration-owned row stats.
This is the single-distribution analogue of
generated_stacked_sufficient_statistics. It performs row-wise sufficient-statistic algebra on the active engine, then converts only the small legacy payload back across the boundary for the existing estimator M-step.
- generated_sufficient_statistics_available(x)[source]
Return true when a declaration can generate single-distribution stats.
- generated_numba_log_density(dist, enc)[source]
Return per-row log densities from a declaration-generated numba loop.
The generated loop evaluates the exponential-family form
base(x) + T(x) dot eta(theta) - A(theta). Distribution declarations still own the statistical metadata; this helper only lowers the row fold to a nopython scalar loop.
- generated_numba_log_density_available(x)[source]
Return true when declarations can emit a generated numba leaf scorer.
Exponential-family leaves use the stacked exp-family loop; other leaves with a
backend_log_density_from_paramshook whose per-row formula lowers cleanly to a numba scalar loop (single encoded array, supported ops, scalar parameters) use the generic symbolic-to-numba compiler in_build_generic_numba_kernel().
- generated_numba_stacked_log_density(enc, params)[source]
Return an
(n, k)score matrix from a declaration-generated numba loop.
- generated_numba_stacked_available(x)[source]
Return true when declarations can emit a generated stacked numba scorer.
- generated_stacked_sufficient_statistics(enc, weights, params, engine)[source]
Return component-stacked legacy sufficient statistics from declarations.
- generated_stacked_sufficient_statistics_available(x)[source]
Return true when a declaration can generate resident stacked stats.
- register_declaration(declaration)[source]
Validate and atomically register one declaration.
Re-registering the same declaration is idempotent. A different declaration for an already registered type is rejected instead of silently changing generated execution semantics process-wide.
- Parameters:
declaration (DistributionDeclaration)
- Return type:
None
- statistic_layout_issues(x, suff_stat)[source]
Return issues mapping a legacy sufficient-statistic payload to a declaration.
This validates the top-level
statistic_values(...)arity and, when a declaration exposes child roles, recursively validates child statistic payloads for tuple/list/map-shaped entries. It stays schema-driven and does not import concrete distribution implementations.
- validate_declaration(x)[source]
Return a declaration or raise
ValueErrorwith schema issues.- Parameters:
x (Any)
- Return type:
DistributionDeclaration
- validate_statistic_layout(x, suff_stat)[source]
Return a declaration or raise
ValueErrorwith statistic-layout issues.
- class RecordDistribution(fields, dists=None)[source]
Bases:
SequenceEncodableProbabilityDistributionProduct distribution over mapping records with a fixed field set.
- Parameters:
fields (Any)
dists (Sequence[SequenceEncodableProbabilityDistribution] | None)
- compute_capabilities()[source]
Return engine support inherited from all child distributions.
- compute_declaration()[source]
Return a child-role declaration for generated metadata consumers.
- density(x)[source]
Return probability density/mass for one mapping record.
- log_density(x)[source]
Return summed child log densities for one mapping record.
- seq_log_density(x)[source]
Return per-row log densities for encoded record fields.
- backend_seq_log_density(x, engine)[source]
Return per-row log densities using backend-aware child scorers.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child parameters for homogeneous named-record mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of record log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy named-record sufficient statistics.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- seq_ld_lambda()[source]
Return legacy sequence log-density callables for this distribution.
- support_size()[source]
Product of field support sizes (
Noneif any field is infinite).- Return type:
int | None
- sampler(seed=None)[source]
Return a sampler that draws mapping records field-by-field.
- Parameters:
seed (int | None)
- Return type:
RecordSampler
- estimator(pseudo_count=None)[source]
Return a record estimator with child estimators from each field.
- Parameters:
pseudo_count (float | None)
- Return type:
RecordEstimator
- decomposition()[source]
Record fields are independent: split along the field (factor) axis, sufficient stats SUM-reduce.
- dist_to_encoder()[source]
Return a data encoder for this record field/source layout.
- Return type:
RecordDataEncoder
- enumerator()[source]
Creates RecordEnumerator iterating mapping records in descending joint probability order.
- Return type:
RecordEnumerator
- conditional_enumerator(given)[source]
Enumerate complete records consistent with the fixed fields in
given.givenis a mapping{source: value}pinning a subset of fields (the canonical most-probable-completion / imputation query: complete missing fields, best first). Because the fields are independent,P(record | given)is proportional to the jointP(record), so descending order over the free fields is also descending conditional order. Each yielded value is a complete record with the fixed fields merged back in, and itslog_probis the full jointlog_density(the enumerator contract:lp == dist.log_density(value)) – the fixed fields enter as a constant offset, which only shifts every score by the same amount.Raises ValueError if
givennames a field this record does not have.
- structural_fine_bucket(value, quantizer)[source]
Sum of child structural buckets – mirrors the count index’s child convolution.
Like
CompositeDistribution.structural_fine_bucket(), but fields are addressed by source name rather than tuple position.- Return type:
- quantized_count_index(quantizer, max_fine_bucket)[source]
Structural count index: the additive law – the carrier’s n-ary product over fields.
Identical reduction to
CompositeDistribution.quantized_count_index()(the joint histogram is the convolution of the per-field histograms in the witness-retaining count semiring); the only difference is that the unranked structural tuple is relabelled into a mapping record keyed by source, so witnesses match what the model actually scores.- Parameters:
max_fine_bucket (int)
- class RecordEstimator(fields, estimators=None)[source]
Bases:
ParameterEstimatorEstimator for independent named fields.
- Parameters:
fields (Any)
estimators (Sequence[ParameterEstimator] | None)
- accumulator_factory()[source]
Return a factory for record sufficient-statistic accumulators.
- Return type:
RecordAccumulatorFactory
- DictRecordDistribution
alias of
RecordDistribution
- DictRecordEstimator
alias of
RecordEstimator
- field(name, source=None)[source]
Declare a named model field and the input key/column it reads.
field('x')reads input key'x'and names the model field'x'. A record is a normalized product law, so every modeled field and every source key must be unique; repeated views belong in an explicit factor model rather than this generative record wrapper.
- record(fields)[source]
Create a
RecordDistributionfrom a field-to-distribution mapping.
- record_estimator(fields)[source]
Create a
RecordEstimatorfrom a field-to-estimator mapping.
- exception EngineNotSupportedError[source]
Bases:
ValueErrorRaised when no kernel can safely evaluate a distribution on an engine.
- class Kernel[source]
Bases:
ABCEvaluation kernel for a fitted distribution.
- abstractmethod score(enc)[source]
Return per-row log densities for an encoded observation batch.
- component_scores(enc)[source]
Return per-row, per-component log densities where meaningful.
- abstractmethod accumulate(enc, weights)[source]
Return sufficient statistics in the legacy estimator format.
- abstractmethod refresh(dist)[source]
Refresh kernel parameters after an EM M-step without rebuilding structure.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
- Return type:
None
- class KernelFactory[source]
Bases:
ABCFactory that builds a Kernel for a distribution and engine.
- abstractmethod build(dist, engine, estimator=None)[source]
Return a kernel for
distonengine.estimatoris optional for pure scoring and required for kernels that need to emit sufficient statistics for an M-step.- Parameters:
dist (SequenceEncodableProbabilityDistribution)
engine (ComputeEngine)
estimator (ParameterEstimator | None)
- Return type:
Kernel
- class GenericKernel(dist, engine=NUMPY_ENGINE, estimator=None)[source]
Bases:
KernelFallback kernel over distribution-owned backend hooks or existing seq_* methods.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
engine (ComputeEngine)
estimator (ParameterEstimator | None)
- score(enc)[source]
Return per-row log densities using backend hooks when available.
- component_scores(enc)[source]
Return per-row component log densities for mixture-like models.
- accumulate(enc, weights)[source]
Accumulate weighted sufficient statistics in estimator-owned format.
- refresh(dist)[source]
Replace the fitted distribution while preserving kernel structure.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
- Return type:
None
- class GenericKernelFactory[source]
Bases:
KernelFactoryGuaranteed fallback factory for distributions that support the engine.
- build(dist, engine, estimator=None)[source]
Build a generic kernel or fail fast when the engine is unsupported.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
engine (ComputeEngine)
estimator (ParameterEstimator | None)
- Return type:
GenericKernel
- class NumbaKernel(dist, engine=NUMPY_ENGINE, estimator=None)[source]
Bases:
KernelKernel adapter over the existing fused-numba
CompiledMixturepath.This kernel intentionally uses the columnar encoding returned by
encode(data)rather than the legacydist_to_encoder().seq_encodepayload. That keeps the high-performance path explicit while giving it the same score/accumulate/refresh surface as other engines.- Parameters:
dist (SequenceEncodableProbabilityDistribution)
engine (ComputeEngine)
estimator (ParameterEstimator | None)
- encode(data)[source]
Encode raw observations into the fused columnar kernel format.
- score(enc)[source]
Return per-row log densities from the fused numba mixture kernel.
- component_scores(enc)[source]
Return per-row, per-component log densities from the fused kernel.
- accumulate(enc, weights)[source]
Use fused posteriors plus row weights to produce legacy statistics.
- refresh(dist)[source]
Refresh parameters after an M-step without rebuilding the compiled object.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
- Return type:
None
- class GeneratedNumbaKernel(dist, engine=NUMPY_ENGINE, estimator=None)[source]
Bases:
KernelGenerated numba kernel from declaration exponential-family metadata.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
engine (ComputeEngine)
estimator (ParameterEstimator | None)
- encode(data)[source]
Encode raw observations with the distribution’s ordinary encoder.
- score(enc)[source]
Return per-row log densities from declaration-generated numba code.
- component_scores(enc)[source]
Return generated component scores for homogeneous generated mixtures.
- accumulate(enc, weights)[source]
Accumulate generated sufficient statistics for leaves or mixtures.
- posteriors(enc)[source]
Return normalized mixture posterior weights for generated mixtures.
- refresh(dist)[source]
Refresh the distribution and regenerated component metadata.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
- Return type:
None
- class NumbaKernelFactory[source]
Bases:
KernelFactoryFactory for generated declaration numba kernels with legacy fused fallback.
- build(dist, engine, estimator=None)[source]
Prefer generated numba kernels, then fused kernels, then stacked fallback.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
engine (ComputeEngine)
estimator (ParameterEstimator | None)
- Return type:
Kernel
- class GeneratedNumbaKernelFactory(fallback=None)[source]
Bases:
KernelFactoryDefault-safe factory that prefers declaration-generated numba kernels.
Unlike
NumbaKernelFactory, this never selects the fusedCompiledMixtureadapter (whose columnar encoding is incompatible with the legacyseq_encodepayloads that the engine estimation path feeds kernels) and never raises: when a generated numba scorer is unavailable, or the engine is not numpy, it defers to a guaranteed fallback (the generic kernel). That makes it safe to register as a default on the kernel dispatch path while still accelerating mixtures of declared exponential-family leaves on the numpy engine.- Parameters:
fallback (KernelFactory | None)
- build(dist, engine, estimator=None)[source]
Build a generated numba kernel on numpy when available, else fall back.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
engine (ComputeEngine)
estimator (ParameterEstimator | None)
- Return type:
Kernel
- class ComponentShardLayout(indices)[source]
Bases:
objectExplicit global component indices represented by one local payload.
- property contiguous: bool
Return whether the indices form one ascending contiguous interval.
- class StackedComponentParams(component_type, strategy, params)[source]
Bases:
objectA generic route for homogeneous component scoring.
- class StackedMixtureResidentStats(component_counts, component_stats, engine, component_type)[source]
Bases:
objectEngine-resident sufficient statistics for a homogeneous mixture.
- Parameters:
- value()[source]
Return sufficient statistics in the legacy
MixtureEstimatorformat.- Return type:
- local_value()[source]
Return this rank’s explicitly indexed component-stat payload.
DTensor-backed model-parallel runs should run component M-steps on the local component shard and all-reduce only scalar mixture-weight totals. This method therefore prefers DTensor
to_local()chunks overfull_tensor(). A contiguous shard retains the legacy integer start; a non-contiguous shard returns its global-index tuple. Every resident statistic tensor must expose the same component layout as the counts.
- estimate(estimator)[source]
Estimate a distribution after converting to the legacy estimator protocol.
- Parameters:
estimator (ParameterEstimator)
- Return type:
- estimate_component_shard(estimator, total_count=None)[source]
Run the component-local part of a mixture M-step for this shard.
Component distributions are independent given posterior sufficient statistics. Mixture weights only need the scalar global total count (or fixed weights), so a model-parallel orchestrator can call this on each shard after an all-reduce of that scalar instead of gathering all component statistics to the driver.
- Parameters:
estimator (ParameterEstimator)
total_count (float | None)
- Return type:
StackedMixtureShardEstimate
- class StackedMixtureShardEstimate(component_indices, components, weights, total_count)[source]
Bases:
objectComponent-local M-step result for a homogeneous mixture shard.
- Parameters:
- property component_start: int
Lowest selected index (legacy contiguous-shard compatibility).
- property component_stop: int
Exclusive upper bound (legacy contiguous-shard compatibility).
- class StackedMixtureKernel(dist, engine, estimator=None)[source]
Bases:
KernelHomogeneous mixture kernel with stacked component parameters.
The mixture mechanics live here: component matrix scoring, row-wise logsumexp, posterior weights, and legacy sufficient-stat dispatch. The leaf family still owns the actual component log-density math through
backend_stacked_paramsandbackend_stacked_log_density.- Parameters:
dist (Any)
engine (ComputeEngine)
estimator (ParameterEstimator | None)
- encode(data)[source]
Encode raw observations with the mixture’s ordinary encoder.
- component_scores(enc)[source]
Return unweighted component log densities with shape
(n, k).
- score(enc)[source]
Return row log densities after adding mixture log weights.
- posteriors(enc)[source]
Return posterior component weights for each encoded row.
- property has_resident_accumulate: bool
Return true when the leaf family can accumulate sufficient stats on the engine.
- resident_accumulate(enc, weights)[source]
Return engine-resident mixture sufficient statistics.
The mixture owns only the posterior mechanics. Leaf families own the sufficient-statistic algebra through
backend_stacked_sufficient_statistics.
- accumulate(enc, weights)[source]
Return mixture sufficient statistics in the legacy estimator format.
- refresh(dist)[source]
Refresh stacked parameters after an M-step without changing structure.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
- Return type:
None
- class StackedMixtureKernelFactory(fallback=None)[source]
Bases:
KernelFactoryFactory for homogeneous mixtures with distribution-owned stacked math.
- Parameters:
fallback (KernelFactory | None)
- build(dist, engine, estimator=None)[source]
Build a stacked mixture kernel when safe, otherwise use fallback.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
engine (ComputeEngine)
estimator (ParameterEstimator | None)
- Return type:
Kernel
- stacked_component_log_density(enc, route, engine)[source]
Evaluate a route returned by
stacked_component_params.
- stacked_component_params(dists, engine)[source]
Return a generic stacked-scoring route for homogeneous components.
Generated declaration-backed routes are attempted first. Families with object lookups, table layouts, derived parameters, or wrapper structure can keep explicit
backend_stacked_*hooks and still compose through this single dispatcher.
- stacked_component_strategy(dist_type)[source]
Describe how homogeneous mixture component scoring will be dispatched.
- estimate_component_shard_value(estimator, component_selection, value, total_count=None)[source]
Estimate the component-local part of a mixture M-step from an explicit shard value.
- tie_component_shard_values(estimator, shard_values)[source]
Apply mixle key tying to component-sharded mixture statistics.
MixtureAccumulator.key_merge/key_replaceassume a full component vector is materialized on one worker. Component-sharded model-parallel runs instead hold ranges[component_start, component_stop). This helper applies the same key protocol to those local ranges by materializing only the component accumulators owned by each shard.
- register_kernel_factory(dist_type, factory)[source]
Register a specialized kernel factory for a distribution class.
- kernel_for(dist, engine=None, estimator=None)[source]
Build the best registered kernel for
distandengine.- Parameters:
dist (SequenceEncodableProbabilityDistribution)
engine (ComputeEngine | None)
estimator (ParameterEstimator | None)
- Return type:
Kernel
- class BernoulliDistribution(p, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBernoulli distribution over {False, True} with success probability p.
- Parameters:
- classmethod compute_capabilities()[source]
Describe backend support for generated Bernoulli kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Bernoulli distributions.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Bernoulli sufficient statistics for generated scoring.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Bernoulli sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Bernoulli natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Bernoulli log partition for generated scoring.
- set_prior(prior)[source]
Attach a Beta parameter prior and precompute conjugate-prior expectations.
With a Beta(a, b) prior on the success probability
pthis caches the digamma terms so thatexpected_log_densityevaluates the variational Bayes expectationE_q[log p(x | p)]viaE[log p] = digamma(a) - digamma(a+b)andE[log(1-p)] = digamma(b) - digamma(a+b). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation
E_q[log p(x | p)]under the Beta prior.Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, p, engine)[source]
Engine-neutral Bernoulli log-mass from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Bernoulli parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Bernoulli log masses.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Bernoulli sufficient statistics using engine-resident arrays.
- to_fisher(**kwargs)[source]
Return the Bernoulli’s count-family Fisher view.
- cdf(x)[source]
Cumulative distribution function P(X <= x) over {0, 1}.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
BernoulliSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
BernoulliEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
BernoulliDataEncoder
- enumerator()[source]
Return an enumerator over the distribution support when available.
- Return type:
BernoulliEnumerator
- class BernoulliEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate a Bernoulli distribution from weighted success counts.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Bernoulli sufficient statistics.
- Return type:
BernoulliAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s success probability under the Beta prior (ELBO global term).
- Parameters:
model (BernoulliDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate the Bernoulli success probability from weighted counts.
The distribution is defined on the open interval (0, 1), so a sample that is all successes or all failures – whose maximum-likelihood
pis exactly 1 or 0 – is clamped_P_BOUNDARY(1e-12) away from the endpoint. When that clamp binds it is reported on the returned model throughnumerical_repairs()asbernoulli-p-clamped(...), and so throughfit_provenance().repairs; an ordinary fit whosepis already interior records nothing.
- class BernoulliEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate False/True in descending probability order.
- Parameters:
dist (BernoulliDistribution)
- class BetaDistribution(a, b, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBeta distribution with positive shape parameters a and b.
- classmethod compute_capabilities()[source]
Describe backend support for generated Beta kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Beta distributions.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Beta sufficient statistics for generated scoring.
Scoring needs only
log_xandlog1m_x(the two natural-parameter partners). The encoder emits the full(log_x, log1m_x, x, x**2)tuple for the M-step, while the symbolic generator supplies just the two scoring symbols frombackend_log_density_from_params; indexing the leading two works for both arities.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Beta sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Beta natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Beta log partition for generated scoring.
- get_parameters()[source]
Return the (a, b) shape pair.
Lets a BetaDistribution serve as a conjugate prior (on a Bernoulli/Geometric/Binomial success probability) under the unified Bayesian estimation protocol.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(log_x, log1m_x, a, b, engine)[source]
Engine-neutral Beta log-density from encoded logs and parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Beta parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Beta log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- entropy()[source]
Differential entropy ln B(a,b) - (a-1)psi(a) - (b-1)psi(b) + (a+b-2)psi(a+b).
- Return type:
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
BetaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
BetaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
BetaDataEncoder
- class BetaEstimator(pseudo_count=None, suff_stat=None, delta=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate beta shape parameters from weighted log-moment statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Beta sufficient statistics.
- Return type:
BetaAccumulatorFactory
- class LaplaceDistribution(mu, b, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLaplace distribution with location mu and scale b > 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated Laplace kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Laplace distributions.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, mu, b, engine)[source]
Engine-neutral Laplace log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Laplace parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Laplace log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return per-component raw weighted observations using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
LaplaceSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
LaplaceEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
LaplaceDataEncoder
- class LaplaceEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorExact weighted-MLE estimator for Laplace location and scale.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Laplace raw-observation statistics.
- Return type:
LaplaceAccumulatorFactory
- class LogisticDistribution(loc=0.0, scale=1.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLogistic distribution with location loc and scale > 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated logistic kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for logistic distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Logistic sufficient statistics in accumulator order.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, loc, scale, engine)[source]
Engine-neutral logistic log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked logistic parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of logistic log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
LogisticSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
LogisticEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
LogisticDataEncoder
- class LogisticEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorMoment estimator for logistic location and scale.
The likelihood MLE has no closed-form M-step. The EM estimator uses the identities mean=loc and var=pi^2 scale^2 / 3; torch gradient MLE can refine both parameters when exact likelihood optimization is desired.
The variance moment is formed from shift-anchored statistics whenever the accumulated sufficient statistics carry that payload (see
LogisticAccumulator), which makes the fit shift-equivariant: estimating onx + creturnsloc + cwithscaleunchanged. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones restored from an older serialization – the historical raw path is used, bit-identically.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for logistic moment statistics.
- Return type:
LogisticAccumulatorFactory
- class LogSeriesDistribution(p, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLogarithmic (log-series) distribution on k = 1, 2, … with shape parameter p in (0, 1).
- classmethod compute_capabilities()[source]
Describe backend support for generated log-series kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for log-series distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row (count, k) sufficient statistics in accumulator order.
- static exp_family_sufficient_statistics(x, engine)[source]
Return the log-series sufficient statistic
T(k) = (k,).
- static exp_family_natural_parameters(params, engine)[source]
Return the log-series natural parameter
eta = log(p).
- static exp_family_log_partition(params, engine)[source]
Return the log-series log partition
A = log(-log(1 - p)).
- static exp_family_base_measure(x, engine)[source]
Return the log-series base measure
log h(k) = -log(k)(independent of p, fixed base).
- static exp_family_from_natural(eta)[source]
Return the log-series with natural parameter
eta = log(p)(sop = exp(eta)).- Parameters:
eta (Any)
- Return type:
LogSeriesDistribution
- static backend_log_density_from_params(k, log_k, log_p, log_norm, engine)[source]
Engine-neutral log-series log-mass from explicit parameters (linear in k and log k).
- density(x)[source]
Return the probability mass at a single observation.
- log_density(x)[source]
Return the log-mass at a single positive integer (or -inf off support).
- seq_log_density(x)[source]
Return vectorized log-mass values for sequence-encoded (k, log k) observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-mass for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of log-series log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked sufficient statistics using engine-resident arrays.
- entropy()[source]
Shannon entropy in nats, by exact summation of the standard series.
The log-series entropy
-sum_k p_k log p_khas no closed form (Fisher, Corbet & Williams, 1943). The series is summed fromk = 1up to this distribution’s own quantile at1 - 1e-16(plus a safety margin), beyond which the remaining tail mass is far below double rounding.- Return type:
- cdf(x)[source]
Cumulative distribution function
P(X <= x), supportx >= 1.Summed directly in bounded blocks (the series has no closed form); past
_SERIES_CAPterms one minus the Euler-Maclaurin tail mass stands in, exact to double rounding by then and never below the partial sum at the cap, so the result is monotone inxand within[0, 1].
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the smallestkwithP(X <= k) >= q.Summed directly in bounded blocks, never through scipy’s generic discrete
ppf. That search brackets the answer by doubling an upper bound untilcdf(bound) >= q, and the summed CDF can saturate one ULP short of aqthis close to one (numpy’s SIMDexpandloground the last bit differently per CPU: the sum reachedq = 1 - 1e-16atk = 5210on arm64 and emulated x86-64 and never did on AVX-512 hosted CI runners), so the bound doubled without limit and the vectorized CDF sums grew until the 16 GB runner was OOM-killed – throughentropy(), which calls this at exactly thatq. Here a block whose terms no longer move the running sum, or the term cap, ends the scan, and the Euler-Maclaurin tail mass answers for whatever lies beyond: the smallestkpast the scan whose tail mass is at most1 - q.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
LogSeriesSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
LogSeriesEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
LogSeriesDataEncoder
- enumerator()[source]
Return an enumerator over k = 1, 2, … in descending probability order.
- Return type:
LogSeriesEnumerator
- class LogSeriesEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the log-series shape p (inverts the mean -> p relation).
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for log-series count statistics.
- Return type:
LogSeriesAccumulatorFactory
- class BinomialDistribution(p, n, min_val=None, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBinomial distribution over
min_val + {0, ..., n}with success probabilityp.- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for generated Binomial density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Binomial distribution.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Binomial sufficient statistics from encoded observations.
The parameter-dependent support shift is handled by
exp_family_sufficient_statistics_from_paramswhen generated scoring supplies the declaration-stacked parameter bundle.
- static exp_family_sufficient_statistics_from_params(x, params, engine)[source]
Return Binomial sufficient statistics for generated scoring.
- static exp_family_natural_parameters(params, engine)[source]
Return Binomial natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Binomial log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return the observation-only Binomial base measure.
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return Binomial support/base measure for generated scoring.
- set_prior(prior)[source]
Attach a Beta parameter prior and precompute conjugate-prior expectations.
With a Beta(a, b) prior on the success probability
pthis caches(E[log p], E[log(1-p)]) = (digamma(a) - digamma(a+b), digamma(b) - digamma(a+b))so thatexpected_log_densityevaluates the variational Bayes expectationE_q[log p(x | p)]. Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation
E_q[log p(x | p)]under the Beta prior.Uses the cached digamma expectations of
log pandlog(1-p); falls back to the plug-inlog_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Returns the probability mass of integer value x.
If x is not an integer between [0,n) or [min_val, n-1-min_val), density is 0.0.
- log_density(x)[source]
Returns the log-probability mass of integer value x.
If x is not an integer between [0,n) or [min_val, n-1-min_val), log-density is -inf.
- seq_log_density(x)[source]
Vectorized evaluation of log-density for sequence encoded data.
Input value x must be obtained from a call to BinomialDataEncoder.seq_encode(data). Returns numpy array of log-density evaluated at all observations contained in encoded data x.
- static backend_log_density_from_params(vals, n, p, min_val, engine)[source]
Engine-neutral binomial log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked binomial parameters for a homogeneous mixture kernel.
A stacked binomial mixture requires components to share the same trial count and shifted support. Mixtures with heterogeneous supports fall back to the generic kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of binomial log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return stacked Binomial sufficient statistics using estimator-owned support bounds.
- to_fisher(**kwargs)[source]
Return the Binomial’s count-family Fisher view.
- cdf(x)[source]
Cumulative distribution function P(X <= x) over min_val + {0..n}.
- quantile(q)[source]
Inverse CDF F^{-1}(q) over min_val + {0..n} (via scipy binom).
- sampler(seed=None)[source]
Returns BinomialSampler for generating samples from BinomialDistribution(n,p,min_val).
- Parameters:
Optional[int] (seed) – Used to set seed on random number generator for sampling.
seed (int | None)
- Returns:
BinomialSampler for BinomialDistribution with seed.
- Return type:
BinomialSampler
- estimator(pseudo_count=None)[source]
Creates a BinomialEstimator for estimating parameters of BinomialDistribution.
- Parameters:
pseudo_count (Optional[float]) – If set, inflates counts for currently set sufficient statistic (p).
- Returns:
BinomialEstimator object.
- Return type:
BinomialEstimator
- dist_to_encoder()[source]
Create the encoder for sequence-encoded binomial observations.
- Returns:
BinomialDataEncoder object.
- Return type:
BinomialDataEncoder
- enumerator()[source]
Returns BinomialEnumerator iterating the support in descending probability order.
- Return type:
BinomialEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index by walking the binomial mode outward.
- class BetaBinomialDistribution(n, a, b, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBeta-binomial distribution over
{0, ..., n}with shape parametersa, b > 0.- density(x)[source]
Return the probability mass at a single count
x.
- log_density(x)[source]
Return the log probability mass at
x(-infoutside{0, ..., n}or non-integer – a fractional count is not a valid beta-binomial outcome).
- seq_log_density(x)[source]
Return vectorized log-mass for an array of counts (
-infoutside{0, ..., n}or non-integer – a fractional count is not a valid beta-binomial outcome).
- cdf(x)[source]
Cumulative distribution function P(X <= x): a log-space partial sum of the pmf over {0..n}.
- quantile(q)[source]
Inverse CDF F^{-1}(q) over {0..n}: the smallest count whose cdf reaches
q(search on the cdf).
- enumerator()[source]
Returns BetaBinomialEnumerator iterating the support in descending probability order.
- Return type:
BetaBinomialEnumerator
- sampler(seed=None)[source]
Return a sampler for drawing counts from this distribution.
- Parameters:
seed (int | None)
- Return type:
BetaBinomialSampler
- estimator(pseudo_count=None)[source]
Return a method-of-moments estimator for
a, bat the fixed number of trialsn.- Parameters:
pseudo_count (float | None)
- Return type:
BetaBinomialEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
BetaBinomialDataEncoder
- class BetaBinomialEstimator(n, pseudo_count=None, suff_stat=None, min_conc=1.0e-6, max_conc=1.0e8, name=None, keys=None)[source]
Bases:
ParameterEstimatorMethod-of-moments estimator for the beta-binomial shape parameters.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for beta-binomial moments.
- Return type:
BetaBinomialAccumulatorFactory
- class BinomialEstimator(max_val=None, min_val=0, pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate Binomial probability and support parameters from sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Create a BinomialAccumulatorFactory from estimator member variables.
- Returns:
BinomialAccumulatorFactory
- Return type:
BinomialAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s success probability under the Beta prior (ELBO global term).
- Parameters:
model (BinomialDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a binomial distribution from accumulated sufficient statistics.
nobsis accepted for estimator API consistency but is not used. The sufficient statistic is(count, sum, min_val, max_val). When a prior statistic andpseudo_countare present, they shrink the empirical success probability toward the estimator’s prior probability.
- class BinomialEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate bounded Binomial support values in descending probability order.
- Parameters:
dist (BinomialDistribution)
- class CategoricalDistribution(pmap=MISSING, default_value=0.0, name=None, keys=None, prob_map=MISSING, prior=None, scoring_only=False)[source]
Bases:
SequenceEncodableProbabilityDistributionCategorical distribution over hashable labels.
- Parameters:
- classmethod compute_capabilities()[source]
Return compute-backend metadata for categorical scoring.
- classmethod compute_declaration()[source]
Return the symbolic declaration for categorical probability maps.
- static exp_family_sufficient_statistics(x, engine)[source]
Return a shape-only fallback; category-aware statistics come from
..._from_params.
- static exp_family_sufficient_statistics_from_params(x, params, engine)[source]
Return the one-hot label indicator
T(x)of shape(n, K)(zeros for off-support labels).Categories are ordered canonically by
sorted(pmap, key=repr)so the columns line up withexp_family_natural_parameters().
- static exp_family_natural_parameters(params, engine)[source]
Return the natural parameter
eta = log(pmap)over categories in canonical key order.
- static exp_family_log_partition(params, engine)[source]
Return the log partition
A = 0(normalization is carried byeta = log p).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return
log h(x) = 0on the support (a key ofpmap) and-inffor off-support labels.
- get_prior()[source]
Return the conjugate parameter prior over the category-probability simplex (or None).
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a DictDirichlet(alpha) prior over the category probabilities this caches the variational expected log-probabilities E[log p_k] = digamma(alpha_k) - digamma(sum_k alpha_k) for each key of
pmapso thatexpected_log_density(x) = E[log p_x] - log(1 + default_value). A scalar alpha is treated as a symmetric Dirichlet of dimensionlen(pmap). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x)] under the DictDirichlet prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Density evaluation of CategoricalDistribution.
p_mat(x) = p_i, if x in pmap.keys(), else p_mat(x) = default_value.
With
default_value > 0and apmapthat does not cover the full label space, this is a smoothed scoring function, not a normalized probability measure – see thedefault_valuenote on__init__().- Parameters:
x (Any) – Evaluate CategoricalDistribution density value at x.
- Returns:
float density value at x
- Return type:
- density_semantics()[source]
Report what
log_densityactually returns, derived from the parameters.This keys off
is_normalized_probability, so an object whose numbers do not describe a law does not claim to be one (MXR-080-1841). Three shapes reportLIKELIHOOD_FACTOR:scoring_only, the author’s declaration that this is an evaluation-only factor,default_value != 0open-world smoothing, which spreads mass over every unseen label and so has no finite total,a pmap that does not sum to one – including the empty pmap, whose total is zero.
An earlier revision returned
EXACTfor the last two, because_owned_generative_componentsrefusesLIKELIHOOD_FACTORand mixtures, HMMs and segment models in this repository are all built from categoricals of exactly those shapes: a component that won zero responsibility this iteration, the explicit no-evidence state fitted on all-empty sequences, and deliberately unnormalized components. Labelling them honestly made them non-composable, so the label was bent instead. That was the wrong half to bend: composition inconvenience cannot turn a non-law into an exact law.The composition layer now decides admissibility for itself, by asking a factor whether it differs from a law only by scale (see
composable_as_componentand_owned_generative_components), so both questions get a truthful answer.
- composable_as_component()[source]
Whether a latent model may use this factor as a component (MXR-080-1841).
A mixture, HMM or segment model normalizes responsibilities across components, so a component that differs from a law by a positive constant scale is absorbed into its own mixing weight and leaves the E-step unchanged; a zero-mass component simply wins no responsibility. A categorical is a lookup over a discrete support, so an unnormalized or empty pmap is exactly such a scaled law and stays admissible.
scoring_onlyis not: it is an author’s declaration that the object is not generative at all, and a declaration is not something the composition layer may reason its way around.- Return type:
- log_density(x)[source]
Log-Density evaluation of CategoricalDistribution.
log(p_mat(x)) = log(p_i), if x in pmap.keys(), else log(p_mat(x)) = log(default_value).
With
default_value > 0and apmapthat does not cover the full label space, this is a smoothed scoring function, not a normalized probability measure – see thedefault_valuenote on__init__().- Parameters:
x (Any) – Evaluate CategoricalDistribution density value at x.
- Returns:
Log-density of Categorical distribution evaluated at x.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of log-density for sequence encoded data.
Input value x must be obtained from a call to CategoricalDataEncoder.seq_encode(data). Returns numpy array of log-density evaluated at all observations contained in encoded data x.
- backend_seq_log_density(x, engine)[source]
Engine-neutral log-density for encoded object categories.
The object-to-index lookup remains Python-side at the encoding boundary; the selected log-probability vector is an engine tensor, so simplex-map parameters can still participate in autograd.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked categorical probabilities for shared finite supports.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of categorical log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return per-component legacy count maps from engine-resident posterior weights.
- to_fisher(**kwargs)[source]
Return the categorical’s one-hot Fisher view (generic fallback for default-augmented maps).
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional random seed.
- Returns:
A configured
CategoricalSampler.- Return type:
CategoricalSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s support.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to current probabilities.
- Returns:
A
CategoricalEstimator.- Return type:
CategoricalEstimator
- dist_to_encoder()[source]
Return an encoder for categorical observations.
- Return type:
CategoricalDataEncoder
- enumerator()[source]
Return an enumerator over support labels in descending probability order.
- Return type:
CategoricalEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index directly from the finite support map.
- class ChineseRestaurantProcessDistribution(alpha, n, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionCRP distribution over partitions of
nitems with concentrationalpha > 0.- density(x)[source]
Return the probability of the partition encoded by label vector
x.
- log_density(x)[source]
Return the Ewens log-probability of the partition that label vector
xinduces.
- seq_log_density(x)[source]
Return the Ewens log-probability for a list of partition label vectors.
- sampler(seed=None)[source]
Return a sampler that draws partitions by the sequential CRP rule.
- Parameters:
seed (int | None)
- Return type:
ChineseRestaurantProcessSampler
- estimator(pseudo_count=None)[source]
Return a maximum-likelihood estimator for the concentration
alphaat fixedn.- Parameters:
pseudo_count (float | None)
- Return type:
ChineseRestaurantProcessEstimator
- dist_to_encoder()[source]
Return the data encoder (passes label vectors through).
- Return type:
ChineseRestaurantProcessDataEncoder
- class ChineseRestaurantProcessEstimator(n, alpha_min=1.0e-6, alpha_max=1.0e6, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the CRP concentration via the monotone expected-blocks equation.
- accumulator_factory()[source]
Return a factory for CRP sufficient-statistic accumulators.
- Return type:
ChineseRestaurantProcessAccumulatorFactory
- class CategoricalEstimator(pseudo_count=None, suff_stat=None, default_value=False, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimator for categorical probability maps from weighted label counts.
- Parameters:
- get_prior()[source]
Return the conjugate parameter prior over the category-probability simplex (or None).
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Set the conjugate parameter prior over the category-probability simplex.
- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- model_log_density(model)[source]
Log-density of the model probability map under the DictDirichlet prior (ELBO global term).
- Parameters:
model (CategoricalDistribution)
- Return type:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
CategoricalAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a CategoricalDistribution from suff_stat value.
If default_value is True, we estimate a default value from the suff_stat counts. Else, it is set to 0.0.
pseudo_count is used to averaged over the number of levels and added to the corresponding counts.
If suff_stat member value is None, estimate for CategoricalDistribution is formed from the suff_stat passed. Otherwise, the suff_stat member value is combined with the suff_stat values passed to estimate.
- Parameters:
- Returns:
- CategoricalDistribution estimated from passed in suff_stat value and sufficient statistic member variable
(if it is not None).
- Return type:
CategoricalDistribution
- class CategoricalEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerator over finite categorical support in descending probability order.
- Parameters:
dist (CategoricalDistribution)
- class MultinomialDistribution(dist, len_dist=NullDistribution(), len_normalized=False, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultinomial distribution over count vectors.
- Parameters:
- compute_capabilities()[source]
Declare generated-compute support inherited from value and length children.
- compute_declaration()[source]
Return the generated-compute declaration for the categorical multinomial.
- to_exponential_family(engine=None)[source]
Return the multinomial exponential-family view, or
None.A multinomial over an exponential-family element is itself an exponential family with the shared element
etaand the count-weighted sufficient statisticT(x) = sum_j c_j T_0(v_j). This holds only when the trial count is not separately modeled (len_distis Null) and the density is not length-normalized (those break the single-exp-family form); it also requires the value element to be an exponential family. Otherwise returnsNone.- Parameters:
engine (Any)
- density(x)[source]
Returns the density of multinomial evaluated at observation x.
See log_density() for details.
- log_density(x)[source]
Returns the log-density of multinomial evaluated at observation x.
Let P_dist(V_k) be a distribution for a countable set of discrete observations of values V_k of type T. Denote
p_k = P_dist(V_k),
as the probability of success for value V_k. Then sum_{k=0}^{inf} p_k = 1. Let x = (x_0, x_1,….,x_{n-1}) be a multinomial observation for ‘n’ trials, where each x_i = (V_j, n_j) for some value V_j in the observation space and n_j is the associated number of success for the value. (note: sum n_j = n). Then, denoting p_j = p_mat(V_j), the normalized count-vector log mass is:
log(p_mat(x)) = log(n!) - sum_j log(n_j!) + sum_j n_j * log(p_j) + log(P_len(n)),
where P_len(n) is a distribution for the number of trials in the multinomial having support on the non-negative integers.
- seq_log_density(x)[source]
Vectorized evaluated of log-density for an encoded sequence of iid multinomial observations.
See log_density() for details on the log-density function for MultinomialDistribution.
- Arg ‘x’ is a tuple of size 7 containing:
x[0] (ndarray[int]): Observation index of sequence values. x[1] (ndarray[float]): Trial size for each observation. x[2] (ndarray[float]): Non-zero trial size indices. x[3] (T1): Sequence encoded flattened list of values from x. x[4] (Optional[T2]): Sequence encoded flatted list of trial sizes. x[5] (np.ndarray[float]): Flattened array of counts for values. x[6] (ndarray[float]): Flattened array of trial sizes.
- Parameters:
x – See above for details.
- Returns:
Numpy array of the log-density at each encoded observation of x.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded count-vector observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child routes for homogeneous multinomial mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of multinomial log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy multinomial sufficient statistics.
- to_fisher(**kwargs)[source]
Structural Fisher view for the multinomial bag.
- sampler(seed=None)[source]
Return a sampler for iid multinomial bags.
- Parameters:
seed (int | None) – Optional random seed.
- Returns:
A configured
MultinomialSampler.- Return type:
MultinomialSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from the value and length models.
- Parameters:
pseudo_count (float | None) – Optional smoothing count for child estimators.
- Returns:
A configured
MultinomialEstimator.- Return type:
MultinomialEstimator
- dist_to_encoder()[source]
Return an encoder for sparse multinomial observations.
- Return type:
MultinomialDataEncoder
- enumerator()[source]
Returns MultinomialEnumerator iterating (value, count)-pair lists in descending probability order.
- Return type:
MultinomialEnumerator
- class MultinomialEstimator(estimator, len_estimator=NullEstimator(), len_dist=None, len_normalized=False, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate a categorical multinomial from value and length sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
MultinomialAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a multinomial distribution from aggregated sufficient statistics.
- class MultinomialEnumerator(dist)[source]
Bases:
DistributionEnumeratorReserved exact enumerator for categorical multinomials.
Construction currently fails closed because arbitrary category distributions do not expose the finite, unique support manifest required to enumerate normalized count-vector probabilities.
- Parameters:
dist (MultinomialDistribution)
- class CompositeDistribution(dists, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionProduct distribution over heterogeneous component variables.
- Parameters:
dists (Sequence[SequenceEncodableProbabilityDistribution])
prior (Sequence[SequenceEncodableProbabilityDistribution] | None)
- compute_capabilities()[source]
Return compute-backend metadata shared by all component distributions.
- property count: int
Number of components, derived from the canonical immutable child tuple.
- get_prior()[source]
Return the joint prior as the list of per-component child priors (in component order).
- Return type:
list[SequenceEncodableProbabilityDistribution | None]
- set_prior(prior)[source]
Distribute per-component parameter priors to the wrapped child distributions.
CompositeDistributionowns no parameters of its own; the joint prior factors over the independent components.prior=Noneis a no-op (children keep their existing priors, leaving the MLE path byte-identical); otherwisepriormust be a sequence of exactlycountchild priors that are pushed to the children via their ownset_prior.- Parameters:
prior (Sequence[SequenceEncodableProbabilityDistribution | None] | None)
- Return type:
None
- expected_log_density(x)[source]
Prior-expected log-density: sum of the component
expected_log_densityvalues atx.
- seq_expected_log_density(x)[source]
Vectorized prior-expected log-density: sum of the component
seq_expected_log_densityvalues.- Parameters:
x (E)
- Return type:
- compute_declaration()[source]
Return the symbolic declaration for the product of component distributions.
- marginal(indices)[source]
The marginal sub-composite over the given component
indices.Because the components are independent, the marginal of a subset of coordinates is just the sub-product over those coordinates, in the caller’s requested order. Indices must be unique, integer, in range, and non-empty. Used (with
condition()) byMixtureDistribution.conditionalto score the observed coordinates of a partial observation.
- condition(observed)[source]
The conditional sub-composite over the UNobserved components given
observed.observedmaps a component index to its (present) value. Since the components are independent, conditioning leaves the unobserved factors unchanged – the conditional is the sub-product over the coordinates not inobserved(the observed values do not enter). This is the per-component piece that makesMixtureDistribution.conditionalreturn the posterior/imputation over the missing fields of a partial observation.
- density(x)[source]
Evaluates density of CompositeDistribution for single observation tuple x.
p_mat(x) = p_mat(x_0 | dist_0)*p_mat(x_1 | dist_1)*…*p_mat(x_{n-1} | dist_{n-1}),
where dist_k is the k^{th} element of member variable dists and is consistent with data type type(x[k]).
- Parameters:
x (Tuple[Any, ...]) – Tuple of length = len(dists), the k^{th} data type must be consistent with dists[k].
- Returns:
Density as float.
- Return type:
- density_semantics()[source]
Return joined density semantics over all component distributions.
- log_density(x)[source]
Evaluates log-density of CompositeDistribution for single observation tuple x.
log(p_mat(x)) = log(p_mat(x_0 | dist_0)) + log(p_mat(x_1 | dist_1)) + … + log(p_mat(x_{n-1} | dist_{n-1})),
where dist_k is the k^{th} element of member variable dists and is consistent with data type type(x[k]).
- Parameters:
x (Tuple[Any, ...]) – Tuple of length = len(dists), the k^{th} data type must be consistent with dists[k].
- Returns:
Log-density as float.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of log density for Tuple of dist encoded data.
Each entry of x is an encoded sequence, encoded by the DataSequenceEncoder of dist[k].dist_to_encoder().
Note: len(x) == len(dists). :param x: Tuple of length = len(dists), with k^{th} entry given by encoded sequence of dist[k]’s. :type x: E
- Returns:
np.ndarray of log_density evaluated at all encoded data points.
- Parameters:
x (E)
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density by composing child distributions.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child parameters for homogeneous composite mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of composite log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy composite sufficient statistics.
- support_size()[source]
Product of child support sizes (
Noneif any child is infinite).- Return type:
int | None
- to_fisher(**kwargs)[source]
Structural Fisher view (product of child views).
- to_exponential_family(engine=None)[source]
Return the product exponential-family view, or
None.A composite is an exponential family iff every child is: the canonical pieces concatenate (
eta,T) and add (A,log h). ReturnsNonewhen any child is not a (single) exponential family.- Parameters:
engine (Any)
- sampler(seed=None)[source]
Return a sampler that samples each component independently.
- Parameters:
seed (Optional[int]) – Seed to set for sampling with RandomState.
- Returns:
CompositeSampler object.
- Return type:
CompositeSampler
- estimator(pseudo_count=None)[source]
Return a composite estimator built from the component estimators.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics in estimation.
- Returns:
CompositeEstimator object.
- Return type:
CompositeEstimator
- decomposition()[source]
Composite factors are independent: split along the factor axis, sufficient stats SUM-reduce.
- dist_to_encoder()[source]
Return a tuple encoder assembled from the component encoders.
Passes ‘encoders’, which is a list of DataSequenceEncoders for each component of the CompositeDistribution.
- Returns:
CompositeDataEncoder object.
- Return type:
CompositeDataEncoder
- enumerator()[source]
Creates CompositeEnumerator iterating tuples in descending joint probability order.
- Return type:
CompositeEnumerator
- conditional_enumerator(given)[source]
Enumerate complete tuples consistent with the fixed positions in
given, best-first.givenis a mapping{position: value}pinning a subset of coordinates (most-probable completion / imputation). Because the components are independent, descending order over the free coordinates is descending conditional order; each yielded tuple has the fixed positions filled in and carries the full jointlog_density(the fixed positions are a constant offset). Raises ValueError for an out-of-range position.
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded index with a DP over additive quantized child costs.
Each child item is assigned an integer cost ceil(bits/bin_width_bits). The composite cost is the sum of those integer costs, so the bin counts are a convolution of child cost-bin counts. Items are unranked lazily from the child bin offsets when requested; the returned log probability is still the exact joint log-density.
- structural_fine_bucket(value, quantizer)[source]
Sum of child structural buckets – mirrors the count index’s child convolution.
- Return type:
- quantized_count_index(quantizer, max_fine_bucket)[source]
Structural count index: the ADDITIVE law – the carrier’s n-ary product over children.
The complete log density is the sum of independent child log densities, so the joint count histogram is the
times/product(convolution) of the child histograms in the witness-retaining count semiring (mixle.enumeration.quantization.semiring). Children are consumed by their counts and lazy unranker – never drained – so a child with astronomically large support (e.g. a Sequence) composes without being materialized. Swapping the carrier (e.g. a tropical one) would reuse this same reduction.- Parameters:
max_fine_bucket (int)
- class CompositeEstimator(estimators, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimator that fits each independent component distribution from its own statistics.
- Parameters:
estimators (Sequence[ParameterEstimator])
keys (str | None)
prior (Sequence[Any] | None)
- property count: int
Number of child estimators, derived from the canonical immutable tuple.
- get_prior()[source]
Return the joint prior as the list of per-component child estimator priors (in order).
- set_prior(prior)[source]
Distribute per-component parameter priors to the child estimators.
prior=Noneis a no-op (children keep their existing priors). Otherwisepriormust be a sequence of exactlycountpriors pushed to the children via their ownset_prior.
- model_log_density(model)[source]
Sum the child estimators’
model_log_densityon the corresponding child models (ELBO global term).- Parameters:
model (CompositeDistribution)
- Return type:
- accumulator_factory()[source]
Return an accumulator factory assembled from the child estimators.
- Return type:
CompositeAccumulatorFactory
- estimate(nobs, suff_stat)[source]
- Estimate a CompositeDistribution from an aggregated sufficient statistics Tuple for a given number of
observations (nobs).
- Parameters:
nobs (Optional[float]) – Weighted number of observations used to form suff_stat.
suff_stat (SS) – Tuple of sufficient statistics for each ParameterEstimator of estimators.
- Returns:
- CompositeDistribution estimated from argument aggregated sufficient statistics (suff_stat), from a given
number of observation (nobs).
- Return type:
CompositeDistribution
- class CompositeEnumerator(dist)[source]
Bases:
DistributionEnumeratorBest-first enumerator over the Cartesian product of component supports.
- Parameters:
dist (CompositeDistribution)
- class ConditionalDistribution(dmap, default_dist=NullDistribution(), given_dist=NullDistribution(), name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionConditionalDistribution models pairs (x0, x1) with density P_cond(x1 | x0) * P_given(x0), where the conditional distributions are looked up from a dictionary keyed by x0.
- Parameters:
- get_prior()[source]
Return the joint prior as
(per_branch_priors, default_prior, given_prior).per_branch_priorsis a dict keyed likedmapof each conditional branch’s prior.
- set_prior(prior)[source]
Distribute per-branch priors to the conditional branches, default, and given distributions.
prior=Noneis a no-op (children keep their existing priors, leaving the MLE path byte-identical). Otherwiseprioris(per_branch_priors, default_prior, given_prior): eachdmapbranch prior is pushed to the matching child viaset_prior, and the default/given priors are pushed todefault_dist/given_dist.
- expected_log_density(x)[source]
Prior-expected log-density: selected branch
expected_log_density+ given term.Mirrors
log_density: unmatched conditioning values with no default score-inf.
- seq_expected_log_density(x)[source]
Vectorized prior-expected log-density mirroring
seq_log_density.- Parameters:
x (E0)
- Return type:
- compute_capabilities()[source]
Declare generated-compute support joined across branch, default, and given models.
- density_semantics()[source]
Classify a conditional kernel without a given law as a likelihood factor.
- compute_declaration()[source]
Return the generated-compute declaration for the conditional distribution.
- density(x)[source]
Evaluates density of ConditionalDistribution at Tuple x.
Calls log_density() and returns the exponentiated result. See log_density() for details.
- Parameters:
x (Tuple[T0, T1]) – T0 data type much match keys of dmap, T1 much match value of dmap distribution for key value.
- Returns:
Density of ConditionalDistribution at Tuple x
- Return type:
- log_density(x)[source]
Evaluate log-density of ConditionalDistribution at Tuple x.
- Log-density:
log(P(x)) = log(P_cond(x[1] | x[0])) + log(P_given(x[0])), where log(P_cond(x[1] | x[0])) is defined from dmap, and log(P_given(x[0])) is defined from given_dist.
Note: Log-density is evaluated to -np.inf, if x[0] not in dmap and default_dist is NullDistribution().
- Parameters:
x (Tuple[T0, T1]) – T0 data type much match keys of dmap, T1 much match value of dmap distribution for key value.
- Returns:
Log-density of ConditionalDistribution at Tuple x.
- Return type:
- seq_log_density(x)[source]
Arkouda vectorized evaluation of the log-density on sequence encoded data x.
x Tuple of length 5:
x[0] (int): length of x (i.e. total observations). x[1] (Tuple[T0]): Unique conditional values in data. x[2] (Tuple[E0,...]): Tuple of encoded data sequences for each given key. x[3] (Tuple[ak.pdarray,...]): Tuple containing idxs for observation corresponding to x[1] values. x[4] (Optional[Encoded[T0]]): If the given_encoder is not the NullDataEncoder, the observed conditional values of data type T0 are sequence encoded by given_encoder. Else return None.
- Parameters:
x (E0) – See above for details.
- Returns:
Numpy array of log-density evaluated at each encoded data point.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for grouped conditional encodings.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child routes for homogeneous conditional mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of conditional log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return versioned per-component conditional sufficient statistics.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- sampler(seed=None)[source]
Create a sampler for this conditional distribution.
- Parameters:
seed (Optional[int]) – Seed for the sampler’s random number generator.
- Returns:
ConditionalDistributionSampler configured from this distribution.
- Return type:
ConditionalDistributionSampler
- conditional_sampler(seed=None)[source]
Return a sampler that can draw values for caller-supplied given values.
- Parameters:
seed (int | None)
- Return type:
ConditionalDistributionSampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this conditional distribution.
Used to estimate a ConditionalDistribution from data observations.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate the sufficient statistics of ConditionalDistribution.
- Returns:
ConditionalDistributionEstimator with estimators for the branch, default, and given distributions.
- Return type:
ConditionalDistributionEstimator
- dist_to_encoder()[source]
Create a data encoder for conditional-distribution observations.
- Return type:
ConditionalDistributionDataEncoder
- enumerator()[source]
Creates a ConditionalDistributionEnumerator iterating (given, value) pairs in descending joint probability order.
Requires an enumerable given distribution and enumerable conditional distributions; raises EnumerationError otherwise.
- Returns:
ConditionalDistributionEnumerator object.
- Return type:
ConditionalDistributionEnumerator
- class ConditionalDistributionEstimator(estimator_map, default_estimator=NullEstimator(), given_estimator=NullEstimator(), name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorConditionalDistributionEstimator estimates a ConditionalDistribution from aggregated sufficient statistics.
- Parameters:
- get_prior()[source]
Return the joint prior as
(per_branch_priors, default_prior, given_prior)from child estimators.
- set_prior(prior)[source]
Distribute per-branch priors to the child estimators (branches, default, given).
prior=Noneis a no-op. Each branch prior is pushed to the matching estimator viaset_prior; default/given priors go to the default/given estimators.
- model_log_density(model)[source]
Sum each branch’s estimator
model_log_densityplus the default and given terms.- Parameters:
model (ConditionalDistribution)
- Return type:
- accumulator_factory()[source]
Return an accumulator factory for the given, branch, and default estimators.
- Return type:
ConditionalDistributionAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a ConditionalDistribution from aggregated data.
Calls the estimate() member function of each ParameterEstimator instance for estimator_map, default_estimator, and given_estimator.
Input suff_stat if a Tuple of size three containing sufficient statistics compatible with each respective ParameterEstimator. Entry one of the Tuple must be a dict with keys of data type T0, matching the data type for the given distribution.
Return the conditional distribution estimated from the sufficient statistics in
suff_stat.- Parameters:
nobs (Optional[float]) – Not used. Kept for consistency.
suff_stat (ConditionalStatistics) – See description above.
- Returns:
ConditionalDistribution object.
- Return type:
ConditionalDistribution
- class ConditionalDistributionEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates (given, value) pairs of a ConditionalDistribution in descending joint probability order.
- Parameters:
dist (ConditionalDistribution)
- class ConditionalStatistics(schema_version, branches, default_nobs, default, given_nobs, given)[source]
Bases:
NamedTupleVersioned sufficient statistics for a fixed conditional branch layout.
- Parameters:
- schema_version: int
Alias for field number 0
- branches: tuple[ConditionalBranchStatistics, ...]
Alias for field number 1
- default_nobs: float
Alias for field number 2
- given_nobs: float
Alias for field number 4
- class ConditionalBranchStatistics(key, nobs, statistic)[source]
Bases:
NamedTupleOne branch’s effective count and child sufficient statistic.
- key: Any
Alias for field number 0
- nobs: float
Alias for field number 1
- statistic: Any
Alias for field number 2
- exception NonGenerativeConditionalError[source]
Bases:
TypeErrorRaised when a conditional factor without a given law is asked to generate pairs.
- ConditionalEstimator
alias of
ConditionalDistributionEstimator
- ConditionalEnumerator
alias of
ConditionalDistributionEnumerator
- class ChowLiuTreeDistribution(parents, marginal_dists, conditional_dists, default_dists=None, feature_order=None, parent_values=None, name=None, keys=None, pseudo_count=None, mi_pseudo_count=None, default_policy='marginal')[source]
Bases:
SequenceEncodableProbabilityDistributionChow-Liu tree over fixed-position fields with generic conditional models.
parents[i]gives the parent feature of featurei; exactly one entry must beNoneand is treated as the root. The root uses its marginal distribution. Non-root features useconditional_dists[i][freeze(x[parent])]when present, otherwisedefault_dists[i]if one was supplied.- Parameters:
marginal_dists (Sequence[SequenceEncodableProbabilityDistribution])
conditional_dists (Sequence[dict[Hashable, SequenceEncodableProbabilityDistribution] | None])
default_dists (Sequence[SequenceEncodableProbabilityDistribution | None] | None)
name (str | None)
keys (str | None)
pseudo_count (Any)
mi_pseudo_count (float | None)
default_policy (str)
- compute_capabilities()[source]
Describe backend support shared by the tree’s component distributions.
- compute_declaration()[source]
Return a composite compute declaration for tree marginals and conditionals.
- density(x)[source]
Return the probability density or mass at a single observation.
- conditional_dist(child, parent_value)[source]
Return the conditional distribution associated with a child and parent assignment.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral grouped scoring for fixed Chow-Liu tree factors.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
ChowLiuTreeSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
ChowLiuTreeEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
ChowLiuTreeDataEncoder
- enumerator()[source]
Return an enumerator over the distribution support when available.
- Return type:
ChowLiuTreeEnumerator
- class ChowLiuStatistics(total_weight, num_features, marginal_counts, marginal_values, joint_counts, marginal_stats, conditional_stats)[source]
Bases:
NamedTupleVersioned, tuple-compatible generic Chow–Liu sufficient statistics.
- Parameters:
- total_weight: float
Alias for field number 0
- num_features: int
Alias for field number 1
- joint_counts: dict[tuple[int, int], dict[tuple[Hashable, Hashable], float]]
Alias for field number 4
- property schema_version: int
Return the serialized statistic schema version.
- class ChowLiuTreeEstimator(estimators, root=0, pseudo_count=None, mi_pseudo_count=None, default_policy='marginal', keys=None, name=None)[source]
Bases:
ParameterEstimatorEstimate a generic Chow-Liu tree from fixed-length tuple observations.
Structure learning uses empirical mutual information over observed field values, so it is best suited to finite/enumerable or intentionally discretized coordinates. Once an edge is chosen, the child conditional distribution for each parent value is estimated with that child’s supplied estimator.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Chow-Liu structure and parameter statistics.
- Return type:
ChowLiuTreeAccumulatorFactory
- class ChowLiuTreeEnumerator(dist)[source]
Bases:
DistributionEnumeratorFinite-support enumerator for a ChowLiuTreeDistribution.
- Parameters:
dist (ChowLiuTreeDistribution)
- class DiracLengthMixtureDistribution(len_dist, p, v=0, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMixture between a fixed length and a learned length distribution.
- Parameters:
- p
Probability of being drawn from length distribution. Must be between 0 and 1.
- Type:
- len_dist
Distribution with support on non-negative integers.
- Type:
SequenceEncodableProbabilityDistribution
- name
Optional distribution name.
- Type:
Optional[str]
- compute_capabilities()[source]
Declare generated-compute support inherited from the length distribution.
- compute_declaration()[source]
Return the generated-compute declaration for the Dirac-length mixture.
- density(x)[source]
Evaluate density of length Dirac mixture distribution at observation x.
See log_density() for details.
- log_density(x)[source]
Evaluate the log-density of length Dirac mixture distribution at observation x.
log(P(x)) = log( p*P_1(x) + (1-p)*Delta_{v}(x) ),
- component_log_density(x)[source]
Log-density of each mixture component (length distribution, dirac at v) at x.
- posterior(x)[source]
Posterior probability of each mixture component given observation x.
- seq_component_log_density(x)[source]
Vectorized component log-densities at sequence encoded input x.
- Parameters:
x (E) – Sequence encoded data from DiracLengthMixtureDataEncoder.
- Returns:
Numpy array of shape (len(x), 2) of component log-densities.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of the mixture log-density at sequence encoded input x.
- Parameters:
x (E) – Sequence encoded data from DiracLengthMixtureDataEncoder.
- Returns:
Numpy array of log-density (float) of len(x).
- Return type:
- backend_seq_component_log_density(x, engine)[source]
Engine-neutral component log densities for encoded length/dirac mixtures.
- backend_seq_log_density(x, engine)[source]
Engine-neutral mixture log-density for encoded length/dirac observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for shared-dirac length mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of length/dirac mixture log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy
(component_counts, length_stat)statistics.
- seq_posterior(x)[source]
Vectorized component posterior probabilities at sequence encoded input x.
- Parameters:
x (E) – Sequence encoded data from DiracLengthMixtureDataEncoder.
- Returns:
Numpy array of shape (len(x), 2) of component posteriors.
- Return type:
- sampler(seed=None)[source]
Create a DiracLengthMixtureSampler from parameters of this distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
DiracLengthMixtureSampler object.
- Return type:
DiracLengthMixtureSampler
- estimator(pseudo_count=None)[source]
Create a DiracLengthMixtureEstimator with matching dirac value v.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics.
- Returns:
DiracLengthMixtureEstimator object.
- Return type:
DiracLengthMixtureEstimator
- dist_to_encoder()[source]
Returns a DiracLengthMixtureDataEncoder for encoding sequences of iid integer observations.
- Return type:
DiracLengthMixtureDataEncoder
- enumerator()[source]
Returns a DiracLengthMixtureEnumerator iterating the union of the length-distribution support and the dirac point v in descending probability order.
- Return type:
DiracLengthMixtureEnumerator
- class DiracLengthMixtureEstimator(estimator, v=0, fixed_p=None, suff_stat=None, pseudo_count=None, name=None, keys=(None, None))[source]
Bases:
ParameterEstimatorEstimate Dirac-length mixture distributions.
- Parameters:
estimator (ParameterEstimator) – Estimator for the length distribution.
v (int) – Dirac location.
fixed_p (Optional[float]) – Hold the length-distribution weight p fixed at this value.
suff_stat (Optional[float]) – Prior value of p used with pseudo_count for regularization.
pseudo_count (Optional[float]) – Used to inflate the component count statistics.
name (Optional[str]) – Optional name assigned to estimated distributions.
keys (Tuple[Optional[str], Optional[str]]) – Keys for the mixture weights and component statistics.
- estimator
Estimator for the length distribution.
- Type:
ParameterEstimator
- v
Dirac location.
- Type:
- pseudo_count
Used to inflate the component count statistics.
- Type:
Optional[float]
- suff_stat
Prior value of p used with pseudo_count for regularization.
- Type:
Optional[float]
- keys
Keys for the mixture weights and component statistics.
- name
Optional name assigned to estimated distributions.
- Type:
Optional[str]
- fixed_p_vec
Fixed component weights [p, 1-p] when fixed_p is given.
- Type:
Optional[np.ndarray]
- accumulator_factory()[source]
Returns a DiracLengthMixtureAccumulatorFactory consistent with this estimator.
- Return type:
DiracLengthMixtureAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a DiracLengthMixtureDistribution from accumulated sufficient statistics.
- Parameters:
nobs (Optional[float]) – Weighted number of observations.
suff_stat (Tuple[np.ndarray, SS0]) – Component counts and length-distribution statistics.
- Returns:
DiracLengthMixtureDistribution object.
- Return type:
DiracLengthMixtureDistribution
- class DiracLengthMixtureEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates the union of the length-distribution support and the dirac point v.
The model is a two-component mixture: the length distribution with weight p and a dirac delta at v with weight 1-p. The dirac component contributes the trivial single-point stream [(v, 0.0)]. Supports may overlap (the length distribution can also emit v), so candidates are de-duplicated and re-scored exactly with the mixture log-density.
- Parameters:
dist (DiracLengthMixtureDistribution)
- class DirichletDistribution(alpha, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionDirichlet distribution over probability vectors, with concentration parameters alpha.
- classmethod compute_capabilities()[source]
Declare backend support for Dirichlet generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Dirichlet distribution.
- get_parameters()[source]
Return the concentration vector alpha.
Lets a DirichletDistribution serve as a conjugate prior (on a Categorical/Mixture weight simplex) under the unified Bayesian estimation protocol.
- Return type:
- cross_entropy(dist)[source]
Cross entropy -E_self[log dist(x)] for a Dirichlet argument.
Accepts another
DirichletDistribution(full concentration vector) or aSymmetricDirichletDistribution(scalar concentration broadcast to this distribution’s dimension). Both arise as the conjugate prior/posterior over the same simplex during variational Bayes (e.g. the ELBO global term in DPM).- Parameters:
dist (SequenceEncodableProbabilityDistribution)
- Return type:
- density(x)[source]
Evaluate the density of a dirichlet observation.
See log_density() for details.
- log_density(x)[source]
Evaluate the log-density of a dirichlet observation.
The log-density of a Dirichlet with dim = K, is given by
log(p_mat(x)) = -log(Const) + sum_{k=0}^{K-1} (alpha_k -1)*log(x_k), for sum_k x_k = 1.0,
else -inf. In above
log(Const) = sum_{k=0}^{K-1} log(Gamma(alpha_k)) - log(Gamma(sum_{k=0}^{K-1} alpha_k)).
- seq_log_density(x)[source]
Vectorized evaluation of the log-density at a sequence-encoded input x.
- Parameters:
x (Tuple[np.ndarray, np.ndarray, np.ndarray]) – Encoded data from DirichletDataEncoder.seq_encode(), a tuple of (log of observations, observations, squared observations).
- Returns:
Numpy array containing the log-density of each encoded observation. Rows that are not on the simplex (a negative or non-finite entry, or a row that doesn’t sum to one) score
-inf, mirroringlog_density– the encoder’s clipped log representation alone can’t distinguish a genuine near-zero coordinate from a negative one, so validation reads the accompanying raw observations instead.- Return type:
- static backend_log_density_from_params(log_x, alpha, log_const, engine)[source]
Engine-neutral Dirichlet log-density from encoded log observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded Dirichlet observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for equal-dimensional Dirichlet mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Dirichlet component log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy Dirichlet sufficient statistics.
- to_fisher(**kwargs)[source]
Return the Dirichlet’s log-coordinate Fisher view (generic fallback for degenerate alpha).
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional random seed.
- Return type:
DirichletSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution.
When
pseudo_countis provided, the normalized concentration vector regularizes the estimate.- Parameters:
pseudo_count (float | None) – Optional weight for the current normalized concentration vector.
- Return type:
DirichletEstimator
- dist_to_encoder()[source]
Create the encoder for iid Dirichlet observations.
- Return type:
DirichletDataEncoder
- class DirichletEstimator(dim=None, pseudo_count=None, suff_stat=None, delta=1.0e-8, keys=None, use_mpe=False, name=None)[source]
Bases:
ParameterEstimatorEstimator for Dirichlet concentration parameters.
- Parameters:
- accumulator_factory()[source]
Create a Dirichlet accumulator factory from this estimator’s settings.
- Return type:
DirichletAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a Dirichlet distribution from aggregated sufficient statistics.
suff_statis(count, sum_log_x, sum_x, sum_x2). The concentration parameters are solved from the mean-log-probability statistic with a safeguarded Newton solver, orfind_alphawhenuse_mpeis set.nobsis accepted for estimator API consistency but counts are taken fromsuff_stat[0].
- class DiagonalGaussianDistribution(mu, covar=MISSING, name=None, keys=None, covariance=MISSING, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultivariate Gaussian distribution with independent components (diagonal covariance matrix).
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for diagonal Gaussian generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the diagonal Gaussian.
- static exp_family_sufficient_statistics(x, engine)[source]
Return vector sufficient statistics for generated diagonal-Gaussian scoring.
- static exp_family_natural_parameters(params, engine)[source]
Return vector natural parameters for generated diagonal-Gaussian scoring.
- static exp_family_log_partition(params, engine)[source]
Return the diagonal-Gaussian log partition for generated scoring.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return row-wise legacy accumulator statistics for generated resident reductions.
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a MultivariateNormalGamma(mu0, lam, a, b) prior over (mu, tau=1/covar) this caches the expected natural parameters [ea, eb, e1, e2] with e1 = E[mu*tau] and e2 = -0.5*E[tau] per component (ea, eb scalars summed over components), so that
expected_log_density(x) = x.e1 + (x*x).e2 - ea + eb. Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x | mu, tau)] under the prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.- Return type:
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density at observation x.
See log_density() for details.
- Parameters:
x (Union[Sequence[float], np.ndarray]) – Length-dim observation vector.
- Returns:
Density at x.
- log_density(x)[source]
Evaluate the log-density at observation x.
The log-density is given by
log(p(x)) = -0.5*sum_{i=1}^{n} (x_i-m_i)^2 / s2_i - 0.5*log(s2_i) - (n/2)*log(2*pi).
Computed in the CENTERED form the formula above states,
-0.5*sum (x-mu)^2/covar, not in the algebraically equal expanded formx^2*ca + x*cb + cc. The expanded form is three terms of sizeO(|x|^2/covar)summing to anO(1)answer, so at|x| ~ 1e9with unit variance it cancels away every significant digit: the scorer returned round-number garbage (measured: log-likelihoods of exactly 66560.0 and -135168.0 on unit-variance data at offset 1.7e9), and because EM selects the model with the best objective, anoptimize/fitrun at that offset returned the WORSE of its own iterates.x - muis exact for operands of the same magnitude, so the centered form is accurate at any offset; it is also one gemv instead of two. The full-covariance estimator’s scorer always used the centered form – this is the diagonal one catching up, and it makes the documented formula true (T1-F1). The expanded coefficients remain available asca/cb/ccfor the fused kernels.- Parameters:
x (Union[Sequence[float], np.ndarray]) – Length-dim observation vector.
- Returns:
Log-density at x.
- condition(observed)[source]
Return the conditional over the unobserved dimensions given
observed.A diagonal Gaussian has independent coordinates, so conditioning on some of them leaves the rest unchanged: the result is just
DiagonalGaussian(mu[unobserved], covar[unobserved])(the observed values do not shift the unobserved mean or variance). Provided so diagonal-covariance Gaussian mixtures supportMixtureDistribution.conditional()– there the responsibilities still update from how well each component explains the observed coordinates, even though the within-component coordinates are independent. Raises if no dimension is left unobserved.
- marginal(keep)[source]
Return the marginal over the dimensions
keep:DiagonalGaussian(mu[keep], covar[keep]).Marginalizing a diagonal Gaussian simply drops the other independent coordinates (order kept).
- density_cumulative(x)[source]
Exact probability-ordered cumulative
G(x) = P(p(Y) >= p(x))– the highest-density-region mass throughx(multivariate analogue of a CDF). For a diagonal Gaussian the squared Mahalanobis distancesum_i (x_i-mu_i)^2/var_iis chi-square(dim), soG = chi2.cdf(maha2, dim). Used bymixle.enumeration.density_rank.density_rank()to return an EXACT cumulative.
- density_quantile(q)[source]
Inverse of
density_cumulative(): a representative point at cumulative-density indexq.qis the highest-density-region mass, whose boundary is the squared-Mahalanobis levelchi2.ppf(q, dim); a representative point on that contour offsets the first coordinate bysqrt(level * var_0)(Mahalanobis distance exactly the level). Sweepingqenumerates the support in descending density.
- seq_log_density(x)[source]
Vectorized evaluation of the log-density at a sequence-encoded input x.
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim) from DiagonalGaussianDataEncoder.seq_encode().
- Returns:
Numpy array of length sz containing the log-density of each encoded observation.
- Return type:
- static backend_log_density_from_params(x, mu, covar, engine)[source]
Engine-neutral diagonal Gaussian log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked diagonal-Gaussian parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of diagonal-Gaussian log densities.
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional seed for the sampler’s random state.
- Returns:
A configured
DiagonalGaussianSampler.- Return type:
DiagonalGaussianSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s shape.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to mean and variance estimates.
- Returns:
A
DiagonalGaussianEstimator.- Return type:
DiagonalGaussianEstimator
- dist_to_encoder()[source]
Return an encoder for iid diagonal Gaussian observations.
- Return type:
DiagonalGaussianDataEncoder
- class DiagonalGaussianEstimator(dim=None, pseudo_count=(None, None), suff_stat=(None, None), name=None, keys=None, prior=None, min_covar=None, ridge=None)[source]
Bases:
ParameterEstimatorEstimator for diagonal Gaussian distributions.
The fit is SHIFT-EQUIVARIANT:
fit(x + c)returns the variances ofx + cto within about1e-7relative for any constantcthe data can carry, epoch seconds (~1.7e9) included. That is not free from the declared(sum, sum2, count)statistics – their variance is the cancellation-proneE[x^2] - mu^2, which at offset 1e7 was tens of percent wrong and at 1.7e9 thousands-fold wrong or collapsed onto the floor – soDiagonalGaussianAccumulatorcarries a conditioning-gated shift-anchored moment track and this estimator reads it. Statistics that arrive already reduced and WITHOUT that track (an engine kernel’s stacked moments, a hand-built tuple) cannot be corrected here and take the historical path; when they are too ill-conditioned for it,estimatewarns rather than returning variances it cannot stand behind.The
1e-7is a measured relative bound, not a figure of speech, and the error is NOT uniform across the offset range. Once the anchored track engages, the variances are exact to a few ulps (~1e-14 relative, and unchanged from offset 1.7e9 to 1e10). The bound is set by the band just BELOW the conditioning gate, where the rawE[x^2] - mu^2form is still in use because it is accurate enough to be worth its single pass: atmean^2/variancejust under the gate’s4e6the worst case measured over seeds, sample sizes and scales is3.1e-8relative. An earlier revision of this docstring promised “a few ulps” everywhere, which overstated that band by roughly eight orders of magnitude (T1-07).VARIANCE FLOOR. The fitted variances are the exact per-coordinate maximum-likelihood ones whenever every coordinate has a positive variance of its own. The M-step floors each coordinate at
ridge * var_i(defaultridge=1e-6) – RELATIVE to that coordinate’s own variance, so the safeguard is equivariant under any per-coordinate change of units and, sitting strictly below the variance it guards, never binds on such a coordinate. It is not priced offmean(var)across coordinates: that coupled columns a diagonal covariance exists to keep independent, and inflated the smallest variance of a plain probability/dollars/count table 3.03x (T1-03).A coordinate with no positive variance of its own – a constant column, an EM component holding a single point – still has to be lifted, because a zero variance is an infinite density. It gets
ridge * mean(var over the coordinates that have one), the same manufactured jitter the full covariance estimator uses for a degenerate direction. The absolutemin_covar(default1e-8) is the last resort when nothing carries a scale at all (every coordinate non-positive, orridge=0.0), and becomes a hard per-coordinate lower bound as soon as it is passed explicitly – which is howmixle.taskregularizes its diagonal Gaussians.A floor that actually lifted a coordinate is recorded on the fitted distribution as a
variance-floored(...)entry innumerical_repairs()– and therefore infit_provenance().repairs– naming the coordinate and how far it moved. Manufactured jitter is always reported; an explicitmin_covardominating a positive variance is reported once it exceeds_FLOOR_MATERIAL_RATIOof it. An ordinary fit lifts nothing and records nothing. Because the default floor never binds on a coordinate with its own variance,ridge=0.0is not the route to the maximum-likelihood fit here – it removes the only scale the degenerate-column jitter can be priced from and hands those coordinates to the absolutemin_covarinstead.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
DiagonalGaussianAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model parameters under the MultivariateNormalGamma prior (ELBO global term).
The prior is over (mu, tau=1/covar), so the model’s covariance is inverted before scoring.
- Parameters:
model (DiagonalGaussianDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a diagonal Gaussian distribution from aggregated sufficient statistics.
- Suff_stat is a Tuple of size 3 containing:
suff_stat[0] (np.ndarray): Component-wise sum of weighted observation values. suff_stat[1] (np.ndarray): Component-wise sum of weighted squared observation values. suff_stat[2] (float): Sum of weights for each observation.
- class ExponentialDistribution(beta, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionExponential distribution on non-negative real values with scale
beta.- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for generated Exponential density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Exponential distribution.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Exponential sufficient statistics for generated scoring.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Exponential sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Exponential natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Exponential log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return Exponential support base measure for generated scoring.
- set_prior(prior)[source]
Attach a parameter prior and precompute the conjugate Gamma expectations.
The exponential rate is
1/beta; with a Gamma(k, theta) prior on that rate this caches the variational expected natural parameters so thatexpected_log_density(x) = e1*x - eawhere the natural parameter iseta = -rate,E[eta] = -k*thetaandE[-log(-eta)] = psi(k) + ln theta(mapping the prior’s(k, theta)to the bstats[a, b] = [k, 1/theta]form). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x | rate)] under the Gamma prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density of exponential distribution with scale beta.
See log_density() for details.
- log_density(x)[source]
Evaluate the log-density of exponential distribution with scale beta.
log(f(x;beta)) = -log(beta) - x/beta, for x >= 0, else -np.inf.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
Vectorized call to log-density on each observation value x.
- Parameters:
x (np.ndarray) – Numpy array of floats.
- Returns:
Numpy array of log-density (float) of len(x).
- Return type:
- static backend_log_density_from_params(x, beta, engine)[source]
Engine-neutral exponential log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Exponential parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Exponential log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Exponential sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return the Exponential’s count-family Fisher view.
- sampler(seed=None)[source]
Create a sampler with scale
beta.- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
ExponentialSampler object.
- Return type:
ExponentialSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized with this distribution’s scale.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics.
- Returns:
ExponentialEstimator.
- Return type:
ExponentialEstimator
- dist_to_encoder()[source]
Return the encoder for exponential observations.
- Return type:
ExponentialDataEncoder
- class ExponentialEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate Exponential scale parameters from accumulated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Create an exponential accumulator factory with this estimator’s keys.
- Return type:
ExponentialAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s rate (1/beta) under the Gamma prior (ELBO global term).
- Parameters:
model (ExponentialDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate ExponentialDistribution from suff_stat arg.
Estimate ExponentialDistribution from sufficient statistic tuple suff_stat, counting a float value for count and sum. If pseudo_count is set, this is used to re-weight the member value “suff_stat”, which is the scale of ExponentialEstimator object.
- class GammaDistribution(k, theta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGamma distribution parameterized by shape and scale.
- classmethod compute_capabilities()[source]
Declare backend support for generated Gamma density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Gamma distribution.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Gamma sufficient statistics for generated scoring.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Gamma sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Gamma natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Gamma log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return Gamma support base measure for generated scoring.
- get_parameters()[source]
Return the (shape k, scale theta) pair.
Lets a GammaDistribution serve as a conjugate prior (on a Poisson/Exponential rate, or a Gamma scale) under the unified Bayesian estimation protocol.
- cross_entropy(dist)[source]
Cross entropy -E_self[log dist(x)] for a Gamma argument (closed form).
Used as the conjugate prior/posterior cross-entropy term in variational Bayes (e.g. the ELBO global term in DPM for Poisson/Exponential-rate components).
- Parameters:
dist (GammaDistribution)
- Return type:
- density(x)[source]
Density of gamma distribution evaluated at x.
See log_density() for details.
- log_density(x)[source]
Log-density of gamma distribution evaluated at x.
Log-density given by, If x > 0.0,
log(f(x;k,theta)) = -gammaln(k) - k*log(theta) + (k-1) * log(x) - x / theta,
else,
-np.inf
- seq_log_density(x)[source]
Vectorized evaluation of sequence encoded observations from gamma distribution.
- Input must be x (Tuple[ndarray, ndarray]):
x[0]: Numpy array of floats containing observations from gamma distribution. x[1]: Numpy array of floats containing log of observation values.
- Parameters:
x (Tuple[np.ndarray, np.ndarray]) – See above for details.
- Returns:
Numpy array containing log-density evaluated at all observations of encoded sequence x.
- Return type:
- static backend_log_density_from_params(vals, log_vals, k, theta, engine)[source]
Engine-neutral gamma log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Gamma parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Gamma log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Gamma sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional seed for the sampler’s random state.
- Returns:
A configured
GammaSampler.- Return type:
GammaSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s shape.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to the current distribution moments.
- Returns:
A
GammaEstimator.- Return type:
GammaEstimator
- dist_to_encoder()[source]
Return an encoder for iid Gamma observations.
- Return type:
GammaDataEncoder
- class GammaEstimator(pseudo_count=(0.0, 0.0), suff_stat=(1.0, 0.0), threshold=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate Gamma shape and scale parameters from sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
GammaAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a Gamma distribution from aggregated sufficient statistics.
The tuple is interpreted as
(count, sum, sum_of_logs).
- static estimate_shape(avg_sum, avg_sum_of_logs, threshold)[source]
Estimates the shape parameter of GammaDistribution.
- class GaussianDistribution(mu, sigma2, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionUnivariate Gaussian distribution.
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for generated Gaussian density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Gaussian distribution.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Gaussian sufficient statistics for generated scoring.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Gaussian sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Gaussian natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Gaussian log partition for generated scoring.
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a NormalGamma(mu0, lam, a, b) prior over (mu, tau=1/sigma2) this caches the variational expected natural parameters [ea, eb, e1, e2] so that
expected_log_density(x) = x*(e1 + x*e2) - ea + eb(the VB E-step term). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x | mu, tau)] under the NormalGamma prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Density of Gaussian distribution at observation x.
See log_density() for details.
- log_density(x)[source]
Log-density of Gaussian distribution at observation x.
- Log-density of Gaussian with mean mu and variance sigma2 given by,
log(f(x;mu, sigma2)) = -0.5*log(2*pi*sigma2) - 0.5*(x-mu)^2/sigma2, for real-valued x.
- seq_ld_lambda()[source]
Return vectorized log-density callables for encoded data.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- Parameters:
x (np.ndarray) – Numpy array of floats.
- Returns:
Numpy array of log-density (float) of len(x).
- Return type:
- static backend_log_density_from_params(x, mu, sigma2, engine)[source]
Engine-neutral Gaussian log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- gradient_log_prior(priors, prior_strength, torch, engine)[source]
Distribution-owned MAP prior contribution for Gaussian parameters.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Gaussian parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Gaussian log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Gaussian sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return the Gaussian’s own Fisher view.
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional seed for the sampler’s random state.
- Returns:
A configured
GaussianSampler.- Return type:
GaussianSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s shape.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to the current mean and variance.
- Returns:
A
GaussianEstimator.- Return type:
GaussianEstimator
- dist_to_encoder()[source]
Return an encoder for iid scalar Gaussian observations.
- Return type:
GaussianDataEncoder
- class GaussianEstimator(pseudo_count=(None, None), suff_stat=(None, None), name=None, keys=None, prior=None, min_covar=None, compensated=False)[source]
Bases:
ParameterEstimatorEstimate Gaussian mean and variance from accumulated sufficient statistics.
The variance is formed from shift-anchored statistics whenever the accumulated statistics carry that payload (see
GaussianAccumulator), which makes the fit shift-equivariant at any data offset. Statistics that arrive WITHOUT that payload cannot be corrected here – the information cancellation destroyed is not in them any more – and that is a reachable state, not a theoretical one: an engine kernel stacks the declared(sum, sum2, count, count2)moments directly, sooptimize(x + 1.7e9, GaussianEstimator(), engine=NUMPY_ENGINE)on sd ~2 data returned a variance 7.9e9 times too large.estimatenow WARNS in that case rather than returning it silently; the remedy is to accumulate throughGaussianAccumulator(which anchors automatically) or to subtract a constant origin from the data before fitting.ON GENUINELY DEGENERATE (zero-spread) DATA the equivariance guarantee above does not apply, and cannot: the true variance of a point mass is 0 and the true density is a Dirac delta, so the floor returned is a convention, not a measurement, and no offset makes one convention more correct than another. This estimator’s convention is
ratio * mu**2(scale-relative, so it is a UV of noise on 10 uV data and 2.9e10 on data at the Unix epoch); its siblingDiagonalGaussianEstimatoruses a flat1e-8regardless of magnitude – the two disagree by up to 18 orders of magnitude on identical degenerate input (T1-05, campaign four), and neither is “right”. A caller that needs a specific, fixed value on this exact input – not just a safeguard against it – should passmin_covar=<value>explicitly, which both estimators honor exactly.- Parameters:
- accumulator_factory()[source]
Return GaussianAccumulatorFactory with name and keys passed.
- Return type:
GaussianAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model parameters under the NormalGamma prior (ELBO global term).
The prior is over (mu, tau=1/sigma2), so the model’s (mu, sigma2) is mapped accordingly.
- Parameters:
model (GaussianDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a Gaussian distribution from aggregated sufficient statistics.
The tuple is interpreted as
(sum_x, sum_x2, count_for_mean, count_for_variance). Optional pseudo-counts smooth the corresponding mean and variance estimates.
- class InverseGammaDistribution(alpha, beta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionInverse-gamma distribution with shape alpha > 0 and rate beta > 0 on x > 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated inverse-gamma kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for inverse-gamma distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row (count, 1/x, -log x) sufficient statistics in accumulator order.
- static exp_family_sufficient_statistics(x, engine)[source]
Return inverse-gamma sufficient statistics
T(x) = (log x, 1/x).
- static exp_family_natural_parameters(params, engine)[source]
Return inverse-gamma natural parameters
eta = (-(alpha + 1), -beta).
- static exp_family_log_partition(params, engine)[source]
Return inverse-gamma log partition
A = lgamma(alpha) - alpha * log(beta).
- static exp_family_from_natural(eta)[source]
Return the inverse-gamma with natural parameters
eta = (-(alpha + 1), -beta).- Parameters:
eta (Any)
- Return type:
InverseGammaDistribution
- static backend_log_density_from_params(log_x, inv_x, alpha, beta, log_const, engine)[source]
Engine-neutral inverse-gamma log-density from explicit parameters (linear in log x and 1/x).
- get_parameters()[source]
Return the (shape alpha, rate beta) pair (so this can serve as a conjugate prior).
- cross_entropy(dist)[source]
Cross entropy -E_self[log dist(x)] for an inverse-gamma argument (closed form).
- Parameters:
dist (InverseGammaDistribution)
- Return type:
- mean()[source]
Mean E[X] = beta / (alpha - 1) for alpha > 1, else inf (the mean integral diverges).
- Return type:
- variance()[source]
Variance beta^2 / ((alpha-1)^2 (alpha-2)) for alpha > 2, else inf.
- Return type:
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (or -inf off support).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded (log x, 1/x) observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of inverse-gamma log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function P(X <= x) = Q(alpha, beta/x) (0 for x <= 0).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
InverseGammaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
InverseGammaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
InverseGammaDataEncoder
- class InverseGammaEstimator(pseudo_count=None, suff_stat=None, threshold=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the inverse-gamma shape and rate.
Fits the gamma distribution to the reciprocals
y = 1/x(y ~ Gamma(alpha, 1/beta)) by the standard log-mean / mean shape equation, then maps back to(alpha, beta) = (k, 1/theta).- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for inverse-gamma statistics.
- Return type:
InverseGammaAccumulatorFactory
- class InverseGaussianDistribution(mu, lam, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionInverse Gaussian (Wald) distribution with mean mu > 0 and shape lam > 0 on x > 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated inverse-Gaussian kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for inverse Gaussian distributions.
- static exp_family_sufficient_statistics(x, engine)[source]
Return the (x, 1/x) sufficient statistics for generated scoring.
- static exp_family_natural_parameters(params, engine)[source]
Return the (-lam/(2*mu^2), -lam/2) natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return the inverse Gaussian log partition -0.5*log(lam) - lam/mu.
- static exp_family_base_measure(x, engine)[source]
Return the support base measure -0.5*log(2*pi) - 1.5*log(x) (or -inf off support).
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row (count, x, 1/x) sufficient statistics in accumulator order.
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (or -inf off support).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- Parameters:
x (Tuple[ndarray, ndarray, ndarray]) – Tuple of observations, reciprocals, and log values produced by the InverseGaussianDataEncoder.
- Returns:
Numpy array of log-density values, with -inf entries off the positive support.
- Return type:
- static backend_log_density_from_params(vals, inv_vals, log_vals, mu, lam, engine)[source]
Engine-neutral inverse Gaussian log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of inverse Gaussian log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function P(X <= x) (Wald, via scipy invgauss).
- entropy()[source]
Differential entropy in nats (closed form).
H = -E[log f(X)] = 1/2 log(2 pi e / lam) + 3/2 E[log X](the quadratic term integrates to exactly 1/2 sinceE[(X - mu)^2 / X] = mu^2 / lam), withE[log X] = log(mu) - e^{2z} E_1(2z)atz = lam / mu– the order-derivative identity for the BesselK_{1/2}under the GIG representation,E_1the exponential integral. The scaled producte^x E_1(x)switches to its asymptotic series whereexpoverflows.- Return type:
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
InverseGaussianSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (Optional[float]) – Re-weight the sufficient statistics of this instance toward its own moments when not None (a simple ridge toward the current parameters).
- Returns:
InverseGaussianEstimator object.
- Return type:
InverseGaussianEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
InverseGaussianDataEncoder
- class InverseGaussianEstimator(pseudo_count=None, suff_stat=None, min_param=_MIN_IG_PARAM, max_param=_MAX_IG_PARAM, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the inverse Gaussian mean and shape.
The MLE is closed form:
mu = mean(x)and1/lam = mean(1/x) - 1/mu.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for inverse-Gaussian statistics.
- Return type:
InverseGaussianAccumulatorFactory
- class GeometricDistribution(p, name=None, keys=None, prior=None)[source]
Bases:
CachedParameterLaw,SequenceEncodableProbabilityDistributionGeometric distribution on
{1, 2, ...}with success probabilityp.- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for generated Geometric density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Geometric distribution.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Geometric sufficient statistics in accumulator order.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Geometric sufficient statistic
T(x) = (x,)(support x = 1, 2, …).
- static exp_family_natural_parameters(params, engine)[source]
Return Geometric natural parameter
eta = log(1 - p).
- static exp_family_log_partition(params, engine)[source]
Return Geometric log partition
A = log(1 - p) - log(p).
- static exp_family_from_natural(eta)[source]
Return the Geometric with natural parameter
eta = log(1 - p).- Parameters:
eta (Any)
- Return type:
GeometricDistribution
- set_prior(prior)[source]
Attach a Beta parameter prior and precompute conjugate-prior expectations.
With a Beta(a, b) prior on the success probability
pthis caches the digamma terms(digamma(a), digamma(b), digamma(a+b))so thatexpected_log_densityevaluates the variational Bayes expectationE_q[log p(x | p)]viaE[log p] = digamma(a) - digamma(a+b)andE[log(1-p)] = digamma(b) - digamma(a+b). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation
E_q[log p(x | p)]under the Beta prior.Uses the cached digamma expectations of
log pandlog(1-p); falls back to the plug-inlog_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Density of geometric distribution evaluated at x.
P(x=k) = (k-1)*log(1-p) + log(p), for x = 1,2,…, else 0.0.
- log_density(x)[source]
Log-density of geometric distribution evaluated at x.
See density() for details.
- seq_log_density(x)[source]
Vectorized log-density evaluated on sequence encoded x.
- static backend_log_density_from_params(x, p, engine)[source]
Engine-neutral geometric log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked geometric parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of geometric log densities.
- to_fisher(**kwargs)[source]
Return the Geometric’s count-family Fisher view.
- cdf(x)[source]
Cumulative distribution function P(X <= x) = 1 - (1-p)^floor(x), support x >= 1.
- quantile(q)[source]
Inverse CDF F^{-1}(q), support >= 1 (via scipy geom).
- sampler(seed=None)[source]
Create a sampler from this geometric distribution.
- Parameters:
seed (Optional[int]) – Used to set seed on random number generator.
- Returns:
GeometricSampler configured from this distribution.
- Return type:
GeometricSampler
- estimator(pseudo_count=None)[source]
Create an estimator for a geometric distribution.
- Parameters:
pseudo_count (Optional[float]) – Regularize empirical summary statistics.
- Returns:
GeometricEstimator configured with this distribution’s prior and name.
- Return type:
GeometricEstimator
- dist_to_encoder()[source]
Return the encoder for geometric observations.
- Return type:
GeometricDataEncoder
- enumerator()[source]
Returns GeometricEnumerator iterating the support {1, 2, …} in descending probability order.
- Return type:
GeometricEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index directly from the geometric tail formula.
- class GeometricEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate Geometric success probabilities from accumulated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Create a geometric accumulator factory with this estimator’s name and keys.
- Return type:
GeometricAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s success probability under the Beta prior (ELBO global term).
- Parameters:
model (GeometricDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a geometric distribution from weighted count and sum statistics.
nobsis accepted for estimator API consistency but is not used.suff_statis(count, sum). Without a pseudo-count, the estimate isp = count / sum; with a pseudo-count, the empirical statistic is shrunk toward the estimator’s prior statistic when available.
- class GeometricEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate geometric support values in descending probability order.
- Parameters:
dist (GeometricDistribution)
- class GumbelDistribution(loc=0.0, scale=1.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGumbel (extreme value type I) distribution with location loc and scale beta > 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated Gumbel kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Gumbel distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Gumbel sufficient statistics in accumulator order.
- static backend_log_density_from_params(x, loc, scale, engine)[source]
Engine-neutral Gumbel log-density from explicit parameters.
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Gumbel parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Gumbel log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Gumbel sufficient statistics using engine-resident arrays.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
GumbelSampler
- estimator(pseudo_count=None)[source]
Return a moment estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
GumbelEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
GumbelDataEncoder
- class GumbelEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorMoment estimator for the Gumbel location and scale.
Inverts the Gumbel moments:
beta = sqrt(6 * var) / piandloc = mean - beta * gammawhere gamma is the Euler-Mascheroni constant.The variance moment is formed from shift-anchored statistics whenever the accumulated sufficient statistics carry that payload (see
GumbelAccumulator), which makes the fit SHIFT-EQUIVARIANT: estimating onx + creturnsloc + cwithscaleunchanged, for any constantcthe data can carry – epoch seconds (~1.7e9) and 2**31 included. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, andestimatewarns rather than returning a scale it cannot stand behind.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Gumbel moment statistics.
- Return type:
GumbelAccumulatorFactory
- class HalfNormalDistribution(sigma, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionHalf-normal distribution with scale sigma > 0 on x >= 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated half-normal kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for half-normal distributions.
- static exp_family_sufficient_statistics(x, engine)[source]
Return the (x**2,) sufficient statistic for generated scoring.
- static exp_family_natural_parameters(params, engine)[source]
Return the (-1/(2*sigma^2),) natural parameter for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return the half-normal log partition log(sigma).
- static exp_family_base_measure(x, engine)[source]
Return the support base measure 0.5*log(2/pi) (or -inf off support x >= 0).
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row (count, x**2) sufficient statistics in accumulator order.
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (or -inf off support).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- Parameters:
x (Tuple[ndarray, ndarray]) – Tuple of observations and squared observations produced by the HalfNormalDataEncoder.
- Returns:
Numpy array of log-density values, with -inf entries off the non-negative support.
- Return type:
- static backend_log_density_from_params(vals, sq_vals, sigma, engine)[source]
Engine-neutral half-normal log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of half-normal log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function P(X <= x) (0 for x < 0).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
HalfNormalSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (Optional[float]) – Re-weight the second moment toward this instance’s own E[x**2] = sigma**2 when not None (a simple ridge toward the current parameter).
- Returns:
HalfNormalEstimator object.
- Return type:
HalfNormalEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
HalfNormalDataEncoder
- class HalfNormalEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the half-normal scale: sigma = sqrt(mean(x**2)).
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for half-normal statistics.
- Return type:
HalfNormalAccumulatorFactory
- class NegativeBinomialDistribution(r, p, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionNegative binomial distribution over non-negative integer counts.
- classmethod compute_capabilities()[source]
Describe backend support for generated negative-binomial kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for negative binomial distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row negative-binomial sufficient statistics in accumulator order.
The accumulator’s
NegativeBinomialAccumulator.value()returns(count, sum, histogram); the third row stat carries the per-row counts so the declaration’skind="histogram"reducer can fold them into the weighted count histogram the dispersion (r) solve needs.
- static exp_family_sufficient_statistics(x, engine)[source]
Return the NegativeBinomial sufficient statistic
T(x) = (x,)(rfixed).
- static exp_family_natural_parameters(params, engine)[source]
Return the NegativeBinomial natural parameter
eta = log(1 - p)(rfixed).
- static exp_family_log_partition(params, engine)[source]
Return the NegativeBinomial log partition
A = -r * log(p)(rfixed).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return the NegativeBinomial base measure
log h(x) = lgamma(x+r) - lgamma(r) - log(x!).The base measure carries the binomial-coefficient term and depends on the fixed shape
r; invalid (non-integer / negative) counts are mapped to-inf.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(vals, log_fact, r, p, engine)[source]
Engine-neutral negative-binomial log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked negative-binomial parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of negative-binomial log densities.
- to_fisher(**kwargs)[source]
Return the NegativeBinomial’s count-family Fisher view.
- entropy()[source]
Shannon entropy in nats, by exact summation of the standard series.
The negative-binomial entropy
-sum_k p_k log p_khas no closed form (Johnson, Kemp & Kotz, Univariate Discrete Distributions, ch. 5). The series is summed over the support up to this distribution’s own quantile at1 - 1e-16(plus a safety margin), beyond which the tail mass is far below double rounding – the same effective-support truncation PoissonDistribution.entropy() uses, but driven by the exact CDF (viabetainc) rather than a Gaussian-tail heuristic, since the negative binomial can be heavy-tailed.- Return type:
- cdf(x)[source]
Cumulative distribution function P(X <= x) = I_p(r, floor(x)+1).
- quantile(q)[source]
Inverse CDF F^{-1}(q) (via scipy nbinom).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
NegativeBinomialSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
NegativeBinomialEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
NegativeBinomialDataEncoder
- enumerator()[source]
Return an enumerator over the distribution support when available.
- Return type:
NegativeBinomialEnumerator
- class NegativeBinomialEstimator(r=1.0, pseudo_count=None, suff_stat=None, estimate_r=True, threshold=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate
randpfor a negative binomial distribution.By default the dispersion
ris recovered by a 1-D solve of the digamma score equation (pprofiled out), thenpfollows in closed form. Passestimate_r=Falseto holdrfixed at the constructor value (the historical geometric/fixed-shape M-step). Therargument is the initial value / fallback whenestimate_r=True.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for negative-binomial statistics.
- Return type:
NegativeBinomialAccumulatorFactory
- resident_accumulation_supported()[source]
Dispersion estimation needs the full count histogram, not fixed-width resident stats.
- Return type:
- static estimate_dispersion(histogram, r_init, threshold)[source]
Solve the negative-binomial dispersion MLE from a weighted count histogram.
With
pprofiled to its MLEp = r / (r + xbar), the score forrisg(r) = sum_k h(k) [digamma(k + r) - digamma(r)] - N * log(1 + xbar / r),
which is strictly decreasing and crosses zero exactly when the data are over-dispersed (sample variance > mean). Under equi/under-dispersion the MLE runs off to the Poisson limit, so
ris capped at_MAX_NB_SHAPE.
- class NegativeBinomialEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate the infinite support in descending probability order.
- Parameters:
dist (NegativeBinomialDistribution)
- class ParetoDistribution(xm, alpha, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionPareto type-I distribution with scale xm > 0 and shape alpha > 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated Pareto kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Pareto distributions.
- static exp_family_sufficient_statistics(x, engine)[source]
Return the Pareto sufficient statistic
T(x) = (log x,)(scalexmfixed).
- static exp_family_natural_parameters(params, engine)[source]
Return the Pareto natural parameter
eta = -alpha(scalexmfixed).
- static exp_family_log_partition(params, engine)[source]
Return the Pareto log partition
A = -log(alpha) - alpha * log(xm).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return the Pareto base measure
log h(x) = -log(x)on[xm, inf)(-infbelowxm).
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(vals, log_vals, xm, alpha, engine)[source]
Engine-neutral Pareto log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Pareto parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Pareto log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Pareto sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- variance()[source]
Variance xm^2 alpha / ((alpha-1)^2 (alpha-2)) for alpha > 2, else inf.
- Return type:
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
ParetoSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
ParetoEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
ParetoDataEncoder
- class ParetoEstimator(pseudo_count=None, suff_stat=None, min_denom=1.0e-12, name=None, keys=None)[source]
Bases:
ParameterEstimatorMLE estimator for Pareto scale and shape.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Pareto sufficient statistics.
- Return type:
ParetoAccumulatorFactory
- class RayleighDistribution(sigma, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionRayleigh distribution with scale sigma > 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated Rayleigh kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Rayleigh distributions.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Rayleigh sufficient statistics for generated scoring.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Rayleigh sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Rayleigh natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Rayleigh log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return Rayleigh support/base measure for generated scoring.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(vals, vals2, log_vals, sigma, engine)[source]
Engine-neutral Rayleigh log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Rayleigh parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Rayleigh log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
RayleighSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
RayleighEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
RayleighDataEncoder
- class RayleighEstimator(pseudo_count=None, suff_stat=None, min_sigma=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorClosed-form MLE estimator for Rayleigh scale.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Rayleigh sufficient statistics.
- Return type:
RayleighAccumulatorFactory
- class StudentTDistribution(df, loc=0.0, scale=1.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionStudent’s t distribution with degrees of freedom df, location loc, and scale > 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated Student-t kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Student-t distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Student-t sufficient statistics in accumulator order.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, df, loc, scale, engine)[source]
Engine-neutral Student-t log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Student-t parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Student-t log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- entropy()[source]
Differential entropy log(scale) + (df+1)/2 [psi((df+1)/2) - psi(df/2)] + log(sqrt(df) B(df/2, 1/2)).
- Return type:
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
StudentTSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
StudentTEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
StudentTDataEncoder
- class StudentTEstimator(df=5.0, pseudo_count=None, suff_stat=None, min_scale=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorMoment-style fixed-df estimator for Student’s t location and scale.
The exact MLE has no simple closed-form update. This estimator keeps df fixed and uses weighted moments, while generic gradient optimizers such as
mixle.inference.gradient_fit.fit_mle/fit_mapcan fit all three parameters through distribution-owned backend math.The variance moment is formed from shift-anchored statistics whenever the accumulated sufficient statistics carry that payload (see
StudentTAccumulator), which makes the fit SHIFT-EQUIVARIANT: estimating onx + creturnsloc + cwithscaleunchanged, for any constantcthe data can carry – epoch seconds (~1.7e9) and 2**31 included. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, andestimatewarns rather than returning a scale it cannot stand behind.min_scale(default 1e-8) is an absolute floor on the returnedscale; it exists for genuinely constant data, and a fit that lands on it is reporting no resolvable spread.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for fixed-df Student-t moments.
- Return type:
StudentTAccumulatorFactory
- class UniformDistribution(low, high, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionContinuous uniform distribution on [low, high].
- classmethod compute_capabilities()[source]
Describe backend support for generated uniform kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for uniform distributions.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(x, low, high, engine)[source]
Engine-neutral uniform log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked uniform parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of uniform log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Uniform sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
UniformSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
UniformEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UniformDataEncoder
- class UniformEstimator(pseudo_count=None, suff_stat=None, min_width=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorMLE estimator for uniform support endpoints.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for uniform support statistics.
- Return type:
UniformAccumulatorFactory
- class VonMisesDistribution(mu, kappa, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionVon Mises distribution on the circle with mean direction mu and concentration kappa >= 0.
Observations are angles in radians, interpreted modulo
2*pi:log_density(x)equalslog_density(x + 2*pi*k)for every integerk, and the density normalizes over one period, not over the real line. Scores are therefore comparable only to other circular models – see the module docstring for why a wrapped fit of real-line data can spuriously out-score every real-line family.- classmethod compute_capabilities()[source]
Describe backend support for generated von Mises kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for von Mises distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row (count, cos, sin) sufficient statistics in accumulator order.
- static exp_family_sufficient_statistics(x, engine)[source]
Return von Mises sufficient statistics
T(x) = (cos x, sin x).
- static exp_family_natural_parameters(params, engine)[source]
Return von Mises natural parameters
eta = (kappa cos mu, kappa sin mu).
- static exp_family_log_partition(params, engine)[source]
Return von Mises log partition
A = log(2 pi I_0(kappa)) = -log_const.
- static exp_family_from_natural(eta)[source]
Return the von Mises with natural parameters
eta = (kappa cos mu, kappa sin mu).- Parameters:
eta (Any)
- Return type:
VonMisesDistribution
- static backend_log_density_from_params(cos_t, sin_t, eta1, eta2, log_const, engine)[source]
Engine-neutral von Mises log-density from natural parameters (linear in cos/sin).
- density(x)[source]
Return the probability density at a single angle.
- log_density(x)[source]
Return the log-density at a single angle (radians), wrapping
xmodulo2*pi.Any finite real is accepted; values outside
(-pi, pi]are folded onto the circle, so this is the density ofx mod 2*pi, normalized over one period only.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded (cos, sin) observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked natural parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of von Mises log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked sufficient statistics using engine-resident arrays.
- sampler(seed=None)[source]
Return a sampler for drawing angles from this distribution.
- Parameters:
seed (int | None)
- Return type:
VonMisesSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
VonMisesEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
VonMisesDataEncoder
- class WrappedCauchyDistribution(mu, rho, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionWrapped Cauchy distribution with mean direction
muand concentrationrhoin[0, 1).- density(x)[source]
Return the probability density at a single angle (radians).
- log_density(x)[source]
Return the log-density at a single angle (radians).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded
(cos, sin)observations.
- classmethod compute_capabilities()[source]
Describe backend support for generated wrapped-Cauchy kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for wrapped Cauchy distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Per-row circular moments in accumulator order
(sum_cos, sum_sin, count).
- static backend_log_density_from_params(cos_t, sin_t, cos_mu, sin_mu, rho, engine)[source]
Engine-neutral wrapped-Cauchy log-density from pre-computed observation/parameter trig.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded
(cos, sin)data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked wrapped-Cauchy parameters (trig computed host-side) for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of wrapped-Cauchy log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Stacked circular moments
(sum_cos, sum_sin, count)using engine-resident arrays.
- sampler(seed=None)[source]
Return a sampler for drawing angles from this distribution.
- Parameters:
seed (int | None)
- Return type:
WrappedCauchySampler
- estimator(pseudo_count=None)[source]
Return a closed-form (mean-resultant) estimator for
muandrho.- Parameters:
pseudo_count (float | None)
- Return type:
WrappedCauchyEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution (cos/sin of the angle).
- Return type:
WrappedCauchyDataEncoder
- class WrappedCauchyEstimator(rho_max=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate
muandrhofrom the mean resultant (the first trigonometric moment).- accumulator_factory()[source]
Return an accumulator factory for circular-resultant statistics.
- Return type:
WrappedCauchyAccumulatorFactory
- exception WrappedCauchyFitError[source]
Bases:
RuntimeErrorRaised when circular moments have no finite wrapped-Cauchy fit.
- class ProjectedNormalDistribution(mu_x, mu_y, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionIsotropic projected normal
PN(mu)on the circle,mu = (mu_x, mu_y).- density(x)[source]
Return the probability density at a single angle (radians).
- log_density(x)[source]
Return the log-density at a single angle (radians).
- seq_log_density(x)[source]
Return vectorized log-density for sequence-encoded
(cos, sin)observations.
- classmethod compute_capabilities()[source]
Describe backend support for generated projected-normal kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for projected normal distributions.
- classmethod backend_legacy_sufficient_statistics(x, params, engine)[source]
Per-row E-step stats
(E[r] cos, E[r] sin, 1)under the CURRENT estimate’s parameters.
- classmethod backend_log_density_from_params(cos_t, sin_t, mu_x, mu_y, engine)[source]
Engine-neutral projected-normal log-density from
(cos, sin)and the mean vector.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded
(cos, sin)data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked projected-normal mean vectors for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of projected-normal log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Stacked E-step resultants
(sum r cos, sum r sin, count)under per-component parameters.
- sampler(seed=None)[source]
Return a sampler that draws
N(mu, I_2)and returns the angle.- Parameters:
seed (int | None)
- Return type:
ProjectedNormalSampler
- estimator(pseudo_count=None)[source]
Return an EM (latent-radius) estimator for
mu.- Parameters:
pseudo_count (float | None)
- Return type:
ProjectedNormalEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution (cos/sin of the angle).
- Return type:
ProjectedNormalDataEncoder
- class ProjectedNormalEstimator(name=None, keys=None)[source]
Bases:
ParameterEstimatorEM estimator:
mu = mean(E[r|theta] u(theta))(one M-step per accumulated E-step).- accumulator_factory()[source]
Return an accumulator factory for projected-normal EM statistics.
- Return type:
ProjectedNormalAccumulatorFactory
- exception ProjectedNormalFitError[source]
Bases:
RuntimeErrorRaised when projected-normal EM statistics do not define a finite fit.
- class WrappedNormalDistribution(mu, sigma2, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionWrapped normal distribution with mean direction
muand wrapped variancesigma2> 0.- property K: int
Number of wraps summed on each side of the window.
- density(x)[source]
Return the probability density at a single angle (radians).
- log_density(x)[source]
Return the log-density at a single angle (radians).
- seq_log_density(x)[source]
Return vectorized log-density for a sequence-encoded array of angles.
- classmethod compute_capabilities()[source]
Describe backend support for generated wrapped-normal kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for wrapped normal distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Per-row circular moments
(sum_cos, sum_sin, count)— uses the engine trig tier.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density: the (2K+1)-branch wrapped logsumexp on engine ops.
- sampler(seed=None)[source]
Return a sampler that wraps
N(mu, sigma2)onto the circle.- Parameters:
seed (int | None)
- Return type:
WrappedNormalSampler
- estimator(pseudo_count=None)[source]
Return a closed-form (mean-resultant) estimator for
muandsigma2.- Parameters:
pseudo_count (float | None)
- Return type:
WrappedNormalEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution (the angle itself).
- Return type:
WrappedNormalDataEncoder
- class WrappedNormalEstimator(sigma2_max=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate
muandsigma2from the mean resultant (rho = exp(-sigma2/2)).- accumulator_factory()[source]
Return an accumulator factory for circular-resultant statistics.
- Return type:
WrappedNormalAccumulatorFactory
- exception WrappedNormalFitError[source]
Bases:
RuntimeErrorRaised when circular moments have no finite wrapped-normal fit.
- class GeneralizedGaussianDistribution(mu, alpha, beta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGeneralized Gaussian (exponential power) with location
mu, scalealphaand shapebeta.- classmethod compute_declaration()[source]
Return the structured compute declaration for generalized Gaussian distributions.
- static backend_log_density_from_params(x, mu, alpha, beta, engine)[source]
Engine-neutral generalized-Gaussian log-density:
log_norm - (abs(x-mu)/alpha)**beta.
- seq_log_density(x)[source]
Return vectorized log-density for a sequence-encoded array of observations.
- kurtosis()[source]
Excess kurtosis Gamma(5/beta)Gamma(1/beta)/Gamma(3/beta)^2 - 3.
- Return type:
- entropy()[source]
Differential entropy 1/beta - log(beta / (2 alpha Gamma(1/beta))).
- Return type:
- sampler(seed=None)[source]
Return a sampler (Gamma magnitude with a random sign).
- Parameters:
seed (int | None)
- Return type:
GeneralizedGaussianSampler
- estimator(pseudo_count=None)[source]
Return a method-of-moments estimator for
mu,alpha,beta.- Parameters:
pseudo_count (float | None)
- Return type:
GeneralizedGaussianEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution (the raw value).
- Return type:
GeneralizedGaussianDataEncoder
- class GeneralizedGaussianEstimator(pseudo_count=None, suff_stat=None, beta_bounds=(0.25, 50.0), name=None, keys=None, prior_central=None)[source]
Bases:
ParameterEstimatorMethod-of-moments estimator:
mu= mean,betafrom excess kurtosis,alphafrom variance.The reduced moments are formed about a reference point rather than about zero whenever the accumulated statistics carry a shift-anchored payload (see
GeneralizedGaussianAccumulator), which makes the fit shift-equivariant:estimateonx + creturnsmu + cwithalphaandbetaunchanged. With a plain raw tuple – statistics restored from an older serialization, or a hand-built one – the historical raw path is used unchanged.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for generalized-Gaussian raw moments.
- Return type:
GeneralizedGaussianAccumulatorFactory
- class NakagamiDistribution(m, omega, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionNakagami distribution with shape
m >= 1/2and spreadomega = E[X^2] > 0.- log_density(x)[source]
Return the log-density at
x, including the exact limit at zero.
- seq_log_density(x)[source]
Return vectorized log-density for a sequence-encoded array of observations.
- classmethod compute_capabilities()[source]
Describe backend support for generated Nakagami kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Nakagami distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Per-row Nakagami power sums in accumulator order
(count, sum x^2, sum x^4).
- static backend_log_density_from_params(x, m, omega, engine)[source]
Engine-neutral Nakagami log-density with the exact limit at zero.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked Nakagami parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Nakagami log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Stacked Nakagami power sums
(count, sum x^2, sum x^4)using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function P(X <= x) = P(m, m x^2 / omega) (0 for x <= 0).
- entropy()[source]
Differential entropy m + lgamma(m) + (1/2 - m) psi(m) + (1/2) log(omega/m) - log(2).
Derived via the entropy of a monotone transform:
X = sqrt(Y)withY = X^2 ~ Gamma(m, omega/m)(Nakagami, ‘The m-distribution’, 1960), soh(X) = h(Y) - log(2) - E[log X] = h(Y) - log(2) - (1/2)(E[log Y])and bothh(Y)andE[log Y]are standard Gamma-distribution identities. Reduces exactly to the Rayleigh entropy atm = 1.- Return type:
- sampler(seed=None)[source]
Return a sampler (
X = sqrt(Gamma(m, omega/m))).- Parameters:
seed (int | None)
- Return type:
NakagamiSampler
- estimator(pseudo_count=None)[source]
Return a closed-form method-of-moments estimator.
- Parameters:
pseudo_count (float | None)
- Return type:
NakagamiEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution (the raw value).
- Return type:
NakagamiDataEncoder
- class NakagamiEstimator(pseudo_count=None, suff_stat=None, m_min=0.5, name=None, keys=None)[source]
Bases:
ParameterEstimatorMethod-of-moments estimator:
omega = E[X^2],m = E[X^2]^2 / Var[X^2](clamped m >= 1/2).Var[X^2]comes from the shift-anchored moment track whenever the accumulated statistics carry that payload (seeNakagamiAccumulator). The shape is the reciprocal of the relative spread ofX^2, so the rawE[X^4] - E[X^2]^2form loses abouteps * m: measured against exact rational arithmetic, 2.0e-10 relative at m=1e6, 2.6e-8 at 1e8 and 2.6e-6 at 1e10, now 2.0e-10, 4.7e-16 and 1.0e-13. With a plain raw tuple the historical path is used bit-identically, andestimatewarns rather than returning a shape it cannot stand behind.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Nakagami power-sum statistics.
- Return type:
NakagamiAccumulatorFactory
- class RicianDistribution(nu, sigma, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionRician distribution with non-centrality
nu >= 0and scalesigma > 0.- log_density(x)[source]
Return the log-density at
x(-inf for x <= 0).
- seq_log_density(x)[source]
Return vectorized log-density for a sequence-encoded array of observations.
- classmethod compute_capabilities()[source]
Describe backend support for generated Rician kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Rician distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Per-row Rician power sums in accumulator order
(count, sum x^2, sum x^4).
- static backend_log_density_from_params(x, nu, sigma, engine)[source]
Engine-neutral Rician log-density (
-infforx <= 0).
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked Rician parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Rician log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Stacked Rician power sums
(count, sum x^2, sum x^4)using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function P(X <= x) (Marcum-Q, via scipy rice).
- quantile(q)[source]
Inverse CDF F^{-1}(q) (via scipy rice).
- mean()[source]
Mean sigma sqrt(pi/2) L_{1/2}(-nu^2/(2 sigma^2)) (stable via the scaled Bessel ive).
- Return type:
- entropy()[source]
Differential entropy in nats, by adaptive quadrature of -f(x) log f(x) over x > 0.
At
nu = 0the Rician is exactly the Rayleigh, whose entropy is the closed form1 + log(sigma / sqrt(2)) + euler_gamma / 2. Fornu > 0the density’slog I0(x nu / sigma^2)term has no closed-form expectation (Rice, ‘Mathematical analysis of random noise’, 1944/1945), so the integral is evaluated numerically against the exact log-density.- Return type:
- sampler(seed=None)[source]
Return a sampler (the envelope of a 2-D Gaussian offset by
nu).- Parameters:
seed (int | None)
- Return type:
RicianSampler
- estimator(pseudo_count=None)[source]
Return a closed-form method-of-moments estimator.
- Parameters:
pseudo_count (float | None)
- Return type:
RicianEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution (the raw value).
- Return type:
RicianDataEncoder
- class RicianEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorMethod-of-moments estimator from
E[X^2]andE[X^4](closed-form quadratic in sigma^2).The quadratic is solved in its RATIONALIZED form,
sigma^2 = Var(X^2) / (2 (E[X^2] + sqrt(E[X^2]^2 - Var(X^2)))), whenever the accumulated statistics carry the shift-anchored payload (seeRicianAccumulator). Algebraically it is the same root as(m2 - sqrt(2 m2^2 - m4)) / 2, but it differences raw moments once instead of twice, and the one difference it needs is supplied exactly by the anchored track. That makes the fit accurate at anynu/sigma: measured against exact rational arithmetic on the same 2000-point samples, the historical form lost 5.4e-9 relative atnu/sigma1e4, 4.1e-5 at 1e6 and 44% at 1e8, and now measures 3.5e-15, 7.1e-13 and 3.5e-11. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical path is used bit-identically, andestimatewarns rather than returning a scale it cannot stand behind.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Rician power-sum statistics.
- Return type:
RicianAccumulatorFactory
- class VonMisesEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the von Mises mean direction and concentration.
The MLE is
mu = atan2(sum sin, sum cos)andkappa = A^{-1}(R)whereRis the mean resultant length andA(kappa) = I_1(kappa) / I_0(kappa).The data must be angles in radians. Any finite real is accepted and wrapped modulo
2*pi(onlycos/sinenter the statistics), so fitting a non-angular real-line column does not fail – it silently fits the circular law ofx mod 2*pi, whose log-likelihood is normalized over one period and is not comparable to real-line families (see the module docstring).- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for von Mises circular moments.
- Return type:
VonMisesAccumulatorFactory
- exception VonMisesFitError[source]
Bases:
RuntimeErrorRaised when circular moments have no finite von Mises fit.
- class WeibullDistribution(shape, scale, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionWeibull distribution with shape > 0 and scale > 0 on x >= 0.
- classmethod compute_capabilities()[source]
Describe backend support for generated Weibull kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Weibull distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Weibull sufficient statistics in accumulator order.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(vals, log_vals, shape, scale, engine)[source]
Engine-neutral Weibull log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Weibull parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Weibull log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- entropy()[source]
Differential entropy gamma*(1 - 1/shape) + log(scale/shape) + 1.
- Return type:
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
WeibullSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
WeibullEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
WeibullDataEncoder
- class GeneralizedParetoDistribution(scale, shape, loc=0.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGeneralized Pareto distribution with threshold
loc, scale> 0and shapexi.- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (
-infoutside the support).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- classmethod compute_capabilities()[source]
Describe backend support for generated generalized-Pareto kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for generalized Pareto distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Per-row GPD moment sums in accumulator order
(sum, sum2, count).
- static backend_log_density_from_params(x, scale, shape, loc, engine)[source]
Engine-neutral GPD log-density; the
abs(xi) < tolexponential limit is selected per element.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked GPD parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of GPD log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Stacked GPD moment sums
(sum, sum2, count)using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
GeneralizedParetoSampler
- estimator(pseudo_count=None)[source]
Return a method-of-moments estimator for
scaleandshapeat the fixed thresholdloc.- Parameters:
pseudo_count (float | None)
- Return type:
GeneralizedParetoEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
GeneralizedParetoDataEncoder
- class GeneralizedParetoEstimator(loc=0.0, pseudo_count=None, suff_stat=None, min_scale=1.0e-12, xi_max=0.5 - 1.0e-6, xi_min=-10.0, name=None, keys=None)[source]
Bases:
ParameterEstimatorMethod-of-moments estimator for GPD scale and shape at a fixed threshold
loc.Both inverted moments – the exceedance mean
sum_x/count - locand the varianceE[x^2]-E[x]^2– are differences taken at DATA magnitude, so a threshold far from zero destroys them: peaks over a threshold at epoch seconds fittedshape=0(the exponential limit) instead of+0.16, silently. Whenever the accumulated statistics carry the shift-anchored payload (seeGeneralizedParetoAccumulator) both moments are formed about a data anchor instead, which makes the fit THRESHOLD-EQUIVARIANT: estimating onx + cwith the threshold atloc + creturns the samescaleandshape, for any constantcthe data can carry. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, andestimatewarns rather than returning moments it cannot stand behind.The
pseudo_countprior is carried as the raw pairsuff_stat = (mean0, second0); a plain 2-tuple has its variance and exceedance-mean offset recovered by differencing (second0 - mean0**2andmean0 - locrespectively), which is the prior’s own encoding and is unaffected by the anchored track – a prior whose mean sits far from zero loses precision in both reconstructions, so express such a prior in threshold-relative coordinates, or build it withGeneralizedParetoDistribution.estimator(), which carries both exactly (seeGeneralizedParetoPriorMoments).locis a property, not a bare attribute: reassigning it re-targets this SAME estimator at a new threshold (the “threshold stability” / mean-residual-life re-thresholding workflow) and, when apseudo_countprior is configured, re-anchors its frozen(mean0, second0)moments to the new origin so the prior keeps meaning what it meant when built instead of being silently reinterpreted relative to the wrongloc(T1-01).- Parameters:
- property loc: float
The fixed threshold
muobservations are exceedances over.
- accumulator_factory()[source]
Return an accumulator factory for generalized-Pareto moments.
- Return type:
GeneralizedParetoAccumulatorFactory
- class GeneralizedExtremeValueDistribution(loc, scale, shape, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGeneralized Extreme Value distribution with location
loc, scale> 0and shapexi.- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (
-infoutside the support).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- classmethod compute_capabilities()[source]
Describe backend support for generated GEV kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for GEV distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Per-row GEV moment sums in accumulator order
(sum, sum2, sum3, count).Deliberately not wired into the declaration as
legacy_sufficient_statistics. The generated statistic path reduces every declared statistic with a weighted sum, ignoringStatisticSpec.additive, so it cannot produce the observed range the M-step needs to keep the fitted support around the data (see_shape_covering_range()) – it would silently handestimatea summed min and max. GEV therefore accumulates through the hostseq_update, which is three dot products for a univariate leaf; engine-resident scoring viabackend_seq_log_densityis unaffected. Reinstate this hook once the generated path honours non-additive support bounds.
- static backend_log_density_from_params(x, loc, scale, shape, engine)[source]
Engine-neutral GEV log-density; the
abs(xi) < tolGumbel limit is selected per element.s^{-1/xi}is computed asexp(-log(s)/xi)so the whole expression stays on engine ops.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked GEV parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of GEV log densities.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact).
- mean()[source]
Mean: loc + scale*(Gamma(1-xi)-1)/xi (loc+scale*euler_gamma at xi=0); inf for xi>=1.
- Return type:
- variance()[source]
Variance: scale^2 (Gamma(1-2xi)-Gamma(1-xi)^2)/xi^2 (scale^2 pi^2/6 at xi=0); inf for xi>=1/2.
- Return type:
- entropy()[source]
Differential entropy log(scale) + euler_gamma * xi + euler_gamma + 1.
- Return type:
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
GeneralizedExtremeValueSampler
- estimator(pseudo_count=None)[source]
Return a method-of-moments estimator for
loc,scaleandshape.- Parameters:
pseudo_count (float | None)
- Return type:
GeneralizedExtremeValueEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
GeneralizedExtremeValueDataEncoder
- class GeneralizedExtremeValueEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-12, xi_max=1.0 / 3.0 - 1.0e-4, xi_min=-1.0, name=None, keys=None, prior_central=None)[source]
Bases:
ParameterEstimatorMethod-of-moments estimator for GEV location, scale and shape.
This is a moment estimator, not an MLE: the shape is solved from the skewness-vs-
xirelation, and the shape is additionally constrained so the fitted support covers the observed range (see_shape_covering_range()). Whenever that constraint rewrites the shape – or the rewritten shape still scores the extreme observation catastrophically and the estimate falls back to the Gumbel limit – the returned distribution is not the raw moment fit, and the change is recorded innumerical_repairs()sofit_provenance()carries it (MXR-080-1202).The reduced moments are formed about a reference point rather than about zero whenever the accumulated statistics carry a shift-anchored payload (see
GeneralizedExtremeValueAccumulator), which makes the fit shift-equivariant:estimateonx + creturnsloc + cwithscaleandshapeunchanged. With a plain raw tuple – statistics restored from an older serialization, or a hand-built one – the historical raw path is used unchanged.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for GEV raw-moment statistics.
- Return type:
GeneralizedExtremeValueAccumulatorFactory
- class WeibullEstimator(pseudo_count=None, suff_stat=None, min_shape=1.0e-3, max_shape=1.0e3, min_scale=1.0e-12, name=None, keys=None)[source]
Bases:
ParameterEstimatorMoment estimator for Weibull shape and scale.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Weibull moment statistics.
- Return type:
WeibullAccumulatorFactory
- class GateBufferReceipt(rows_seen, rows_retained, rows_dropped, capacity, selection='deterministic_hash_top_k')[source]
Bases:
objectBounded deterministic coreset status for gate-training rows.
- class GateOptimizationReceipt(converged, steps_completed, initial_loss, final_loss, gradient_norm, termination)[source]
Bases:
objectOutcome of a bounded softmax-gate optimization.
- class GatedMixtureDistribution(components, gate, name=None, keys=None, *, gate_fit_receipt=None, gate_buffer_receipt=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA mixture whose weights are a gate
p(k | z); observations are(z, y)pairs.- Parameters:
- log_density(x)[source]
Return
log p(y | z)for one covariate/response pair.
- seq_log_density(enc)[source]
Return vectorized conditional log-densities for encoded
(z, y)pairs.
- posterior(x)[source]
Return posterior expert responsibilities for one
(z, y)observation.
- sampler(seed=None)[source]
Return a conditional sampler that requires a covariate
z.- Parameters:
seed (int | None)
- Return type:
GatedMixtureSampler
- estimator(pseudo_count=None)[source]
Return an EM estimator for experts and the covariate-dependent gate.
- Parameters:
pseudo_count (float | None)
- Return type:
GatedMixtureEstimator
- dist_to_encoder()[source]
Return the encoder for covariates plus expert response encodings.
- Return type:
GatedMixtureDataEncoder
- class GatedMixtureEstimator(component_estimators, gate, gate_steps=200, gate_lr=0.1, gate_tol=1.0e-8, max_buffer_rows=10_000, name=None, keys=None)[source]
Bases:
ParameterEstimatorM-step: refit each expert from its responsibility-weighted stats, refit the gate on
(z, resp).- Parameters:
- accumulator_factory()[source]
Return a factory for gated-mixture sufficient-statistic accumulators.
- Return type:
GatedMixtureAccumulatorFactory
- class SoftmaxGate(weight, bias, *, fit_receipt=None)[source]
Bases:
objectA torch-free multinomial-logistic gate
p(k | z) = softmax(W z + b)_k, fit on soft targets.fit(Z, R)minimizes the soft cross-entropy-sum_{n,k} R_{n,k} log p(k | z_n)by gradient descent –Rare the responsibilities (rows need not sum to 1; the sample weight is folded in).- Parameters:
weight (np.ndarray)
bias (np.ndarray)
fit_receipt (GateOptimizationReceipt | None)
- classmethod zeros(n_classes, n_features)[source]
Create a zero-logit gate with uniform initial class probabilities.
- log_prob_batch(z)[source]
(n, K)log-gatelog p(k | z_n)for each row ofz(shape(n, p)).
- fit_with_receipt(z, resp, *, steps=200, lr=0.1, tol=1.0e-8)[source]
Fit a softmax gate and return explicit convergence/failure status.
- class HeterogeneousMixtureDistribution(components, w=MISSING, name=None, weights=MISSING)[source]
Bases:
SequenceEncodableProbabilityDistributionMixture distribution with component-specific observation encoders.
- Parameters:
- compute_capabilities()[source]
Return compute-backend metadata shared by heterogeneous mixture components.
- compute_declaration()[source]
Return the symbolic declaration for heterogeneous mixture weights and components.
- density(x)[source]
Evaluate the density of the heterogeneous mixture at one observation.
See log_density() for details.
- Parameters:
x (T) – (T): Single observation from heterogeneous mixture distribution. T is data type of components.
- Returns:
Density at x.
- Return type:
- density_semantics()[source]
Return joined density semantics over heterogeneous mixture components.
- log_density(x)[source]
Evaluate log-density of heterogeneous mixture distribution at observation x.
A K-component heterogeneous mixture has log-density,
log(p_mat(x)) = log(sum_{z=k}^{K} p_mat(x|z=k)*p_mat(z=k)),
where p_mat(x|z=k) is component-k log-density at x, and p_mat(z=k) = w[k]. A log-sum-exp is used to evaluate the sum inside the log of the right-hand side above. (See mixle.utils.vector.log_sum() for details).
Recall: p_mat(x|z=k) need only be compatible with same data type T. They are need not be the same distribution.
- Parameters:
x (T) – (T): Single observation from heterogeneous mixture distribution. T is data type of components.
- Returns:
Log-density at x.
- Return type:
- component_log_density(x)[source]
Evaluate component-wise log-density of heterogeneous mixture distribution at observation x.
A K-component heterogeneous mixture has log-density,
log(p_mat(x)) = log(sum_{z=k}^{K} p_mat(x|z=k)*p_mat(z=k)),
where p_mat(x|z=k) is component-k log-density at x, and p_mat(z=k) = w[k].
This function returns an ndarray[float] of length K, containing log(p_mat(x|z=k)) as its k^{th} entry.
- Parameters:
x (T) – (T): Single observation from mixture distribution. T is data type of components.
- Returns:
Numpy array of floats containing component-wise log-density at x.
- Return type:
- posterior(x)[source]
Obtain the posterior distribution for each heterogeneous mixture component at observation x.
The posterior distribution of component ‘k’ at observation x is given by,
p_mat(Z=k|x) = p_mat(x|Z=k)*p_mat(z=k) / p_mat(x),
where
p_mat(x) = sum_{k=1}^{K} p_mat(x|Z=k)*p_mat(z=k) = sum_{k=1}^{K} p_mat(x|Z=k)*w[k].
This function returns an ndarray[float] of length K, containing p_mat(Z=k|x) as its k^{th} entry.
- Parameters:
x (T) – (T): Single observation from heterogeneous mixture distribution. T is data type of components.
- Returns:
Numpy array of floats containing posterior distribution at observation x.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of component-wise log-density for encoded sequence x.
Evaluates the log-density of each observation in the encoded sequence x (see log_density() for details).
- Arg x must be a Tuple of length two containing and encoded from
HeterogeneousMixtureDataEncoder.seq_encode(data) with data type Sequence[T] for data.
- x[0] (List[np.ndarray[int]]): The component ids for each distinct SequenceEncodableProbabilityDistribution
subclass.
- x[1] (List[T1,T2,..Tk]): A list of sequence encodings of iid an iid observation sequence for each
‘k’ distinct SequenceEncodableProbabilityDistribution subclasses. The data type for each encoding is assumed to be of type Ti.
The returned value is an ndarray[float] with shape (sz,K), where K is the number of mixture components, and sz is the number of iid observations in the encoded sequence x.
- Note: A row-wise log-sum-exp is performed for numerical stability. If a row contains a log-density value of,
-np.inf is returned for the corresponding observation value in the encoded sequence x.
- seq_component_log_density(x)[source]
Vectorized evaluation of component-wise log-density for encoded sequence x.
- Arg x must be a Tuple of length two containing and encoded from
HeterogeneousMixtureDataEncoder.seq_encode(data) with data type Sequence[T] for data.
- x[0] (List[np.ndarray[int]]): The component ids for each distinct SequenceEncodableProbabilityDistribution
subclass.
- x[1] (List[T1,T2,..Tk]): A list of sequence encodings of iid an iid observation sequence for each
‘k’ distinct SequenceEncodableProbabilityDistribution subclasses. The data type for each encoding is assumed to be of type Ti.
Creates a 2-d numpy array of floats with vectorized evaluations of component_log_density() stored in the rows corresponding to an observation in encoded sequence x.
The returned value is an ndarray[float] with shape (sz,K), where K is the number of mixture components, and sz is the number of iid observations in the encoded sequence x.
- backend_seq_component_log_density(x, engine)[source]
Engine-neutral component log densities for heterogeneous encoded data.
- backend_seq_log_density(x, engine)[source]
Engine-neutral heterogeneous-mixture log-density for encoded data.
- seq_posterior(x)[source]
Vectorized evaluation of posterior of HeterogeneousMixtureDistribution for encoded sequence x.
- Arg x must be a Tuple of length two containing and encoded from
HeterogeneousMixtureDataEncoder.seq_encode(data) with data type Sequence[T] for data.
- x[0] (List[np.ndarray[int]]): The component ids for each distinct SequenceEncodableProbabilityDistribution
subclass.
- x[1] (List[T1,T2,..Tk]): A list of sequence encodings of iid an iid observation sequence for each
‘k’ distinct SequenceEncodableProbabilityDistribution subclasses. The data type for each encoding is assumed to be of type Ti.
Vectorized evaluation the posterior of each observation in the encoded sequence x (see posterior() for details).
The returned value is an ndarray[float] with shape (sz,K), where K is the number of mixture components, and sz is the number of iid observations in the encoded sequence x. Each row contains the posterior of the corresponding encoded observation.
- Note: A row-wise log-sum-exp is performed for numerical stability. If a row contains a log-density value of,
-np.inf is returned for the corresponding observation value in the encoded sequence x.
- sampler(seed=None)[source]
Return a sampler for this heterogeneous mixture.
- Parameters:
seed (Optional[int]) – Seed to set for sampling with RandomState.
- Returns:
HeterogeneousMixtureSampler object.
- Return type:
HeterogeneousMixtureSampler
- estimator(pseudo_count=None)[source]
Return an estimator with one child estimator per component.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics in estimation.
- Returns:
HeterogeneousMixtureEstimator object.
- Return type:
HeterogeneousMixtureEstimator
- decomposition()[source]
Heterogeneous mixture components split along the component axis (logsumexp responsibilities inside a shard; per-component stats SUM-reduce). Components are NOT homogeneous, so there is no stacked-parameter tensor to DTensor-shard (engine_axis=None -> host-shard executor mode).
- dist_to_encoder()[source]
Return a data encoder assembled from the component distribution encoders.
- Return type:
HeterogeneousMixtureDataEncoder
- enumerator()[source]
Returns a HeterogeneousMixtureEnumerator iterating the union of component supports in descending mixture probability order.
- Return type:
HeterogeneousMixtureEnumerator
- class HeterogeneousMixtureEstimator(estimators, fixed_weights=None, suff_stat=None, pseudo_count=None, name=None, keys=(None, None))[source]
Bases:
ParameterEstimatorEstimator for heterogeneous mixture weights and component distributions.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory built from the component estimator factories.
- Return type:
HeterogeneousMixtureAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a heterogeneous mixture from aggregated sufficient statistics.
suff_statis a two-item tuple containing:suff_stat[0] (np.ndarray): Sufficient statistics for mixture weights. suff_stat[1] (Tuple[T1,…,Tk]): Tuple of K sufficient statistics for the heterogeneous mixture components.
suff_stat[1]is passed to the corresponding component estimator.If
fixed_weightsis notNone,suff_stat[0]is ignored and the estimated distribution uses the fixed weights.If
pseudo_countis set, observed counts are blended with either the estimator’s prior statistics or a uniform pseudo-count allocation.If
pseudo_countisNone, observed component counts determine the weights.
- class HeterogeneousMixtureEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerator over the deduplicated union of heterogeneous component supports.
- Parameters:
dist (HeterogeneousMixtureDistribution)
- class HeterogeneousPCFGDistribution(binary_rules, terminal_rules, start=None, nonterminals=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionCNF PCFG whose terminal productions emit arbitrary distributions.
- Parameters:
binary_rules (BinaryRuleInput | None) – Either
{parent: [(left, right, prob), ...]}or a flat sequence of(parent, left, right, prob)rules.terminal_rules (TerminalRuleInput) – Either
{parent: [(emission_dist, prob), ...]}or a flat sequence of(parent, emission_dist, prob)rules.start (Any | None) – Start nonterminal. If omitted, the first nonterminal is used.
nonterminals (Sequence[Any] | None) – Optional explicit nonterminal order.
name (str | None) – Optional model name.
Rule probabilities are normalized over all rules sharing a parent.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- compute_capabilities()[source]
Engine readiness intersected from the terminal emission distributions.
The CKY inside dynamic program is expressed in ComputeEngine ops (see
backend_seq_log_density), so the grammar is engine-ready on whatever engines all of its terminal emission leaves support (numpy plus, e.g., torch for autograd/GPU).
- backend_seq_log_density(x, engine)[source]
Engine-routed CKY inside scoring (numpy + torch).
Terminal log-densities come from each emission leaf’s own engine backend score, and the inside dynamic program runs in ComputeEngine ops. Per-sequence charts are still a Python loop (variable-length parses), so this trades the tuned NumPy
_insidefor engine portability and differentiability rather than raw speed.
- to_fisher(**kwargs)[source]
Inside-outside Fisher view for the PCFG.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
HeterogeneousPCFGSampler
- enumerator()[source]
Return an exact support enumerator for acyclic enumerable PCFGs.
- Return type:
HeterogeneousPCFGEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded index with an inside-style DP over quantized derivation costs.
Terminal emission distributions must themselves support
quantized_index. The DP counts grammar derivations by additive quantized bit cost and lazily unranks those derivations into emitted terminal sequences. For unambiguous grammars this is an index over distinct sequences; for ambiguous grammars the same sequence can be represented by multiple derivations, and the returned log probability is still the exact PCFGlog_densityof that sequence.
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
HeterogeneousPCFGEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
HeterogeneousPCFGDataEncoder
- class HeterogeneousPCFGEstimator(binary_rules, terminal_rules, start=None, nonterminals=None, pseudo_count=None, name=None, keys=(None, None))[source]
Bases:
ParameterEstimatorEstimator for a fixed-topology heterogeneous PCFG.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for this fixed grammar topology.
- Return type:
HeterogeneousPCFGAccumulatorFactory
- class InducedHeterogeneousPCFGEstimator(max_nonterminals, terminal_estimators, start='S', nonterminal_prefix='NT', terminal_rule_mass=0.5, rule_pseudo_count=1.0e-3, prune_threshold=0.0, min_rule_prob=0.0, name=None, keys=(None, None))[source]
Bases:
ParameterEstimatorOvercomplete sparse PCFG structure learner.
This estimator builds a finite grammar skeleton automatically:
Knonterminals namedstart, prefix1, ..., prefixK-1.every binary rule
A -> B C.every terminal rule
A -> terminal_family_j.
EM learns rule probabilities and terminal emission parameters. Rules whose expected count is below
prune_thresholdor whose normalized probability is belowmin_rule_probare assigned probability zero, but the rule layout is kept stable so repeated calls toseq_estimateremain compatible.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for the induced grammar skeleton.
- Return type:
HeterogeneousPCFGAccumulatorFactory
- initial_model(terminal_distributions, rng=None, jitter=0.0)[source]
Create an overcomplete starting grammar without hand-written rules.
terminal_distributionsmay contain one distribution per terminal family, in which case each nonterminal gets its own copy of the same family list, or one distribution per generated terminal rule.- Parameters:
terminal_distributions (Sequence[SequenceEncodableProbabilityDistribution])
rng (RandomState | None)
jitter (float)
- Return type:
HeterogeneousPCFGDistribution
- class HeterogeneousPCFGEnumerator(dist)[source]
Bases:
DistributionEnumeratorExact best-first enumerator for acyclic heterogeneous PCFGs.
- Parameters:
dist (HeterogeneousPCFGDistribution)
- class HiddenAssociationDistribution(cond_dist, given_dist=NullDistribution(), len_dist=NullDistribution(), name=None, keys=(None, None))[source]
Bases:
SequenceEncodableProbabilityDistributionHidden association model: values of a second set are emitted conditionally on values drawn from a first set.
- Parameters:
- compute_capabilities()[source]
Return backend capability metadata for this concrete hidden association model.
- compute_declaration()[source]
Return the generated-compute declaration for hidden association.
- log_density(x)[source]
Log-density of the hidden association model at observation x.
For each emitted value in x[1], marginalizes the conditional emission density over the given values in x[0] weighted by their counts, then adds the log-density of the given set under given_dist and of the total emission count under len_dist.
- seq_log_density(x)[source]
Evaluation of log-density at sequence encoded input x (loops over log_density).
- backend_seq_log_density(x, engine)[source]
Evaluate encoded log-densities through distribution-owned backend composition.
- emission_mixture(s1)[source]
The per-emission distribution
q(.|S1)as a mixture, or None for an empty/degenerate S1.q(emitted|S1) = sum_u (c_u/n1) P(emitted|u)is a finite mixture of the conditional emission distributionscond_dist.dmap[u]weighted by the given-bag’s normalized counts – enumerable whenever those component distributions are. Requirescond_distto be aConditionalDistribution(so the per-given components are available).
- enumerator()[source]
Enumerate
(S1, S2)observations in descending probability order.The model factors as
given_dist(S1) * [prod_e q(e|S1)^{c_e}] * P_len(n): the emitted bag S2 is drawn iid from the per-given mixtureq(.|S1)(seeemission_mixture()). Enumeration is a conditional product – the outer stream enumerates S1 fromgiven_distand, for each S1, the inner stream enumerates S2 as a multiset best-first search overq(.|S1)’s own enumeration underlen_dist, merged by descending total score withgiven_dist(S1)as the frontier bound. Requires an enumerable non-nullgiven_distand a ConditionalDistributioncond_dist.- Return type:
DistributionEnumerator
- sampler(seed=None)[source]
Return a sampler for iid grouped-count pairs.
Requires non-null given_dist and len_dist.
- Parameters:
seed (int | None) – Optional random seed.
- Returns:
A configured
HiddenAssociationSampler.- Return type:
HiddenAssociationSampler
- estimator(pseudo_count=None)[source]
Return an estimator built from the child estimators.
- Parameters:
pseudo_count (float | None) – Unused; accepted for protocol consistency.
- Returns:
A configured
HiddenAssociationEstimator.- Return type:
HiddenAssociationEstimator
- dist_to_encoder()[source]
Return an encoder for grouped-count hidden-association observations.
- Return type:
HiddenAssociationDataEncoder
- class HiddenAssociationEstimator(cond_estimator, given_estimator=NullEstimator(), len_estimator=NullEstimator(), pseudo_count=None, name=None, keys=(None, None))[source]
Bases:
ParameterEstimatorEstimator for hidden association distributions.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
HiddenAssociationAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a HiddenAssociationDistribution from aggregated sufficient statistics.
- Parameters:
nobs (Optional[float]) – Number of observations, passed to the given and length estimators.
suff_stat (Tuple[SS1, Optional[SS2], Optional[SS3]]) – Conditional, given, and size suff stats.
- Returns:
HiddenAssociationDistribution object.
- Return type:
HiddenAssociationDistribution
- class StructuredHMM(emissions, pi, transition, emission_estimators=None, keys=(None, None), name=None, len_dist=None, terminal_states=None, final_states=None)[source]
Bases:
objectAn HMM whose transition is a
TransitionOperator(dense / low-rank / a combinator).emissionsis one observation distribution per state;pithe initial-state distribution;transitionanyTransitionOperator. The scaled forward-backward and EM call the operator’sforward/backward/accumulate/estimate, so a low-rank or factorial transition runs the SAME inference at its own cost (O(K r) for low-rank).emission_estimators(one per state) drives the emission M-step; default reusesemissions[k].estimator().- Parameters:
transition (TransitionOperator)
- viterbi(seq)[source]
Most-likely state path (Viterbi / max-product). Uses the transition matrix, so it works for any operator; O(T K^2) – a read-out, not the EM hot loop.
- posterior_decode(seq)[source]
Per-position MAP state argmax_k P(z_t = k | x) from the forward-backward posteriors gamma.
- enumerator()[source]
Enumerate observation sequences in descending marginal probability (top_k / rank / seek / nucleus / certified estimates). Enumeration depends only on pi, the transition MATRIX, the emissions and a length distribution – not on the operator’s internal structure – so it reuses the built-in HMM enumerator (an A*-style best-first search over the trellis) on the dense matrix. Requires
len_dist(a distribution over sequence length) and enumerable (discrete) emissions.
- dist_to_enumerator()[source]
Return the sequence enumerator for this HMM.
- state_posteriors(seq)[source]
The full smoothing posteriors gamma[t,k] = P(z_t = k | x).
- sampler(seed=None)[source]
Return a sampler for observation sequences.
- fit(seqs, *, max_its=50, tol=1e-6, fast=True, weights=None)[source]
Fit by Baum-Welch through the transition operator.
fast=Trueuses the numba-jitted dense forward-backward when possible. The returnedHMMFitResultremains unpackable as(fitted_hmm, loglik_trace)and also exposes a validateddiagnosticsreceipt.
- class StructuredHMMEstimator(emission_estimators, transition_proto, keys=(None, None), name=None, len_dist=None, terminal_states=None)[source]
Bases:
ParameterEstimatorEstimator (M-step) for a
StructuredHMM: re-estimates pi, the transition OPERATOR (any structure – dense/low-rank/combinator), and each state’s emission from the Baum-Welch statistics.keys=(init_key, trans_key)tie the initial / transition parameters across HMMs that share them.- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- estimate(nobs, suff_stat)[source]
Estimate an HMM from Baum-Welch sufficient statistics.
- class TransitionOperator[source]
Bases:
objectA row-stochastic state-transition operator behind the HMM forward-backward.
Subclasses provide the two linear maps the recursions need plus an M-step from expected transition mass.
forward/backwardmust be consistent withas_matrix(forward(a) == a @ A,backward(v) == A @ v); the low-overhead operators never materializeA.- to_dict()[source]
Return a safe JSON-compatible representation of this operator.
- classmethod from_dict(payload)[source]
Reconstruct an operator from
to_dictoutput.
- forward(alpha)[source]
Push a state-belief row vector one transition forward.
- backward(v)[source]
Pull an emission-weighted belief vector one transition backward.
- as_matrix()[source]
Materialize the transition matrix when an explicit matrix is needed.
- Return type:
- new_accumulator()[source]
Create an empty transition sufficient-statistic accumulator.
- Return type:
- accumulate(acc, alpha_t, w_next, scale)[source]
Add one transition’s expected mass.
alpha_tis the (normalized) forward belief at t,w_next = b_{t+1} * beta_{t+1}the emission-weighted backward belief at t+1,scalethe forward normalizerc_{t+1}(so the per-step posterior transition mass is exact).
- class DenseTransition(a, prior=None)[source]
Bases:
TransitionOperatorThe usual dense K x K row-stochastic transition (O(K^2) forward-backward).
prior(a K x K pseudocount matrix) is added to the expected counts before each M-step re-normalization – a Dirichlet/MAP transition. A diagonal prior is a sticky self-transition bias (seesticky_transition()); a flat prior is symmetric-Dirichlet smoothing.- Parameters:
a (np.ndarray)
prior (np.ndarray | None)
- forward(alpha)[source]
Push a state-belief row vector forward with the dense matrix.
- backward(v)[source]
Pull a vector backward with the dense matrix.
- as_matrix()[source]
Return the dense row-stochastic transition matrix.
- new_accumulator()[source]
Create dense expected-transition-count storage.
- accumulate(acc, alpha_t, w_next, scale)[source]
Accumulate one dense expected-transition-count contribution.
- estimate(acc)[source]
Estimate a row-normalized dense transition from expected counts.
- class LowRankTransition(g, phi)[source]
Bases:
TransitionOperatorA = G @ Phi: each state’s next-state distribution is a mix of
rshared transition profiles.Gis K x r row-stochastic (state -> profile mixing),Phiis r x K row-stochastic (profile -> next-state).A = G @ Phiis K x K row-stochastic with rank <= r. Forward ((alpha @ G) @ Phi), backward (G @ (Phi @ v)) and the M-step are all O(K r) – never forming A – and the parameter count is 2 K r instead of K^2.- Parameters:
g (np.ndarray)
phi (np.ndarray)
- forward(alpha)[source]
Push a state-belief row vector through the low-rank transition.
- backward(v)[source]
Pull a vector backward through the low-rank transition.
- as_matrix()[source]
Materialize the implied dense transition matrix.
- new_accumulator()[source]
Create state-profile and profile-next sufficient-statistic storage.
- accumulate(acc, alpha_t, w_next, scale)[source]
Accumulate one exact low-rank transition contribution.
- estimate(acc)[source]
Estimate low-rank transition factors from accumulated statistics.
- class BlockDiagonalTransition(blocks)[source]
Bases:
TransitionOperatorIndependent sub-chains: the states partition into blocks and transitions stay within a block.
A model whose initial state picks a block and then evolves inside it – a mixture of regimes that do not switch. Build it from any sub-operators (each block can itself be dense or low-rank). Exact, block-local forward-backward and M-step.
- forward(alpha)[source]
Push each block’s belief mass forward independently.
- backward(v)[source]
Pull each block’s vector backward independently.
- as_matrix()[source]
Materialize the block-diagonal transition matrix.
- new_accumulator()[source]
Create one transition accumulator per block.
- accumulate(acc, alpha_t, w_next, scale)[source]
Accumulate block-local expected transition mass.
- estimate(acc)[source]
Estimate each block and return a new block-diagonal transition.
- class KroneckerTransition(op1, op2)[source]
Bases:
TransitionOperatorFactorial HMM: the state is the pair
(s1, s2)of two chains evolving in parallel, withA = A1 (x) A2(Kronecker). State index isi1 * K2 + i2.Forward-backward uses the reshape identity (
alpha @ (A1 (x) A2)reshapes toA1^T @ M @ A2), so a step is O(K1 K2 (K1 + K2)) instead of O((K1 K2)^2) – the whole point of a factorial HMM. The E-step is exact over the joint state; the M-step is the standard factorial marginal update (each factor re-estimated from the marginalized joint transition mass), verified to keep EM monotone.- Parameters:
op1 (TransitionOperator)
op2 (TransitionOperator)
- forward(alpha)[source]
Push a joint belief through the Kronecker-factorized transition.
- backward(v)[source]
Pull a joint vector backward through the Kronecker transition.
- as_matrix()[source]
Materialize the dense Kronecker transition matrix.
- new_accumulator()[source]
Create marginal transition-count accumulators for both factors.
- accumulate(acc, alpha_t, w_next, scale)[source]
Accumulate exact marginalized factor transition statistics.
- estimate(acc)[source]
Estimate both Kronecker factors from marginalized expected counts.
- class SparseTransition(n_states, edges, values=None)[source]
Bases:
TransitionOperatorOnly the given
(from, to)edges are allowed (left-to-right / banded HMMs). Forward, backward and the M-step are O(#edges) – transitions outside the edge set stay exactly zero through EM, so the structure is preserved. Build edges yourself or withleft_to_right_edges()/banded_edges().- Parameters:
n_states (int)
- forward(alpha)[source]
Push a state-belief row vector through the sparse transition.
- backward(v)[source]
Pull a vector backward through the sparse transition.
- as_matrix()[source]
Materialize the sparse transition as a dense matrix.
- new_accumulator()[source]
Create one expected-count slot per allowed edge.
- accumulate(acc, alpha_t, w_next, scale)[source]
Accumulate one sparse expected-transition contribution.
- estimate(acc)[source]
Estimate a sparse transition over the same allowed edge set.
- class InputOutputHMM(emissions, pi, transitions, emission_estimators=None, name=None, terminal_states=None)[source]
Bases:
objectInput-output HMM (IOHMM): an exogenous discrete input
u_tselects which transition governs each step. Holds oneTransitionOperatorper input symbol; the emission is per-state. Data is(obs_seq, input_seq)pairs whereinput_seq[t]in {0..M-1} drives the transition from t to t+1.Lets a covariate steer the dynamics – regime switching driven by an observed control, the difference between a plain HMM and a controlled Markov model. (Input-dependent emissions are a natural extension; here emissions depend on state only.)
- seq_log_density(x, input_seqs=None)[source]
Per-sequence forward log-likelihood. Two call forms: -
seq_log_density(obs_seqs, input_seqs)– the explicit two-list API; or -seq_log_density(records)– one list of(obs, input)-pair sequences (the 5-part contract).
- viterbi(seq, inputs=None)[source]
Most-likely state path (Viterbi / max-product), conditioned on the input/control sequence: step t -> t+1 maximizes over the transition
inputs[t]selects. Call asviterbi(record)on one(observation, input)-pair sequence or asviterbi(obs_seq, input_seq). Uses the per-input transition matrices, so it works for any operator; O(T K^2) – a read-out, not the EM hot loop.
- posterior_decode(seq, inputs=None)[source]
Per-position MAP state argmax_k P(z_t = k | x, u) from the forward-backward posteriors gamma.
- state_posteriors(seq, inputs=None)[source]
The full smoothing posteriors gamma[t,k] = P(z_t = k | x, u), conditioned on the inputs.
- sampler(seed=None)[source]
Return a sampler for
(observation, input)-pair records along a given control sequence.
- fit(obs_seqs, input_seqs, *, max_its=50, tol=1e-6, weights=None)[source]
Fit the IOHMM by weighted Baum-Welch and return a diagnostics-bearing result.
- log_density(seq)[source]
Return the log likelihood of one
(observation, input)sequence.
- dist_to_encoder()[source]
Return the pass-through IOHMM sequence encoder.
- estimator(pseudo_count=None)[source]
Return the estimator for this IOHMM structure.
- class ExplicitDurationHMM(emissions, pi, transition_matrix, durations, max_duration, name=None)[source]
Bases:
objectHidden semi-Markov model (explicit-duration HMM): each state emits for a random duration drawn from a per-state duration distribution, then switches state (the transition matrix has a zero diagonal – dwell time is modeled explicitly, not as a self-loop). This captures non-geometric state durations a plain HMM cannot.
durationsis one length-max_durationprobability vector per state (over d = 1..max_duration). A sequence has an exogenous fixed observation horizon. Its final latent duration is right-censored when it extends beyond that horizon, exactly matchingsample(length). Forward/EM are O(T * K * max_duration).- forward_loglik(seq)[source]
Fixed-horizon log likelihood, marginalizing a possibly right-censored final duration.
- fit(seqs, *, max_its=50, tol=1e-6, weights=None)[source]
Fit the explicit-duration HMM by weighted Baum-Welch with a diagnostics receipt.
- log_density(seq)[source]
Return the explicit-duration HMM log likelihood for one sequence.
- seq_log_density(x)[source]
Score a batch of observation sequences.
- dist_to_encoder()[source]
Return the pass-through explicit-duration sequence encoder.
- estimator(pseudo_count=None)[source]
Return the estimator for this explicit-duration HMM structure.
- to_structured_hmm(len_dist=None)[source]
The HSMM as an EQUIVALENT StructuredHMM via the remaining-duration expansion: K*D sub-states (k, r) = “state k with r steps left in the segment”. The expanded chain emits from state k at every sub-state, decrements deterministically (k,r)->(k,r-1), and at (k,1) switches segment with A[k,k’]*dur[k’](d’). Reading the first T expanded-chain emissions exactly represents the right-censored fixed horizon, so no final-state constraint is applied. This hands the HSMM the full StructuredHMM read-out API and, with
len_dist, enumeration. O(K*D) states.
- enumerator(len_dist)[source]
Enumerate fixed-horizon observation sequences in descending marginal probability, given a
len_distover total sequence length. Built on the exact right-censored HMM expansion;.top_k(k)-> [(sequence, log_prob), …].
- state_posteriors(seq)[source]
Per-position smoothing posteriors gamma[t, j] = P(z_t = j | obs), marginalizing the durations (sum the posterior of every segment that covers position t). Rows sum to 1.
- posterior_decode(seq)[source]
Per-position MAP state argmax_j P(z_t = j | obs).
- viterbi_segments(seq)[source]
Most-likely segmentation (max-product over the segment lattice): a list of (state, start, observed_duration) segments covering the sequence, O(T K D). The last tuple describes the observed portion of a right-censored latent duration.
- sampler(seed=None)[source]
Return a sampler for explicit-duration HMM sequences.
- class HMMFitDiagnostics(algorithm, converged, iterations, termination_reason, log_likelihood_trace, initial_log_likelihood, final_log_likelihood, final_absolute_delta, final_relative_delta, monotone, n_sequences, total_weight, approximate)[source]
Bases:
objectMachine-readable receipt for a structured-family EM fit.
- class HMMFitResult(model, trace, diagnostics)[source]
Bases:
tupleBackward-compatible
(model, trace)result with a fit diagnostics receipt.- property model
Return the fitted model.
- property log_likelihood_trace
Return the accepted model log-likelihood trajectory.
- jit_forward_loglik(hmm)[source]
Compile the scaled forward log-likelihood recursion to a single jax.jit XLA program (lax.scan over time). Returns a callable
score(seq) -> float: emission log-densities are evaluated on the host (arbitrary emissions), then the forward scan runs jitted on the transition matrix. Works for any operator (usesas_matrix()); the win is large T / K. Requires the JAX optional extra.Precision follows the caller’s ambient JAX policy rather than mixle’s: with the default
jax_enable_x64=Falsethe scan runs in float32, so the returned score agrees withseq_log_densityto roughly float32 relative precision, not to float64. Enable x64 in your own process if you need more – mixle does not set it for you (MXR-080-0147 removed the import-time global mutation that used to make this path silently float64).- Parameters:
hmm (StructuredHMM)
- stationary_initial(op, *, iters=2000, tol=1e-13)[source]
The transition’s stationary distribution (pi @ A == pi), by power iteration through
op.forward– so it is O(K r) for a low-rank op, never forming A. Use it to COUPLE a StructuredHMM’s initial state to its transition (pi = stationary_initial(transition)): the chain starts in its long-run distribution instead of a free, separately-estimated pi. Answers “do the initial states match the transition?” – they can, by construction.
- sticky_transition(a, kappa)[source]
A dense transition with a STICKY self-transition prior:
kappapseudocounts on the diagonal favor staying in a state (longer dwell times, cleaner segmentation – the sticky-HMM idea).- Parameters:
kappa (float)
- Return type:
DenseTransition
- dirichlet_transition(a, alpha)[source]
A dense transition with a symmetric Dirichlet(
alpha) smoothing prior on every row (MAP).- Parameters:
alpha (float)
- Return type:
DenseTransition
- kron_initial(pi1, pi2)[source]
Factorized initial distribution
pi1 (x) pi2for a factorial (Kronecker) HMM – the two chains start independently. Matches aKroneckerTransitionso the joint initial respects the factors.- Return type:
- left_to_right_edges(n_states, skip=1)[source]
Edges for a left-to-right (Bakis) HMM: each state may stay or advance up to
skipstates.
- banded_edges(n_states, bandwidth=1)[source]
Edges for a banded transition: state i connects to i-bandwidth .. i+bandwidth (local time-series).
- exception HiddenMarkovNonterminationError(*, mode, max_steps, last_state=None)[source]
Bases:
RuntimeErrorRaised when bounded stopping-time sampling does not reach its terminal event.
- class HiddenMarkovModelDistribution(topics=MISSING, w=MISSING, transitions=MISSING, taus=None, len_dist=NullDistribution(), name=None, terminal_values=None, use_numba=None, weights=MISSING, prior=None, terminal_states=None, components=MISSING)[source]
Bases:
SequenceEncodableProbabilityDistributionHidden Markov model distribution for variable-length observation sequences.
- Parameters:
topics (Sequence[SequenceEncodableProbabilityDistribution])
w (Sequence[float] | np.ndarray)
len_dist (SequenceEncodableProbabilityDistribution | None)
name (str | None)
terminal_values (set[T] | None)
use_numba (bool | None)
weights (Sequence[float] | np.ndarray)
components (Sequence[SequenceEncodableProbabilityDistribution])
- get_prior()[source]
Returns the chain conjugate prior in
(init_prior, row_priors)form (or None).Per-state emission component priors are owned by the emission distributions themselves.
- set_prior(prior)[source]
Set the conjugate Dirichlet chain prior and precompute its digamma expectations.
With Dirichlet
init_priorand Dirichletrow_priors(over the fixed hidden states 0..S-1) this caches the digamma expectations E[ln p_k] = psi(alpha_k) - psi(sum alpha) used by expected_log_density and setshas_conj_prioraccordingly.prior=Noneleaves the distribution a plain point model.- Parameters:
prior –
(init_prior, row_priors)tuple or None.- Return type:
None
- expected_log_density(x)[source]
Forward log-likelihood with digamma-expected initial/transition log-probabilities and the topics’ expected_log_density emissions.
Falls back to the plug-in log_density(x) when no conjugate prior is set. Not supported for the taus/topic-mixture parameterization (falls back to log_density there).
- Parameters:
x (List[T]) – Observed sequence of HMM emissions.
- Returns:
Expected log-density of the observed HMM sequence x.
- Return type:
- seq_expected_log_density(x)[source]
Vectorized expected_log_density() at sequence-encoded input x.
Falls back to seq_log_density(x) when no conjugate prior is set or for the taus parameterization.
- compute_capabilities()[source]
Return compute-backend metadata for HMM scoring and Baum-Welch updates.
- compute_declaration()[source]
Return the symbolic declaration for HMM chain, emission, and length statistics.
- density(x)[source]
Returns the density of HMM for an observed sequence x.
See ‘HiddenMarkovDistribution.log_density()’ for details.
- Parameters:
x (List[T]) – Observed sequence of HMM emissions.
- Returns:
Density of HMM for observed sequence x.
- Return type:
- log_density(x)[source]
Returns the log-density of HMM for observed sequence x.
Density for a sequence of length N is given by recursively evaluating the conditional density,
p_mat(x_mat(0),x_mat(1),....,x_mat(t)) = p_mat(x_mat(t) given x_mat(0),...,x_mat(t-1)) = p_mat(x_mat(t) given Z(t)) * p_mat(Z(t) given Z(t-1)) * p_mat(Z(t-1) given x_mat(0),....,x_mat(t-1))for t = 1,2,…,N-1. p_mat(Z(0)) is given by ‘w’, p_mat(x_mat(t)|Z(t)) is given by emission distribution ‘topics’ for t = 0,1,…,N-1.
The returned density is given by
p_mat(x_mat) = p_mat(x_mat(0),x_mat(1),….,x_mat(t))*P_len(N).
where P_len(N) is the length distribution ‘len_dist’, if assigned. Note: All calculations are done on the log scale with log-sum-exp used to prevent numerical underflow.
If ‘has_topics’ is true, ‘weighed_log_sum_exp’ and ‘log_sum’ calls from mixle.utils.vector are used to handle the emission distributions being treated as mixture distributions with weights ‘log_taus’.
- Parameters:
x (List[T]) – Observed sequence of HMM emissions.
- Returns:
Log-density of observed HMM sequence x.
- Return type:
- seq_log_density(x)[source]
Return one HMM log-density value per encoded observation sequence.
Impossible observation/state combinations are reported as
-infin the returned vector. Valid finite inputs should not produceNaNin the public result.
- backend_seq_log_density(x, engine)[source]
Engine-neutral forward scores for non-numba encoded HMM batches.
The compiled/numba encoding remains on the legacy NumPy path. The standard blocked encoding is converted through the active engine and composes child distribution-owned backend scores.
- seq_posterior(x, filtered=False)[source]
Return per-sequence posterior state probabilities for encoded observations.
Each returned array holds the forward-backward SMOOTHING marginals
P(z_t = k | x_1..T)(one row per position), matching every otherseq_posteriorin the package. Passfiltered=Truefor the forward-only filtered probabilitiesP(z_t = k | x_1..t).
- viterbi(x)[source]
Return the most likely latent-state path for a single observation sequence.
The path is recovered by backpointer backtracking (max-product / Viterbi), so it is the jointly most probable state SEQUENCE – not the per-position argmax of the score matrix.
- latent_posterior(x)[source]
Return the exact chain posterior
q(z | x)over hidden states for one observation sequence.The returned
MarkovChainLatentPosteriorcan.marginals()(forward-backward smoothing probabilities),.sample(rng)a full state path by FFBS,.mode()(the Viterbi path), or.entropy()(the exact chain entropy).- Parameters:
x (list[T])
- Return type:
MarkovChainLatentPosterior
- posterior_predictive(x, seed=None)[source]
Draw a new observation sequence conditioned on
x.Sample a full hidden-state path from the posterior
q(z | x)by FFBS, then emit a fresh observation from each state’s emission distribution – “given the sequence I saw, draw a new sequence from the states it most likely passed through”. Returns a list the length ofx.
- seq_viterbi(x)[source]
Return maximum-likelihood hidden-state assignments for encoded sequences.
Each sequence’s assignment is its Viterbi path, recovered by backpointer backtracking. The result is indexed in the encoder’s flattened sequence layout (time-banded for the blocked encoding, sequence-contiguous for the numba encoding). Use the data encoder metadata to map flattened assignments back to individual sequences when working directly with encoded data.
- to_fisher(**kwargs)[source]
Return a Fisher view backed by HMM forward-backward statistics.
- density_semantics()[source]
Return joined density semantics over emissions and the optional length distribution.
- sampler(seed=None)[source]
Create a sampler for hidden paths and emitted observations.
Sampling requires either a length distribution or terminal-state stopping behavior. When a length distribution is present, it should be a sequence-encodable distribution over nonnegative integers.
- Parameters:
seed (int | None) – Optional seed for the sampler’s random state.
- Returns:
A
HiddenMarkovSamplerconfigured with the model parameters.- Return type:
HiddenMarkovSampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this hidden Markov distribution.
- Parameters:
pseudo_count (Optional[float]) – Prior mass used to smooth transition and emission statistics.
- Returns:
Estimator configured with matching emission and length estimators.
- Return type:
HiddenMarkovEstimator
- decomposition()[source]
The HMM splits along its STATE axis (the per-state emission distributions).
Unlike a mixture this is NOT suff-stat-separable – the forward-backward couples all states across time – so the executor does not reduce it; instead the per-state emission scoring and accumulation (the dominant cost for rich emissions) are distributed inside the Baum-Welch E-step (host-shard mode,
engine_axis=None), while the recursion stays serial. Exposing the axis lets the balance planner use the cluster for a massive HMM even on a single observation sequence.
- dist_to_encoder()[source]
Return an encoder for HMM observation sequences and optional lengths.
- Return type:
HiddenMarkovDataEncoder
- enumerator()[source]
Return an enumerator over observation sequences in descending marginal probability order.
- Return type:
HiddenMarkovModelEnumerator
- determinize(max_states=1 << 16, max_denominator=10**9)[source]
Weighted determinization (Mohri 1997; Mohri & Riley 2002) of this terminal-value HMM into a
DeterminizedSequenceDistribution.Rebuilds the (possibly ambiguous) machine over belief states so each sequence has a single path and edge weights multiply to the exact marginal – giving exact, duplicate-free n-best sequences and sub-linear structural seek, where ranking the original HMM gives n-best paths. Float probabilities are rationalized (
max_denominator) for decidable belief-equality. Requires terminal_values and finite/enumerable emissions; raises EnumerationError if not finitely determinizable withinmax_states(the twins property fails – keep the original HMM’s exact O(index) path instead).
- quantized_count_index(quantizer, max_fine_bucket)[source]
BoundedCount for the MARGINAL HMM law: a forward count DP over the trellis with an iterative emission-split unrank, reaching a 2**M budget structurally.
log p(x) = logsumexp over latent paths. We count (state-path, observation) PAIRS by their joint cost log w_{s0} + sum_t log trans(s_t|s_{t-1}) + sum_t log emit_{s_t}(x_t): the forward DP pools paths into a per-(length, end-state) count histogram, where each step convolves the prefix histogram with the emission’s count index (choosing the emitted symbol). This is the HMM analogue of the Mixture bound – a conservative UPPER bound that does NOT deduplicate an observation produced by multiple paths and bins by the joint (dominant-path / tropical) cost rather than the exact logsumexp; every unranked value still carries its exact marginal
log_density. Unranking is one iterative backward walk over t: each step does a local times-split (recover the emitted symbol + bucket split) and a plus-choice (recover the predecessor state) – O(L), no recursion. Falls back to capped enumerate-and-bin for non-plain HMMs (taus / terminal_values) or emissions that cannot count structurally.- Parameters:
max_fine_bucket (int)
- is_canonical_copy(value, coarse_bin, quantizer)[source]
Stateless dedup: keep an observation only at its min-cost (canonical) path’s bin.
The structural index emits an observation once per state-path that can generate it; the canonical copy is the one at the minimal joint fine bucket. A min-plus forward pass over the trellis computes that minimum exactly (mirroring the count-index’s fine-bucket sums), so the check is O(L * n_states^2) with no state. Falls back to True for non-plain HMMs.
- class HiddenMarkovEstimator(estimators, len_estimator=NullEstimator(), pseudo_count=(None, None), name=None, keys=(None, None, None), use_numba=None, prior=None, steady_state_init=False, terminal_states=None)[source]
Bases:
ParameterEstimatorEstimator for HMM initial, transition, emission, and optional length distributions.
- Parameters:
- accumulator_factory()[source]
Return a factory that accumulates Baum-Welch statistics for this estimator.
- get_prior()[source]
Returns the chain conjugate prior in
(init_prior, row_priors)form (or None).Per-state emission component priors are owned by the topic estimators themselves.
- set_prior(prior)[source]
Set the conjugate Dirichlet chain prior and flag whether it admits the conjugate update.
- Parameters:
prior –
(init_prior, row_priors)tuple or None; has_conj_prior is set when both the initial-state prior and all row priors are Dirichlet.- Return type:
None
- model_log_density(model)[source]
Log-density of the model parameters under the priors (ELBO global term).
Sums the Dirichlet log-densities of the initial-state and transition probabilities (floored at a tiny constant so boundary MAP estimates score finitely) plus each topic estimator’s model_log_density of its emission distribution. Returns the emission-only sum without a conjugate chain prior.
- Parameters:
model (HiddenMarkovModelDistribution) – Model to score.
- Returns:
Prior log-density of the model parameters.
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate HiddenMarkovModel from aggregated sufficient statistics contained in arg ‘suff_stat’.
Sufficient statistics in arg ‘suff_stat’ are a Tuple containing:
suff_stat[0] (int): Number of hidden states. suff_stat[1] (np.ndarray): Initial state counts. suff_stat[2] (np.ndarray): State counts. suff_stat[3] (np.ndarayy): State transition counts. suff_stat[4] (List[T1]): List of Sufficient statistics for the emission distribution accumulators. Each having type S0. suff_stat[5] (Optional[T2]): Optional sufficient statistics of the length distribution.
Note: T1 is the type for the sufficient statistics of the emission accumulators. T2 is the type for the length accumulator.
If pseudo_count[0] is not None, the initial counts in ‘suff_stat’ is re-weighted in estimation. If pseudo_count[1] is not None, the transition counts in ‘suff_stat’ are re-weighted in estimation.
- class HiddenMarkovModelEnumerator(dist, topics=None, log_w=None, log_transitions=None, len_dist=None, path_root=None)[source]
Bases:
DistributionEnumeratorBest-first enumerator over HMM observation sequences marginalized over hidden states.
- Parameters:
dist (SequenceEncodableProbabilityDistribution)
topics (Sequence[SequenceEncodableProbabilityDistribution] | None)
log_w (np.ndarray | None)
log_transitions (np.ndarray | None)
len_dist (SequenceEncodableProbabilityDistribution | None)
path_root (str | None)
- HiddenMarkovModelEstimator
alias of
HiddenMarkovEstimator
- class QuantizedHiddenMarkovModelDistribution(theta, levels, transition_exponents, emission_exponents, initial_exponents=None, init_mode='quantized', k_max=None, len_dist=NullDistribution(), name=None, terminal_values=None, use_numba=None, terminal_states=None, fit_diagnostics=None)[source]
Bases:
HiddenMarkovModelDistributionHidden Markov model distribution with quantized observation summaries.
- Parameters:
theta (float)
levels (Sequence[Any])
transition_exponents (Sequence[Sequence[int]] | np.ndarray)
emission_exponents (Sequence[Sequence[int]] | np.ndarray)
initial_exponents (Sequence[int] | np.ndarray | None)
init_mode (str)
k_max (int | None)
len_dist (SequenceEncodableProbabilityDistribution | None)
name (str | None)
terminal_values (set | None)
use_numba (bool | None)
fit_diagnostics (QuantizedHMMFitDiagnostics | None)
- compute_declaration()[source]
Return the generated-compute declaration for the quantized HMM.
- classmethod left_to_right(theta, levels, transition_exponents, emission_exponents, initial_exponents=None, **kwargs)[source]
Construct a left-to-right (upper-triangular) quantized HMM.
transition_exponentsmust be upper triangular: every entry strictly below the diagonal is a structural zero (negative exponent), so the hidden-state path is monotone non-decreasing (a Bakis chain). This makes a sentence’s state paths exactly its monotone segmentations – only polynomially many in the length (O(L^{n-1})) rather than then^Lof a general HMM – which bounds the path/sequence ambiguity. When the per-state emission supports are additionally disjoint the model is unambiguous (one path per sentence); then the structural descending-probability seek/unrank coincides with the exact marginal order (up to quantization granularity, no path over-count), which a general HMM’s structural seek cannot.- Raises:
ValueError – if
transition_exponentsis not square or not upper triangular.- Parameters:
- Return type:
QuantizedHiddenMarkovModelDistribution
- to_fisher(**kwargs)[source]
Forward-backward Fisher view for the quantized HMM.
- estimator(pseudo_count=None)[source]
Return an estimator matching this quantized HMM configuration.
- Parameters:
pseudo_count (Optional[float]) – Per-cell pseudo count for the initial, transition, and emission expected counts. When None, unobserved cells become structural zeros.
- Returns:
QuantizedHiddenMarkovEstimator object.
- Return type:
QuantizedHiddenMarkovEstimator
- enumerator()[source]
Return an exact descending-probability enumerator over observation sequences.
For the ordinary (length-distribution) case this is the quantized-HMM-specialized enumerator, which avoids constructing per-state categorical streams and uses the cached quantized emission log-probability matrix directly. For the
terminal_valuesstopping-time case it delegates toHiddenMarkovModelEnumerator, which implements that support (the quantized specialization only covers the length-distribution path).
- determinize(max_states=1 << 16)[source]
Weighted determinization (Mohri 1997; Mohri & Riley 2002) of this terminal-value quantized HMM into a
DeterminizedSequenceDistribution.Rebuilds the machine over belief states (exact rational arithmetic) so each sequence has a single path and edge weights multiply to the exact marginal – yielding exact, duplicate-free n-best sequences (not n-best paths). Requires terminal_values. Raises EnumerationError if the belief expansion exceeds
max_states(the twins property fails – not finitely determinizable; keep the original HMM’s exact O(index) enumerate-and-bin path instead).- Parameters:
max_states (int)
- class QuantizedHiddenMarkovEstimator(num_states, levels=None, pseudo_count=None, k_max=None, fixed_theta=None, init_mode='quantized', len_estimator=NullEstimator(), name=None, keys=(None, None, None), use_numba=None, max_quant_its=50, split_collapsed=False, split_nats=math.log(2.0))[source]
Bases:
ParameterEstimatorEstimate quantized hidden Markov models from accumulated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Returns a HiddenMarkovAccumulatorFactory with categorical emission accumulators.
- Return type:
HiddenMarkovAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a QuantizedHiddenMarkovModelDistribution from Baum-Welch expected counts.
- Sufficient statistics in arg ‘suff_stat’ are the HiddenMarkovAccumulator value:
suff_stat[0] (int): Number of hidden states. suff_stat[1] (np.ndarray): Initial state counts. suff_stat[2] (np.ndarray): State counts. suff_stat[3] (np.ndarray): State transition counts. suff_stat[4] (Sequence[Dict[Any, float]]): Per-state categorical emission counts. suff_stat[5] (Optional[Any]): Optional sufficient statistics of the length distribution.
- Parameters:
- Returns:
QuantizedHiddenMarkovModelDistribution object.
- Return type:
QuantizedHiddenMarkovModelDistribution
- class QuantizedHiddenMarkovModelEnumerator(dist)[source]
Bases:
DistributionEnumeratorExact best-first enumerator specialized for QuantizedHiddenMarkovModelDistribution.
- Parameters:
dist (QuantizedHiddenMarkovModelDistribution)
- QuantizedHiddenMarkovModelEstimator
alias of
QuantizedHiddenMarkovEstimator
- class HierarchicalMixtureDistribution(topics, mixture_weights, topic_weights, len_dist=NullDistribution(), name=None, keys=(None, None))[source]
Bases:
SequenceEncodableProbabilityDistributionOuter mixture over sequence mixtures with shared topic distributions.
Data type:
Sequence[T], whereTis the data type of the topic distributions.- Parameters:
- compute_capabilities()[source]
Declare generated-compute support inherited from topics and length model.
- compute_declaration()[source]
Return the generated-compute declaration for the hierarchical mixture.
- density(x)[source]
Evaluate the density of an observation from hierarchical mixture distribution.
- Parameters:
x (Sequence[T]) – A sequence of type data type T’s.
- Returns:
Density evaluated at x.
- Return type:
- log_density(x)[source]
Evaluate the log density of an observation from hierarchical mixture distribution.
Note: Observation is a sequence.
- Parameters:
x (Sequence[T]) – A sequence of type data type T’s.
- Returns:
Log-density evaluated at x.
- Return type:
- posterior(x)[source]
Compute the posterior over the mixture components for the outer-mixture at observed value x.
- Parameters:
x (Sequence[T]) – An observed sequence of data type T.
- Returns:
Numpy array of length ‘num_mixtures’.
- Return type:
- component_log_density(x)[source]
Evaluate the component-wise log-density for an observation from a hierarchical mixture model.
- Parameters:
x (Sequence[T]) – An observation from a hierarchical mixture model.
- Returns:
Numpy array length of ‘num_mixtures’.
- Return type:
- to_mixture()[source]
Return the equivalent flat mixture of sequence distributions.
- Return type:
MixtureDistribution
- seq_component_log_density(x)[source]
Vectorized evaluation of the outer-mixture component-wise log-density for an encoded sequence x.
This returns a numpy array with shape (rv[0], ‘num_mixtures’).
Note: This density is a Mixture of Sequence of Mixture, so the data must be bin-counted as last step in code.
- Encoded sequence ‘x’ is a Tuple of length 5 containing:
x[0] (int): Number of independent observations. x[1] (ndarray[int]): Observation sequence index for each value in flattened x. x[2] (ndarray[int]): Length of each observation in x. x[3] (E): Encoded sequence of flattened observed values (has type E). x[4] (Optional[E2]): Encoded sequence of lengths (has type E2).
- seq_log_density(x)[source]
Vectorized evaluation of the log-density for an encoded sequence of observations in x.
- Encoded sequence ‘x’ is a Tuple of length 5 containing:
x[0] (int): Number of independent observations. x[1] (ndarray[int]): Observation sequence index for each value in flattened x. x[2] (ndarray[int]): Length of each observation in x. x[3] (E): Encoded sequence of flattened observed values (has type E). x[4] (Optional[E2]): Encoded sequence of lengths (has type E2).
- backend_seq_component_log_density(x, engine)[source]
Engine-neutral outer-component log densities for hierarchical-mixture encoded sequences.
- backend_seq_log_density(x, engine)[source]
Engine-neutral hierarchical-mixture log-density for encoded sequences.
- seq_posterior(x)[source]
Vectorized evaluation of the posterior over each outer-mixture component for an encoded sequence x.
- Encoded sequence ‘x’ is a Tuple of length 5 containing:
x[0] (int): Number of independent observations. x[1] (ndarray[int]): Observation sequence index for each value in flattened x. x[2] (ndarray[int]): Length of each observation in x. x[3] (E): Encoded sequence of flattened observed values (has type E). x[4] (Optional[E2]): Encoded sequence of lengths (has type E2).
- to_fisher(**kwargs)[source]
Reuse the equivalent flat mixture’s Fisher view.
- density_semantics()[source]
Return exact-or-approximate density semantics joined from child models.
- sampler(seed=None)[source]
Return a sampler for this hierarchical mixture.
- Parameters:
seed (int | None)
- Return type:
HierarchicalMixtureSampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this hierarchical mixture.
- Parameters:
pseudo_count (Optional[float]) – Prior mass used to smooth mixture and topic weights during estimation.
- Returns:
Estimator configured with matching topic and length estimators.
- Return type:
HierarchicalMixtureEstimator
- dist_to_encoder()[source]
Return a data encoder for iid hierarchical-mixture observations.
- Return type:
HierarchicalMixtureDataEncoder
- enumerator()[source]
Returns a HierarchicalMixtureEnumerator iterating sequences in descending probability order.
- Return type:
HierarchicalMixtureEnumerator
- class HierarchicalMixtureEstimator(estimators, num_mixtures, len_estimator=NullEstimator(), len_dist=None, suff_stat=None, pseudo_count=None, name=None, keys=(None, None))[source]
Bases:
ParameterEstimatorEstimate hierarchical-mixture distributions from sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
HierarchicalMixtureEstimatorAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a hierarchical mixture from aggregated sufficient statistics.
suff_statis a four-item tuple containing:suff_stat[0] (ndarray[float]): Aggregated token-level component counts with shape (num_mixtures, num_topics). Row-normalized into the topic weightstaus. suff_stat[1] (ndarray[float]): Aggregated document-level outer-posterior sums with length num_mixtures. Normalized into the outer weightsw-- the EM maximizer forwis the document-level posterior sum, NOT the (length-weighted) token-level row sums. suff_stat[2] (Tuple[SS1,...]): One sufficient-statistic value per topic. suff_stat[3] (Optional[SS2]): Sufficient statistics for the length estimator.
- class HierarchicalMixtureEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates the support of a HierarchicalMixtureDistribution in descending probability order.
- Parameters:
dist (HierarchicalMixtureDistribution)
- class IndianBuffetProcessDistribution(num_features, alpha=1.0, beta_params=None, feature_probs=None, min_prob=1.0e-128, name=None, keys=None, data_format='auto')[source]
Bases:
SequenceEncodableProbabilityDistributionFinite-truncated Indian buffet process over binary feature rows.
- Parameters:
num_features (int) – Truncation level K.
alpha (float) – IBP concentration parameter.
beta_params (Sequence[Sequence[float]] | ndarray | None) – Optional (K, 2) variational Beta parameters for q(pi_k). If omitted, the prior Beta(alpha / K, 1) is used.
feature_probs (Sequence[float] | ndarray | None) – Optional plug-in feature probabilities. When supplied without beta_params, a lightweight Beta posterior with matching mean is created for expected-log-density calls.
min_prob (float) – Minimum plug-in probability used when feature_probs are given.
name (str | None) – Optional distribution name.
keys (str | None) – Optional key for tying sufficient statistics.
data_format (str) – ‘dense’, ‘sparse’, or ‘auto’ input interpretation.
- classmethod compute_capabilities()[source]
Declare generic table-kernel capabilities for finite IBP rows.
- classmethod compute_declaration()[source]
Return the structured declaration for finite IBP parameters and statistics.
- density(x)[source]
Return the probability density or mass at a single observation.
- density_semantics()[source]
Return that plug-in densities use posterior mean feature probabilities.
- log_density(x)[source]
Plug-in log-density of one feature row using E_q[pi_k].
- expected_log_density(x)[source]
VB expected log-density E_q[log p(z | pi)] for one observed row.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized plug-in log-density for encoded feature rows.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked finite-IBP parameters for equal-feature mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of finite-IBP component log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy
(feature_counts, total_count, alpha)statistics.
- seq_expected_log_density(x)[source]
Return vectorized expected log-density values for encoded observations.
- seq_local_elbo(x)[source]
Per-row VB contribution; rows are observed, so there is no local entropy.
- enumerator()[source]
Enumerate feature rows in descending probability order.
The plug-in row density factorizes over features –
log p(z) = sum_k [z_k log pi_k + (1-z_k) log(1-pi_k)]withpi_k = E_q[feature_probs]– so the truncated IBP row is a product of independent Bernoulli features and enumerates by best-first over the per-feature supports (the same structure as the Erdos-Renyi graph). Rows are emitted in the configureddata_format(a dense 0/1 list, or a sorted list of active feature indices when sparse), each carrying its exactlog_density.- Return type:
DistributionEnumerator
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
IndianBuffetProcessSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
IndianBuffetProcessEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
IndianBuffetProcessDataEncoder
- class IndianBuffetProcessEstimator(num_features, alpha=1.0, pseudo_count=None, suff_stat=None, estimate_alpha=True, min_alpha=1.0e-12, max_alpha=1.0e12, min_prob=1.0e-128, name=None, keys=None, data_format='auto')[source]
Bases:
ParameterEstimatorVariational Bayes estimator for the finite-truncated IBP.
pseudo_count follows the convention used by other mixle.stats Bernoulli estimators: if suff_stat is supplied, it is treated as a prior probability vector and re-weighted by pseudo_count; otherwise pseudo_count is centered at the IBP prior mean alpha / (alpha + K).
- Parameters:
- accumulator_factory()[source]
Return a factory for finite IBP sufficient-statistic accumulators.
- Return type:
IndianBuffetProcessAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Update the variational Beta posterior and optional concentration parameter.
- class IntegerChowLiuTreeDistribution(dependency_list, conditional_log_densities, feature_order=None, name=None, keys=None, pseudo_count=None, enumeration_item_budget=_DEFAULT_ENUMERATION_ITEM_BUDGET)[source]
Bases:
SequenceEncodableProbabilityDistributionInteger Chow-Liu tree distribution factorizing a joint over fixed-length integer vectors along a tree.
Data type: Union[Sequence[int], np.ndarray] (fixed-length vector of non-negative integers).
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for integer Chow-Liu generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the integer Chow-Liu tree.
- density(x)[source]
Density of integer Chow-Liu tree distribution at observation x.
See log_density() for details.
- log_density(x)[source]
Log-density of integer Chow-Liu tree distribution at observation x.
Sums the conditional log-densities of each feature given its parent in the dependency tree (the root feature contributes its marginal log-density).
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- Parameters:
x (np.ndarray) – 2-d numpy array of N integer vectors with num_features columns.
- Returns:
Numpy array of log-density (float) of length N.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized table lookup for fixed integer tree factors.
- sampler(seed=None)[source]
Create a sampler for this integer Chow-Liu tree distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
Sampler bound to this distribution.
- Return type:
IntegerChowLiuTreeSampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this integer Chow-Liu tree distribution.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics.
- Returns:
Estimator configured with the same feature count and state count.
- Return type:
IntegerChowLiuTreeEstimator
- dist_to_encoder()[source]
Return a data encoder for integer Chow-Liu tree observations.
- Return type:
IntegerChowLiuTreeDataEncoder
- class IntegerChowLiuStatistics(num_features, num_states, counts, marginal_counts)[source]
Bases:
NamedTupleVersioned, tuple-compatible integer Chow–Liu statistics.
- num_features: int
Alias for field number 0
- num_states: int
Alias for field number 1
- counts: ndarray
Alias for field number 2
- marginal_counts: ndarray
Alias for field number 3
- property schema_version: int
Return the serialized statistic schema version.
- class IntegerChowLiuTreeEstimator(num_features=None, num_states=None, pseudo_count=None, suff_stat=None, keys=None, name=None, enumeration_item_budget=_DEFAULT_ENUMERATION_ITEM_BUDGET)[source]
Bases:
ParameterEstimatorEstimator for the IntegerChowLiuTreeDistribution. Learns the dependency tree with the Chow-Liu algorithm.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- estimate(nobs, suff_stat)[source]
Estimate an IntegerChowLiuTreeDistribution from sufficient statistics via the Chow-Liu algorithm.
Pairwise mutual information is computed from the (optionally smoothed) joint and marginal counts, a maximum mutual information spanning tree is extracted, and conditional densities are computed along the tree rooted at feature 0.
- class IntegerChowLiuTreeEnumerator(dist, max_items=_DEFAULT_ENUMERATION_ITEM_BUDGET)[source]
Bases:
DistributionEnumeratorEnumerates the finite support of an integer Chow-Liu tree.
- Parameters:
dist (IntegerChowLiuTreeDistribution)
max_items (int | None)
- class IgnoredDistribution(dist, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionFixed-parameter wrapper that delegates the wrapped distribution’s likelihood exactly.
- Parameters:
dist (SequenceEncodableProbabilityDistribution | None)
name (str | None)
- compute_capabilities()[source]
Return the compute capabilities delegated from the wrapped distribution.
- compute_declaration()[source]
Return a declaration that marks this wrapper as carrying no estimable statistics.
- get_prior()[source]
Delegate to the wrapped distribution’s
get_prior(Ignored owns no prior).- Return type:
- set_prior(prior)[source]
Delegate to the wrapped distribution’s
set_prior;Nonekeeps existing behavior.- Parameters:
prior (Any)
- Return type:
None
- expected_log_density(x)[source]
Delegate prior-expected log-density to the wrapped distribution.
- Parameters:
x (T)
- Return type:
- seq_expected_log_density(x)[source]
Delegate vectorized prior-expected log-density to the wrapped distribution.
- Parameters:
x (E)
- Return type:
- density(x)[source]
Evaluate the density of the IgnoredDistribution at x.
- Parameters:
x (T) – Type corresponding to attribute ‘dist’.
- Returns:
Density of attribute ‘dist’ at x
- Return type:
- log_density(x)[source]
Evaluate the log-density of the IgnoredDistribution at x.
- Parameters:
x (T) – Type corresponding to attribute ‘dist’.
- Returns:
log-density of attribute ‘dist’ at x.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- Parameters:
x (E)
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density delegated to the wrapped distribution.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child parameters for homogeneous ignored-wrapper mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of delegated child log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return empty legacy statistics for each ignored component.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
IgnoredSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
IgnoredEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
IgnoredDataEncoder
- class IgnoredEstimator(dist=None, pseudo_count=None, suff_stat=None, keys=None, name=None)[source]
Bases:
ParameterEstimatorEstimator that returns the wrapped distribution unchanged inside an ignored wrapper.
- Parameters:
- accumulator_factory()[source]
Return a factory that creates no-op ignored accumulators.
- get_prior()[source]
Delegate to the wrapped distribution’s
get_prior(Ignored estimates nothing of its own).- Return type:
- class IntegerBernoulliEditDistribution(log_edit_pmat, init_dist=None, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBernoulli edit set distribution: each integer independently transitions in/out between two sets.
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for integer Bernoulli-edit generated kernels.
- density(x)[source]
Density of the Bernoulli edit set distribution at observation x.
See log_density() for details.
- log_density(x)[source]
Log-density of the joint observation (x[0], x[1]).
Computes log p(x[1] | x[0]) by summing per-integer edit log-probabilities for kept, added, and removed elements, plus log p(x[0]) under init_dist.
- conditional_log_density(previous, next_set)[source]
Return
log p(next_set | previous)without an initial-law factor.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- Parameters:
x (E) – Sequence encoded (prev set, next set) observations from IntegerBernoulliEditDataEncoder.seq_encode().
- Returns:
Numpy array of log-density values, one per encoded observation.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded integer edit-set observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer edit-set parameters for shared support and init policy.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer edit-set component log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy
(edit_counts, total_weight, init_stat)statistics.
- sampler(seed=None)[source]
Create a sampler for this integer Bernoulli edit distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
Sampler bound to this distribution.
- Return type:
IntegerBernoulliEditSampler
- estimator(pseudo_count=None)[source]
Create an IntegerBernoulliEditEstimator with matching num_vals.
- Parameters:
pseudo_count (Optional[float]) – Used to re-weight sufficient statistics in estimation.
- Returns:
Estimator configured with matching support size.
- Return type:
IntegerBernoulliEditEstimator
- dist_to_encoder()[source]
Return a data encoder for integer Bernoulli edit observations.
- Return type:
IntegerBernoulliEditDataEncoder
- enumerator()[source]
Returns IntegerBernoulliEditEnumerator iterating set-pairs in descending probability order.
- Return type:
IntegerBernoulliEditEnumerator
- exception IntegerBernoulliEditFitError[source]
Bases:
RuntimeErrorRaised when edit statistics do not identify a valid transition law.
- class IntegerBernoulliEditEstimator(num_vals=MISSING, init_estimator=None, min_prob=1.0e-128, pseudo_count=None, suff_stat=None, name=None, keys=None, num_values=MISSING)[source]
Bases:
ParameterEstimatorEstimate integer Bernoulli edit distributions from aggregated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
IntegerBernoulliEditAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an IntegerBernoulliEditDistribution from aggregated sufficient statistics.
- class IntegerBernoulliEditEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates finite previous/next integer-set pairs in descending probability order.
- Parameters:
dist (IntegerBernoulliEditDistribution)
- class IntegerStepBernoulliEditDistribution(log_edit_pmat, init_dist=None, name=None, keys=None)[source]
Bases:
IntegerBernoulliEditDistributionStep Bernoulli edit set distribution: each integer independently transitions in/out between two sets.
Identical in form to
IntegerBernoulliEditDistribution; only the estimator (a two-level step fit) differs.- Parameters:
- sampler(seed=None)[source]
Create a sampler for this integer step Bernoulli edit distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
Sampler bound to this distribution.
- Return type:
IntegerStepBernoulliEditSampler
- estimator(pseudo_count=None)[source]
Create an IntegerStepBernoulliEditEstimator with matching num_vals.
- Parameters:
pseudo_count (Optional[float]) – Used to re-weight sufficient statistics in estimation.
- Returns:
Estimator configured with matching support size.
- Return type:
IntegerStepBernoulliEditEstimator
- dist_to_encoder()[source]
Return a data encoder for integer step Bernoulli edit observations.
- Return type:
IntegerStepBernoulliEditDataEncoder
- enumerator()[source]
Returns IntegerStepBernoulliEditEnumerator iterating set-pairs in descending probability order.
- Return type:
IntegerStepBernoulliEditEnumerator
- class IntegerStepBernoulliEditEstimator(num_vals=MISSING, init_estimator=None, min_prob=1.0e-128, pseudo_count=None, suff_stat=None, name=None, keys=None, num_values=MISSING)[source]
Bases:
IntegerBernoulliEditEstimatorEstimate integer step Bernoulli edit distributions with a two-level edit-probability fit.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
IntegerStepBernoulliEditAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an IntegerStepBernoulliEditDistribution from aggregated sufficient statistics.
Per-element edit probabilities are estimated as in the non-step edit estimator, then the addition and removal probabilities are each replaced by a two-level step-function fit.
- class IntegerStepBernoulliEditEnumerator(dist)[source]
Bases:
IntegerBernoulliEditEnumeratorEnumerates finite previous/next integer-set pairs for the step edit-set distribution.
- Parameters:
dist (IntegerBernoulliEditDistribution)
- class IntegerHiddenAssociationDistribution(state_prob_mat, cond_weights, alpha=0.0, prev_dist=NullDistribution(), len_dist=NullDistribution(), name=None, keys=(None, None), use_numba=None)[source]
Bases:
SequenceEncodableProbabilityDistributionInteger hidden association model: words of a second set are emitted through hidden states conditioned on words of a first set.
- Parameters:
- compute_capabilities()[source]
Return backend capability metadata for this concrete integer association model.
- compute_declaration()[source]
Return the generated-compute declaration for integer hidden association.
- log_density(x)[source]
Log-density of the integer hidden association model at observation x.
For each emitted word in x[1], marginalizes over the given words in x[0] (weighted by count) and the hidden states, mixing with a uniform density with probability alpha. Adds the log-density of x[0] under prev_dist and of the total emission count under len_dist.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- Parameters:
x (E) – Sequence encoded observations from IntegerHiddenAssociationDataEncoder.seq_encode(). Uses the numba kernel when the encoding was produced with use_numba=True.
- Returns:
Numpy array of log-density values, one per encoded observation.
- Return type:
- backend_seq_log_density(x, engine)[source]
Evaluate encoded log-densities using a backend-neutral compute engine.
- conditional_word_log_probs(s1)[source]
Log of the per-emission word distribution
q(.|S1)for a given S1 bag, or None if empty.q(w|S1) = (1-alpha) * sum_u (c_u/n1) * sum_s cond_weights[u,s] * state_prob_mat[s,w] + alpha/W– the smoothed mixture the model uses to score each emitted word. Returns None for an empty S1 (n1 = 0), whose conditional is degenerate (the model’s own density is undefined there).
- enumerator()[source]
Enumerate
(S1, S2)observations in descending probability order.The model factors as
prev_dist(S1) * [prod_w q(w|S1)^{c_w}] * P_len(n2): the emitted bag S2 is a trial-count multinomial whose word distributionq(.|S1)depends on the given bag S1. Enumeration is a conditional product – the outer stream enumerates S1 fromprev_distand, for each S1, the inner stream enumerates S2 by the multinomial bag search underlen_dist, merged by descending total score withprev_dist(S1)as the outer frontier bound. Requires an enumerable, non-nullprev_distso the S1 support is defined.- Return type:
DistributionEnumerator
- sampler(seed=None)[source]
Return a sampler for iid integer hidden-association observations.
Requires non-null prev_dist and len_dist.
- Parameters:
seed (int | None) – Optional random seed.
- Returns:
A configured integer hidden-association sampler.
- Return type:
IntegerHiddenAssociationSampler
- estimator(pseudo_count=None)[source]
Return an estimator with matching dimensions and child estimators.
- Parameters:
pseudo_count (float | None) – Unused; accepted for protocol consistency.
- Returns:
A configured integer hidden-association estimator.
- Return type:
IntegerHiddenAssociationEstimator
- dist_to_encoder()[source]
Return an encoder for integer hidden-association observations.
- Return type:
IntegerHiddenAssociationDataEncoder
- class IntegerHiddenAssociationEstimator(num_vals, num_states, alpha=0.0, prev_estimator=NullEstimator(), len_estimator=NullEstimator(), suff_stat=None, pseudo_count=None, use_numba=None, name=None, keys=(None, None))[source]
Bases:
ParameterEstimatorEstimator for integer hidden-association distributions.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
IntegerHiddenAssociationAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an IntegerHiddenAssociationDistribution from aggregated sufficient statistics.
- Parameters:
nobs (Optional[float]) – Number of observations, passed to the prev and length estimators.
suff_stat (Tuple[np.ndarray, np.ndarray, np.ndarray, Optional[SS1], Optional[SS2]]) – Init counts, weight counts, state counts, prev suff stats, and size suff stats.
- Returns:
IntegerHiddenAssociationDistribution object.
- Return type:
IntegerHiddenAssociationDistribution
- class IntegerMarkovChainDistribution(num_values, cond_dist, lag=1, init_dist=NullDistribution(), len_dist=NullDistribution(), keys=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMarkov-chain distribution over integer-valued states.
- Parameters:
- compute_capabilities()[source]
Declare generated-compute support inherited from initial and length distributions.
- compute_declaration()[source]
Return the generated-compute declaration for the integer Markov chain.
- density_semantics()[source]
Classify missing initial/length laws as conditional likelihood factors.
- density(x)[source]
Density of integer Markov chain evaluated at x.
See log_density() for details.
- log_density(x)[source]
Log-density of integer Markov chain evaluated at x.
The initial child scores exactly the first
lagstates, each later state is scored by its lag-indexed transition row, and the length child scores the actual sequence length. Shorter observations are rejected.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at every observation in encoded sequence.
See log_density() for details on likelihood evaluation.
- Sequence encoded arg ‘x’ is a Tuple of length 7 containing:
seq_len (ndarray[int]): Actual observed sequence lengths. init_idx (ndarray[int]): Observed sequence index of chains with lengths >= lag. seq_idx (ndarray[int]): Observed sequence index of chains with transitions. u_seq_idx (ndarray[object]): Numpy array of tuples containing the unique transitions. u_seq_values (ndarray[object]): Numpy array of tuples containing the transitions. init_enc (Optional[E]): Sequence encoding of initial values (has type E). len_enc (Optional[E2]): Sequence encoding of length values (has type E2).
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for grouped integer Markov-chain encodings.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer Markov-chain parameters for shared support/lag.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer Markov-chain log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component versioned fixed-support sufficient statistics.
- sampler(seed=None)[source]
Return a sampler for this integer Markov chain.
- Parameters:
seed (int | None)
- Return type:
IntegerMarkovChainSampler
- transition_sampler(seed=None)[source]
Return a sampler exposing only
sample_givenfor conditional transition use.- Parameters:
seed (int | None)
- Return type:
IntegerMarkovChainSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this integer Markov chain.
- Parameters:
pseudo_count (float | None)
- dist_to_encoder()[source]
Return a data encoder for iid integer Markov-chain observations.
- Return type:
IntegerMarkovChainDataEncoder
- enumerator()[source]
Returns IntegerMarkovChainEnumerator iterating integer sequences in descending probability order.
- Return type:
IntegerMarkovChainEnumerator
- class IntegerMarkovChainEstimator(num_values, lag=1, init_estimator=NullEstimator(), len_estimator=NullEstimator(), init_dist=None, len_dist=None, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate integer Markov-chain transition probabilities and child models.
- Parameters:
- get_prior()[source]
Returns the implicit per-row symmetric-Dirichlet prior
pseudo_countinduces, or None.pseudo_countsmoothing (cond_mat += pseudo_countbefore row-normalizing inestimate()) is the exact MAP point estimate under an independentSymmetricDirichletDistribution(pseudo_count + 1)prior on each row of the conditional matrix – seemodel_log_density(). Letsmixle.inference.estimation.optimize()auto-detect the'map'objective instead of silently tracking plain (unpenalized) MLE for a pseudo-count-regularized fit.
- model_log_density(model)[source]
Log-density of the fitted conditional matrix under the implicit row prior (see
get_prior()), plusinit_dist/len_dist’s ownmodel_log_densitywhen the estimator that actually fit them (rather than a fixed, caller-supplied distribution) exposes one. Returns0.0(a plain MLE fit) whenpseudo_countis None.- Parameters:
model (IntegerMarkovChainDistribution)
- Return type:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
IntegerMarkovChainAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an integer Markov-chain distribution from versioned sufficient statistics.
- Parameters:
nobs (Optional[float]) – Number of observations used in aggregation of ‘suff_stat’.
suff_stat (IntegerMarkovChainStatistics) – See above for details.
- Returns:
IntegerMarkovChainDistribution object.
- Return type:
IntegerMarkovChainDistribution
- class IntegerMarkovChainEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates integer Markov-chain sequences in descending probability order.
- Parameters:
dist (IntegerMarkovChainDistribution)
- class IntegerMarkovChainStatistics(schema_version, num_values, lag, transition_counts, initial_nobs, initial, length_nobs, length)[source]
Bases:
NamedTupleImmutable sufficient statistics for one fixed integer-chain support.
- Parameters:
- schema_version: int
Alias for field number 0
- num_values: int
Alias for field number 1
- lag: int
Alias for field number 2
- initial_nobs: float
Alias for field number 4
- length_nobs: float
Alias for field number 6
- exception NonGenerativeIntegerMarkovChainError[source]
Bases:
TypeErrorRaised when a conditional integer-chain factor is asked to generate sequences.
- class IntegerProbabilisticLatentSemanticIndexingDistribution(state_word_mat, doc_state_mat, doc_vec, len_dist=NullDistribution(), name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionInteger-valued probabilistic latent semantic indexing distribution.
- Parameters:
- compute_capabilities()[source]
Return backend capability metadata for this concrete PLSI instance.
- compute_declaration()[source]
Return the symbolic distribution declaration for code generation and PPL introspection.
- density(x)[source]
Evaluate the density of PLSI model for an observation x.
See log_density() for details on the density evaluation.
- log_density(x)[source]
Evaluate the log-density of PLSI model for an observation of x.
Consider an Integer PLSI model for a corpus of documents with S states, V word values, and D documents ids (authors).
Let x (Tuple[int, Sequence[Tuple[int, float]]]) be an observation from a PLSI model, consisting of x = (d, [(v_0, c_0), (v_1, c_1), …, (v_{k-1}, c_{k-1})]), where the ‘d’ is some document d_id in the corpus and each tuple (v_i, c_i) corresponds to a value-count couple in the corpus. The log-likelihood is given by
log(p_mat(x)) = log(p_mat(d)) + sum_{j=0}^{k-1} c_k*log( sum_{s=0}^{S-1} p_mat(d|s)p_mat(s|v_k) ) + log(P_len(nn)),
where P_len(nn) is the density of the length distribution for ‘nn’ representing the total number of words in the document.
- component_log_density(x)[source]
Evaluate the log-density for each state in the PLSI.
Returns count*log(p_mat(W|S)) for each word-count pair in the document. Returned value is S by 1 where S is the number of components in the model.
- seq_log_density(x)[source]
Vectorized evaluation of the log-density for an encoded sequence of iid observation from a PLSI model.
See log_density() function for details on the log-likelihood.
The encoded sequence ‘x’ is a Tuple length 2. The first component contains data type Optional[T1] corresponding to the sequence encoding of the lengths. The second component is a Tuple of length 6 containing
xv (ndarray[int]): Numpy array of flattened word values. xc (ndarray[float]): Numpy array of flattened counts for word values above. xd (ndarray[int]): Document id for each word-count pair in the arrays above. xi (ndarray[int]): Observed sequence index for each word-count pair in the arrays above. xn (ndarray[float]): Numpy array of the total number of words in each document. xm (ndarray[float]): Flattened array of document id's for the lengths above (len = len(x)).
- backend_seq_log_density(x, engine)[source]
Evaluate encoded PLSI log densities using a backend-neutral compute engine.
- seq_component_log_density(x)[source]
- Vectorized evaluation of the component log-density for each observation in an encoded sequence of iid PLSI
observations.
See component_log_density() function for details on component log-likelihood evaluation.
The encoded sequence ‘x’ is a Tuple length 2. The first component contains data type Optional[T1] corresponding to the sequence encoding of the lengths. The second component is a Tuple of length 6 containing
xv (ndarray[int]): Numpy array of flattened word values. xc (ndarray[float]): Numpy array of flattened counts for word values above. xd (ndarray[int]): Document id for each word-count pair in the arrays above. xi (ndarray[int]): Observed sequence index for each word-count pair in the arrays above. xn (ndarray[float]): Numpy array of the total number of words in each document. xm (ndarray[float]): Flattened array of document id's for the lengths above (len = len(x)).
- enumerator()[source]
Enumerate PLSI observations
(doc_id, bag)in descending probability order.A PLSI observation factors as
P(doc) * [prod_w q_d(w)^{c_w}] * P_len(n)whereq_dis the per-document word distributionprob_mat @ state_mat[d]andnthe total word count, so it is a document-labelled mixture of trial-count multinomials: for each document the bags enumerate by a multiset best-first search under a length frontier driven bylen_dist(the real trial-count distribution), and the per-document streams are merged by descending score with the document log-probability as offset. Requires a modelledlen_distunless every per-document word distribution is sub-stochastic-free; an absent length distribution leaves the bag support infinite and is enumerated by the multinomial term alone.- Return type:
DistributionEnumerator
- sampler(seed=None)[source]
Return a sampler for iid integer PLSI observations.
- Parameters:
seed (int | None)
- Return type:
IntegerProbabilisticLatentSemanticIndexingSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s dimensions.
- Parameters:
pseudo_count (float | None) – Optional smoothing count for topic, word, and document counts.
- Returns:
A configured integer PLSI estimator.
- Return type:
IntegerProbabilisticLatentSemanticIndexingEstimator
- dist_to_encoder()[source]
Return an encoder for integer PLSI observations.
- Return type:
IntegerProbabilisticLatentSemanticIndexingDataEncoder
- class IntegerProbabilisticLatentSemanticIndexingEstimator(num_vals, num_states, num_docs, len_estimator=NullEstimator(), pseudo_count=(None, None, None), suff_stat=(None, None, None), name=None, keys=(None, None, None))[source]
Bases:
ParameterEstimatorEstimator for integer PLSI word/state/document probabilities and the optional length model.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
IntegerProbabilisticLatentSemanticIndexingAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an integer PLSI distribution from aggregated sufficient statistics.
- Parameters:
- Returns:
A fitted integer PLSI distribution.
- Return type:
IntegerProbabilisticLatentSemanticIndexingDistribution
- class IntegerUniformSpikeDistribution(k, num_vals, p, min_val=0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionUniform integer distribution with extra probability mass at one value.
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for integer-uniform-spike generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the integer uniform spike.
- density(x)[source]
Density of the integer uniform spike distribution at observation x.
See log_density() for details.
- log_density(x)[source]
Log-density of the integer uniform spike distribution at observation x.
Returns log(p) if x equals the spike value k, log((1-p)/(num_vals-1)) for any other integer in [min_val, max_val], and -inf outside the range.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- Parameters:
x (np.ndarray) – Numpy array of integer observations.
- Returns:
Numpy array of log-density (float) of len(x).
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral log-density for encoded integer spike observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer-uniform-spike parameters for a shared support.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer-uniform-spike log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy
(min_val, count_vec)statistics.
- sampler(seed=None)[source]
Create an IntegerUniformSpikeSampler from parameters of this distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
IntegerUniformSpikeSampler object.
- Return type:
IntegerUniformSpikeSampler
- estimator(pseudo_count=None)[source]
Create an IntegerUniformSpikeEstimator for the current integer range.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics.
- Returns:
IntegerUniformSpikeEstimator object.
- Return type:
IntegerUniformSpikeEstimator
- dist_to_encoder()[source]
Returns an IntegerUniformSpikeDataEncoder for encoding sequences of iid integer observations.
- Return type:
IntegerUniformSpikeDataEncoder
- enumerator()[source]
Returns an IntegerUniformSpikeEnumerator iterating the support in descending probability order.
- Return type:
IntegerUniformSpikeEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index directly from the finite integer support.
- class IntegerUniformSpikeEstimator(min_val=None, max_val=None, pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator for integer-uniform-spike distributions from weighted counts.
- Parameters:
- accumulator_factory()[source]
Returns an IntegerUniformSpikeAccumulatorFactory consistent with this estimator.
- Return type:
IntegerUniformSpikeAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an IntegerUniformSpikeDistribution by maximizing the spike location and weight.
The spike location k is chosen to maximize the likelihood of the accumulated counts (with optional pseudo_count regularization from the estimator configuration).
- class IntegerUniformSpikeEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates the support [min_val, max_val] in descending probability order.
The spike value k is yielded first when p >= (1-p)/(num_vals-1), otherwise last; the remaining values share the same probability and are yielded in ascending integer order. Zero-probability values are skipped.
- Parameters:
dist (IntegerUniformSpikeDistribution)
- class IntegerMultinomialDistribution(min_val=0, p_vec=None, len_dist=NullDistribution(), name=None, keys=None, prob_vec=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultinomial distribution over integer-keyed count maps.
- Parameters:
- compute_capabilities()[source]
Declare generated-compute support inherited from the trial-count distribution.
- compute_declaration()[source]
Return the generated-compute declaration for the integer multinomial.
- static exp_family_sufficient_statistics(x, engine)[source]
Return a shape-only fallback; category-aware count vectors come from
..._from_params.
- static exp_family_sufficient_statistics_from_params(x, params, engine)[source]
Return the per-category count vector
T(x)of shape(sz, K)(counts of in-support values).
- static exp_family_natural_parameters(params, engine)[source]
Return the natural parameter
eta = log(p_vec)(one entry per category).
- static exp_family_log_partition(params, engine)[source]
Return the log partition
A = 0(normalization is carried byeta = log p).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return the multinomial log coefficient in support and
-infoutside support.
- density(x)[source]
Evaluate the density of IntegerMultinomialDistribution at observed value x.
- log_density(x)[source]
Evaluate the log-density of IntegerMultinomialDistribution at observed value x.
Normalized conditional count-vector log-mass given by
log(p_mat(x)) = log(n!) - sum_k log(x_k!) + sum_k x_k*log(p_k) + log(p_mat(n)), for x having k integer categories and n the total trial count.
Note: x has k integer values and p_k denotes the probability of success for integer-category x_k. The
len_distdefaults toNullDistribution, whose log-density is zero for any input; this gives a conditional count-vector mass at each observed total, while a real length law makes it a joint mass.
- seq_log_density(x)[source]
- Vectorized evaluation of log-density for an encoded sequence of iid observations from integer multinomial
distribution.
Arg ‘x’ is a Tuple of length 5 containing:
sz (int): Total number of observed integermultinomial samples. idx (ndarray): Numpy index array for each Tuple[value, count] in flattened x. cnt (ndarray): Number of successes for each value in flattened x. val (ndarray): Integer-category value array in flattened x. tcnt (Optional[T1]): Sequence encoded number of trials for each sequence (length sz), with type T if length DataSequenceEncoder is not NullDataEncoder and returns type T. Else None.
- Parameters:
x (See above for details) – Sequence encoding of iid integer multinomial observation.
- Returns:
Numpy array of log-density evaluated at each observation in encoding.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded integer count vectors.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer-count-vector parameters for homogeneous mixture kernels.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer-multinomial log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy
(min_val, count_vec, length_stat)statistics.
- sampler(seed=None)[source]
Create a sampler for this integer multinomial distribution.
- Parameters:
seed (Optional[int]) – Set seed on random number generator used in sampling.
- Returns:
Sampler bound to this distribution.
- Return type:
IntegerMultinomialSampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this distribution.
- Parameters:
pseudo_count (Optional[float]) – Optional prior mass assigned to this distribution’s current category probabilities during estimation.
- Returns:
Estimator configured with the same support, name, and length estimator.
- Return type:
IntegerMultinomialEstimator
- dist_to_encoder()[source]
Return a data encoder using the encoder supplied by
len_dist.- Return type:
IntegerMultinomialDataEncoder
- class DirichletMultinomialDistribution(alpha, n, name=None, keys=None, *, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS, max_frontier_entries=_DEFAULT_MAX_FRONTIER_ENTRIES)[source]
Bases:
SequenceEncodableProbabilityDistributionDirichlet-multinomial over
K-category count vectors summing ton(concentrationalpha).- Parameters:
- density(x)[source]
Return the probability mass at a single count vector
x.
- log_density(x)[source]
Return the log-mass at
x(-infif any count is negative, non-integer, or the total is notn– a fractional category count is not a valid Dirichlet-multinomial outcome even when the (real-valued) total happens to sum ton).
- seq_log_density(x)[source]
Vectorized log-mass for a stack of count vectors, shape
(N, K)(-infrows where any count is negative, non-integer, or the row total is notn).
- sampler(seed=None)[source]
Return a sampler for drawing count vectors from this distribution.
- Parameters:
seed (int | None)
- Return type:
DirichletMultinomialSampler
- estimator(pseudo_count=None)[source]
Return a Minka fixed-point MLE estimator for
alphaat the fixed number of trialsn.- Parameters:
pseudo_count (float | None)
- Return type:
DirichletMultinomialEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
DirichletMultinomialDataEncoder
- class DirichletMultinomialEstimator(dim, n, max_iter=500, tol=1.0e-9, pseudo_count=None, name=None, keys=None, min_alpha=_DEFAULT_MIN_ALPHA, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS, max_frontier_entries=_DEFAULT_MAX_FRONTIER_ENTRIES)[source]
Bases:
ParameterEstimatorMinka fixed-point maximum-likelihood estimator for the Dirichlet-multinomial concentration.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Dirichlet-multinomial statistics.
- Return type:
DirichletMultinomialAccumulatorFactory
- class IntegerMultinomialEstimator(min_val=None, max_val=None, len_estimator=NullEstimator(), len_dist=None, name=None, pseudo_count=None, suff_stat=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate integer-category multinomial probabilities from count statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
IntegerMultinomialAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a distribution from aggregated sufficient statistics.
If
pseudo_countis not set, prior sufficient statistics are ignored during estimation.suff_statcontains:suff_stat[0] (int): Minimum integer category represented by the count vector. suff_stat[1] (np.ndarray): Weighted counts for consecutive integer categories. suff_stat[2] (Optional[SS0]): Sufficient statistics for the length estimator.
- class IntegerMultinomialEnumerator(dist, *, max_outcomes_per_length=100_000)[source]
Bases:
DistributionEnumeratorEnumerate normalized integer count-vector masses with a modeled trial-count law.
- Parameters:
dist (IntegerMultinomialDistribution)
max_outcomes_per_length (int)
- class IntegerCategoricalDistribution(min_val, p_vec=MISSING, name=None, keys=None, prob_vec=MISSING, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionCategorical distribution over a bounded integer range.
- Parameters:
- classmethod compute_capabilities()[source]
Return compute-backend metadata for integer-categorical scoring.
- classmethod compute_declaration()[source]
Return the symbolic declaration for bounded integer-categorical probabilities.
- static exp_family_sufficient_statistics(x, engine)[source]
Return raw values; category-aware one-hot statistics come from
..._from_params.
- static exp_family_sufficient_statistics_from_params(x, params, engine)[source]
Return the one-hot category indicator
T(x)of shape(n, K)(zeros off support).
- static exp_family_natural_parameters(params, engine)[source]
Return the natural parameter
eta = log(p_vec)(one entry per category).
- static exp_family_log_partition(params, engine)[source]
Return the log partition
A = 0(normalization is carried byeta = log p).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return
log h(x) = 0on the support[min_val, min_val+K)and-infoutside it.
- get_parameters()[source]
Return the probability vector p_vec (lets it be scored by a Dirichlet conjugate prior).
- Return type:
- get_prior()[source]
Return the conjugate parameter prior over the probability vector (or None).
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a Dirichlet(alpha) (or SymmetricDirichlet(alpha)) prior over the probability vector this caches the variational expected log-probabilities E[log p_k] = digamma(alpha_k) - digamma(sum_k alpha_k) so that
expected_log_density(x) = E[log p_{x - min_val}]. Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x)] under the (symmetric) Dirichlet prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density of the integer categorical at observation x.
p_mat(x_mat=x) = p_vec[x] if x in support [min_val, max_val], else 0.0.
- log_density(x)[source]
Evaluate the log-density of the integer categorical at observation x.
log_p(x_mat=x) = log_p_vec[x] if x in support [min_val, max_val], else -np.inf.
- seq_log_density(x)[source]
Vectorized evaluation of IntegerCategorical log_density() for sequence encoded iid observations x.
- static backend_log_density_from_params(x, min_val, log_p_vec, engine)[source]
Engine-neutral integer-categorical log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer-categorical parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer-categorical log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy
(min_val, count_vec)statistics.
- to_fisher(**kwargs)[source]
Return the integer-categorical one-hot Fisher view.
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional random seed.
- Return type:
IntegerCategoricalSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution.
When
pseudo_countis provided, the distribution’s probabilities are used as prior sufficient statistics during estimation.- Parameters:
pseudo_count (float | None) – Weight assigned to the distribution’s current probability vector during estimation.
- Return type:
IntegerCategoricalEstimator
- dist_to_encoder()[source]
Return the encoder for iid integer categorical observations.
- Return type:
IntegerCategoricalDataEncoder
- enumerator()[source]
Return IntegerCategoricalEnumerator iterating the support in descending probability order.
- Return type:
IntegerCategoricalEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index directly from the finite integer support.
- class IntegerCategoricalEstimator(min_val=None, max_val=None, pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimator for bounded integer-categorical probability vectors.
- Parameters:
- get_prior()[source]
Return the conjugate parameter prior over the probability vector (or None).
- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Set the conjugate parameter prior over the probability vector.
- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- model_log_density(model)[source]
Log-density of the model probability vector under the (symmetric) Dirichlet prior.
- Parameters:
model (IntegerCategoricalDistribution)
- Return type:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator’s support and keys.
Note: If min_val and max_val are BOTH not None, these values are passed to IntegerCategoricalAccumulatorFactory. Else, they are obtained from member variable suff_stat. One of these conditions must be satisfied.
Returns:
- Return type:
IntegerCategoricalAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an integer-categorical distribution from weighted counts.
nobsis accepted for estimator API consistency but is not used.suff_statis(min_val, count_vec). Whenpseudo_countand a prior statistic are present, the estimate combines observed counts with the weighted prior probability vector.
- class IntegerCategoricalEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerator over bounded integer support in descending probability order.
- Parameters:
dist (IntegerCategoricalDistribution)
- class IntegerBernoulliSetDistribution(log_pvec, log_nvec=None, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionDistribution over finite sets of integer-valued Bernoulli outcomes.
- Parameters:
- classmethod compute_capabilities()[source]
Declare the generic table-kernel capabilities for integer-set likelihoods.
- classmethod compute_declaration()[source]
Return the structured compute declaration for Bernoulli-set statistics.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral log-density for encoded integer Bernoulli-set observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer Bernoulli-set parameters for shared support size.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer Bernoulli-set log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy
(inclusion_counts, total_weight)statistics.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
IntegerBernoulliSetSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
IntegerBernoulliSetEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
IntegerBernoulliSetDataEncoder
- enumerator()[source]
Returns IntegerBernoulliSetEnumerator iterating subsets in descending probability order.
- Return type:
IntegerBernoulliSetEnumerator
- exception IntegerBernoulliSetFitError[source]
Bases:
RuntimeErrorRaised when integer Bernoulli-set statistics do not identify a fit.
- class IntegerBernoulliSetEstimator(num_vals=MISSING, min_prob=1.0e-128, pseudo_count=None, suff_stat=None, name=None, keys=None, num_values=MISSING)[source]
Bases:
ParameterEstimatorEstimate per-integer Bernoulli inclusion probabilities from aggregate counts.
- Parameters:
- accumulator_factory()[source]
Return a factory for integer Bernoulli-set sufficient-statistic accumulators.
- Return type:
IntegerBernoulliSetAccumulatorFactory
- class IntegerBernoulliSetEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate integer subsets in descending probability order.
- Parameters:
dist (IntegerBernoulliSetDistribution)
- class JointMixtureDistribution(components1, components2, w1=None, w2=None, taus12=None, taus21=None, keys=(None, None, None), name=None, joint_weights=None)[source]
Bases:
SequenceEncodableProbabilityDistributionJoint mixture distribution over paired observations.
Observations are
(x1, x2)tuples. The first tuple element is scored bycomponents1and the second bycomponents2.- Parameters:
- compute_capabilities()[source]
Intersect generated-compute backend support across all child components.
- compute_declaration()[source]
Return the generated-compute declaration for the paired latent mixture.
- density(x)[source]
Evaluate the density of a joint mixture observation x.
See log_density() for details.
- Parameters:
x (Tuple[T0, T1]) – A single (X1, X2) observation.
- Returns:
Density evaluated at x.
- Return type:
- log_density(x)[source]
Evaluate the log-density of a joint mixture observation x.
The log-density at x = (x1, x2) is
log(sum_{i=1}^{N} w_i * f_i(x1) * sum_{j=1}^{M} tau12_{ij} * g_j(x2)),
evaluated with a log-sum-exp for numerical stability.
- Parameters:
x (Tuple[T0, T1]) – A single (X1, X2) observation.
- Returns:
Log-density evaluated at x.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of the log-density for an encoded sequence of observations x.
- Encoded sequence ‘x’ is a Tuple of length 3 containing:
x[0] (int): Number of observations. x[1] (E0): Encoded sequence of X1 values. x[2] (E1): Encoded sequence of X2 values.
- backend_seq_log_density(x, engine)[source]
Engine-neutral log-density for encoded joint-mixture observations.
- to_fisher(**kwargs)[source]
Structural Fisher view for the joint mixture.
- density_semantics()[source]
Return exact-or-approximate density semantics joined from child components.
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional random seed.
- Returns:
A configured
JointMixtureSampler.- Return type:
JointMixtureSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s components.
- Parameters:
pseudo_count (float | None) – Optional smoothing count for latent-state counts.
- Returns:
A
JointMixtureEstimator.- Return type:
JointMixtureEstimator
- dist_to_encoder()[source]
Return an encoder for paired joint-mixture observations.
- Return type:
DataSequenceEncoder
- enumerator()[source]
Return an enumerator over pairs in descending probability order.
- Return type:
JointMixtureEnumerator
- class JointMixtureEstimator(estimators1, estimators2, suff_stat=None, pseudo_count=None, keys=(None, None, None), name=None)[source]
Bases:
ParameterEstimatorEstimator for paired latent mixture distributions.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
JointMixtureEstimatorAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a joint mixture distribution from aggregated sufficient statistics.
The tuple is interpreted as
(x1_counts, x2_counts, joint_counts, x1_child_stats, x2_child_stats).- Parameters:
- Returns:
A fitted joint mixture distribution.
- Return type:
JointMixtureDistribution
- class JointMixtureEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates the support of a JointMixtureDistribution in descending probability order.
- Parameters:
dist (JointMixtureDistribution)
- class LogGaussianDistribution(mu, sigma2, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLog-normal distribution where
log(X)is Gaussian with meanmuand variancesigma2.- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for generated log-Gaussian density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the log-Gaussian distribution.
- static exp_family_sufficient_statistics(x, engine)[source]
Return log-Gaussian sufficient statistics for generated scoring.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row log-Gaussian sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return log-Gaussian natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return log-Gaussian log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return log-Gaussian base measure for generated scoring.
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a NormalGamma(mu0, lam, a, b) prior over (mu, tau=1/sigma2) of log(X) this caches the variational expected natural parameters [ea, eb, e1, e2] exactly as in the Gaussian case, so that
expected_log_density(x) = y*(e1 + y*e2) - ea + eb - ywith y = log(x). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x | mu, tau)] under the NormalGamma prior.
With a conjugate prior this is the Gaussian VB expected log-likelihood evaluated at log(x), plus the Jacobian term -log(x); without a prior it falls back to log_density(x).
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded (logged) observations.
- density(x)[source]
Density of Log-Gaussian distribution at observation x.
See log_density() for details.
- log_density(x)[source]
Log-density of log-Gaussian distribution at observation x.
- Log-density of log-Gaussian with log-mean mu and log-variance sigma2 given by,
log(f(x;mu, sigma2)) = -0.5*log(2*pi*sigma2) - log(x) - 0.5*(log(x)-mu)^2/sigma2, for positive x.
- seq_ld_lambda()[source]
Return vectorized log-density callables for fast scoring.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- Parameters:
x (np.ndarray) – Numpy array of floats.
- Returns:
Numpy array of log-density (float) of len(x).
- Return type:
- static backend_log_density_from_params(x, mu, sigma2, engine)[source]
Engine-neutral log-Gaussian log-density on log-encoded data.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for log-encoded data.
- gradient_log_prior(priors, prior_strength, torch, engine)[source]
Distribution-owned MAP prior contribution for log-Gaussian parameters.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked log-Gaussian parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of log-Gaussian log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked log-Gaussian sufficient statistics using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact). The continuous ‘index of’ a value.
- quantile(q)[source]
Inverse CDF
F^{-1}(q): the value at cumulative-probability indexq(continuous unranking).
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- sampler(seed=None)[source]
Create a sampler from this log-Gaussian distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
LogGaussianSampler object.
- Return type:
LogGaussianSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s parameters.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics.
- Returns:
LogGaussianEstimator object.
- Return type:
LogGaussianEstimator
- dist_to_encoder()[source]
Return the encoder for log-Gaussian observations.
- Return type:
LogGaussianDataEncoder
- class LogGaussianEstimator(pseudo_count=(None, None), suff_stat=(None, None), min_covar=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate log-Gaussian location and variance from accumulated log moments.
The variance is formed from shift-anchored log moments whenever the accumulated statistics carry that payload (see
LogGaussianAccumulator), which makes the fit SCALE-EQUIVARIANT: estimating ona * xreturnsmu + log(a)withsigma2unchanged, for any positiveathe data can carry. A large multiplicative scale is a large additive offset onlog(x), which is the same cancellation the sibling location-scale families repaired; here it costs ~1.4e-7 ofsigma2on values around 1e6 with a 0.2% spread. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, andestimatewarns rather than returning a variance it cannot stand behind.- Parameters:
- accumulator_factory()[source]
Return GaussianAccumulatorFactory with name and keys passed.
- Return type:
LogGaussianAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model parameters under the NormalGamma prior (ELBO global term).
The prior is over (mu, tau=1/sigma2) of log(X), so the model’s (mu, sigma2) is mapped.
- Parameters:
model (LogGaussianDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a log-Gaussian distribution from accumulated log moments.
suff_statis(sum_log_x, sum_log_x2, count, count2).nobsis accepted for estimator API consistency but is not used.
- class MarkovChainDistribution(init_prob_map, transition_map, len_dist=NullDistribution(), default_value=0.0, name=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMarkov-chain distribution over finite-state sequences.
- Parameters:
- get_prior()[source]
Returns the conjugate prior in
(states, init_prior, row_priors)form (or None).
- set_prior(prior)[source]
Set the conjugate Dirichlet prior and precompute its digamma expectations.
With Dirichlet
init_priorand Dirichletrow_priors(each over the fixed orderedstates) this caches the digamma expectations E[ln p_k] = psi(alpha_k) - psi(sum alpha) used by expected_log_density and setshas_conj_prioraccordingly.prior=Noneleaves the distribution a plain point model.- Parameters:
prior –
(states, init_prior, row_priors)tuple or None.- Return type:
None
- expected_log_density(x)[source]
Variational E_q[log p(x)] under the Dirichlet priors over a state sequence.
Replaces the initial/transition log-probabilities with their digamma expectations E[ln p_k] = psi(alpha_k) - psi(sum alpha); the length term is added as in log_density(). Falls back to the plug-in log_density(x) when no conjugate prior is set.
- Parameters:
x (List[T]) – An observed Markov chain state sequence.
- Returns:
Expected log-density of the Markov chain at x.
- Return type:
- seq_expected_log_density(x)[source]
Vectorized expected_log_density() at sequence-encoded input x.
Falls back to seq_log_density(x) when no conjugate prior is set.
- compute_capabilities()[source]
Return compute-backend metadata inherited from the optional length distribution.
- density_semantics()[source]
Classify a chain without a length law as a conditional fixed-length factor.
- compute_declaration()[source]
Return the symbolic declaration for Markov-chain transition and length statistics.
- density(x)[source]
Return density of MarkovChainDistribution at observed sequence x.
Returns exponential of log_density(x). See log_density() for details.
- Parameters:
x (List[T]) – An observed Markov chain sequence of data type T.
- Returns:
Density of Markov chain at x.
- Return type:
- log_density(x)[source]
Return log-density of MarkovChainDistribution at observed sequence x.
Density of Markov chain is given by for sequence of length n, x=[x[0],x[1],…,x[n-1]]
p_mat(x) = p_mat(x[0])*p_mat(x[1]|x[0])*…*p_mat(x[n-1]|x[n-2])*P_len(n)
where p_mat(x[i+1]|x[i]) is the transition probability, p_mat(x[0]) is the init-probability, and P_len(n) is given by the length distribution density.
Note if len(x) = 0, only log(P_len(0)) is returned.
- Parameters:
x (List[T]) – An observed Markov chain sequence of data type T.
- Returns:
Log-density of Markov chain at x.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of log_density of Markov Chain for an encoded sequence of observations x.
Computationally efficient implementation of log_density() for sequence encoded data x.
The arg value x is a Tuple of length 8 with entries:
x[0] (int): Number of total observations (number of Markov sequences). x[1] (ndarray[int]): Sequence index for initial state observations. x[2] (ndarray[int]): Sequence index for non-initial state observations in a sequence greater than len 1. x[3] (ndarray[int]): Numpy array of observations index in inv_key_map for initial states. x[4] (ndarray[int]): State-to-state index value of inv_key_map for initial state value. x[5] (ndarray[int]): State-to-state index value of inv_key_map for transition. x[6] (ndarray[T]): Maps integer index value to value in state-space (T). x[7] (Optional[T1]): Encoded sequence of lengths from len_encoder. None if no length distribution to be estimated.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded Markov-chain sequences.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked fixed-support Markov-chain parameters.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Markov-chain sequence log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return versioned per-component fixed-layout Markov statistics.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for fixed-support autograd fitting.
- sampler(seed=None)[source]
Return a sampler for this Markov-chain distribution.
Raises exception if length distribution (len_dist) was not specified in initialization.
- Parameters:
seed (Optional[int]) – Used to set the seed of random number generator for sampling.
- Returns:
MarkovChainSampler object.
- Return type:
MarkovChainSampler
- path_sampler(seed=None)[source]
Return a sampler for caller-supplied path lengths.
- Parameters:
seed (int | None)
- Return type:
MarkovChainSampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this Markov-chain distribution.
- Parameters:
pseudo_count (Optional[float]) – Prior mass used to smooth initial and transition counts.
- Returns:
Estimator configured with the same length estimator and prior.
- Return type:
MarkovChainEstimator
- dist_to_encoder()[source]
Create a data encoder for Markov-chain observation sequences.
Note: len_encoder is passed as NullDataEncoder() if len_dist is not to be estimated.
- Returns:
Encoder using this distribution’s length encoder.
- Return type:
MarkovChainDataEncoder
- enumerator()[source]
Returns MarkovChainEnumerator iterating state sequences in descending probability order.
- Return type:
MarkovChainEnumerator
- quantized_count_index(quantizer, max_fine_bucket)[source]
Structural count index: a forward DP carrying a count histogram per (length, end-state).
log p(x) = log p_init(x0) + sum_i log p_trans(x_i|x_{i-1}) + log p(len). The forward recursion is lifted into the count semiring: alpha[t][s] is the histogram (over the fine bucket of accumulated log probability) of length-t prefixes ending in state s, with
alpha[1][s] = delta(bucket(log p_init(s)))andalpha[t+1][s'] = sum_s alpha[t][s].shift(bucket(log p_trans(s'|s))). Per length L the sequence histogram pools the end states and shifts by the length term; the total pools lengths. Sequences are unranked by choosing the end state, then walking the trellis backward choosing predecessors by count.- Parameters:
max_fine_bucket (int)
- class MarkovChainStatistics(schema_version, states, initial_counts, transition_counts, length_nobs, length)[source]
Bases:
NamedTupleImmutable, versioned sufficient statistics over one closed state layout.
- Parameters:
- schema_version: int
Alias for field number 0
- length_nobs: float
Alias for field number 4
- exception NonGenerativeMarkovChainError[source]
Bases:
TypeErrorRaised when a fixed-length Markov factor is asked to generate whole sequences.
- class MarkovChainEstimator(pseudo_count=None, levels=None, len_estimator=NullEstimator(), name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimator for finite-state Markov-chain transition maps and optional length law.
- Parameters:
- accumulator_factory()[source]
Returns MarkovChainAccumulatorFactory for creating MarkovChainAccumulator.
- Return type:
MarkovChainAccumulatorFactory
- get_prior()[source]
Returns the conjugate prior in
(states, init_prior, row_priors)form (or None).
- set_prior(prior)[source]
Set the conjugate Dirichlet prior and flag whether it admits the conjugate update.
- Parameters:
prior –
(states, init_prior, row_priors)tuple or None; has_conj_prior is set when all priors are Dirichlet.- Return type:
None
- model_log_density(model)[source]
Log-density of the model’s probabilities under the Dirichlet priors.
Sums the Dirichlet log-densities of the initial-state probabilities and each transition row (floored at a tiny constant so MAP estimates that sit on the simplex boundary score finitely). Returns 0.0 without a conjugate prior.
- Parameters:
model (MarkovChainDistribution) – Model to score.
- Returns:
Prior log-density of the model parameters.
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate MarkovChainDistribution from aggregated sufficient statistics from observed data.
- Arg suff_stat is a Tuple of length three containing,
suff_stat[0] (Dict[T, float]): Maps initial state values to their aggregated counts. suff_stat[1] (Dict[T, Dict[T, List[float]]]): Maps state to state transition counts. suff_stat[2] (T1): Sufficient statistic value of length accumulator. (Assumed type T1).
If member variable pseudo_count is set estimate1() is called to aggregated weighted sufficient statistics. Else estimate0() is called to obtain estimates for MarkovChainDistribution directly from arg ‘suff_stat’.
- Parameters:
nobs (Optional[float]) – Number of observations. Passed to estimate1() or estimate2().
suff_stat (MarkovChainStatistics) – Seed above for details.
- Returns:
MarkovChainDistribution object.
- Return type:
MarkovChainDistribution
- estimate0(nobs, suff_stat)[source]
Estimate MarkovChainDistribution from aggregated sufficient statistics from observed data.
Maximum likelihood estimates for initial state probabilities, transition probabilities, and the length distribution are obtained directly from aggregated data in ‘suff_stat’.
A state with no outgoing transition evidence gets a uniform transition row. That row appears in no likelihood factor, so it is one of the (many) exact maximizers rather than a guess, but it is not a row the data chose: every such state is reported through
MarkovChainDistribution.numerical_repairs()on the returned model, asmarkov-row-uniform(no outgoing transitions: ...).- Arg suff_stat is a Tuple of length three containing,
suff_stat[0] (Dict[T, float]): Maps initial state values to their aggregated counts. suff_stat[1] (Dict[T, Dict[T, List[float]]]): Maps state to state transition counts. suff_stat[2] (T1): Sufficient statistic value of length accumulator. (Assumed type T1).
- Parameters:
nobs (Optional[float]) – Number of observations. Passed to estimate1() or estimate2().
suff_stat (MarkovChainStatistics) – Seed above for details.
- Returns:
MarkovChainDistribution object.
- Return type:
MarkovChainDistribution
- estimate1(nobs, suff_stat)[source]
Estimate MarkovChainDistribution from aggregated sufficient statistics from observed data.
Maximum likelihood estimates for initial state probabilities, transition probabilities, and the length distribution are obtained by a weighted aggregation of sufficient statistics in ‘suff_stat’, and member variables of MarkovChainEstimator object.
- Arg suff_stat is a Tuple of length three containing,
suff_stat[0] (Dict[T, float]): Maps initial state values to their aggregated counts. suff_stat[1] (Dict[T, Dict[T, List[float]]]): Maps state to state transition counts. suff_stat[2] (T1): Sufficient statistic value of length accumulator. (Assumed type T1).
- Parameters:
nobs (Optional[float]) – Number of observations. Passed to estimate1() or estimate2().
suff_stat (MarkovChainStatistics) – Seed above for details.
- Returns:
MarkovChainDistribution object.
- Return type:
MarkovChainDistribution
- class MarkovChainEnumerator(dist)[source]
Bases:
DistributionEnumeratorBest-first enumerator for finite-state sequences with a modeled length law.
- Parameters:
dist (MarkovChainDistribution)
- class ProbabilisticPCADistribution(w, mu, sigma2, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionProbabilistic PCA: x ~ N(mu, W W^T + sigma2 I) with q latent factors.
- Parameters:
- classmethod compute_capabilities()[source]
Return compute-backend metadata for PPCA scoring.
- property w: ndarray
Return an owned snapshot of the factor loadings.
- property mu: ndarray
Return an owned snapshot of the mean.
- property sigma2: float
Return the immutable isotropic noise variance.
- property inv_covar: ndarray
Return an owned snapshot of the cached covariance inverse.
- transform(x)[source]
Return the posterior mean of the latent factors E[z | x] = M^{-1} W^T (x - mu).
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
ProbabilisticPCASampler
- estimator(pseudo_count=None)[source]
Return a closed-form ML estimator with the latent dimension fixed at this model’s q.
- Parameters:
pseudo_count (float | None)
- Return type:
ProbabilisticPCAEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
ProbabilisticPCADataEncoder
- class ProbabilisticPCAEstimator(latent_dim, dim=None, min_sigma2=_MIN_SIGMA2, name=None, keys=None)[source]
Bases:
ParameterEstimatorClosed-form maximum-likelihood estimator for PPCA (Tipping & Bishop eigen-solution).
- Parameters:
- accumulator_factory()[source]
Return a factory for PPCA sufficient-statistic accumulators.
- Return type:
ProbabilisticPCAAccumulatorFactory
- class MixtureDistribution(components, w=MISSING, name=None, weights=MISSING, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionFinite mixture over homogeneous component distributions.
componentsdefine both the conditional familiesp(x | z=k)and the observation type accepted by the mixture.wcontains the component probabilities and is cached aslog_wfor stable scalar and vectorized scoring. Zero-weight components are retained for structural compatibility but contribute-infto log-density calculations.- Parameters:
components (Sequence[SequenceEncodableProbabilityDistribution]) – Component distributions. Each component should support the same raw observation shape and sequence-encoding contract.
w (np.ndarray | list[float]) – Component weights. The values are interpreted as simplex weights and should sum to one.
name (str | None) – Optional display name for diagnostics and generated artifacts.
prior (SequenceEncodableProbabilityDistribution | None) – Optional joint mixture prior or weight prior.
- components
Component distribution objects.
- w
Component weights as a NumPy array.
- zw
Boolean mask for zero-weight components.
- log_w
Log weights, with zero-weight entries represented as
-inf.
- num_components
Number of mixture components.
- compute_capabilities()[source]
Return compute-backend metadata shared by all mixture components.
- compute_declaration()[source]
Return the symbolic declaration for mixture weights and component statistics.
- get_prior()[source]
Return the joint mixture prior, or
Nonefor a plain point model.When a weight prior is attached the joint prior is the
(weight_prior, tuple(component priors))pair produced bymixture_prior(); otherwiseNone.- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Attach a weight prior (and optional per-component priors), caching weight expectations.
With a (symmetric) Dirichlet weight prior this caches the variational weight expectations
E[log w_k] = digamma(alpha_k) - digamma(sum_j alpha_j)used byexpected_log_density. Component priors, when supplied, are delegated to each component viacomponent.set_prior.prior=None(the default) leaves the mixture a plain point model (byte-identical MLE behaviour).- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Return the optimized local variational log-evidence bound.
This compatibility name does not compute the generally intractable
E[log(sum_k w_k p_k(x))]. With conjugate priors it returnslogsumexp_k(E[log w_k] + E[log p_k(x)]), the optimized local variational lower bound. Usevariational_log_evidence_bound()when the semantic distinction matters. Without a conjugate weight prior it falls back to the plug-inlog_density.- Parameters:
x (T)
- Return type:
- variational_log_evidence_bound(x)[source]
Return the local variational lower bound for one observation.
- Parameters:
x (T)
- Return type:
- seq_expected_log_density(x)[source]
Return vectorized local variational log-evidence bounds.
This is the sequence form of
variational_log_evidence_bound(), retained under the framework-wide compatibility name.- Parameters:
x (T1)
- Return type:
- seq_variational_log_evidence_bound(x)[source]
Return local variational lower bounds for encoded observations.
- Parameters:
x (T1)
- Return type:
- density(x)[source]
Return the mixture density at one raw observation.
- Parameters:
x (T) – Observation accepted by every component family.
- Returns:
exp(log_density(x)).- Return type:
- density_semantics()[source]
Return joined density semantics over all mixture components.
- log_density(x)[source]
Return the mixture log-density at one raw observation.
The calculation is
logsumexp_k(log p_k(x) + log w_k). Component families are responsible for returning-inffor observations outside support; the mixture combines those values without converting them toNaN.- Parameters:
x (T) – Observation accepted by every component family.
- Returns:
Finite log-density when at least one positive-weight component can score the observation, otherwise
-inf.- Return type:
- conditional(observed)[source]
Return the conditional mixture over the unobserved coordinates given
observed.The conditional of a mixture is itself a mixture: for
sum_k w_k f_kobservingx_o,P(x_u | x_o) = sum_k w’_k f_k(x_u | x_o), w’_k proportional to w_k f_k.marginal(x_o)(x_o),
i.e. the component responsibilities are updated by how well each component explains the observed coordinates and each component is replaced by its own conditional. Because the result is a full
MixtureDistributionyou can both score it and.sampler(seed).sample()from it – the latter isgiven=-style conditional sampling that first draws a component from the posterior responsibilities, then draws the unobserved coordinates from that component’s conditional.Requires each component to support
marginal(indices)andcondition(observed)(e.g. the multivariate Gaussian / Student-t).observedmaps coordinate index to its fixed value.
- component_log_density(x)[source]
Return component-wise log densities for one raw observation.
- Parameters:
x (T) – Observation accepted by every component family.
- Returns:
One log-density per component, before mixture weights are applied.
- Return type:
- posterior(x)[source]
Return component responsibilities for one raw observation.
Responsibilities are proportional to
w[k] * p_k(x). An observation outside every component’s support receives zero responsibility and therefore cannot fabricate component statistics.- Parameters:
x (T) – Observation accepted by every component family.
- Returns:
Responsibility vector over component labels. It sums to one when the evidence is possible and is all zero otherwise.
- Return type:
- seq_component_log_density(x)[source]
Return vectorized component log densities for encoded observations.
xmust be produced byMixtureDataEncoder.seq_encodeor by an equivalent component encoder. The output has shape(n, k)wherenis the number of encoded observations andkis the number of mixture components.- Parameters:
x (T1) – Encoded observation batch.
- Returns:
Component log-density matrix before mixture weights are applied.
- Return type:
- seq_log_density(x)[source]
Return vectorized mixture log densities for encoded observations.
Each row is evaluated with a row-wise log-sum-exp over component scores plus log weights. Rows for which every positive-weight component is impossible return
-inf.- Parameters:
x (T1) – Encoded observation batch.
- Returns:
One log-density per encoded observation.
- Return type:
- backend_seq_component_log_density(x, engine)[source]
Engine-neutral component log densities for encoded data.
- backend_seq_log_density(x, engine)[source]
Engine-neutral mixture log-density for encoded data.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- seq_posterior(x)[source]
Return vectorized component responsibilities for encoded observations.
Each row is proportional to
w[k] * p_k(x_i). Rows where all positive-weight components are impossible receive zero responsibility, matchingposterior()without inventing latent assignments.- Parameters:
x (T1) – Encoded observation batch.
- Returns:
(n, k)responsibility matrix. Possible rows sum to one; impossible rows sum to zero.- Return type:
- latent_posterior(x)[source]
Return the latent posterior
q(z | x)over component labels for raw observationsx.q(z)is the exact independent-categorical posterior whose marginals are the EM responsibilities. The returnedCategoricalLatentPosteriorcan.marginals()(the responsibilities),.sample(rng)component labels,.mode()(the MAP labels), or.entropy().- Parameters:
x (Sequence[T])
- Return type:
CategoricalLatentPosterior
- posterior_predictive(x, seed=None)[source]
Draw posterior-predictive observations conditioned on
x.For each observed
x_ithe component is sampled from the latent posteriorq(z_i | x_i)and a fresh observation is emitted from that component – i.e. “given I sawx_i, draw a new point from the same mixture component it likely came from”. Returns a list the length ofx. Draws are grouped by component and scattered (vectorized) via the shared sampling helper.
- support_size()[source]
Upper bound on distinct support points: the sum over components (union <= sum).
- Return type:
int | None
- tropical_displacement_bits()[source]
log2(#positive-weight components)– the tropical-vs-marginal cost gap (in bits).The marginal
log p(x) = logsumexp_k (log w_k + log p_k(x))is bounded by its largest termM(x) = max_k (log w_k + log p_k(x))viaM(x) <= log p(x) <= M(x) + log K, whereKis the number of components that can contribute (positive weight). The structural seek bins by the tropical costM(x);mixle.enumeration.density_rank.marginal_seek()widens its smear window by this many bits so the reported rank bracket provably contains the TRUE marginal rank.K <= 1means the marginal is a single term ->0.0(the seek is then exact). When the component supports are provably disjoint every value lands in one component, soM(x)equals the marginal and there is likewise no displacement ->0.0(the seek is exact and tight).- Return type:
- to_fisher(**kwargs)[source]
Structural Fisher view for the mixture.
- sampler(seed=None)[source]
Return a sampler that draws from the mixture distribution.
- Parameters:
seed (int | None) – Optional
RandomStateseed for reproducible draws.- Returns:
MixtureSamplerbound to this distribution.- Raises:
ValueError – If this mixture is a likelihood factor rather than a normalized law.
- Return type:
MixtureSampler
A component may be a scaled law – an unnormalized categorical, an open-world smoothed emission, a component that won zero responsibility – and
_owned_generative_componentsadmits those deliberately, because a constant scale cancels in the E-step’s responsibility normalization. It does NOT cancel in the composite: a mass-0.75 component under weight 0.5 leaves the mixture with total mass 0.875, anddensity_semantics()reportsLIKELIHOOD_FACTORto say so. The sampler used to ignore that and draw as though the weights described a law, so the scorer and the sampler described different objects (MXR-080-1857).Refusing here rather than at construction is the point: scoring such a mixture is legitimate and tested (an open-world component has infinite total mass and no finite scale to absorb), so the object must remain constructible. What it cannot do is pretend to be a generative law.
- estimator(pseudo_count=None)[source]
Return an estimator with matching component structure.
- Parameters:
pseudo_count (float | None) – Optional smoothing mass applied through the estimator path.
- Returns:
MixtureEstimatorsuitable for fitting observations of the same type as this distribution.- Return type:
MixtureEstimator
- decomposition()[source]
Mixture components split along the component axis. Responsibilities (logsumexp) are computed INSIDE a shard; across shards the per-component sufficient stats SUM-reduce plus one scalar total-count all-reduce – the homogeneous stacked-kernel + DTensor path (engine_axis=0).
- dist_to_encoder()[source]
Return an encoder that delegates observation encoding to components.
- Return type:
MixtureDataEncoder
- enumerator()[source]
Return an enumerator over the union of component supports.
- Return type:
MixtureEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index from a global mixture frontier.
The primary path pulls candidates from weighted component enumerator heads. The log-sum of those heads bounds every unseen value, so construction stops when the live global frontier falls below
2**(-max_bits). This avoids the looser per-componentlog2(K)candidate expansion. If a component cannot enumerate, the method falls back to the structured cross-index path.
- quantized_count_index(quantizer, max_fine_bucket)[source]
BoundedCount for the MARGINAL mixture law: pool weight-scaled component count indices.
log p(x) = logsumexp_k (log w_k + log p_k(x)) has no exact structural count – overlapping component supports would need value-level deduplication. This builds the count semiring’s
plus-fold overscale(component_index, log w_k)instead, which:reaches a 2**M budget structurally (no enumeration), and
is a conservative UPPER bound – a value shared by several components is counted once per component, and each value is binned by its dominant weighted component (the tropical cost, within log2(K) bits of the exact logsumexp).
Every unranked value still carries its exact mixture
log_density(re-evaluated by the budget builder). For an exact small-budget index (best-first union with dedup), usequantized_index. Components that cannot count structurally raise EnumerationError.- Parameters:
max_fine_bucket (int)
- structural_fine_bucket(value, quantizer)[source]
Dominant weighted-component structural bucket (mirrors the plus-of-scaled-children index).
- Return type:
- is_canonical_copy(value, coarse_bin, quantizer)[source]
Stateless dedup: keep
valueonly at its dominant (best-weighted) component’s bin.The canonical bin is the coarse bin of the minimum, over components, of the component’s structural fine bucket shifted by the weight term. O(K) model evaluations, no state.
- class ResponsibilityAttentionDistribution(key_means, emission, position_prior=None, sigma2=1.0, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionOne generative-gate attention head; a mixture over context positions (EM-able).
- Parameters:
- density(x)[source]
Density
p(query, target | context)at one observation.
- log_density(x)[source]
Log conditional density
log p(query, target | context)at one observation(ctx, y, t).
- seq_log_density(x)[source]
Vectorized
log p(query, target | context)over an encoded batch ->(n,).
- predict_proba(context, query)[source]
Predictive target distribution
p(target | context, query)(target marginalized over z).Attention here does not see the target:
a_i ∝ pi_i N(query; K[c_i]), thenp(target) = sum_i a_i emission[c_i, :]. Accepts a single example or a batch.
- sampler(seed=None)[source]
Return a sampler for synthetic responsibility-attention observations.
- Parameters:
seed (int | None)
- Return type:
ResponsibilityAttentionSampler
- estimator(pseudo_count=None)[source]
Return a closed-form EM estimator for this attention head.
- Parameters:
pseudo_count (float | None)
- Return type:
ResponsibilityAttentionEstimator
- dist_to_encoder()[source]
Return the encoder for contexts, query vectors, and targets.
- Return type:
ResponsibilityAttentionDataEncoder
- class ResponsibilityAttentionEstimator(num_symbols, context_length, query_dim, num_targets, *, sigma2=1.0, estimate_sigma2=False, min_sigma2=1e-6, emission_smoothing=1e-6, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate a
ResponsibilityAttentionDistributionby closed-form EM M-steps.- Parameters:
- accumulator_factory()[source]
Return a factory for responsibility-attention sufficient-statistic accumulators.
- Return type:
ResponsibilityAttentionAccumulatorFactory
- sequence_to_triples(tokens, context_length, *, num_symbols=None, embeddings=None)[source]
Unroll a token sequence into the
(context, query, target)triples this head consumes.For each prediction point
p(with a full window behind it and a next token ahead), emitscontext = tokens[p-N+1 : p+1](theNmost recent tokens, including the current one),queryderived from the current tokentokens[p](its embedding, or a one-hot), andtarget = tokens[p+1]. This is the bridge from a real sequence to the iid-triple leaf.Scope: with the single-hop leaf this yields an attention-weighted next-token model whose predictive is a function of the current token (an attention-flavoured bigram) – because the emission is keyed by the attended token’s identity, the prediction depends only on which token the query selects. In-context copy / induction (example-specific values) is what the multi-hop / stackable extension adds; this helper is the plumbing both share.
- Parameters:
tokens (Sequence[int]) – a 1-D sequence of integer token ids.
context_length (int) – the attention window
N.num_symbols (int | None) – vocabulary size (for the one-hot query dim); inferred from
tokensif omitted.embeddings (ndarray | None) – optional
(S, D)embedding table; if given the query isembeddings[token], otherwise a one-hot of dimensionnum_symbols.
- Returns:
A list of
(context, query, target)triples ready formixle.inference.optimize().- Return type:
- class VariationalEmbeddingAttentionDistribution(mean, log_var, emission, position_prior, sigma2=0.5, name=None, optimizer_state=None)[source]
Bases:
SequenceEncodableProbabilityDistributionResponsibility-attention head over tied latent embeddings (mean-field posterior).
- Parameters:
- density(x)[source]
Return the posterior-mean probability of one attention observation.
- log_density(x)[source]
Plug-in (posterior-mean) log conditional density
log p(target | context, query).
- seq_log_density(x)[source]
Posterior-mean log density over an encoded batch ->
(n,)(usese = m).
- predict_proba(context, query)[source]
Predictive target distribution from posterior-mean attention;
(T,)or(n, T).
- sampler(seed=None)[source]
Sample iid observations from the posterior-mean plug-in law used by scoring.
- Parameters:
seed (int | None)
- Return type:
VariationalEmbeddingAttentionSampler
- posterior_predictive_sampler(seed=None)[source]
Sample iid observations, independently drawing an embedding table for every event.
- Parameters:
seed (int | None)
- Return type:
VariationalEmbeddingAttentionSampler
- estimator(pseudo_count=None)[source]
Return a variational EM estimator initialized with this model’s dimensions.
- Parameters:
pseudo_count (float | None)
- Return type:
VariationalEmbeddingAttentionEstimator
- dist_to_encoder()[source]
Return the encoder for contexts, queries, and targets.
- Return type:
VariationalEmbeddingAttentionDataEncoder
- class VariationalEmbeddingAttentionEstimator(num_symbols, context_length, embed_dim, num_targets, *, sigma2=0.5, lr=0.05, mc=6, prior_strength=1.0, emission_smoothing=1e-4, seed=0, name=None, keys=None)[source]
Bases:
ParameterEstimatorStateless variational-EM estimator consuming explicit model-carried Adam state.
- Parameters:
- accumulator_factory()[source]
Return a factory for variational embedding attention accumulators.
- Return type:
VariationalEmbeddingAttentionAccumulatorFactory
- class ChainedAttentionDistribution(keys, emission, sigma2=0.1, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionAn L-hop stack of responsibility-attention heads (chained, content-addressed).
- density(x)[source]
Return the probability of one chained-attention observation.
- log_density(x)[source]
Return the log-probability of one context/query/target observation.
- seq_log_density(x)[source]
Return vectorized log-probabilities for encoded chained-attention observations.
- Return type:
- predict_proba(context_keys, context_values, query)[source]
Predictive target distribution (target marginalized);
(T,)or(n, T).
- sampler(seed=None)[source]
Return a sampler for synthetic chained-attention observations.
- Parameters:
seed (int | None)
- Return type:
ChainedAttentionSampler
- estimator(pseudo_count=None)[source]
Return a closed-form EM estimator for this attention chain.
- Parameters:
pseudo_count (float | None)
- Return type:
ChainedAttentionEstimator
- dist_to_encoder()[source]
Return the encoder for context keys, values, query symbols, and targets.
- Return type:
ChainedAttentionDataEncoder
- class ChainedAttentionEstimator(n_hops, num_symbols, num_targets, *, sigma2=0.1, emission_smoothing=1e-4, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorClosed-form EM estimator: per-hop key tables (GMM means of one-hot queries) + emission counts.
- Parameters:
- accumulator_factory()[source]
Return a factory for chained-attention sufficient-statistic accumulators.
- Return type:
ChainedAttentionAccumulatorFactory
- class VariationalMultiHopAttentionDistribution(mean, log_var, emission, sigma2=0.3, name=None, optimizer_state=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA 2-hop chain over tied latent embeddings (mean-field posterior).
- Parameters:
- density(x)[source]
Return the probability of one context/query/target observation.
- Return type:
- log_density(x)[source]
Return the log-probability of one context/query/target observation.
- Return type:
- seq_log_density(x)[source]
Return vectorized log-probabilities for encoded two-hop attention observations.
- Return type:
- predict_proba(context_keys, context_values, query)[source]
Predictive target distribution (posterior-mean embeddings);
(T,)or(n, T).- Return type:
- embeddings()[source]
Return posterior mean embeddings for the tied latent symbols.
- Return type:
- sampler(seed=None)[source]
Sample iid observations from the posterior-mean plug-in law used by scoring.
- Parameters:
seed (int | None)
- Return type:
VariationalMultiHopAttentionSampler
- posterior_predictive_sampler(seed=None)[source]
Sample iid observations, independently drawing an embedding table for every event.
- Parameters:
seed (int | None)
- Return type:
VariationalMultiHopAttentionSampler
- estimator(pseudo_count=None)[source]
Return a variational EM estimator initialized with this model’s dimensions.
- Parameters:
pseudo_count (float | None)
- Return type:
VariationalMultiHopAttentionEstimator
- dist_to_encoder()[source]
Return the encoder for context keys, values, query symbols, and targets.
- Return type:
VariationalMultiHopAttentionDataEncoder
- class VariationalMultiHopAttentionEstimator(num_symbols, embed_dim, num_targets, *, sigma2=0.3, lr=0.05, mc=5, prior_strength=0.1, anneal_iters=100, emission_smoothing=1e-4, seed=0, name=None, keys=None)[source]
Bases:
ParameterEstimatorStateless variational-EM estimator with model-carried Adam state and prior annealing.
- Parameters:
- accumulator_factory()[source]
Return a factory for variational multi-hop attention accumulators.
- estimate(nobs, suff_stat)[source]
Apply one variational EM update and return the updated attention distribution.
- class Posterior[source]
Bases:
ABCA model-derived distribution exposing one uniform interface for draws and summaries.
Only
sample()(a single draw) is required.samples()loops it by default; vectorized subtypes override it.mean/mode/marginals/entropy/intervalraiseNotImplementedErrorunless a subtype defines them, so each realization implements exactly the summaries that are meaningful for it.- abstractmethod sample(rng=None)[source]
Draw a single sample from the posterior (
rngis a seed,RandomState, orNone).
- samples(n, rng=None)[source]
Draw
nsamples; loopssample()by default (override for a vectorized draw).
- mode()[source]
The maximum-a-posteriori configuration (not defined for every realization).
- Return type:
- marginals()[source]
Per-component marginals – e.g. the EM E-step responsibilities (not always defined).
- Return type:
- class LatentPosterior[source]
Bases:
PosteriorThe posterior
q(z | x)over a model’s latent variables (exact or mean-field).- abstractmethod marginals()[source]
Per-latent marginal responsibilities – the quantity the EM M-step consumes.
- Return type:
- abstractmethod sample(rng=None)[source]
Draw the latent variables
z ~ q(z | x)(rngis a seed, RandomState, or None).
- class CategoricalLatentPosterior(responsibilities, support=None)[source]
Bases:
LatentPosteriorIndependent categorical latents
q(z) = prod_i Cat(z_i; r_i).The exact posterior for a finite mixture’s component labels (and the per-token topic factor of an LDA document).
responsibilitiesis the row-stochastic(N, K)matrixr_ik = q(z_i = k | x_i);supportmaps columnkto its latent label (default0..K-1).- sample(rng=None)[source]
Draw one latent label per observation; returns an
(N,)array of support labels.
- class MarkovChainLatentPosterior(log_pi, log_A, log_b)[source]
Bases:
LatentPosteriorChain-structured latents
q(z_1..z_T | x)for an HMM – exact, via forward-backward.Built from the log initial distribution
log_pi(K,), the log transition matrixlog_A(K, K)(rowj-> columnk), and the per-position emission log-likelihoodslog_b(T, K). The latents are coupled (a Markov chain), so:marginals() -> the
(T, K)forward-backward smoothing probabilitiesq(z_t = k | x)sample(rng) -> a full state path(T,)by forward-filter / backward-sample (FFBS) mode() -> the Viterbi (max-product) path(T,)entropy() -> the exact scalar chain entropyH[q(z_1..z_T | x)]- log_likelihood()[source]
The sequence log-likelihood
log p(x)(the forward normalizer).- Return type:
- property is_impossible: bool
Whether the supplied evidence has zero probability under the chain model.
- sample(rng=None)[source]
Draw a state path
z ~ q(z | x)via FFBS; returns(T,)state indices.
- entropy()[source]
Exact scalar chain entropy via the FFBS factorization
q = q(z_T) prod_t q(z_t|z_{t+1}).- Return type:
- to_dataframe()[source]
Return the per-position state posterior as a
pandas.DataFrame.One row per sequence position
twith columnst(position),state(the Viterbi MAP state frommode()), and onestate_{k}_probcolumn per latent state holding the forward-backward smoothing probability frommarginals(). Deterministic: unlikesample(),mode/marginalsare exact closed-form quantities, not random draws. Requires thepandasextra (pip install mixle[pandas]).- Return type:
- to_parquet(path, **kwargs)[source]
Write the per-position state posterior to a Parquet file; see
to_dataframe().kwargsforward toDataFrame.to_parquet(e.g.engine=,compression=). Needs a Parquet engine in addition to pandas –pip install mixle[arrow](pyarrow) or fastparquet.
- class MeanFieldLDAPosterior(gamma, phi, counts)[source]
Bases:
LatentPosteriorMean-field variational posterior for one LDA document:
q(theta, z) = Dir(theta; gamma) prod_n Cat(z_n; phi_n).The Blei-Ng-Jordan variational factorization made into an object instead of loose
gamma/phiarrays.gamma(K,)is the document’s variational Dirichlet parameter (q(theta));phi(W, K)the per-distinct-word topic responsibilities (q(z_n), rows sum to 1);counts(W,)the word counts. Note the latents are heterogeneous (continuoustheta+ discretez), sosamplereturns the pair(theta, z)andentropyis a scalar.- topic_proportions()[source]
The mean document-topic distribution
E_q[theta] = gamma / sum(gamma)(K,).- Return type:
- marginals()[source]
The
(W, K)per-distinct-word topic responsibilitiesq(z_n).- Return type:
- sample(rng=None)[source]
Draw the full latent
(theta, z):theta ~ Dir(gamma)and per-token topicszfromphi.
- exception ImpossiblePosteriorError[source]
Bases:
ValueErrorRaised when an operation requires a posterior law but the evidence has zero probability.
- class ImpossiblePosteriorResult(reason, log_evidence=-inf)[source]
Bases:
objectTyped explanation that a model/evidence pair does not define a conditional probability law.
- class MixtureEstimator(estimators, fixed_weights=None, suff_stat=None, pseudo_count=None, name=None, keys=(None, None), prior=None, w_min=0.0, robust=False, init=None)[source]
Bases:
ParameterEstimatorEstimator for mixture weights and component distributions from EM sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return a mixture accumulator factory matching the component estimators.
- Return type:
MixtureAccumulatorFactory
- get_prior()[source]
Return the joint mixture prior, or
Nonefor a plain MLE estimator.When a weight prior is attached the joint prior is the
(weight_prior, tuple(component priors))pair produced bymixture_prior().- Return type:
SequenceEncodableProbabilityDistribution | None
- set_prior(prior)[source]
Attach a weight prior (and optional per-component priors).
With a (symmetric) Dirichlet weight prior the estimator switches to the conjugate MAP weight update; component priors, when supplied, are delegated to each component estimator via
estimator.set_prior(those carry out their own conjugate updates).prior=Noneleaves the estimator a plain MLE estimator (byte-identical behaviour).- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- model_log_density(model)[source]
Log density of the model parameters under this estimator’s prior (ELBO global term).
Returns the Dirichlet weight-prior log-density evaluated at
model.wplus the sum of each component estimator’smodel_log_densityat the corresponding component model. Returns0.0for a plain MLE estimator with no priors anywhere.- Parameters:
model (MixtureDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a mixture distribution from EM sufficient statistics.
suff_statis(component_counts, component_suff_stats). Component parameters are delegated to the child estimators. Mixture weights follow the fixed-weight, conjugate-prior, pseudo-count, or plain-MLE path selected by the estimator configuration. Plain-MLE weights may be floored byw_minand are always renormalized.
- class MixtureEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerator over the deduplicated union of weighted component supports.
- Parameters:
dist (MixtureDistribution)
- class MultivariateGaussianDistribution(mu, covar=MISSING, name=None, keys=None, covariance=MISSING, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultivariate normal distribution with mean vector mu and full covariance matrix covar.
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for multivariate Gaussian generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the multivariate Gaussian.
- static exp_family_sufficient_statistics(x, engine)[source]
Return vector/matrix sufficient statistics for generated MVN scoring.
- static exp_family_natural_parameters(params, engine)[source]
Return natural parameters for generated MVN scoring.
- static exp_family_log_partition(params, engine)[source]
Return the full-covariance Gaussian log partition.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return row-wise legacy accumulator statistics for generated resident reductions.
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a NormalWishart(m0, kappa, W, nu) prior over (mu, Lambda=covar^-1) this caches the prior parameters and E[ln|Lambda|], the quantities needed by
expected_log_density. Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x | mu, Lambda)] under the NormalWishart prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.- Return type:
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density at x.
- Parameters:
x (np.ndarray) – Observation from multivariate Gaussian distribution.
- Returns:
Density at x.
- Return type:
- log_density(x)[source]
Evaluate the log-density at x.
The log-density is given by
log(p(x)) = -0.5*k*log(2*pi) - 0.5*log|covar| - 0.5*(x-mu)’ covar^{-1} (x-mu).
- Parameters:
x (np.ndarray) – Observation from multivariate Gaussian distribution.
- Returns:
Log-density at x.
- Return type:
- density_cumulative(x)[source]
Exact probability-ordered cumulative
G(x) = P(p(Y) >= p(x))– the highest-density-region mass whose boundary passes throughx(the multivariate analogue of a CDF; a coordinate-wise CDF is undefined without a total order on R^d).For a multivariate Gaussian
p(y) >= p(x)iff the squared Mahalanobis distance is no larger, and that distance is chi-square withdimdegrees of freedom, soG(x) = chi2.cdf(maha2, dim). Used bymixle.enumeration.density_rank.density_rank()to return an EXACT cumulative for the MVN.
- density_quantile(q)[source]
Inverse of
density_cumulative(): a representative point at cumulative-density indexq.The multivariate analogue of a quantile / inverse-CDF: a coordinate-wise quantile is undefined without a total order on R^d, but the density ordering gives one.
qis the highest-density region mass, so the boundary is the squared-Mahalanobis levelchi2.ppf(q, dim); we return a representative point on that contour,mu + sqrt(level) * L[:, 0]wherecovar = L L^T(so its Mahalanobis distance is exactly the level). Sweepingqenumerates the support in descending density.
- seq_log_density(x)[source]
Vectorized evaluation of the log-density at a sequence-encoded input x.
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim) from MultivariateGaussianDataEncoder.seq_encode().
- Returns:
Numpy array of length sz containing the log-density of each encoded observation.
- Return type:
- static backend_log_density_from_params(x, mu, inv_covar, log_det, engine)[source]
Engine-neutral multivariate Gaussian log-density from inverse covariance.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked full-covariance Gaussian parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of full-covariance Gaussian log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy sufficient statistics on the active engine.
The weighted second moment
sum_n w[n,k] x_n x_n^Tis accumulated per component as a gemm(x * w[:, k]).T @ xinstead of reducing a per-sample, per-component(n, k, dim, dim)outer-product tensor. That intermediate isN*K*dim*dim(~20 GB at n=2e4, k=8, dim=128 — it OOMs a GPU); the per-component gemm holds only an(n, dim)temporary and hands the reduction to BLAS/cuBLAS. The first moment is likewisew.T @ xrather than a reduced(n, k, dim)tensor.
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional seed for the sampler’s random state.
- Returns:
A configured
MultivariateGaussianSampler.
- condition(observed)[source]
Return the conditional distribution over the unobserved dimensions given
observed.observedmaps dimension index to its fixed value; the result is the closed-form Gaussian conditional over the remaining dimensions (in increasing index order):mu_{u|o} = mu_u + Sigma_uo Sigma_oo^{-1} (x_o - mu_o), Sigma_{u|o} = Sigma_uu - Sigma_uo Sigma_oo^{-1} Sigma_ou.
Sampling the result is
given=-style conditional sampling (draw the unobserved coordinates consistent with the observed ones). Raises if no dimension is left unobserved.
- marginal(keep)[source]
Return the marginal Gaussian over dimensions
keep.N(mu, Sigma)marginalized to index setkeepisN(mu[keep], Sigma[keep, keep]). The order ofkeepis preserved, so the result’s dimensions follow the given order.
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s shape.
If pseudo_count is passed, the current mean and covariance are used to regularize the estimate.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to mean and covariance estimates.
- Returns:
A
MultivariateGaussianEstimator.
- dist_to_encoder()[source]
Return an encoder for iid multivariate Gaussian observations.
- Return type:
MultivariateGaussianDataEncoder
- class MultivariateGaussianEstimator(dim=None, pseudo_count=(None, None), suff_stat=(None, None), name=None, keys=None, prior=None, min_covar=None, ridge=None, track_conditioning=False, degenerate_ratio=1.0e-6)[source]
Bases:
ParameterEstimatorEstimator for multivariate Gaussian distributions.
The fitted covariance is NOT the raw maximum-likelihood estimate unless
ridge=0.0is passed: by default the M-step regularizes each diagonal entry of the empirical covariance ascov_ii + eps_iwitheps_i = ridge * cov_ii(defaultridge=1e-6) so a singular empirical covariance – e.g. an EM component holding fewer thandpoints – remains factorizable. Eacheps_iis RELATIVE to its own coordinate’s variance, so the ridge is a negligible ~1e-6 relative perturbation whatever the units, per column: the fit is equivariant under any per-coordinate change of units, and heterogeneous-unit data is no longer penalized (the former trace-scaled ridge priced a microscale column’s jitter off the macroscale columns, inflating the smallest variances – and with them the log-likelihood and AIC – by up to ~5 orders of magnitude, T1-05). A coordinate with no positive variance of its own gets its jitter from the mean of the coordinates that have one; the absolutemin_covar(default1e-8) is the last resort for a covariance with no scale at all (all-zero diagonal, orridge=0.0) and becomes a hard per-coordinate floor as soon as it is passed explicitly.A materially binding ridge is recorded on the fitted distribution as a
covariance-ridged(...)entry innumerical_repairs()– and therefore infit_provenance().repairs. “Materially” means the jitter exceeded_RIDGE_MATERIAL_RATIOof the smallest raw variance (an explicitmin_covardominating a small variance, or manufactured jitter on a variance-free coordinate – never the default per-coordinate ridge on a full-rank fit), or the raw covariance was not positive-definite on its own and the ridge is what makes it factorable – the rank-deficient case this ridge exists for. Passridge=0.0to recover the exact MLE up to themin_covarabsolute jitter floor.The fit is SHIFT-EQUIVARIANT:
fit(x + c)returns the covariance ofx + cto within a few ulps for any constantcthe data can carry, epoch seconds (~1.7e9) included. That is not free from the declared(sum, sum2, count)statistics – their covariance is the cancellation-proneE[xx^T] - mu mu^T, which at offset 1e7 fitted a visibly wrong correlation and at 1e8 a matrix so far from positive-definite that the constructor refused it – soMultivariateGaussianAccumulatorcarries a conditioning-gated shift-anchored moment track and this estimator reads it. Statistics that arrive already reduced and WITHOUT that track (an engine kernel’s stacked moments, a hand-built tuple) cannot be corrected here and take the historical path; when they are too ill-conditioned for it,estimatewarns rather than returning a covariance it cannot stand behind.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
MultivariateGaussianAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model parameters under the NormalWishart prior (ELBO global term).
The prior is over (mu, Lambda=covar^-1), so the model’s covariance is inverted before scoring.
- Parameters:
model (MultivariateGaussianDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a multivariate normal distribution with from aggregated sufficient statistics.
- Suff_stat is a Tuple of size 3 containing:
suff_stat[0] (np.ndarray): Component-wise sum of weighted observation values. suff_stat[1] (np.ndarray): Component-wise sum of weighted squared observation values. suff_stat[2] (float): Sum of weights for each observation.
- class NullDistribution(name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionNon-generative likelihood identity assigning log-score zero to every observation.
- Parameters:
name (str | None)
- classmethod compute_capabilities()[source]
Declare backend support for the zero-cost null distribution.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the null distribution.
- density(x)[source]
Density of NullDistribution. Always 1.0.
- Parameters:
x (Optional[Any]) – Observation of any type (ignored).
- Returns:
1.0 for any input.
- Return type:
- density_semantics()[source]
Identify this exact score as a non-generative likelihood factor.
- log_density(x)[source]
Log-density of NullDistribution. Always 0.0.
- Parameters:
x (Optional[Any]) – Observation of any type (ignored).
- Returns:
0.0 for any input.
- Return type:
- seq_log_density(x)[source]
Vectorized log-density evaluated at sequence encoded input x. Always 0.0.
- Parameters:
x (Optional[Any]) – Sequence encoded data; NullDataEncoder returns the sequence length.
- Returns:
A zero vector with one entry per encoded observation.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density: zero for every encoded row.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for homogeneous null mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)zero matrix for null-component log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return empty legacy statistics for each null component.
- sampler(seed=None)[source]
Reject generation from a likelihood identity with no normalized sample space.
- Parameters:
seed (int | None)
- Return type:
NullSampler
- estimator(pseudo_count=None)[source]
Create an estimator for the null distribution.
- Parameters:
pseudo_count (Optional[float]) – Kept for interface consistency (has no effect on estimation).
- Returns:
NullEstimator configured with this distribution’s name.
- Return type:
NullEstimator
- dist_to_encoder()[source]
Return the encoder used for null-distribution observations.
- Return type:
NullDataEncoder
- enumerator()[source]
Reject enumeration because a neutral factor has no probability support.
- Return type:
NullEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Reject indexing because a neutral factor has no probability support.
- class NullEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator that always produces a NullDistribution regardless of the data.
- accumulator_factory()[source]
Return a factory for null accumulators.
- Return type:
NullAccumulatorFactory
- estimate(nobs, suff_stat=None)[source]
Returns a NullDistribution; arguments are ignored.
- Parameters:
nobs (Optional[float]) – Number of observations (ignored).
suff_stat (Optional[Any]) – Sufficient statistics (ignored).
- Returns:
NullDistribution carrying this estimator’s name.
- Return type:
NullDistribution
- class NullEnumerator(dist)[source]
Bases:
DistributionEnumeratorDeprecated guard that rejects enumeration of a neutral factor.
- Parameters:
dist (NullDistribution)
- exception NeutralFactorError[source]
Bases:
TypeErrorRaised when a neutral likelihood identity is used as a generative law.
- marginalized(dist, missing_value=MISSING)[source]
Wrap
distso amissing_valueentry is marginalized out (not modeled).The wrapped field contributes log-density 0 and no sufficient statistics for missing observations, so estimation uses only the present ones. Equivalent to
OptionalDistribution(dist, p=None, missing_value=missing_value)– this is the principled missing-at-random treatment, not a degenerate case.
- composite_with_missing(dists, missing_value=MISSING)[source]
Build a
CompositeDistributionoverdistsin which every field toleratesmissing_value.Each field is wrapped with
marginalized(), so any field of an observation tuple may bemissing_valueand is integrated out of the likelihood (scoring and EM). Build the composite once and passMISSINGfor absent fields in your data – no per-field bookkeeping.
- class OptionalDistribution(dist, p=None, missing_value=None, name=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMixture-style wrapper that models missing observations explicitly.
- Parameters:
- compute_capabilities()[source]
Return compute capabilities inherited from the observed-data distribution.
- set_prior(prior)[source]
Distribute the joint prior
(p_prior, dist_prior)to the missing probability and base dist.prior=Noneis a no-op (point model, existing behavior byte-identical). Otherwise the first element is a conjugate Beta prior onp(caching the digamma expectations used byexpected_log_density) and the second is pushed to the base distribution’sset_prior.
- expected_log_density(x)[source]
Posterior-expected log-density
E_q[log p(x)]atx.With a conjugate Beta prior on
pthe expectation overpis available in closed form via digamma terms (missing =>da - dab; observed =>db - dab + dist.expected_log_density(x)); otherwise this falls back to the plug-inlog_density.- Parameters:
x (T)
- Return type:
- seq_expected_log_density(x)[source]
Vectorized posterior-expected log-density; falls back to
seq_log_densitywithout a prior.
- compute_declaration()[source]
Return a structured declaration for the optional missingness wrapper.
- density(x)[source]
Evaluate the density of the Optional distribution at x.
See log_density() for details.
- Parameters:
x (T) – Observation from base dist or missing value.
- Returns:
Density at x.
- Return type:
- density_semantics()[source]
Return child semantics for a proper gate or likelihood-factor semantics for MAR.
- property marginalized_core
Return the wrapped law when this is a pure marginalization, else None.
Without a missingness rate this distribution is a likelihood factor: it contributes 1 where the value is absent rather than a normalized density over values-plus-missing. That makes it non-generative, but only because
pwas not supplied – the wrapped law is untouched, and givingpmakes the whole thing generative again. Callers that need to tell “unnormalized because we are marginalizing over missingness” apart from “intrinsically cannot generate” (a scoring-only leaf) read this: the former returns its core, the latter has no such attribute.
- log_density(x)[source]
Evalute the log density of the Optional distribution at x.
If x is a missing value: return log(p) if p is not None, else return 0.0 If x is not the missing_value: if p is not None, return the log_denisty(x) at base dist + log(1-p) else: return log_density(x).
- Parameters:
x (T) – Observation from base dist or missing value.
- Returns:
Log-density at x.
- Return type:
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for optional encoded data.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked optional-wrapper parameters for homogeneous mixture kernels.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of optional-wrapper log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy optional-wrapper sufficient statistics.
- to_fisher(**kwargs)[source]
Fisher view for the optional/missing-gate.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
OptionalSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
OptionalEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
OptionalDataEncoder
- enumerator()[source]
Returns an OptionalEnumerator iterating the support (including the missing value) in descending probability order.
- Return type:
OptionalEnumerator
- class OptionalEstimator(estimator, missing_value=None, est_prob=False, pseudo_count=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate optional missingness probability and observed-data distribution parameters.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for optional sufficient statistics.
- Return type:
OptionalEstimatorAccumulatorFactory
- get_prior()[source]
Return the joint prior as
(p_prior, dist_prior)from this estimator and the base estimator.
- set_prior(prior)[source]
Distribute
(p_prior, dist_prior)to this estimator’spprior and the base estimator.prior=Noneis a no-op (empirical/pseudo-count path stays byte-identical). The first element is a conjugate Beta prior onp; the second is pushed to the base estimator viaset_prior.
- model_log_density(model)[source]
Sum the Beta-prior log-density at
pand the base estimator’s term (ELBO global term).- Parameters:
model (OptionalDistribution)
- Return type:
- exception NonGenerativeOptionalError[source]
Bases:
TypeErrorRaised when a marginalized optional likelihood factor is used to generate data.
- class OptionalEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate the optional support by merging missing mass with observed support.
- Parameters:
dist (OptionalDistribution)
- class PoissonDistribution(lam, name=None, keys=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionPoisson distribution over non-negative integer counts with rate
lam.- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for generated Poisson density kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Poisson distribution.
- static exp_family_sufficient_statistics(x, engine)[source]
Return Poisson sufficient statistics for generated scoring.
- static exp_family_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row Poisson sufficient statistics in accumulator order.
- static exp_family_natural_parameters(params, engine)[source]
Return Poisson natural parameters for generated scoring.
- static exp_family_log_partition(params, engine)[source]
Return Poisson log partition for generated scoring.
- static exp_family_base_measure(x, engine)[source]
Return Poisson base measure for generated scoring.
- set_prior(prior)[source]
Attach a parameter prior and cache the conjugate Gamma expectations.
With a Gamma(k, theta) prior over the rate
lamthis caches (k, theta) so thatexpected_log_density(x) = (psi(k) + ln theta)*x - k*theta - gammaln(x+1)(the VB E-step term using E[ln lam] = psi(k) + ln theta and E[lam] = k*theta). Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x | lam)] under the Gamma prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density of Poisson distribution at observation x.
Calls np.exp(log_density(x)). See log_density() for details.
- log_density(x)[source]
Log-density of Poisson distribution evaluated at x.
Log-density given by,
log(p_mat(x_mat=x; lam) = x*log(lam) - log(x!) - lam, for x in {0,1,2,…}
and -np.inf else.
Note: log(Gamma(x+1.0)) = log(x!), where Gamma is the gamma function.
- seq_log_density(x)[source]
Vectorized log-density evaluated on sequence encoded x.
Arg value x (Tuple[np.ndarray[int], np.ndarray[float]]) is seq_encoded Poisson data from PoissonDataEncoder.seq_encode(), containing
x[0] (np.ndarray[int]): Non-negative integer valued Poisson iid observations, x[1] (np.ndarray[float]): np.log(Gamma(x[0]+1.0)), Gamma is the gamma function.
- static backend_log_density_from_params(vals, log_fact, lam, engine)[source]
Engine-neutral Poisson log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Poisson parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Poisson log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return stacked Poisson sufficient statistics using engine-resident arrays.
- to_fisher(**kwargs)[source]
Return the Poisson’s count-family Fisher view.
- cdf(x)[source]
Cumulative distribution function P(X <= x) = Q(floor(x)+1, lam).
- entropy()[source]
Shannon entropy in nats, by exact summation of the standard series.
The Poisson entropy
-sum_k p_k log p_khas no closed form; the series is summed over the effective supportk <= lam + 40 sqrt(lam) + 40, beyond which the remaining terms are far below double rounding (the tail mass decays super-geometrically).- Return type:
- quantile(q)[source]
Inverse CDF F^{-1}(q) (via scipy poisson).
- sampler(seed=None)[source]
Return a sampler for iid draws from this distribution.
- Parameters:
seed (int | None) – Optional seed for the sampler’s random state.
- Returns:
A configured
PoissonSampler.- Return type:
PoissonSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this distribution’s shape.
- Parameters:
pseudo_count (float | None) – Optional smoothing count applied to the current rate.
- Returns:
A
PoissonEstimator.- Return type:
PoissonEstimator
- dist_to_encoder()[source]
Return an encoder for iid Poisson observations.
- Return type:
PoissonDataEncoder
- enumerator()[source]
Return an enumerator over nonnegative counts in descending probability order.
- Return type:
PoissonEnumerator
- quantized_index(max_bits, bin_width_bits=1.0)[source]
Build a bounded bit-quantized index by walking the Poisson mode outward.
- class PoissonEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimate Poisson rate parameters from accumulated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory matching this estimator.
- Return type:
PoissonAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s rate under the Gamma prior (ELBO global term).
- Parameters:
model (PoissonDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a Poisson distribution from aggregated sufficient statistics.
The tuple is interpreted as
(count, sum).
- class PoissonEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate Poisson support values in descending probability order.
- Parameters:
dist (PoissonDistribution)
- class PointMassDistribution(value, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionFixed Dirac/point-mass distribution assigning all mass to one value.
- classmethod compute_capabilities()[source]
Declare generic NumPy/Torch scoring support for fixed atoms.
- classmethod compute_declaration()[source]
Return the declaration for a fixed non-estimated atom.
- property value: Any
Return an independent copy so callers cannot mutate the model’s atom.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density from encoded equality flags.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked point-mass parameters for identical fixed atoms.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of point-mass log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return per-component empty statistics for fixed point masses.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
PointMassSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
PointMassEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
PointMassDataEncoder
- enumerator()[source]
Return an enumerator over the distribution support when available.
- Return type:
PointMassEnumerator
- class PointMassEstimator(value, pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator that always returns the configured point mass.
- Parameters:
- accumulator_factory()[source]
Return a factory for point-mass no-op accumulators.
- Return type:
PointMassAccumulatorFactory
- class PointMassEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate the single atom of a PointMassDistribution.
- Parameters:
dist (PointMassDistribution)
- class SelectDistribution(dists, choice_function, weights=None)[source]
Bases:
SequenceEncodableProbabilityDistributionSelectDistribution routes each observation to one child distribution via a choice function.
Two modes, set by
weights:Conditional (
weights is None, the default) – the density isp(x) = p_{c(x)}(x): the choice function selects which child scoresxand the result is that child’s density. There is no branch distribution, so this is a density conditioned on the branch and cannot be sampled as a standalone generative model.Dispatch mixture (
weightsgiven) – the density isp(x) = w_{c(x)} * p_{c(x)}(x), a normalized mixture over the union of the child supports in which the choice function plays the role of an observed component label. This is the right model for data of disjoint types (e.g. a mix of strings and numbers, where the type identifies the component): unlikeMixtureDistributionthe component is observed, so fitting is closed-form (the weights are the branch proportions, each child is fit on its routed subset – no EM) and sampling draws a branch fromweightsthen a value from that child.
For the dispatch-mixture density to be normalized the choice function must partition the observation space consistently with the children, i.e. every value a child can emit must route back to that child (
choice_function(x) == kforxin childk’s support).- Parameters:
- property count: int
Number of routed children, derived from the immutable child tuple.
- classmethod by_type(children, weights='auto')[source]
Build a dispatch mixture that routes observations to children by their Python type.
The friendly constructor for heterogeneous-typed data: instead of hand-writing (and registering) a choice function, pass each child with the type(s) it emits and the routing is derived automatically via a serializable
TypeDispatch.Example – a mixture of strings and counts:
sel = SelectDistribution.by_type([(str, cat), (int, poisson)]) fitted = estimate(mixed_data, sel.estimator()) # learns branch weights + each child
- Parameters:
children (Sequence[tuple[Any, SequenceEncodableProbabilityDistribution]]) – Sequence of
(type_spec, distribution)pairs.type_specis a type (str,int,float, …), a friendly name ('str','number','float','bytes','bool','complex'), or a tuple of these. Observations route to the FIRST matching child, so order more specific types first.weights (Any) –
'auto'(default) seeds uniform branch weights, giving a fittable generative dispatch mixture whose.estimator()learns the true proportions;Nonegives the weightless conditional density; or pass an explicit weight sequence.
- Returns:
SelectDistribution routing by a TypeDispatch choice function.
- Return type:
SelectDistribution
- compute_capabilities()[source]
Declare generated-compute support inherited from all selectable children.
- density_semantics()[source]
Distinguish conditional routing factors from normalized dispatch mixtures.
- compute_declaration()[source]
Return the generated-compute declaration for the select distribution.
- density(x)[source]
Density of the child distribution selected for observation x.
In dispatch-mixture mode the selected child’s density is scaled by its branch weight.
- Parameters:
x (T) – Observation compatible with the child selected by the choice function.
- Returns:
Density of the selected child distribution at x.
- Return type:
- log_density(x)[source]
Log-density of the child distribution selected for observation x.
In dispatch-mixture mode the selected child’s log-density is offset by
log(weight).- Parameters:
x (T) – Observation compatible with the child selected by the choice function.
- Returns:
Log-density of the selected child distribution at x.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of the log-density on sequence encoded data x.
The encoding groups observations by choice index: x[1][i] is the choice index of group i, x[0][i] holds the original positions of the group’s observations, and x[2][i] is the group’s data encoded by the matching child encoder. Each group is scored by the child distribution its choice index selects.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for choice-grouped encodings.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child parameters for homogeneous select-wrapper mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of choice-routed select log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy select sufficient statistics.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- to_fisher(**kwargs)[source]
Fisher view for the select combinator.
- sampler(seed=None)[source]
Create a sampler that dispatches to the child distributions.
- Parameters:
seed (Optional[int]) – Seed for the random number generator used in sampling.
- Returns:
SelectSampler configured with this distribution’s routing function.
- Return type:
SelectSampler
- estimator(pseudo_count=None, estimate_weights=None)[source]
Creates a SelectEstimator with one child estimator per child distribution.
- Parameters:
pseudo_count (Optional[float]) – Passed through to each child estimator.
estimate_weights (Optional[bool]) – Whether the fitted distribution carries branch weights (the dispatch-mixture model). When
None(default) this follows the current mode – a weighted distribution re-fits weights, a conditional one stays conditional.
- Returns:
SelectEstimator object.
- Return type:
SelectEstimator
- dist_to_encoder()[source]
Create an encoder for routed observations.
- Returns:
SelectDataEncoder configured with the child encoders.
- Return type:
SelectDataEncoder
- enumerator()[source]
Creates a SelectEnumerator iterating the union of child supports in descending select-density order. All children must support enumeration.
- Return type:
SelectEnumerator
- class SelectEstimator(estimators, choice_function, estimate_weights=False)[source]
Bases:
ParameterEstimatorSelectEstimator estimates a SelectDistribution from child sufficient statistics.
- Parameters:
- property count: int
Number of child estimators, derived from the immutable estimator tuple.
- accumulator_factory()[source]
Creates a SelectEstimatorAccumulatorFactory from the child estimators.
- Returns:
SelectEstimatorAccumulatorFactory object.
- Return type:
SelectEstimatorAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a SelectDistribution from aggregated sufficient statistics.
- class TypeDispatch(specs)[source]
Bases:
objectSerializable choice function that routes an observation to a child by its Python type.
specs[i]declares the type(s) that childiemits; an observation routes to the FIRST child it is an instance of. Specs are friendly names (‘str’, ‘int’, ‘float’, ‘number’, ‘bytes’, ‘bool’, ‘complex’) or the matching Python type objects, with numpy scalar types handled automatically. Because its state is just those names, it round-trips through JSON with no manual registration – unlike a hand-written lambda choice function. Order matters: put more specific types first (e.g. ‘bool’ before ‘int’, since a bool is also an integer).- Parameters:
specs (Sequence[Any])
- class SelectStatistics(schema_version, branches)[source]
Bases:
NamedTupleVersioned routed sufficient statistics, one branch entry per child.
- schema_version: int
Alias for field number 0
- exception NonGenerativeSelectError[source]
Bases:
TypeErrorRaised when a conditional select likelihood is used as a generative law.
- certify_select_routing(choice_function, contract_id)[source]
Attach an explicit, stable pushforward-routing assertion to a callable.
The caller asserts that every value generated by child
kroutes back tok. Finite child supports are still checked exhaustively; infinite supports are checked on every generated draw.
- class SelectEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates the union of the child supports in descending select-density order.
- Parameters:
dist (SelectDistribution)
- class SequenceDistribution(dist, len_dist=NullDistribution(), len_normalized=False, name=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionIndependent sequence distribution built from a component observation distribution.
- Parameters:
- compute_capabilities()[source]
Return compute-backend metadata inherited from the element and length distributions.
- get_prior()[source]
Return the joint prior as
(entry_prior, length_prior)from the wrapped children.
- set_prior(prior)[source]
Distribute
(entry_prior, length_prior)to the base and length distributions.prior=Noneis a no-op (children keep their existing priors, leaving the MLE path byte-identical); otherwise the two-element prior is pushed to the base and length children via their ownset_prior.
- expected_log_density(x)[source]
Prior-expected log-density of the sequence
x(sum over entries + length term).
- seq_expected_log_density(x)[source]
Vectorized prior-expected log-density over sequence-encoded input
x.
- compute_declaration()[source]
Return the symbolic declaration for sequence elements and optional length statistics.
- density(x)[source]
Return
exp(log_density(x))under the sequence score contract.In normalized mode only the element log-score is divided by the observed length; the modeled length log-probability remains a full term. That mode is a training objective, not a normalized generative law.
- density_semantics()[source]
Classify conditional and length-normalized modes as likelihood factors.
- log_density(x)[source]
Evaluate the log-density of SequenceDistribution at observed sequence x.
See density() for details.
- Parameters:
x (Sequence[T]) – Sequence of iid observations from base distribution of SequenceDistribution.
- Returns:
Log-density evaluated at observation x.
- Return type:
- seq_ld_lambda()[source]
Return vectorized log-density callables for encoded data.
- seq_log_density(x)[source]
Vectorized evaluation of SequenceDistribution.log-density evaluated on sequence encoded x.
- Parameters:
x (E) – Sequence encoded data observation.
- Returns:
Numpy array of log-density evaluated at each encoded observation value x.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded sequences.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child routes for homogeneous sequence mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of sequence log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component legacy sequence sufficient statistics.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- to_fisher(**kwargs)[source]
Structural Fisher view for the sequence.
- to_exponential_family(engine=None)[source]
Return the iid exponential-family view, or
None.An iid sequence of an exponential family is itself an exponential family with the shared element
etaandT(x) = sum_t T_0(x_t). This holds only when the length is not separately modeled and not length-normalized (a length term or normalization breaks the single-exp-family form); otherwise returnsNone, as does a non-exp-family element.- Parameters:
engine (Any)
- sampler(seed=None)[source]
Create a sampler for this sequence distribution.
Note: If member len_dist (SequenceEncodableDistribution) is NullDistribution() and or not compatible with data type int, an error is thrown.
- Parameters:
seed (Optional[int]) – Used to set seed of random number generator used to sample.
- Returns:
SequenceSampler object.
- Return type:
SequenceSampler
- estimator(pseudo_count=None)[source]
Return an estimator for iid sequence observations and their lengths.
- Parameters:
pseudo_count (float | None)
- Return type:
SequenceEstimator
- decomposition()[source]
Sequences are iid: this names the data (sequence) axis, sufficient stats SUM-reduce. The planner sizes this axis from N (the data), not a fixed model count; the base
distmay itself decompose.
- dist_to_encoder()[source]
Return an encoder for iid sequence observations.
Base distribution DataSequenceEncoder and length distribution DataSequenceEncoder objects are passed.
- Returns:
SequenceDataEncoder object.
- Return type:
SequenceDataEncoder
- enumerator()[source]
Returns SequenceEnumerator iterating sequences in descending probability order.
- Return type:
SequenceEnumerator
- structural_fine_bucket(value, quantizer)[source]
Sum of per-element buckets plus the length term – mirrors the count index’s per-length L-fold element convolution shifted by the length-term bucket.
- Return type:
- quantized_count_index(quantizer, max_fine_bucket)[source]
Structural count index: per-length L-fold self-convolution of the element histogram.
log p(x) = sum_i log p(x_i) + log p(len(x)). For each length L the count histogram of the L-element sum is the L-fold self-convolution of the element count histogram, shifted by the length term’s bucket; the total is the pooled sum over lengths. Lengths come from the length distribution’s enumerator in descending probability, so once the length term alone exceeds the depth bound every later length does too and we stop. Sequences are unranked by resolving the contributing length, then the per-position element buckets via the convolution unranker.
- Parameters:
max_fine_bucket (int)
- class SequenceStatistics(schema_version, element_nobs, length_nobs, elements, lengths)[source]
Bases:
NamedTupleVersioned sequence child statistics with their effective observation counts.
- Parameters:
- schema_version: int
Alias for field number 0
- element_nobs: float
Alias for field number 1
- length_nobs: float
Alias for field number 2
- elements: Any
Alias for field number 3
- exception NonGenerativeSequenceError[source]
Bases:
TypeErrorRaised when a conditional or normalized sequence score is asked to generate.
- class SequenceEstimator(estimator, len_estimator=NullEstimator(), len_dist=NullDistribution(), len_normalized=False, name=None, keys=None, prior=None)[source]
Bases:
ParameterEstimatorEstimator for iid sequence distributions from element and optional length sufficient statistics.
- Parameters:
- get_prior()[source]
Return the joint prior as
(entry_prior, length_prior)from the child estimators.
- set_prior(prior)[source]
Distribute
(entry_prior, length_prior)to the entry and length estimators.prior=Noneis a no-op. The prior is pushed to the entry/length estimators (not to a fixedlen_dist), so each child performs its own conjugate update.
- model_log_density(model)[source]
Sum the entry and length estimators’
model_log_densityon the corresponding children.- Parameters:
model (SequenceDistribution)
- Return type:
- accumulator_factory()[source]
Return SequenceAccumulatorFactory from len_estimator and estimator member variables with keys passed.
- Return type:
SequenceAccumulatorFactory
- class SequenceEnumerator(dist)[source]
Bases:
DistributionEnumeratorBest-first enumerator for finite-length iid sequences with a modeled length law.
- Parameters:
dist (SequenceDistribution)
- class ScheduledHiddenMarkovModelDistribution(inits, transitions, emissions, schedule, len_dist=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionPhase-indexed (length-/position-conditional) HMM. See the module docstring for the modeling story.
- Parameters:
- log_density(x)[source]
Return the log likelihood of one scheduled HMM sequence.
- seq_log_density(x)[source]
Score a batch of scheduled HMM sequences.
- sampler(seed=None)[source]
Return a sampler for scheduled HMM sequences.
- Parameters:
seed (int | None)
- Return type:
ScheduledHMMSampler
- estimator(pseudo_count=None)[source]
Create the matching estimator from this distribution’s own components.
Every phase/state cell retains its own estimator, so heterogeneous emission families survive fitting. The length estimator mirrors
len_distwhen one is modeled.- Parameters:
pseudo_count (float | None)
- Return type:
ScheduledHMMEstimator
- dist_to_encoder()[source]
Return the pass-through scheduled HMM encoder.
- Return type:
ScheduledHMMDataEncoder
- class ScheduledHMMEstimator(n_states, schedule, emission_estimator, len_estimator=None, pseudo_count=1e-8, name=None, *, emission_estimators=None)[source]
Bases:
ParameterEstimatorEM estimator for a
ScheduledHiddenMarkovModelDistributionwith a fixed schedule.emission_estimatoris the backward-compatible homogeneous estimator prototype.emission_estimatorsmay instead provide an exact phase-by-state grid, preserving heterogeneous families.- Parameters:
- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
ScheduledHMMAccumulatorFactory
- class Homogeneous[source]
Bases:
PhaseScheduleOne phase for everything – the ordinary time-homogeneous HMM.
- phase(t, length)[source]
Return the single homogeneous phase.
- class ByPosition(cap)[source]
Bases:
PhaseScheduleAbsolute position:
phi(t, L) = min(t, cap - 1)(positions pastcap-1share the last phase).- Parameters:
cap (int)
- phase(t, length)[source]
Return the absolute-position phase capped at the final phase.
- class ByRelativePosition(bins)[source]
Bases:
PhaseScheduleRelative position:
phi(t, L) = min(bins - 1, floor(bins * t / L))– progress through the sequence.- Parameters:
bins (int)
- phase(t, length)[source]
Return the relative-position phase for
t / length.
- class ByLength(boundaries)[source]
Bases:
PhaseScheduleLength-conditional: phase is the bucket of
Lagainst sortedboundaries(constant within a seq).With
boundaries = [5, 10]there are three phases:L <= 5,5 < L <= 10,L > 10.- Parameters:
boundaries (Sequence[int])
- phase(t, length)[source]
Return the length-bucket phase for the sequence length.
- class SegmentalHiddenMarkovModelDistribution(emissions, w=MISSING, transitions=MISSING, len_dist=NullDistribution(), name=None, weights=MISSING, terminal_states=None)[source]
Bases:
SequenceEncodableProbabilityDistributionHMM whose states emit arbitrary segment-valued distributions.
Observations are lists of segment objects. For example, with
SequenceDistribution(GaussianDistribution(...), len_dist=...)as an emission, each state emits a variable-length list of real values.- Parameters:
- compute_capabilities()[source]
Describe backend support shared by emissions and optional length model.
- compute_declaration()[source]
Return a composite compute declaration for the segmental HMM.
- property topics: list[SequenceEncodableProbabilityDistribution]
Compatibility alias with HiddenMarkovModelDistribution terminology.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral segmental-HMM forward scoring for encoded segment sequences.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
SegmentalHiddenMarkovSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
SegmentalHiddenMarkovEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
SegmentalHiddenMarkovDataEncoder
- enumerator()[source]
Enumerate segment sequences in descending marginal probability order.
The segmental HMM has the standard HMM forward semantics – each position emits one segment from its state’s distribution, scored independently – so it reuses
HiddenMarkovModelEnumeratordirectly via its per-state emission (topics),log_w,log_transitions, andlen_dist. Each segment is drawn from the union of the per-state emission supports, so every emission distribution must itself support enumeration (and a length distribution must be modeled).- Return type:
DistributionEnumerator
- SegmentalHiddenMarkovDistribution
alias of
SegmentalHiddenMarkovModelDistribution
- class SegmentalHiddenMarkovEstimator(estimators, len_estimator=NullEstimator(), pseudo_count=(None, None), name=None, keys=(None, None, None), terminal_states=None)[source]
Bases:
ParameterEstimatorBaum-Welch estimator for SegmentalHiddenMarkovModelDistribution.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Baum-Welch sufficient statistics.
- Return type:
SegmentalHiddenMarkovAccumulatorFactory
- SegmentalHiddenMarkovModelEstimator
alias of
SegmentalHiddenMarkovEstimator
- class BernoulliSetDistribution(pmap=MISSING, min_prob=1.0e-128, name=None, keys=None, prob_map=MISSING, prior=None, posteriors=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBernoulli set distribution: each support element is included in an observed set independently.
- Parameters:
- classmethod compute_capabilities()[source]
Declare backend support for Bernoulli-set generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the Bernoulli set.
- set_prior(prior, posteriors=None)[source]
Attach a (per-element) Beta prior and precompute conjugate-prior expectations.
With a shared Beta(a, b) prior on each element’s inclusion probability
p_kthis caches the digamma expectations so thatexpected_log_densityevaluates the variational Bayes termE_q[log p(x | p)]viaE[log p_k] = digamma(a_k) - digamma(a_k + b_k)andE[log(1 - p_k)] = digamma(b_k) - digamma(a_k + b_k). Whenposteriors(element -> (a_k, b_k)) is supplied, those per-element posterior Beta parameters are used; otherwise the shared prior parameters are broadcast over the support inpmap. Any other prior (includingNone) leaves the distribution a plain point model.
- get_prior()[source]
Return the shared Beta prior (or
None).- Return type:
SequenceEncodableProbabilityDistribution | None
- get_posteriors()[source]
Return the per-element posterior Beta parameters (or
None).
- expected_log_density(x)[source]
Variational expectation
E_q[log p(x | p)]under the per-element Beta prior.Sums
E[log p_k]over elements present in x plusE[log(1 - p_k)]over the remaining support. Falls back to the plug-inlog_density(x)when no conjugate prior is attached.
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Density of the Bernoulli set distribution at observed set x.
See log_density() for details.
- Parameters:
x (Sequence[Any]) – Observed set of distinct elements from the support of pmap.
- Returns:
Density at observation x.
- Return type:
- log_density(x)[source]
Log-density of the Bernoulli set distribution at observed set x.
Sums log(p_k / (1-p_k)) over the elements present in x, plus the constant sum_k log(1-p_k). Returns -inf if x is missing a required element (an element with p_k = 1 when min_prob is 0).
- Parameters:
x (Sequence[Any]) – Observed set of distinct elements from the support of pmap.
- Returns:
Log-density at observation x.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded object-valued sets.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked Bernoulli-set parameters for shared label support.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Bernoulli-set log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return per-component legacy
(count_map, total_weight)statistics.
- sampler(seed=None)[source]
Create a sampler for this Bernoulli set distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
Sampler bound to this distribution.
- Return type:
BernoulliSetSampler
- estimator(pseudo_count=None)[source]
Create a BernoulliSetEstimator, passing pmap as suff_stat if pseudo_count is given.
- Parameters:
pseudo_count (Optional[float]) – Used to re-weight the distribution’s pmap in estimation.
- Returns:
Estimator configured with this distribution’s prior settings.
- Return type:
BernoulliSetEstimator
- dist_to_encoder()[source]
Return a data encoder for Bernoulli set observations.
- Return type:
BernoulliSetDataEncoder
- enumerator()[source]
Returns BernoulliSetEnumerator iterating subsets of the support in descending probability order.
- Return type:
BernoulliSetEnumerator
- exception BernoulliSetFitError[source]
Bases:
RuntimeErrorRaised when Bernoulli-set statistics do not define a fitted law.
- class BernoulliSetEstimator(min_prob=1.0e-128, pseudo_count=None, suff_stat=None, name=None, keys=None, prior=None, support=None)[source]
Bases:
ParameterEstimatorEstimate Bernoulli set distributions from aggregated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
BernoulliSetAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model’s per-element probabilities under the shared Beta prior.
This is the global ELBO term: with a shared Beta(a, b) prior the contribution is the sum over support elements of
log Beta(p_k; a, b). Returns 0.0 when no conjugate prior is attached.- Parameters:
model (BernoulliSetDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a BernoulliSetDistribution from aggregated sufficient statistics.
- class BernoulliSetEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates subsets of the pmap support in descending probability order.
- Parameters:
dist (BernoulliSetDistribution)
- class SparseMarkovAssociationDistribution(init_prob_vec, cond_prob_mat, alpha=0.0, len_dist=NullDistribution(), low_memory=False)[source]
Bases:
SequenceEncodableProbabilityDistributionDistribution for a sparse count set
S2generated from a count setS1.- Parameters:
- density(x)[source]
Density of the sparse Markov association model at observation x.
See log_density() for details.
- log_density(x)[source]
Log-density of the sparse Markov association model at observation x.
Computes log(P(S2 | S1)) (see module docstring, eq. (1)) plus the log-density of the total counts [n1, n2] under len_dist.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- Parameters:
x – Encoded sequence (from SparseMarkovAssociationDataEncoder.seq_encode).
- Returns:
Numpy array of log-densities, one per encoded observation.
- Return type:
- compute_capabilities()[source]
Engine readiness for the dense scoring tail (numpy + torch).
The large word-by-word transition matrix is sliced/gathered host-side with SciPy sparse ops, but the per-pair smoothing, log, and segment reductions run on the active engine (see
backend_seq_log_density), so the model composes on numpy and torch.
- backend_seq_log_density(x, engine)[source]
Validate and score the sparse encoding once, then lift the result to
engine.- Return type:
- density_semantics()[source]
Classify the neutral-length form as a conditional fixed-length factor.
- sampler(seed=None)[source]
Create a sampler for this sparse Markov association distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
Sampler bound to this distribution.
- Return type:
SparseMarkovAssociationSampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this sparse Markov association distribution.
- Parameters:
pseudo_count (Optional[float]) – Prior mass for the initial and conditional simplexes.
- Returns:
Estimator configured with matching size and sparsity settings.
- Return type:
SparseMarkovAssociationEstimator
- dist_to_encoder()[source]
Return a data encoder for sparse Markov association observations.
- Return type:
SparseMarkovAssociationDataEncoder
- class SparseMarkovAssociationEstimator(num_vals=MISSING, alpha=0.0, len_estimator=NullEstimator(), suff_stat=None, pseudo_count=None, low_memory=True, keys=(None, None), num_values=MISSING)[source]
Bases:
ParameterEstimatorEstimate sparse Markov association distributions from sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
SparseMarkovAssociationAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a sparse Markov association distribution from aggregated sufficient statistics.
- Arg suff_stat is a Tuple of length 3 containing:
suff_stat[0] (np.ndarray): Weighted counts for the initial states P(S1). suff_stat[1] (Optional[Union[lil_matrix, csr_matrix]]): Counts for transitions used to estimate P(S2|S1). suff_stat[2] (SS1): Sufficient statistics from the accumulator of the size/len distribution.
- Parameters:
nobs (Optional[float]) – Weighted number of observations.
suff_stat (tuple[ndarray, lil_matrix | csr_matrix | None, SS1]) – See above for details.
- Returns:
SparseMarkovAssociationDistribution.
- Return type:
SparseMarkovAssociationDistribution
- class SpearmanRankingDistribution(sigma, rho=1.0, name=None, keys=None, max_dim=_DEFAULT_MAX_DIM, fit_diagnostics=None, *, _sigma_already_centered=False, _sigma_raw_scale_hint=None)[source]
Bases:
SequenceEncodableProbabilityDistributionExact finite Spearman law over item orderings under a dimension budget.
Known limitation: direct construction from a raw location vector (this class’s
sigmaargument – see the module docstring’s “possibly fractional mean rank vector”) whose entries share an extremely large common offset – beyond_TRUSTED_SIGMA_RAW_SCALE_CEILINGinspearman_rho.py, roughly the range of a 32-bit integer (~2.1e9) – succeeds here, but the one-time float64 cancellation__init__performs while centering it can leave a residual that a later restore (__pysp_setstate__) cannot always distinguish from genuine state corruption, and may then reject with aValueErroreven though it was built validly. The original, pre-centering magnitude is not recoverable from the restored, already-centered state, so this is an accepted, documented limit rather than a bug to silently work around – see the comment above_validate_locationin this module for the full reasoning and exact boundary.- Parameters:
- classmethod compute_capabilities()[source]
Declare generated NumPy and Torch scoring support.
- classmethod compute_declaration()[source]
Return the generated-compute declaration.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return row-wise count and item-indexed rank-vector statistics.
- static backend_log_density_from_params(x, sigma, rho, log_const, engine)[source]
Score item orderings after explicit conversion to rank vectors.
Callers arrive under two shape conventions.
backend_seq_log_densitypasses the natural ones – ranks(n, d)against a singlesigma(d,). The generated scorer inmixle.stats.compute.declarationspre-aligns both sides instead: data picks up a component axis ((n, 1, d)) and every parameter a leading row axis ((1, k, d)), so the two already broadcast. Inserting a component axis unconditionally, as this did, double-counts it on that path and returns an(n, 1, k)score where the contract is(n, k). Only add the axis when the ranks really are still two-dimensional.
- property sigma: ndarray
Return an ownership-safe copy of the canonical mean rank vector.
- density(x)[source]
Return the probability of an item ordering.
- log_density(x)[source]
Return the log-probability of one
x[rank] = itemordering.
- seq_log_density(x)[source]
Return vectorized log-probabilities for item orderings.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized scoring for encoded item orderings.
- classmethod backend_stacked_params(dists, engine)[source]
Stack equal-dimensional Spearman parameters.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an observation-by-component score matrix.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked item-indexed rank-vector statistics.
- sampler(seed=None)[source]
Return an exact conditional-permanent sampler.
- Parameters:
seed (int | None)
- Return type:
SpearmanRankingSampler
- estimator(pseudo_count=None)[source]
Return an estimator preserving the dimension and resource budget.
- Parameters:
pseudo_count (float | None)
- Return type:
SpearmanRankingEstimator
- dist_to_encoder()[source]
Return the item-ordering encoder.
- Return type:
SpearmanRankingDataEncoder
- enumerator()[source]
Return a lazy descending-probability enumerator.
- Return type:
SpearmanRankingEnumerator
- class SpearmanRankingEstimator(dim, rho=None, pseudo_count=None, suff_stat=None, name=None, keys=None, max_rho=1.0e6, max_dim=_DEFAULT_MAX_DIM)[source]
Bases:
ParameterEstimatorEstimate consensus mean ranks and nonnegative Spearman concentration.
- Parameters:
- accumulator_factory()[source]
Return a factory for item-ordering sufficient statistics.
- Return type:
SpearmanRankingAccumulatorFactory
- class SpearmanRankingEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate item orderings by increasing rank-to-item assignment cost.
- Parameters:
dist (SpearmanRankingDistribution)
- class SpearmanRankingFitDiagnostics(concentration_algorithm, converged, iterations, boundary_solution, regularized, pseudo_count)[source]
Bases:
objectConcentration-fit and regularization evidence attached to an estimate.
- class ItemOrdering(values)[source]
-
A permutation whose entry at each rank is the item occupying that rank.
- to_rank_vector()[source]
Return the inverse permutation, indexed by item.
- Return type:
RankVector
- class RankVector(values)[source]
-
A permutation whose entry for each item is that item’s rank.
- to_item_ordering()[source]
Return the inverse permutation, indexed by rank.
- Return type:
ItemOrdering
- item_ordering_to_rank_vector(value)[source]
Convert
x[rank] = itemto ownedrank[item] = rankdata.
- rank_vector_to_item_ordering(value)[source]
Convert
rank[item] = rankto ownedx[rank] = itemdata.
- class KnowledgeGraphDistribution(entity_embeddings, relation_embeddings, name=None, keys=None, fit_receipt=None)[source]
Bases:
SequenceEncodableProbabilityDistributionDistMult knowledge-graph embedding distribution over triples
(h, r, t).entity_embeddingsis(num_entities, dim)andrelation_embeddingsis(num_relations, dim).log_density((h, r, t))is the conditional tail log-probabilitylog p(t | h, r)under the entity softmax.- Parameters:
- score(h, r, t)[source]
DistMult score of a single triple (higher is more plausible).
- tail_log_posterior(h, r)[source]
Length-
num_entitiesvector oflog p(t | h, r)over all tail candidates.
- head_log_posterior(r, t)[source]
Length-
num_entitiesvector oflog p(h | r, t)over all head candidates.
- relation_log_posterior(h, t)[source]
Length-
num_relationsvector oflog p(r | h, t)over all relation candidates.
- complete(h=None, r=None, t=None)[source]
Log-posterior over candidates for the single missing slot of a query.
Exactly one of
h,r,tmust beNone; the returned vector is over entities (for a missing head or tail) or relations (for a missing relation).
- rank(h=None, r=None, t=None, exclude=(), top_n=None)[source]
Rank candidates for the missing slot by log-probability, dropping
excludecandidates.Returns
[(candidate, log_prob), ...]highest first (the most plausible completions).
- recommend(known, top_n=10)[source]
Recommend the most plausible missing tail facts for the
(h, r)contexts inknown.knownis a sequence of observed(h, r, t)triples; for each distinct(h, r)the already-present tails are excluded, the remaining tails are ranked bylog p(t | h, r), and the global toptop_nnew facts are returned as[(h, r, t, log_prob), ...].
- recommend_subgraph(node, known, top_n=5)[source]
Recommend plausible new edges incident to
node(both(node, r, ?)and(?, r, node)).Excludes edges already in
knownand returns the toptop_nby log-probability as[(h, r, t, log_prob), ...], the suggested missing subgraph around the node.
- pattern(pattern, candidates=None, known=None, beam=64)[source]
A subgraph-pattern query over this model for flexible enumeration of missing parts.
patternis a list of triples whose slots are either fixed integer ids or named variables (strings starting with'?'), variables shared across edges (e.g.[(alice, friend, '?x'), ('?x', lives_in, '?c')]). The returnedKnowledgeGraphPatternenumerates the variable bindings (completed subgraphs) in descending joint plausibility, restricts variables tocandidatesif given, drops groundings that add nothing new whenknownis given, and plugs intoConformalStructurefor a calibrated set of completed subgraphs.
- log_density(x)[source]
Return normalized joint
log p(h,r,t)for one triple.
- seq_log_density(x)[source]
Return vectorized tail log-probabilities for encoded triples.
- sampler(seed=None)[source]
Return a sampler for observed triples.
- Parameters:
seed (int | None)
- Return type:
KnowledgeGraphSampler
- estimator(pseudo_count=None)[source]
Return a DistMult embedding estimator for this entity/relation shape.
- Parameters:
pseudo_count (float | None)
- Return type:
KnowledgeGraphEstimator
- dist_to_encoder()[source]
Return the triple encoder used by vectorized methods.
- Return type:
KnowledgeGraphDataEncoder
- class KnowledgeGraphEstimator(num_entities, num_relations, dim=16, lr=0.5, epochs=100, batch_size=256, weight_decay=0.0, init_scale=0.3, max_norm=1.0, directions=('tail',), negatives=None, seed=1, pseudo_count=None, name=None, keys=None, objective=None, initial_model=None)[source]
Bases:
ParameterEstimatorTrain DistMult knowledge-graph embeddings by maximizing the tail-softmax log-likelihood.
estimateruns vectorized mini-batch gradient ascent (epochspasses, batch sizebatch_size, steplrwith L2weight_decay) from a deterministic seeded init, projecting each entity embedding back to the unit ball every epoch so the scale – hence the step size – stays well behaved. Oneoptimize/fititeration (max_its=1) trains the model; the data is supplied through the accumulator like any other estimator.- Parameters:
num_entities (int)
num_relations (int)
dim (int)
lr (float)
epochs (int)
batch_size (int)
weight_decay (float)
init_scale (float)
max_norm (float)
directions (tuple)
negatives (int | None)
seed (int)
pseudo_count (float | None)
name (str | None)
keys (str | None)
objective (str | None)
initial_model (KnowledgeGraphDistribution | None)
- accumulator_factory()[source]
Return a factory for stored-triple accumulators.
- Return type:
KnowledgeGraphAccumulatorFactory
- class KnowledgeGraphEnsemble(members)[source]
Bases:
objectAn ensemble of independently fit
KnowledgeGraphDistributionmodels, for epistemic (model) uncertainty over completions.The members share the entity and relation index spaces but are fit from different random seeds, so where the data pins the answer down they agree and where it does not they disagree. The mean tail posterior averages
p(t | h, r)across members; the epistemic uncertainty is the mutual information (BALD)H(mean) - mean_m H(member_m)– the part of the predictive entropy that comes from disagreement among members rather than from genuine ambiguity.- Parameters:
members (list[KnowledgeGraphDistribution])
- mean_tail_posterior(h, r)[source]
The ensemble-averaged
p(t | h, r)over all tail candidates.
- epistemic_tail_uncertainty(h, r)[source]
Mutual-information (BALD) epistemic uncertainty of the tail completion (nats); 0 if members agree.
Thin wrapper over the general
mixle.inference.uncertainty.decompose_entropy()– the tail posteriorsp(t | h, r)per member are exactly the categorical predictives it splits.
- fit_knowledge_graph_ensemble(triples, num_entities, num_relations, dim=16, members=5, bootstrap=False, rng=None, **estimator_kwargs)[source]
Fit
membersknowledge-graph models and wrap them in an ensemble.Members differ by their random seed; with
bootstrap=Trueeach is also fit on a bootstrap resample of the triples (bagging), which spreads the members further apart where the data is thin and so sharpens the epistemic-uncertainty estimate.
- class PlackettLuceDistribution(log_w, name=None, keys=None, allow_partial=False)[source]
Bases:
SequenceEncodableProbabilityDistributionPlackett-Luce distribution over orderings of K items with log-worths log_w.
Data type: List[int] (an ordering: a permutation of 0,…,K-1, best-ranked item first).
- Parameters:
- classmethod compute_capabilities()[source]
Declare the NumPy execution path used by Plackett-Luce ranking kernels.
- density(x)[source]
Return the probability of an ordering x.
- log_density(x)[source]
Return the log-probability of an ordering
x.xmay be a full ranking (a permutation of0,...,K-1) or a partial / top-m ranking (an ordered list ofm <= Kdistinct items, best first, leaving the otherK-mitems unranked). For a partial ranking the sequential-choice denominator at each stage still includes the unranked items:p(x) = prod_{s=0}^{m-1} w_{x[s]} / (sum_{t>=s} w_{x[t]} + sum_{u unranked} w_u), which reduces to the full-ranking density whenm = K.- Raises:
ValueError – If
xis not 1-D, has a non-integer-valued entry (e.g.0.5, which would otherwise silently truncate to a plausible-looking index instead of being rejected), or its (integer) entries are not distinct item indices in0,...,K-1.- Parameters:
- Return type:
- seq_log_density(x)[source]
Return vectorized log-probabilities for encoded orderings.
A dense
(N, K)integer array (the full-ranking encoding) is scored by the vectorized path; a ragged sequence of variable-length orderings (the partial / top-m encoding) is scored per-ranking vialog_density(), which includes the unranked-item denominator term.
- sampler(seed=None)[source]
Return a sampler for drawing orderings from this distribution.
- Parameters:
seed (int | None)
- Return type:
PlackettLuceSampler
- enumerator()[source]
Return an exact finite enumerator over all orderings in decreasing probability order.
- Return type:
PlackettLuceEnumerator
- estimator(pseudo_count=None)[source]
Return an MM estimator that keeps the item count fixed at this distribution’s K.
- Parameters:
pseudo_count (float | None)
- Return type:
PlackettLuceEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
The returned encoder handles both full rankings and partial/top-m rankings (see
PlackettLuceDataEncoder), so this works regardless of whetherselfwas produced byPlackettLuceEstimatororPlackettLucePartialEstimator.- Return type:
PlackettLuceDataEncoder
- class PlackettLuceEstimator(dim, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorMinorization-Maximization estimator for the Plackett-Luce log-worths (item count K fixed).
- accumulator_factory()[source]
Return a factory for MM sufficient statistics at this estimator’s dimension.
- Return type:
PlackettLuceAccumulatorFactory
- class PlackettLuceEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate Plackett–Luce orderings in descending probability order, lazily (A* best-first).
A ranking’s log-density is
sum_k [theta_{x_k} - logsumexp(theta over the items not yet ranked at step k)]. The state is a chosen prefix with exact partial score g; the best possible completion ranks the remaining items by descending worth (which minimizes the remaining logsumexp denominators), giving an exact admissible bound h. A* on g + h streams the rankings in exact descending order without touching the n! support.- Parameters:
dist (PlackettLuceDistribution)
- class PlackettLucePartialEstimator(dim, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorMM estimator of Plackett-Luce log-worths from partial / top-m rankings (item count K fixed).
- accumulator_factory()[source]
Return a factory for partial-ranking MM sufficient statistics.
- Return type:
PlackettLucePartialAccumulatorFactory
- class MallowsDistribution(sigma0, theta=1.0, name=None, keys=None, fit_diagnostics=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMallows distribution over permutations of 0,…,n-1 with central permutation sigma0 and dispersion theta.
Data type: List[int] (an ordering: a permutation of 0,…,n-1, best-ranked item first).
- Parameters:
- classmethod compute_capabilities()[source]
Return compute-backend metadata for the Mallows distribution.
- kendall_distance(x)[source]
Return the Kendall tau distance between ordering x and the central permutation.
- Raises:
ValueError – If x is not a permutation of 0,…,n-1 (wrong length, a repeated element, a non-integer entry, or an element outside that range). A malformed x is not merely an unlikely ordering – it isn’t an ordering at all, so it is rejected here rather than silently scored (e.g. a repeated index would otherwise still produce a finite, meaningless distance, an out-of-range index can alias a valid rank via numpy’s negative-index wraparound instead of failing loudly, and a fractional entry like 0.5 would otherwise be silently truncated to 0 by the int cast before this check ever saw it).
- Parameters:
- Return type:
- density(x)[source]
Return the probability of an ordering x.
- log_density(x)[source]
Return the log-probability of an ordering x (a permutation of 0,…,n-1).
- seq_log_density(x)[source]
Return vectorized log-probabilities for an (N, n) array of orderings.
- sampler(seed=None)[source]
Return a sampler for drawing orderings from this distribution.
- Parameters:
seed (int | None)
- Return type:
MallowsSampler
- enumerator()[source]
Return an exact finite enumerator over all orderings in decreasing probability order.
- Return type:
MallowsEnumerator
- estimator(pseudo_count=None)[source]
Return an estimator that keeps the item count fixed at this distribution’s n.
- Parameters:
pseudo_count (float | None)
- Return type:
MallowsEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
MallowsDataEncoder
- class MallowsEstimator(dim, theta=None, pseudo_count=None, prior_precede=None, prior_center=None, center_exact_cap=9, allow_approximate_center=False, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator for the Mallows central permutation (Copeland aggregation) and dispersion theta.
- Parameters:
- accumulator_factory()[source]
Return a factory for Mallows sufficient-statistic accumulators.
- Return type:
MallowsAccumulatorFactory
- class MallowsEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate Mallows orderings in descending probability order, lazily.
Kendall distance is separable in the Lehmer code: an ordering’s distance is the sum of digits
L_i in {0,...,n-1-i}(inversions contributed at each rank), each weighted-theta*L_i. So the support is a product over the digits andProductEnumeratorstreams it in increasing distance (descending probability) without materializing the n! permutations; each digit tuple decodes (factorial number system) to a permutation of the identity, relabeled through the central permutation sigma0.- Parameters:
dist (MallowsDistribution)
- class MallowsFitDiagnostics(center_algorithm, center_exact, centers_evaluated, kendall_objective, regularized, pseudo_count)[source]
Bases:
objectCenter-search and regularization evidence attached to a fitted Mallows law.
- class GeneralizedMallowsDistribution(sigma0, theta=1.0, metric='kendall', name=None, keys=None, n_mc=20000, seed=0, max_exact=16, max_enum=9, fit_diagnostics=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMallows distribution under a configurable distance
metric(closed-form normalizer metrics).- Parameters:
- classmethod compute_capabilities()[source]
Declare the NumPy and numba execution path used by Mallows kernels.
- distance(x)[source]
Distance between ordering
xand the central permutation under this metric.- Raises:
ValueError – If x is not a permutation of 0,…,n-1 (wrong length, a repeated element, a non-integer entry, or an element outside that range). A malformed x is not merely an unlikely ordering – it isn’t an ordering at all, so it is rejected here rather than silently scored (e.g. a repeated index would otherwise still produce a finite, meaningless distance, an out-of-range index can alias a valid rank via numpy’s negative-index wraparound instead of failing loudly, and a fractional entry like 0.5 would otherwise be silently truncated to 0 by the int cast before this check ever saw it).
- Parameters:
- Return type:
- density(x)[source]
Return the probability of one ordering under the Mallows model.
- log_density(x)[source]
Return the log-probability of one ordering.
- seq_log_density(x)[source]
Return vectorized log-probabilities for encoded orderings.
- sampler(seed=None)[source]
Return a sampler for this Mallows distribution.
- Parameters:
seed (int | None)
- Return type:
GeneralizedMallowsSampler
- estimator(pseudo_count=None)[source]
Return a Mallows estimator with this metric and item count.
- Parameters:
pseudo_count (float | None)
- Return type:
GeneralizedMallowsEstimator
- dist_to_encoder()[source]
Return the full-ranking encoder used by vectorized methods.
- Return type:
GeneralizedMallowsDataEncoder
- class GeneralizedMallowsEstimator(dim, metric='kendall', theta=None, reservoir=10000, name=None, keys=None, n_mc=20000, seed=0, max_exact=16, max_enum=9, pseudo_count=None, prior_center=None, center_exact_cap=7, allow_approximate_center=False)[source]
Bases:
ParameterEstimatorEstimate the central permutation (Copeland/Borda) and dispersion theta (moment match).
- Parameters:
- accumulator_factory()[source]
Return a factory for Mallows sufficient-statistic accumulators.
- Return type:
GeneralizedMallowsAccumulatorFactory
- class GeneralizedMallowsFitDiagnostics(center_algorithm, center_exact, centers_evaluated, distance_objective, regularized, pseudo_count)[source]
Bases:
objectCenter-search and regularization evidence attached to a fitted model.
- class GeneralizedMallowsComputationDiagnostics(normalizer_algorithm, normalizer_exact, sampler_algorithm, sampler_exact, legacy_n_mc_ignored, legacy_seed_ignored)[source]
Bases:
objectExactness and algorithm provenance for scoring and sampling.
- class GeneralizedMallowsModelDistribution(sigma0, theta=None, name=None, keys=None, fit_diagnostics=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGeneralized Mallows Model: a Kendall Mallows model with a per-stage dispersion vector
theta.- Parameters:
- classmethod compute_capabilities()[source]
Declare the NumPy execution path used by stage-wise Mallows kernels.
- density(x)[source]
Return the probability of one ordering.
- log_density(x)[source]
Return the log-probability of one ordering.
- seq_log_density(x)[source]
Return vectorized log-probabilities for encoded orderings.
- Raises:
ValueError – If any row of x is not a permutation of 0,…,n-1 (wrong length, a repeated element, a non-integer entry, or an element outside that range). A malformed row is not merely an unlikely ordering – it isn’t an ordering at all, so it is rejected here rather than silently scored (e.g. a repeated index would otherwise still produce a finite, meaningless log-density, an out-of-range or negative index reaches the numba RIM kernel below, which has no bounds checking of its own and does not raise – it silently scores too, rather than failing loudly – and a fractional entry like 0.5 would otherwise be silently truncated to 0 by the int cast before this check ever saw it).
- Parameters:
x (ndarray)
- Return type:
- sampler(seed=None)[source]
Return an exact repeated-insertion sampler for this model.
- Parameters:
seed (int | None)
- Return type:
GeneralizedMallowsModelSampler
- estimator(pseudo_count=None)[source]
Return a stage-wise Mallows estimator with this item count.
- Parameters:
pseudo_count (float | None)
- Return type:
GeneralizedMallowsModelEstimator
- dist_to_encoder()[source]
Return the full-ranking encoder used by vectorized methods.
- Return type:
GeneralizedMallowsModelDataEncoder
- class GeneralizedMallowsModelEstimator(dim, reservoir=10000, pseudo_count=None, prior_center=None, center_exact_cap=7, allow_approximate_center=False, name=None, keys=None)[source]
Bases:
ParameterEstimatorFit a center and per-stage dispersions from exact weighted empirical support.
- Parameters:
- accumulator_factory()[source]
Return a factory for stage-wise Mallows sufficient-statistic accumulators.
- Return type:
GeneralizedMallowsModelAccumulatorFactory
- class GeneralizedMallowsModelFitDiagnostics(center_algorithm, center_exact, centers_evaluated, objective, regularized, pseudo_count)[source]
Bases:
objectCenter-search and regularization evidence attached to a fitted stage-wise model.
- class BradleyTerryDistribution(log_w, name=None, keys=None, fit_diagnostics=None, *, _log_w_already_centered=False)[source]
Bases:
SequenceEncodableProbabilityDistributionBradley-Terry paired-comparison model with centered log-worths
log_w.- Parameters:
- classmethod compute_capabilities()[source]
Declare the NumPy and numba execution path used by Bradley-Terry kernels.
- density(x)[source]
Return the probability of one
(winner, loser)comparison.
- log_density(x)[source]
Return the JOINT log-probability of one
(winner, loser)comparison.The pair is drawn uniformly from all
K(K-1)/2unordered pairs and the winner follows Bradley-Terry, soexp(log_density(...))sums to one over all ordered pairs andexp(log_density((i, j))) + exp(log_density((j, i)))is1/C(K, 2)– NOT one. It is notP(i beats j); that conditional iswin_probability().
- win_probability(i, j)[source]
Return
P(i beats j | i and j are compared):sigmoid(log_w[i] - log_w[j]).The conditional a reader of
log_densityexpects.log_densityis the joint over (which pair, uniformly) x (who won), smaller by the factorC(K, 2); this quantity satisfieswin_probability(i, j) + win_probability(j, i) == 1.
- seq_log_density(x)[source]
Return vectorized log-probabilities for encoded pairwise comparisons.
- sampler(seed=None)[source]
Return a sampler for paired-comparison outcomes.
- Parameters:
seed (int | None)
- Return type:
BradleyTerrySampler
- estimator(pseudo_count=None)[source]
Return an MM estimator with this distribution’s item count.
- Parameters:
pseudo_count (float | None)
- Return type:
BradleyTerryEstimator
- dist_to_encoder()[source]
Return the pairwise-comparison encoder used by vectorized methods.
- Return type:
BradleyTerryDataEncoder
- class BradleyTerryEstimator(dim, pseudo_count=None, max_iter=500, tol=1e-10, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood log-worths via the Zermelo / MM fixed point (Hunter 2004).
pseudo_countadds that many fractional wins to EVERY ordered pair (symmetric smoothing). It is what lets an undefeated or winless competitor, or a disconnected comparison graph, fit at all: the unregularized maximum likelihood does not exist there (Ford 1957), and the estimator refuses rather than return a boundary worth. Choosing it: the top of the ranking is stable over a wide range, but near-tied competitors can swap order and the leader’s worth margin shrinks roughly withpseudo_countrelative to the wins per pair, because the prior wins pull every worth toward equality (a 0.05 -> 2.0 sweep on one realistic dataset moved the leader’s margin by ~10x while leaving the top order alone). Start near0.5, half a prior win per ordered pair, shrink it as the comparisons per pair grow, readfit_diagnostics.regularizedandpseudo_counton the result, and compare two values before quoting a margin.- Parameters:
- accumulator_factory()[source]
Return a factory for Bradley-Terry sufficient-statistic accumulators.
- Return type:
BradleyTerryAccumulatorFactory
- class BradleyTerryFitDiagnostics(converged, iterations, l1_change, regularized, pseudo_count)[source]
Bases:
objectConvergence and regularization evidence attached to an estimated model.
- class LowRankPermutationDistribution(u, v, name=None, keys=None, max_exact=12, sinkhorn_iter=200, fit_diagnostics=None)[source]
Bases:
SequenceEncodableProbabilityDistributionPermutation Gibbs model with a low-rank item-by-rank score matrix
S = U V^T.- Parameters:
- classmethod compute_capabilities()[source]
Declare the NumPy and numba execution path used by low-rank permutation kernels.
- density(x)[source]
Return the probability of one ordering.
- log_density(x)[source]
Return the log-probability of one ordering.
- seq_log_density(x)[source]
Return vectorized log-probabilities for encoded orderings.
- sinkhorn_relaxation()[source]
Return an explicitly approximate doubly-stochastic transport relaxation.
- Return type:
- sampler(seed=None)[source]
Return an exact conditional-permanent sampler.
- Parameters:
seed (int | None)
- Return type:
LowRankPermutationSampler
- estimator(pseudo_count=None)[source]
Return an exact-marginal estimator with this dimension and rank.
- Parameters:
pseudo_count (float | None)
- Return type:
LowRankPermutationEstimator
- dist_to_encoder()[source]
Return the full-ranking encoder used by vectorized methods.
- Return type:
LowRankPermutationDataEncoder
- class LowRankPermutationEstimator(dim, rank=2, max_exact=12, sinkhorn_iter=200, max_iter=300, lr=0.5, tol=1.0e-6, pseudo_count=None, prior_marginals=None, require_convergence=True, name=None, keys=None)[source]
Bases:
ParameterEstimatorFit
U, Vby Sinkhorn-marginal gradient ascent toward the empirical item-by-rank marginals.- Parameters:
- accumulator_factory()[source]
Return a factory for low-rank permutation sufficient-statistic accumulators.
- Return type:
LowRankPermutationAccumulatorFactory
- class LowRankPermutationFitDiagnostics(converged, iterations, gradient_norm, regularized, pseudo_count, marginal_algorithm='exact_log_permanent')[source]
Bases:
objectOptimization evidence attached to an estimated low-rank permutation law.
- class LowRankPermutationComputationDiagnostics(normalizer_algorithm='exact_log_permanent', normalizer_exact=True, marginal_algorithm='exact_log_permanent_ratios', marginals_exact=True, sampler_algorithm='exact_conditional_permanent', sampler_exact=True, optional_relaxation='sinkhorn_bethe_transport')[source]
Bases:
objectExactness and algorithm provenance for the represented probability law.
- class ThurstoneDistribution(mu, name=None, keys=None, n_mc=4000, seed=0, smoothing=0.5, fit_diagnostics=None, *, _mu_already_centered=False)[source]
Bases:
SequenceEncodableProbabilityDistributionNormalized finite-sample approximation to a Case V Thurstone law.
- Parameters:
- classmethod compute_capabilities()[source]
Declare the NumPy execution path used to build the approximation.
- density(x)[source]
Return the normalized approximating probability of a full ordering.
- log_density(x)[source]
Return the normalized approximating log-probability of one ordering.
- seq_log_density(x)[source]
Return batch-invariant log-probabilities for encoded full orderings.
- sampler(seed=None)[source]
Return a sampler for this exact approximating categorical law.
- Parameters:
seed (int | None)
- Return type:
ThurstoneSampler
- estimator(pseudo_count=None)[source]
Return a labelled Thurstone-Mosteller pairwise-moment estimator.
- Parameters:
pseudo_count (float | None)
- Return type:
ThurstoneEstimator
- dist_to_encoder()[source]
Return the dense full-ranking encoder used by vectorized methods.
- Return type:
ThurstoneDataEncoder
- class ThurstoneEstimator(dim, n_mc=4000, seed=0, smoothing=0.5, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorLabelled pairwise-moment estimator for Case V Thurstone utilities.
- Parameters:
- accumulator_factory()[source]
Return a factory for Thurstone sufficient-statistic accumulators.
- Return type:
ThurstoneAccumulatorFactory
- class ThurstoneApproximationDiagnostics(method, draws, seed, smoothing, distinct_rankings, support_size, maximum_binomial_standard_error)[source]
Bases:
objectProvenance and uncertainty scale for the approximating categorical law.
- class ThurstoneFitDiagnostics(method, exact_mle, regularized, pseudo_count)[source]
Bases:
objectProvenance for an estimated Thurstone utility vector.
- class ThurstoneMostellerDistribution(mu, name=None, keys=None, fit_diagnostics=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGaussian/probit paired-comparison model
P(i beats j) = Phi((mu_i - mu_j) / sqrt(2)).- Parameters:
- classmethod compute_capabilities()[source]
Return backend capabilities for the probit pairwise likelihood.
- density(x)[source]
Return the probability mass of one winner-loser pair.
- log_density(x)[source]
Return the JOINT log probability of one winner-loser pair.
The pair is drawn uniformly from all
K(K-1)/2unordered pairs and the winner follows the probit rule, soexp(log_density((i, j))) + exp(log_density((j, i)))is1/C(K, 2), not one.P(i beats j | compared)iswin_probability().
- win_probability(i, j)[source]
Return
P(i beats j | i and j are compared)=Phi((mu[i] - mu[j]) / sqrt(2)).
- seq_log_density(x)[source]
Score encoded winner-loser pairs.
- sampler(seed=None)[source]
Return a sampler for winner-loser comparisons.
- Parameters:
seed (int | None)
- Return type:
ThurstoneMostellerSampler
- estimator(pseudo_count=None)[source]
Return the least-squares probit paired-comparison estimator.
- Parameters:
pseudo_count (float | None)
- Return type:
ThurstoneMostellerEstimator
- dist_to_encoder()[source]
Return the encoder for winner-loser pair data.
- Return type:
PairDataEncoder
- class ThurstoneMostellerEstimator(dim, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatormu_i - mu_j = sqrt(2) Phi^{-1}(P(i beats j))from the win-count matrix (least squares).pseudo_countadds that many fractional wins to every ordered pair before the moment step; seeBradleyTerryEstimatorfor how to choose it and what it does to margins. Here it also keeps a never-lost pair away from thePhi^{-1}clip (clipped_pair_probabilitiescounts the pairs that hit it).- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
PairWinAccumulatorFactory
- class ThurstoneMostellerFitDiagnostics(method, exact_mle, graph_connected, clipped_pair_probabilities, regularized, pseudo_count, strongly_connected)[source]
Bases:
objectProvenance and identifiability evidence for the pairwise-moment fit.
- class TieModelFitDiagnostics(model, converged, status, message, iterations, objective, gradient_norm, worth_boundary_hit, tie_parameter_boundary_hit, graph_connected, regularized, pseudo_count, strongly_connected)[source]
Bases:
objectOptimizer, identifiability, and boundary evidence for a tie-model fit.
- class DavidsonDistribution(log_w, nu=1.0, name=None, keys=None, fit_diagnostics=None)[source]
Bases:
_BaseTieDistributionBradley-Terry with ties (Davidson 1970); tie mass
nu sqrt(w_i w_j).- Parameters:
- class DavidsonEstimator(dim, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood Davidson worths and tie parameter (L-BFGS on the count matrices).
pseudo_countadds that many fractional wins to every ordered pair and that many ties to every unordered pair; seeBradleyTerryEstimatorfor how to choose it. Without it, data in which some competitor never lost (or never won) has no finite fit and the estimator raisesValueErrorrather than return a boundary worth.- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
_TieAccumulatorFactory
- class RaoKupperDistribution(log_w, nu=1.5, name=None, keys=None, fit_diagnostics=None)[source]
Bases:
_BaseTieDistributionBradley-Terry with ties via a threshold
nu >= 1(Rao-Kupper 1967).- Parameters:
- class RaoKupperEstimator(dim, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood Rao-Kupper worths and threshold (L-BFGS on the count matrices).
pseudo_countadds that many fractional wins to every ordered pair and that many ties to every unordered pair; seeBradleyTerryEstimatorfor how to choose it. Without it, data in which some competitor never lost (or never won) has no finite fit and the estimator raisesValueErrorrather than return a boundary worth.- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
_TieAccumulatorFactory
- class EwensDistribution(dim, theta=1.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionEwens distribution over permutations of
0..n-1with cycle-weight parametertheta > 0.- classmethod compute_capabilities()[source]
Declare the NumPy and numba execution path used by Ewens kernels.
- density(x)[source]
Return the probability of one permutation.
- log_density(x)[source]
Return the log-probability of one permutation.
- seq_log_density(x)[source]
Return vectorized log-probabilities for encoded permutations.
- sampler(seed=None)[source]
Return an exact Ewens permutation sampler.
- Parameters:
seed (int | None)
- Return type:
EwensSampler
- estimator(pseudo_count=None)[source]
Return a cycle-count moment estimator for this dimension.
- Parameters:
pseudo_count (float | None)
- Return type:
EwensEstimator
- dist_to_encoder()[source]
Return the permutation encoder used by vectorized methods.
- Return type:
EwensDataEncoder
- class EwensEstimator(dim, theta=None, pseudo_count=None, prior_mean_cycles=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorFit
thetaby matching the mean cycle countE[cycles] = sum_i theta/(theta+i).- Parameters:
- accumulator_factory()[source]
Return a factory for Ewens sufficient-statistic accumulators.
- Return type:
EwensAccumulatorFactory
- class SpanningTreeDistribution(weights, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionWeighted spanning-tree distribution over n labeled nodes with symmetric positive edge weights.
Data type: a sequence of n-1 undirected edges (i, j) forming a spanning tree of 0,…,n-1.
- classmethod compute_capabilities()[source]
Describe backend support for weighted spanning-tree operations.
- density(x)[source]
Return the probability of a spanning tree x (a sequence of edges).
- log_density(x)[source]
Return the log-probability of a spanning tree x (a sequence of n-1 edges).
- seq_log_density(x)[source]
Return vectorized log-probabilities for a validated sequence of edge arrays.
- sampler(seed=None)[source]
Return a sampler for drawing spanning trees from this distribution.
- Parameters:
seed (int | None)
- Return type:
SpanningTreeSampler
- enumerator(max_edge_subsets=_DEFAULT_MAX_ENUMERATION_SUBSETS)[source]
Return a probability-ordered enumerator capped at
max_edge_subsetsreturned trees.- Parameters:
max_edge_subsets (int | None)
- Return type:
SpanningTreeEnumerator
- estimator(pseudo_count=None)[source]
Return an estimator that keeps the node count fixed at this distribution’s n.
- Parameters:
pseudo_count (float | None)
- Return type:
SpanningTreeEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
SpanningTreeDataEncoder
- exception SpanningTreeFitError[source]
Bases:
RuntimeErrorRaised when spanning-tree statistics do not identify a valid fit.
- class SpanningTreeEstimator(dim, pseudo_count=None, max_steps=500, learning_rate=1.0, tol=1.0e-7, candidate_support=None, prior_weights=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate edge weights by matching empirical or smoothed tree edge marginals.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for spanning-tree edge counts.
- Return type:
SpanningTreeAccumulatorFactory
- class SpanningTreeEnumerator(dist, max_edge_subsets=_DEFAULT_MAX_ENUMERATION_SUBSETS)[source]
Bases:
DistributionEnumeratorEnumerate supported spanning trees in descending probability order, lazily.
A tree’s probability is the product of its edge weights, so descending probability is increasing total edge cost under
cost = -log(weights)(zero-weight edges become +inf, i.e. absent). Gabow’s k-best spanning-tree algorithm streams the trees in that order from one constrained-MST oracle per node, without scanning the exponential set of edge subsets.- Parameters:
dist (SpanningTreeDistribution)
max_edge_subsets (int | None)
- class MatchingDistribution(weights, max_nodes=_DEFAULT_MAX_NODES, name=None, keys=None, fit_diagnostics=None)[source]
Bases:
SequenceEncodableProbabilityDistributionWeighted bipartite perfect-matching distribution over n left/right nodes (permanent-normalized).
Data type: a permutation x of 0,…,n-1 (left node i matched to right node x[i]).
- Parameters:
- classmethod compute_capabilities()[source]
Return compute-backend metadata for the matching distribution.
- density(x)[source]
Return the probability of a matching x (a permutation).
- log_density(x)[source]
Return the log-probability of a matching x (left i matched to right x[i]).
- seq_log_density(x)[source]
Return vectorized log-probabilities for an (N, n) array of matchings.
- sampler(seed=None)[source]
Return a sampler for drawing matchings from this distribution.
- Parameters:
seed (int | None)
- Return type:
MatchingSampler
- enumerator()[source]
Return an exact finite enumerator over all matchings in decreasing probability order.
- Return type:
MatchingEnumerator
- estimator(pseudo_count=1.0)[source]
Return an estimator that keeps the node count fixed at this distribution’s n.
- Parameters:
pseudo_count (float | None)
- Return type:
MatchingEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
MatchingDataEncoder
- class MatchingEstimator(dim, max_nodes=_DEFAULT_MAX_NODES, pseudo_count=1.0, max_steps=5000, learning_rate=1.0, tol=1.0e-7, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the edge weights (matches empirical and model edge marginals).
- Parameters:
- accumulator_factory()[source]
Return a factory for matching sufficient-statistic accumulators.
- Return type:
MatchingAccumulatorFactory
- class MatchingEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate finite-probability perfect matchings in descending probability order.
Lazily, via Murty’s k-best assignment on the edge-cost matrix
-log(weights): decreasing probability is increasing assignment cost, and zero-weight edges become +inf costs (forbidden), so only positive-probability matchings are yielded. This streams the top matchings without materializing the n! permutation support.- Parameters:
dist (MatchingDistribution)
- class MatchingFitDiagnostics(converged, iterations, max_marginal_error, regularized, pseudo_count)[source]
Bases:
objectConvergence evidence attached to an estimated matching model.
- class RandomDotProductGraphDistribution(positions, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionRandom Dot Product Graph over n nodes with d-dimensional latent positions X (edge prob X X^T).
- classmethod compute_capabilities()[source]
Return compute-backend metadata for RDPG log-density evaluation.
- edge_marginals()[source]
Return the n-by-n matrix of edge probabilities P(A_ij = 1).
- Return type:
- log_density(x)[source]
Return the log-probability of a binary undirected graph x.
- seq_log_density(x)[source]
Return vectorized log-probabilities for a sequence of graph observations.
- Parameters:
x (Sequence[GraphObservation])
- Return type:
np.ndarray
- backend_seq_log_density(x, engine)[source]
Engine-routed RDPG edge log-likelihood (reduction runs on the active engine).
- Parameters:
x (Sequence[GraphObservation])
engine (Any)
- Return type:
Any
- sampler(seed=None)[source]
Return a sampler for drawing graphs from this distribution.
- Parameters:
seed (int | None)
- Return type:
RandomDotProductGraphSampler
- estimator(pseudo_count=None)[source]
Return an ASE estimator that keeps the latent dimension fixed at this distribution’s d.
- Parameters:
pseudo_count (float | None)
- Return type:
RandomDotProductGraphEstimator
- dist_to_encoder()[source]
Return the shared graph data encoder.
- Return type:
GraphDataEncoder
- class RandomDotProductGraphEstimator(dim, num_nodes=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorAdjacency Spectral Embedding estimator for the RDPG latent positions.
- accumulator_factory()[source]
Return a factory for RDPG sufficient-statistic accumulators.
- Return type:
RandomDotProductGraphAccumulatorFactory
- class SemiSupervisedMixtureDistribution(components, w=MISSING, name=None, weights=MISSING)[source]
Bases:
SequenceEncodableProbabilityDistributionSemiSupervisedMixtureDistribution models observations (value, prior) where the optional prior labels re-weight the mixture weights over the listed components.
- Parameters:
- compute_capabilities()[source]
Declare generated-compute support inherited from mixture components.
- compute_declaration()[source]
Return the generated-compute declaration for the semi-supervised mixture.
- density(x)[source]
Density of the semi-supervised mixture at observation x.
See log_density() for details.
- log_density(x)[source]
Log-density of the semi-supervised mixture at observation x = (value, prior).
If prior is None this is the standard mixture log-density. Otherwise the mixture weights are restricted to the components listed in the prior, re-weighted by the prior probabilities, and re-normalized before mixing the component log-densities.
- posterior(x)[source]
Posterior probability of each component for observation x = (value, prior).
Components not listed in the prior (when a prior is present) receive posterior 0.
- seq_log_density(x)[source]
Vectorized evaluation of the log-density on sequence encoded data x.
- Parameters:
x (E) – Sequence encoded data produced by SemiSupervisedMixtureDataEncoder.seq_encode().
- Returns:
Numpy array of log-densities, one entry per encoded observation.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral semi-supervised mixture log-density for encoded observations.
- seq_posterior(x)[source]
Vectorized component posteriors on sequence encoded data x.
- Parameters:
x (E) – Sequence encoded data produced by SemiSupervisedMixtureDataEncoder.seq_encode().
- Returns:
Numpy array of shape (number of observations, num_components) of posteriors.
- Return type:
- density_semantics()[source]
Return exact-or-approximate density semantics joined from component models.
- sampler(seed=None)[source]
Creates a SemiSupervisedMixtureSampler for sampling component values.
- Parameters:
seed (Optional[int]) – Seed for the random number generator used in sampling.
- Returns:
SemiSupervisedMixtureSampler object.
- Return type:
SemiSupervisedMixtureSampler
- estimator(pseudo_count=None)[source]
Creates a SemiSupervisedMixtureEstimator with one child estimator per component.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate the sufficient statistics of the mixture weights.
- Returns:
SemiSupervisedMixtureEstimator object.
- Return type:
SemiSupervisedMixtureEstimator
- dist_to_encoder()[source]
Creates a SemiSupervisedMixtureDataEncoder for encoding sequences of (value, prior) observations.
- Returns:
SemiSupervisedMixtureDataEncoder object.
- Return type:
SemiSupervisedMixtureDataEncoder
- enumerator()[source]
Enumeration is not well-defined for semi-supervised mixtures.
Observations pair a component value with exogenous prior labels: the model defines no distribution over the prior part, so the support over (value, prior) pairs cannot be enumerated with consistent probabilities.
- Raises:
EnumerationError always. –
- Return type:
DistributionEnumerator
- class SemiSupervisedMixtureEstimator(estimators, suff_stat=None, pseudo_count=None, keys=(None, None), name=None)[source]
Bases:
ParameterEstimatorSemiSupervisedMixtureEstimator estimates a SemiSupervisedMixtureDistribution from aggregated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Create an accumulator factory from the child estimators.
- Returns:
Factory configured for this estimator.
- Return type:
SemiSupervisedMixtureEstimatorAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a SemiSupervisedMixtureDistribution from aggregated sufficient statistics.
The mixture weights are the normalized component counts, optionally regularized by pseudo_count and the stored suff_stat weights.
- Parameters:
nobs (Optional[float]) – Not used. Kept for consistency.
suff_stat (Tuple[np.ndarray, Tuple[SS0, ...]]) – Component counts and component sufficient statistics, as returned by SemiSupervisedMixtureEstimatorAccumulator.value().
- Returns:
Estimated distribution.
- Return type:
SemiSupervisedMixtureDistribution
- class TreeHiddenMarkovModelDistribution(topics, w=MISSING, transitions=MISSING, len_dist=NullDistribution(), terminal_level=10, name=None, use_numba=None, weights=MISSING)[source]
Bases:
SequenceEncodableProbabilityDistributionHidden Markov model on a rooted tree with emission distributions of type T.
Data type: Sequence[Tuple[Tuple[int, int], T]] (((node_id, parent_id), emission) per node, root parent -1).
- Parameters:
- compute_capabilities()[source]
Declare generated-compute support from emission and length children.
- compute_declaration()[source]
Return the generated-compute declaration for the tree HMM.
- density(x)[source]
Density of tree HMM at a single observed tree x.
See log_density() for details.
- Parameters:
x (Sequence[Tuple[D, T]]) – Tree as ((node_id, parent_id), emission) tuples (root parent -1).
- Returns:
Density at observation x.
- Return type:
- log_density(x)[source]
Log-density of tree HMM at a single observed tree x.
The hidden states are marginalized out with an upward (beta) message passing recursion over the tree. When a non-null length distribution (len_dist) is set, its contribution to the likelihood (the sum over nodes of len_dist.log_density(num_children)) is included; a NullDistribution length contributes nothing.
- Parameters:
x (Sequence[Tuple[D, T]]) – Tree as ((node_id, parent_id), emission) tuples (root parent -1).
- Returns:
Log-density at observation x.
- Return type:
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
Dispatches to numba kernels or to the pure-numpy level-by-level recursion depending on which encoding (use_numba) the input was created with.
- Parameters:
x (E) – Sequence encoded trees from TreeHiddenMarkovDataEncoder.seq_encode().
- Returns:
Numpy array of log-density (float), one entry per encoded tree.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral tree-HMM scoring for the pure non-numba encoded layout.
- Parameters:
x (tuple[tuple[ndarray, tuple[int, ndarray, ndarray, ndarray], tuple[ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray], E3, tuple[ndarray, E4] | None] | None, tuple[int, ndarray, tuple[ndarray, ndarray, ndarray], tuple[ndarray, ndarray, ndarray, ndarray, list[ndarray], list[ndarray], list[ndarray], list[ndarray], ndarray], E3, tuple[ndarray, E4] | None] | None])
engine (Any)
- Return type:
- seq_posterior(x)[source]
Posterior state membership probabilities for each node of each encoded tree.
- viterbi(x)[source]
Most likely hidden state assignment for each node of a single observed tree.
- Parameters:
x (Sequence[Tuple[D, T]]) – Tree as ((node_id, parent_id), emission) tuples (root parent -1).
- Returns:
Numpy array of int states, one per node of the tree.
- Return type:
- seq_viterbi(x)[source]
Vectorized Viterbi state assignments for sequence encoded trees.
- density_semantics()[source]
Return exact-or-approximate density semantics joined from child models.
- sampler(seed=None)[source]
Create a sampler for this tree hidden Markov distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
Sampler bound to this distribution.
- Return type:
TreeHiddenMarkovSampler
- Raises:
ValueError – If len_dist is a NullDistribution (a length distribution with support on the non-negative integers is required for sampling).
- enumerator()[source]
Not supported: observations are rooted trees, not chains.
The chain best-first enumerator (
HiddenMarkovModelEnumerator) does not apply – the marginal sums over hidden states on a branching tree whose shape is itself governed by the per-node child-countlen_dist, so the support is a set of trees rather than sequences. Usesampler()or the exactlog_densityinstead.- Return type:
DistributionEnumerator
- estimator(pseudo_count=None)[source]
Create a TreeHiddenMarkovEstimator with estimators for the topics and length distribution.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics of the initial state weights, transition matrix, topics, and length distribution.
- Returns:
TreeHiddenMarkovEstimator object.
- Return type:
TreeHiddenMarkovEstimator
- dist_to_encoder()[source]
Return a data encoder for iid tree HMM observations.
- Return type:
TreeHiddenMarkovDataEncoder
- class TreeHiddenMarkovEstimator(estimators, len_estimator=NullEstimator(), pseudo_count=(None, None), name=None, keys=(None, None, None), use_numba=None)[source]
Bases:
ParameterEstimatorEstimator for the TreeHiddenMarkovModelDistribution from aggregated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
TreeHiddenMarkovAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a TreeHiddenMarkovModelDistribution from sufficient statistics (M-step).
Initial state weights and transition rows are normalized counts, optionally smoothed with the pseudo_count pair. A transition row with no observed outgoing transitions – e.g. every training tree is shallow enough that this state is never seen with a child – is filled uniform rather than left at zero when no pseudo-count is given, so that
p_level(the per-level marginal state-occupancy vector derived fromwand this matrix, used throughout scoring) stays strictly positive at every level instead of going hard-zero and later poisoning log_density() on a deeper out-of-sample tree with a silent NaN (T4-01). Every such row is disclosed throughnumerical_repairs()on the returned distribution. Topics and the length distribution are estimated from their respective sufficient statistics.- Parameters:
nobs (Optional[float]) – Number of observations.
suff_stat (Tuple) – Tuple of number of states, initial-state counts, state counts, transition counts, emission sufficient statistics per state, and length sufficient statistics.
- Returns:
Estimated distribution.
- Return type:
TreeHiddenMarkovModelDistribution
- TreeHiddenMarkovModelEstimator
alias of
TreeHiddenMarkovEstimator
- class TransformDistribution(dist, transform=None, density_correction=None, name=None, keys=None, fit_receipt=None)[source]
Bases:
SequenceEncodableProbabilityDistributionPush a child distribution through a fixed invertible transform.
Observations live in transformed space. For fixed continuous transforms, log-density uses the inverse transform and adds the inverse-Jacobian term. The transform is not learned; estimation inverse-transforms observations and delegates sufficient statistics to the child estimator.
- Parameters:
- compute_capabilities()[source]
Return capabilities delegated from the child distribution where safe.
- compute_declaration()[source]
Return a declaration describing this distribution as a transformed child.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for inverse-encoded observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child parameters for homogeneous fixed-transform mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of transformed child log densities.
- gradient_fit_state(engine, torch, leaves, recurse, tensor_param)[source]
Return distribution-owned state for autograd fitting.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
TransformSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
TransformEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
TransformDataEncoder
- enumerator()[source]
Return an enumerator over the distribution support when available.
- Return type:
TransformEnumerator
- exception TransformCompatibilityError[source]
Bases:
TypeErrorRaised when a transform contract is incompatible with its child distribution.
- class TransformContract(input_domain, output_domain, measure='adaptive', bijective=True)[source]
Bases:
objectMachine-checkable declaration for a deterministic bijective transform.
input_domainandoutput_domainuse the same coarse vocabulary as compute-declaration support tags.measureis"adaptive"when the transform supports both counting measure and continuous change-of-variables, or"discrete"for a counting-measure-only mapping.
- exception TransformDomainError[source]
Bases:
ValueErrorRaised when an observation lies outside a transform’s declared domain.
- class TransformFitReceipt(accepted_weight, rejected_weight, rejected_fraction)[source]
Bases:
NamedTupleAccepted/rejected evidence accounting attached to a fitted transform wrapper.
- accepted_weight: float
Alias for field number 0
- rejected_weight: float
Alias for field number 1
- rejected_fraction: float
Alias for field number 2
- class TransformStatistics(schema_version, child, accepted_weight, rejected_weight)[source]
Bases:
NamedTupleVersioned child statistics plus transform-domain evidence accounting.
- schema_version: int
Alias for field number 0
- child: Any
Alias for field number 1
- accepted_weight: float
Alias for field number 2
- rejected_weight: float
Alias for field number 3
- class TransformEstimator(estimator, transform=None, density_correction=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator for fixed-transform distributions.
- Parameters:
- accumulator_factory()[source]
Return the accumulator factory for inverse-transformed observations.
- Return type:
TransformAccumulatorFactory
- class TransformEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate transformed child support for discrete child distributions.
- Parameters:
dist (TransformDistribution)
- class FiniteStochasticTransformDistribution(dist, kernel, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionFinite discrete source pushed through a fixed finite stochastic kernel (noisy channel).
- Parameters:
- log_density(x)[source]
Return
log P(Y = x)for an integer outputx in {0, ..., n-1}.
- seq_log_density(x)[source]
Return per-observation
log P(Y = y)for an encoded batch of outputs.
- sampler(seed=None)[source]
Return a sampler drawing
X ~ distthenY ~ Categorical(kernel[X]).- Parameters:
seed (int | None)
- Return type:
FiniteStochasticTransformSampler
- estimator(pseudo_count=None)[source]
Return an estimator that recovers the source via the channel-inversion-free E-step.
- Parameters:
pseudo_count (float | None)
- Return type:
FiniteStochasticTransformEstimator
- dist_to_encoder()[source]
Return the data encoder for integer outputs.
- Return type:
FiniteStochasticTransformDataEncoder
- enumerator()[source]
Enumerate the finite outputs
yin descendingP(Y = y)order.- Return type:
FiniteStochasticTransformEnumerator
- class FiniteStochasticTransformEstimator(source_estimator, kernel, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator for a fixed-kernel finite stochastic transform (recovers the source).
- accumulator_factory()[source]
Return a factory for finite-transform sufficient-statistic accumulators.
- Return type:
FiniteStochasticTransformAccumulatorFactory
- class FiniteStochasticTransformEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate the finite output support in descending marginal probability.
- Parameters:
dist (FiniteStochasticTransformDistribution)
- class ZeroInflatedDistribution(base, pi, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA base count distribution with an extra point mass of probability
piat zero.- Parameters:
- density(x)[source]
Return the zero-inflated probability at
x.
- log_density(x)[source]
Return
log[(1-pi) p_base(x)]forx > 0, mixed withpiatx == 0.
- seq_log_density(x)[source]
Vectorized zero-inflated log-density for an encoded batch.
- sampler(seed=None)[source]
Return a ZeroInflatedSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
ZeroInflatedSampler
- estimator(pseudo_count=None)[source]
Return an estimator that fits
piand the base by EM over the latent zero source.- Parameters:
pseudo_count (float | None)
- Return type:
ZeroInflatedEstimator
- dist_to_encoder()[source]
Return the data encoder (base encoding + a boolean is-zero mask).
- Return type:
ZeroInflatedDataEncoder
- class ZeroInflatedEstimator(base_estimator, pseudo_count=None, name=None, keys=None, initial_inflation_probability=0.5)[source]
Bases:
ParameterEstimatorEM estimator:
pi = (expected structural zeros) / N, base re-fit on the down-weighted data.- Parameters:
- accumulator_factory()[source]
Return a factory for zero-inflated sufficient-statistic accumulators.
- Return type:
ZeroInflatedAccumulatorFactory
- class BackoffDistribution(base, fallback, escape_weight=DEFAULT_ESCAPE_WEIGHT, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA sharp
basemixed with a broadfallbackunder a pinned escape weight.- Parameters:
- compute_declaration()[source]
Declare the backoff’s support as the support its two children agree on.
A backoff mixes a sharp
basewith a broadfallbackover the SAME sample space, so when both children declare the same support the mixture has it too. Declaring nothing made the composite unusable wherever a caller has to prove what a distribution ranges over:SequenceDistributionrefuses a length model that cannot “prove support on non-negative integers”, andmixle.utils.automaticbuilds exactly this shape – a backoff length model over sequence records – so the automatic path produced a model the library then rejected.Children that disagree (or do not declare) leave the support unstated, which is the honest answer rather than a guess.
- density_semantics()[source]
Join both children’s semantics – a backoff is only exact when everything it mixes is.
The base-class default returns
EXACT, which is a claim about the whole mixture. A backoff over a child explicitly markedLIKELIHOOD_FACTOR(a categorical used as an unnormalized factor, say) inherits that child’s missing normalizer: the escape-weighted sum of an exact law and an unnormalized factor is itself unnormalized. ReportingEXACTthere tells a caller a density integrates to one when it does not.
- log_density(x)[source]
Return the mixture log-density at
x.Finite whenever either component can score
x, which is the reason this class exists: the base may return-inffor an unobserved outcome and the total stays finite.
- component_log_densities(x)[source]
Return the two weighted component log-density vectors for encoded data
x.
- seq_log_density(x)[source]
Vectorized mixture log-density over sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler that draws the component first, then the value.
- Parameters:
seed (int | None)
- Return type:
BackoffSampler
- estimator(pseudo_count=None)[source]
Return an estimator for this backoff structure, reusing the children’s own estimators.
- Parameters:
pseudo_count (float | None)
- Return type:
BackoffEstimator
- dist_to_encoder()[source]
Return an encoder that encodes each observation for both components.
- Return type:
BackoffDataEncoder
- class BackoffEstimator(base_estimator, fallback_estimator, escape_weight=DEFAULT_ESCAPE_WEIGHT, max_escape_weight=DEFAULT_MAX_ESCAPE_WEIGHT, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator for
BackoffDistributionwith a bounded escape weight.- Parameters:
- accumulator_factory()[source]
Return the matching accumulator factory.
- Return type:
BackoffAccumulatorFactory
- class HurdleDistribution(base, pi, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA zero hurdle (probability
pi) followed by a zero-truncated base for the positive counts.- Parameters:
- log_density(x)[source]
Return
log piatx == 0, elselog[(1-pi) p_base(x) / (1 - p_base(0))].
- seq_log_density(x)[source]
Vectorized hurdle log-density for an encoded batch.
- sampler(seed=None)[source]
Return a HurdleSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
HurdleSampler
- estimator(pseudo_count=None)[source]
Return an estimator that fits
pi(the zero rate) and the base on the positives – closed form.- Parameters:
pseudo_count (float | None)
- Return type:
HurdleEstimator
- dist_to_encoder()[source]
Return the data encoder (base encoding + a boolean is-zero mask).
- Return type:
HurdleDataEncoder
- class HurdleEstimator(base_estimator, pseudo_count=None, name=None, keys=None, trunc_max_iter=100, trunc_threshold=1.0e-10)[source]
Bases:
ParameterEstimatorClosed-form
pi(the zero rate) plus the zero-truncated MLE of the base over the positives.The two parts are independent.
piis the observed zero rate. The count part is the base fit by maximum likelihood under the zero truncation – NOT the base fit naively to the positives, which is biased (it recovers the truncated mean, so the fitted model would not match the data). The truncated MLE is obtained by a short EM that treats the removed zeros as missing data: given the current base, the positives implyN_missing = N_pos * P0/(1-P0)hypothetical base zeros; refit the base to the positives plus those pseudo-zeros and iterate. (If the base has no mass at 0 there is no truncation and the positives are fit directly.)- Parameters:
- accumulator_factory()[source]
Return a factory for hurdle sufficient-statistic accumulators.
- Return type:
HurdleAccumulatorFactory
- class SurvivalDistribution(base, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionRight-censored survival likelihood over a base event-time distribution.
- density(x)[source]
Return the likelihood contribution of
(t, event).
- log_density(x)[source]
Return
log f(t)for an observed event, elselog S(t)for a right-censored time.
- seq_log_density(x)[source]
Vectorized likelihood: base density for events, log survival for censored rows.
- sampler(seed=None)[source]
Return a sampler (draws uncensored event times; censoring is exogenous).
- Parameters:
seed (int | None)
- Return type:
SurvivalSampler
- estimator(pseudo_count=None)[source]
Return an estimator that fits the base under right-censoring by conditional-quantile EM.
- Parameters:
pseudo_count (float | None)
- Return type:
SurvivalEstimator
- dist_to_encoder()[source]
Return the data encoder (base encoding of the times + the event mask).
- Return type:
SurvivalDataEncoder
- class SurvivalEstimator(base_estimator, n_impute=16, name=None, keys=None)[source]
Bases:
ParameterEstimatorFit the base event-time distribution under right-censoring (conditional-quantile imputation EM).
- accumulator_factory()[source]
Return a factory for right-censored survival sufficient-statistic accumulators.
- Return type:
SurvivalAccumulatorFactory
- class TruncatedDistribution(base, allowed=None, forbidden=None, name=None, keys=None, fit_receipt=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA base distribution restricted to an allowed support and renormalized.
- Parameters:
- density(x)[source]
Return the renormalized probability/density at
x.
- log_density(x)[source]
Return
log p_base(x) - log Zfor allowedx, else-inf.
- seq_log_density(x)[source]
Return per-row truncated log-densities for an encoded batch.
- sampler(seed=None)[source]
Return a rejection sampler over the allowed support.
- Parameters:
seed (int | None)
- Return type:
TruncatedSampler
- estimator(pseudo_count=None)[source]
Return the explicit projection estimator, not a truncated-likelihood MLE.
The projection fits the child to retained observations and then reapplies the support restriction. It deliberately omits the parameter-dependent
-n log Z(theta)term, so the returned model carries a receipt withlikelihood_aware=False.- Parameters:
pseudo_count (float | None)
- Return type:
TruncatedProjectionEstimator
- dist_to_encoder()[source]
Return the data encoder (base encoding + an allowed-membership mask).
- Return type:
TruncatedDataEncoder
- support_size()[source]
Cardinality of the retained support (
Noneif infinite).- Return type:
int | None
- enumerator()[source]
Enumerate the allowed support in descending (renormalized) probability order.
- Return type:
TruncatedEnumerator
- TruncatedEstimator
alias of
TruncatedProjectionEstimator
- class TruncatedProjectionEstimator(base_estimator, allowed=None, forbidden=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorApproximate projection that fits the base only to retained observations.
This is intentionally not called a truncated MLE: it omits the parameter-dependent normalizer from the objective and marks every fitted model with
likelihood_aware=False.- Parameters:
- accumulator_factory()[source]
Return a factory for truncated-data sufficient-statistic accumulators.
- Return type:
TruncatedAccumulatorFactory
- class TruncatedProjectionFitReceipt(accepted_weight, rejected_weight, rejected_fraction, likelihood_aware)[source]
Bases:
NamedTupleEvidence accounting for the explicit untruncated-base projection fit.
- Parameters:
- accepted_weight: float
Alias for field number 0
- rejected_weight: float
Alias for field number 1
- rejected_fraction: float
Alias for field number 2
- likelihood_aware: bool
Alias for field number 3
- class TruncatedStatistics(schema_version, child, accepted_weight, rejected_weight)[source]
Bases:
NamedTupleVersioned sufficient statistics for support-filtered projection fitting.
- schema_version: int
Alias for field number 0
- child: Any
Alias for field number 1
- accepted_weight: float
Alias for field number 2
- rejected_weight: float
Alias for field number 3
- class TruncatedEnumerator(dist)[source]
Bases:
DistributionEnumeratorFilter the base enumeration to the allowed support, renormalized by
-log Z.- Parameters:
dist (TruncatedDistribution)
- class CensoredDistribution(base, name=None, keys=None, *, fit_receipt=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA base distribution whose observations may be interval/left/right censored.
- Parameters:
- density(x)[source]
Return the contribution of
x(density for exact, interval mass for censored).
- log_density(x)[source]
Log-likelihood contribution of
x.Exact observation
x->log p_base(x); interval(a, b)->log P(a <= X <= b)(see_interval_log_mass()).
- seq_log_density(x)[source]
Per-row censored log-densities for an encoded batch.
- sampler(seed=None)[source]
Return exact evidence from the base; censoring requires a separate observation process.
- Parameters:
seed (int | None)
- Return type:
CensoredSampler
- estimator(pseudo_count=None)[source]
Return the explicit exact-only projection estimator with an effective-count receipt.
This is not a censored MLE. Use
likelihood_estimator()with a base-family-specific fitting callback when interval evidence must influence the fitted parameters.- Parameters:
pseudo_count (float | None)
- Return type:
ExactOnlyCensoredEstimator
- likelihood_estimator(fit)[source]
Return a likelihood-aware estimator backed by a declared base-family fitting callback.
fit(observations, weights, initial_base)receives validated exact/interval evidence and must optimize the full censored objective, returning a fitted base distribution.
- dist_to_encoder()[source]
Return the data encoder (exact observations + censoring intervals split out).
- Return type:
CensoredDataEncoder
- class CensoredInterval(lower, upper)[source]
Bases:
objectClosed interval likelihood evidence with validated ordered bounds.
- class ExactObservation(value)[source]
Bases:
objectExplicit exact evidence; useful when the child value could otherwise look like metadata.
- Parameters:
value (Any)
- CensoredEstimator
alias of
ExactOnlyCensoredEstimator
- class ExactOnlyCensoredEstimator(base_estimator, name=None, keys=None)[source]
Bases:
ParameterEstimatorProjection estimator that deliberately excludes interval evidence and reports its weight.
- accumulator_factory()[source]
Return a factory for censored-data sufficient-statistic accumulators.
- Return type:
CensoredAccumulatorFactory
- class CensoredLikelihoodEstimator(initial_base, fit, name=None, keys=None)[source]
Bases:
ParameterEstimatorDelegate full censored-objective optimization to a declared base-family callback.
- Parameters:
- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
CensoredLikelihoodAccumulatorFactory
- class CensoredExactOnlyFitReceipt(exact_weight, censored_weight, censored_fraction, likelihood_aware)[source]
Bases:
NamedTuple- Parameters:
- exact_weight: float
Alias for field number 0
- censored_weight: float
Alias for field number 1
- censored_fraction: float
Alias for field number 2
- likelihood_aware: bool
Alias for field number 3
- class CopulaDistribution(marginals, copula, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionJoint over
dscalar fields =dmarginals coupled by a copula core (Sklar’s theorem).marginalsis a length-dsequence of CONTINUOUS mixle leaves, each exposinglog_density, deterministiccdf/quantilemethods, and the estimator/encoder contract – a marginal with enumerable (discrete/atomic) support is rejected at construction (see module docstring: the continuous Sklar density formula this class implements is not a valid probability model for discrete marginals).copulais a distribution on(0,1)^d(e.g.GaussianCopulaDistribution) whosedimmust equallen(marginals). An observation is a length-dtuple/array of scalars(x_1, ..., x_d).- Parameters:
- density(x)[source]
Return the joint density at one raw observation.
- log_density(x)[source]
Sklar’s decomposition: sum of marginal log-densities + the copula log-density at the PIT scores.
- seq_log_density(enc)[source]
Vectorized: per-column marginal log-densities (summed) plus the copula log-density at the PIT scores.
- sampler(seed=None)[source]
Return a sampler that draws copula scores and inverts the marginals.
- Parameters:
seed (int | None)
- Return type:
CopulaSampler
- estimator(pseudo_count=None)[source]
Return an IFM estimator for marginals followed by the copula core.
- Parameters:
pseudo_count (float | None)
- Return type:
CopulaEstimator
- dist_to_encoder()[source]
Return an encoder that preserves marginal encodings and raw columns.
- Return type:
CopulaDataEncoder
- class CopulaEstimator(marginal_estimators, copula_estimator, dim, copula_prototype, name=None, keys=None)[source]
Bases:
ParameterEstimatorIFM estimator: fit each marginal from its sub-stats, PIT the buffered data, fit the copula on the scores.
- Parameters:
- accumulator_factory()[source]
Return a factory for IFM copula sufficient-statistic accumulators.
- Return type:
CopulaAccumulatorFactory
- class CopulaIFMStatistics(schema_version, marginal_statistics, columns, weights, marginal_effective_count, copula_effective_count)[source]
Bases:
NamedTupleVersioned IFM state with explicit stage-specific effective counts.
- Parameters:
- schema_version: int
Alias for field number 0
- columns: ndarray
Alias for field number 2
- weights: ndarray
Alias for field number 3
- marginal_effective_count: float
Alias for field number 4
- copula_effective_count: float
Alias for field number 5
- exception CopulaQuantileError[source]
Bases:
RuntimeErrorRaised when a marginal quantile violates its declared CDF inverse contract.
- class ExponentiallyModifiedGaussianDistribution(mu, sigma2, lam, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionExponentially-modified Gaussian:
X = N(mu, sigma2) + Exp(rate=lam).- density(x)[source]
Density of the EMG at observation
x(seelog_density).
- log_density(x)[source]
Stable log-density of the EMG at
x.log f(x) = log(lam/2) - 0.5*u^2 + log_erfcx(z)withu = (x - mu)/sigmaandz = (lam*sigma - u)/sqrt(2).
- seq_ld_lambda()[source]
Return vectorized log-density callables for encoded data.
- seq_log_density(x)[source]
Vectorized EMG log-density at sequence-encoded input
x.
- classmethod compute_capabilities()[source]
Declare NumPy/Torch scoring capabilities for EMG log-density kernels.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized EMG log-density for encoded data.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact, via scipy’s exponnorm).
- sampler(seed=None)[source]
Return an ExponentiallyModifiedGaussianSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
ExponentiallyModifiedGaussianSampler
- estimator(pseudo_count=None)[source]
Return an ExponentiallyModifiedGaussianEstimator (method-of-moments).
- Parameters:
pseudo_count (float | None)
- Return type:
ExponentiallyModifiedGaussianEstimator
- dist_to_encoder()[source]
Return the encoder for exponentially modified Gaussian observations.
- Return type:
ExponentiallyModifiedGaussianDataEncoder
- class ExponentiallyModifiedGaussianEstimator(name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate EMG parameters from weighted central moments.
The fit is SHIFT-EQUIVARIANT: estimating on
x + creturnsmu + cwithsigma2andlamunchanged, for any constantcthe data can carry – epoch seconds (~1.7e9), 2**31 and 1e12 included. The moments come fromExponentiallyModifiedGaussianAccumulator, which centers each batch twice for exactly this reason; a single centering pass moved the fit by 1.3e-4 at 1e12, silently.- accumulator_factory()[source]
Return a factory for EMG central-moment accumulators.
- Return type:
ExponentiallyModifiedGaussianAccumulatorFactory
- class SkellamDistribution(mu1, mu2, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionSkellam distribution:
K = N1 - N2for independentN1 ~ Poisson(mu1),N2 ~ Poisson(mu2).- density(x)[source]
Probability mass at integer
x(seelog_density).
- log_density(x)[source]
Stable Skellam log-mass at integer
x(-inffor non-integer input).
- seq_log_density(x)[source]
Vectorized Skellam log-mass at sequence-encoded integer counts
x.
- entropy()[source]
Shannon entropy in nats, by exact two-sided summation of the standard series.
The Skellam entropy
-sum_k p_k log p_khas no closed form. The sum runs over the support between this distribution’s own quantiles at1e-16and1 - 1e-16(plus a safety margin on each side), beyond which the remaining tail mass on both sides is far below double rounding. Terms where the scaled Bessel term underflows to exactly zero (mass indistinguishable from 0 at double precision) are dropped, matching thep log p -> 0limit.- Return type:
- classmethod compute_capabilities()[source]
Describe backend support for generated Skellam scoring kernels.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized Skellam log-mass for encoded data (see class backend note).
The series yields the UNSCALED
log I_k(notlog ive = log I_k - z), so the constant here is-(mu1 + mu2)— the legacy path’s-sqrt_diff_sqplus its implicit-z.
- cdf(x)[source]
Cumulative distribution function P(X <= x) (via scipy skellam).
- quantile(q)[source]
Inverse CDF F^{-1}(q) (via scipy skellam).
- sampler(seed=None)[source]
Return a SkellamSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
SkellamSampler
- estimator(pseudo_count=None)[source]
Return a SkellamEstimator (method of moments).
- Parameters:
pseudo_count (float | None)
- Return type:
SkellamEstimator
- dist_to_encoder()[source]
Return the encoder for Skellam observations.
- Return type:
SkellamDataEncoder
- enumerator()[source]
Return an enumerator over all integers in descending probability order.
- Return type:
SkellamEnumerator
- class SkellamEstimator(pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate
(mu1, mu2)by the (exact, closed-form) method of moments.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for Skellam moment statistics.
- Return type:
SkellamAccumulatorFactory
- class SkewNormalDistribution(loc, scale, shape, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionSkew-normal distribution with location
loc, scale> 0and shapealpha.- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- classmethod compute_capabilities()[source]
Describe backend support for generated skew-normal scoring kernels.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized skew-normal log-density for encoded data.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact).
- mean()[source]
Mean E[X] = loc + scale * delta * sqrt(2/pi), delta = shape / sqrt(1 + shape^2).
- Return type:
- variance()[source]
Variance Var[X] = scale^2 (1 - 2 delta^2 / pi), delta = shape / sqrt(1 + shape^2).
- Return type:
- entropy()[source]
Differential entropy log(scale) + 0.5 log(2 pi e) - log(2) - E[log Phi(alpha Y)].
Yis the standard skew-normal(alpha);E[Y^2] = 1for every alpha (a property of the two-Gaussian stochastic representation) collapses the Gaussian part of the log-density to a closed form, leavingE[log Phi(alpha Y)]. That term has no closed form for general alpha (Arellano-Valle, Contreras-Reyes & Genton, ‘Shannon entropy and mutual information for multivariate skew-elliptical distributions’, Scand. J. Statist. 40 (2013)), so it is evaluated by adaptive quadrature against the standard skew-normal density itself.- Return type:
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
SkewNormalSampler
- estimator(pseudo_count=None)[source]
Return a method-of-moments estimator for
loc,scaleandshape.- Parameters:
pseudo_count (float | None)
- Return type:
SkewNormalEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
SkewNormalDataEncoder
- class SkewNormalEstimator(pseudo_count=None, suff_stat=None, min_scale=1.0e-12, name=None, keys=None)[source]
Bases:
ParameterEstimatorMethod-of-moments estimator for skew-normal location, scale and shape.
The fit is SHIFT-EQUIVARIANT: estimating on
x + creturnsloc + cwithscaleandshapeunchanged, for any constantcthe data can carry – epoch seconds (~1.7e9), 2**31 and 1e12 included. The moments come fromSkewNormalAccumulator, which centers each batch twice for exactly this reason; a single centering pass left the fitted shape 1.1e-3 off at 1e12, silently.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for skew-normal moment statistics.
- Return type:
SkewNormalAccumulatorFactory
- class TweedieDistribution(mu, phi, p=1.5, name=None, keys=None, *, max_series_terms=_DEFAULT_MAX_SERIES_TERMS, max_series_work=_DEFAULT_MAX_SERIES_WORK, series_tolerance=_DEFAULT_SERIES_TOLERANCE)[source]
Bases:
SequenceEncodableProbabilityDistributionTweedie (compound Poisson-Gamma) distribution on
[0, inf)with fixed powerp in (1, 2).- Parameters:
- density(x)[source]
Probability density (or the point mass at 0) at
x(seelog_density).
- log_density(x)[source]
Tweedie log-density:
log P(Y=0) = -lamat 0, the series forx > 0,-infforx < 0.
- seq_log_density(x)[source]
Vectorized Tweedie log-density at sequence-encoded non-negative observations
x.
- classmethod compute_capabilities()[source]
Return compute-backend metadata for Tweedie scoring.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized Tweedie log-density for encoded data (see class backend note).
- sampler(seed=None)[source]
Return a TweedieSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
TweedieSampler
- estimator(pseudo_count=None)[source]
Return a TweedieEstimator (method of moments at the fixed power
p).- Parameters:
pseudo_count (float | None)
- Return type:
TweedieEstimator
- dist_to_encoder()[source]
Return the encoder for Tweedie observations.
- Return type:
TweedieDataEncoder
- exception TweedieSeriesResourceError(*, required_terms, rows, max_terms, max_work)[source]
Bases:
RuntimeErrorA Tweedie density series exceeded its declared term or work budget.
- class TweedieEstimator(p=1.5, pseudo_count=None, suff_stat=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate
(mu, phi)at fixed powerpby the (exact) method of moments.- Parameters:
- accumulator_factory()[source]
Return a factory for Tweedie moment accumulators.
- Return type:
TweedieAccumulatorFactory
- class BirthDeathSamplingDistribution(birth_rate, death_rate, sampling_rate=0.0, initial_population=1, horizon=10.0, name=None, keys=None, prior_shape=1.0, prior_rate=0.0)[source]
Bases:
SequenceEncodableProbabilityDistributionGeneral linear birth-death-sampling process (fossilized birth-death is the
sampling_rate>0case).- Parameters:
- density(x)[source]
Probability density of one trajectory (see
log_density).
- log_density(x)[source]
Log-likelihood of one fully-observed trajectory
(n0, T, events).
- seq_log_density(x)[source]
Vectorized log-likelihood for validated
(N, 6)encoded rows.
- sampler(seed=None)[source]
Return a BirthDeathSamplingSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
BirthDeathSamplingSampler
- estimator(pseudo_count=None)[source]
Return a fixed-configuration closed-form MLE or Gamma MAP estimator.
- Parameters:
pseudo_count (float | None)
- Return type:
BirthDeathSamplingEstimator
- dist_to_encoder()[source]
Return the encoder for birth-death samples.
- Return type:
BirthDeathSamplingDataEncoder
- class BirthDeathSamplingStatistics(births, deaths, samplings, population_exposure, trajectory_weight, horizon_weight)[source]
Bases:
NamedTupleVersioned, tuple-compatible aggregate birth-death statistics.
- Parameters:
- births: float
Alias for field number 0
- deaths: float
Alias for field number 1
- samplings: float
Alias for field number 2
- population_exposure: float
Alias for field number 3
- trajectory_weight: float
Alias for field number 4
- horizon_weight: float
Alias for field number 5
- property schema_version: int
Return the serialized statistic schema version.
- class BirthDeathSamplingEstimator(name=None, keys=None, pseudo_count=None, initial_population=1, horizon=10.0, prior_shape=None, prior_rate=None)[source]
Bases:
ParameterEstimatorClosed-form per-channel MLE or Gamma-prior MAP estimator.
- Parameters:
- accumulator_factory()[source]
Return a factory for birth-death-sampling sufficient-statistic accumulators.
- Return type:
BirthDeathSamplingAccumulatorFactory
- class ContinuousTimeMarkovChainDistribution(rates, initial_state=0, horizon=10.0, name=None, keys=None, prior_shape=1.0, prior_rate=0.0)[source]
Bases:
SequenceEncodableProbabilityDistributionCTMC on
Kstates with generatorQ(off-diagonal rates); MLE is closed form (GLOBAL_UNIQUE).- Parameters:
- property generator: ndarray
The generator matrix
Q(off-diagonal rates, diagonal = -exit rate).
- density(x)[source]
Return the probability density of one fully observed trajectory.
- log_density(x)[source]
Return the log-likelihood of one fully observed CTMC trajectory.
- seq_log_density(x)[source]
Return vectorized log-likelihoods for encoded trajectory statistics.
- sampler(seed=None)[source]
Return a Gillespie sampler for trajectories from this CTMC.
- Parameters:
seed (int | None)
- Return type:
ContinuousTimeMarkovChainSampler
- estimator(pseudo_count=None)[source]
Return the closed-form rate estimator for this state space.
pseudo_count=cis the compatibility shorthand for independent off-diagonalGamma(shape=1+c, rate=c)priors. With no override, the distribution’s explicit edgewise priors are preserved.- Parameters:
pseudo_count (float | None)
- Return type:
ContinuousTimeMarkovChainEstimator
- dist_to_encoder()[source]
Return the trajectory-statistics encoder used by vectorized methods.
- Return type:
ContinuousTimeMarkovChainDataEncoder
- class ContinuousTimeMarkovChainStatistics(transition_counts, dwell_times)[source]
Bases:
NamedTupleVersioned, tuple-compatible aggregate CTMC statistics.
- transition_counts: ndarray
Alias for field number 0
- dwell_times: ndarray
Alias for field number 1
- property schema_version: int
Return the serialized statistic schema version.
- class ContinuousTimeMarkovChainEstimator(num_states, pseudo_count=None, initial_state=0, horizon=10.0, name=None, keys=None, prior_shape=None, prior_rate=None)[source]
Bases:
ParameterEstimatorClosed-form independent-edge CTMC MLE or Gamma-prior MAP estimator.
For edge
i -> j, an explicitGamma(shape_ij, rate_ij)prior givesq_ij = (n_ij + shape_ij - 1) / (T_i + rate_ij). Shapes must be at least one so the finite non-negative MAP is well defined. The defaultshape=1, rate=0recovers the MLE. The legacypseudo_count=cspelling maps coherently toshape=1+c, rate=con every off-diagonal edge; it cannot be mixed with explicit priors.- Parameters:
- accumulator_factory()[source]
Return a factory for CTMC sufficient-statistic accumulators.
- Return type:
ContinuousTimeMarkovChainAccumulatorFactory
- class InhomogeneousPoissonProcessDistribution(rates, t_max=None, edges=None, name=None, keys=None, prior_shape=1.0, prior_rate=0.0)[source]
Bases:
SequenceEncodableProbabilityDistributionInhomogeneous Poisson process with piecewise-constant intensity on a fixed window.
- Parameters:
- intensity(t, times=None, marks=None)[source]
Conditional rate
lambda(t) = rates[bin containing t].The inhomogeneous Poisson process is not self-exciting, so the rate depends only on
t.times/marksare accepted forTemporalPointProcesssignature parity and ignored. RaisesValueErrorfortoutside the support[edges[0], edges[-1]].
- expected_count(t_start, t_end, times=None, marks=None)[source]
Compensator
integral_{t_start}^{t_end} lambda(s) ds– the piecewise-rate integral.Computed as
sum_b rate_b * width(overlap([t_start, t_end], bin_b)).times/marksare accepted for signature parity and ignored. Witht_start=edges[0], t_end=edges[-1]this returns the full integralsum_b rate_b width_bused bylog_density.
- density(x)[source]
Probability density of one realization
x(a sequence of event times).
- log_density(x)[source]
Log-likelihood of one realization:
sum_b n_b log rate_b - sum_b rate_b width_b.
- seq_log_density(x)[source]
Vectorized log-likelihood for a
(num_realizations, num_bins)matrix of per-bin counts.
- sampler(seed=None)[source]
Return an InhomogeneousPoissonProcessSampler for this distribution.
- Parameters:
seed (int | None)
- Return type:
InhomogeneousPoissonProcessSampler
- estimator(pseudo_count=None)[source]
Return an InhomogeneousPoissonProcessEstimator over the same bin edges.
- Parameters:
pseudo_count (float | None)
- Return type:
InhomogeneousPoissonProcessEstimator
- dist_to_encoder()[source]
Returns an InhomogeneousPoissonProcessDataEncoder bound to these bin edges.
- Return type:
InhomogeneousPoissonProcessDataEncoder
- class InhomogeneousPoissonProcessStatistics(bin_counts, realization_weight)[source]
Bases:
NamedTupleVersioned, tuple-compatible process statistics.
- bin_counts: ndarray
Alias for field number 0
- realization_weight: float
Alias for field number 1
- property schema_version: int
Return the serialized statistic schema version.
- class InhomogeneousPoissonProcessEstimator(num_bins=None, t_max=None, edges=None, name=None, keys=None, pseudo_count=None, prior_shape=None, prior_rate=None)[source]
Bases:
ParameterEstimatorClosed-form MLE:
rate_b = (weighted events in bin b) / (width_b * weighted realizations).- Parameters:
- accumulator_factory()[source]
Return a factory for inhomogeneous Poisson sufficient-statistic accumulators.
- Return type:
InhomogeneousPoissonProcessAccumulatorFactory
- class RenewalProcessDistribution(interarrival, window, name=None, keys=None, max_events=_DEFAULT_MAX_EVENTS)[source]
Bases:
SequenceEncodableProbabilityDistributionRenewal process with i.i.d. inter-arrivals
interarrivalobserved on[0, window].- log_density(x)[source]
Exact log-likelihood of one realization (observed gaps + censored survival).
- seq_log_density(x)[source]
Vectorized log-likelihood for encoded realizations (flattened gaps + per-realization survival).
- sampler(seed=None)[source]
Return a sampler that draws gaps until the cumulative time exceeds
window.- Parameters:
seed (int | None)
- Return type:
RenewalProcessSampler
- estimator(pseudo_count=None)[source]
Return an estimator that fits the inter-arrival distribution to the observed gaps.
- Parameters:
pseudo_count (float | None)
- Return type:
RenewalProcessEstimator
- dist_to_encoder()[source]
Return the data encoder (delegates gap encoding to the inter-arrival encoder).
- Return type:
RenewalProcessDataEncoder
- class RenewalProcessStatistics(gap_statistics, completed_gaps, completed_weights, censored_times, censored_weights)[source]
Bases:
NamedTupleVersioned renewal evidence including right-censoring.
- Parameters:
- gap_statistics: Any
Alias for field number 0
- completed_gaps: ndarray
Alias for field number 1
- completed_weights: ndarray
Alias for field number 2
- censored_times: ndarray
Alias for field number 3
- censored_weights: ndarray
Alias for field number 4
- property schema_version: int
Return the serialized statistic schema version.
- class RenewalProcessEstimator(interarrival_estimator, window, name=None, keys=None, max_events=_DEFAULT_MAX_EVENTS)[source]
Bases:
ParameterEstimatorFit supported inter-arrival families to the full censored likelihood.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for observed inter-arrival gaps.
- Return type:
RenewalProcessAccumulatorFactory
- class HawkesProcessDistribution(mu, alpha, beta, window, name=None, keys=None, max_events=_DEFAULT_MAX_EVENTS)[source]
Bases:
SequenceEncodableProbabilityDistributionUnivariate Hawkes process with an exponential excitation kernel on a fixed window.
- Parameters:
- intensity(t, times, marks=None)[source]
Conditional rate
lambda(t) = mu + alpha sum_{t_i < t} exp(-beta (t - t_i))given the history.timesis the event history;marksis accepted forTemporalPointProcesssignature parity (the univariate Hawkes process is unmarked) and is ignored.
- expected_count(t_start, t_end, times, marks=None)[source]
Compensator
integral_{t_start}^{t_end} lambda(s) dsof the intensity given the history.marksis accepted for signature parity and ignored (the univariate process is unmarked).
- density(x)[source]
Probability density of one realization
x(a sequence of event times).
- log_density(x)[source]
Exact log-likelihood of one realization (a strictly increasing event-time sequence in
[0, window]).The conditional intensity is defined over the strict history
t_j < t(see the class docstring), so a realization with a tied timestamp pair (t_j == t_iforj != i) is not a validt_1 < ... < t_nhistory – like any other malformed ordering, it scores-infrather than silently letting one of the tied events excite the other.
- seq_log_density(x)[source]
Vectorized exact log-likelihood over a padded
(num_realizations, max_len)time matrix.
- sampler(seed=None)[source]
Return a HawkesProcessSampler (Ogata thinning) for this distribution.
- Parameters:
seed (int | None)
- Return type:
HawkesProcessSampler
- estimator(pseudo_count=None)[source]
Return a HawkesProcessEstimator over the same observation window.
- Parameters:
pseudo_count (float | None)
- Return type:
HawkesProcessEstimator
- dist_to_encoder()[source]
Returns a HawkesProcessDataEncoder bound to this window.
- Return type:
HawkesProcessDataEncoder
- class MultivariateHawkesProcessDistribution(mu, alpha, beta, window, name=None, keys=None, max_events=_DEFAULT_MAX_EVENTS)[source]
Bases:
SequenceEncodableProbabilityDistributionMultivariate Hawkes process: baselines
mu(D), excitationalpha(D, D), decaybeta.- Parameters:
- intensity(t, times, marks)[source]
Per-mark conditional rate vector (the vector-valued variant of
intensity).Returns
lambda(t)of shape(D,)withlambda_k(t) = mu_k + sum_{(t_i, m_i) < t} alpha[k, m_i] exp(-beta (t - t_i)).
- expected_count(t_start, t_end, times, marks)[source]
Per-mark compensator vector (the vector-valued variant of
expected_count).Returns
(D,)with the integral oflambda_kover[t_start, t_end]given the history.
- density(x)[source]
Probability density of one realization (a sequence of
(time, mark)events).
- log_density(x)[source]
Exact log-likelihood of one realization of marked events sorted by time.
- seq_log_density(x)[source]
Log-likelihood for a list of realizations.
- sampler(seed=None)[source]
Return a sampler (multivariate Ogata thinning).
- Parameters:
seed (int | None)
- Return type:
MultivariateHawkesProcessSampler
- estimator(pseudo_count=None)[source]
Return an exact finite-window estimator.
- Parameters:
pseudo_count (float | None)
- Return type:
MultivariateHawkesProcessEstimator
- dist_to_encoder()[source]
Return the data encoder (passes realizations through; the likelihood is per-realization).
- Return type:
MultivariateHawkesProcessDataEncoder
- class MultivariateHawkesProcessEstimator(dim, window, name=None, keys=None, max_events=_DEFAULT_MAX_EVENTS)[source]
Bases:
ParameterEstimatorExact weighted finite-window maximum-likelihood estimator.
- accumulator_factory()[source]
Return an accumulator factory for branching EM statistics.
- Return type:
MultivariateHawkesProcessAccumulatorFactory
- class HawkesProcessEstimator(window, name=None, keys=None, max_events=_DEFAULT_MAX_EVENTS)[source]
Bases:
ParameterEstimatorExact weighted finite-window maximum-likelihood estimator.
- accumulator_factory()[source]
Return a factory for Hawkes EM sufficient-statistic accumulators.
- Return type:
HawkesProcessAccumulatorFactory
- class ExponentialTiltedDistribution(base, theta, statistic=None, log_normalizer=None, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA base distribution reweighted by
exp(theta . T(x))and renormalized byZ(theta).- Parameters:
- density(x)[source]
Return the tilted probability/density at
x.
- log_density(x)[source]
Return
log p_base(x) + theta . T(x) - log Z.
- seq_log_density(x)[source]
Return per-row tilted log-densities for an encoded batch.
- closed_form()[source]
Return the in-family tilted distribution when the tilt closes in the base family, else None.
- Return type:
SequenceEncodableProbabilityDistribution | None
- sampler(seed=None)[source]
Return a sampler (exact for registered/enumerable bases; SIR otherwise).
- Parameters:
seed (int | None)
- Return type:
ExponentialTiltedSampler
- estimator(pseudo_count=None, fit='theta')[source]
Return an estimator.
fit='theta'fits the tilt by the exponential-family score equationE_theta[T] = mean(T(data))(base + statistic fixed);fit='base'holdsthetafixed and refits the base on the data, re-tilting (the fixed-tilt analogue of the truncation estimator).
- dist_to_encoder()[source]
Return the data encoder (base encoding plus the precomputed statistic per row).
- Return type:
ExponentialTiltedDataEncoder
- support_size()[source]
Tilting preserves the support, so the cardinality is the base’s.
- Return type:
int | None
- enumerator()[source]
Enumerate the support in descending tilted-probability order.
- Return type:
ExponentialTiltedEnumerator
- class ExponentialTiltedEstimator(prototype, pseudo_count=None, fit='theta', max_iter=60, tol=1e-8)[source]
Bases:
ParameterEstimatorFit the tilt by the exp-family score equation (
fit='theta') or refit the base (fit='base').- Parameters:
- accumulator_factory()[source]
Return a factory for exponential-tilt sufficient-statistic accumulators.
- Return type:
ExponentialTiltedAccumulatorFactory
- class ExponentialTiltedEnumerator(dist)[source]
Bases:
DistributionEnumeratorReweight the base enumeration by
theta . T(a) - log Zand re-sort descending.- Parameters:
dist (ExponentialTiltedDistribution)
- register_exponential_tilt(dist_type, fn)[source]
Register an analytic identity-statistic tilt
fn(base, theta) -> TiltResultfordist_type.
- registered_tilt_families()[source]
Return the names of base families with a registered analytic tilt.
- class IdentityTransform[source]
Bases:
objectIdentity transform y = x.
- log_abs_det_inverse_jacobian(y)[source]
Return the log absolute inverse-Jacobian determinant.
- class AffineTransform(loc=0.0, scale=1.0)[source]
Bases:
objectAffine transform y = loc + scale * x.
- forward(x)[source]
Apply the affine map to a child-space value.
- inverse(y)[source]
Map a transformed-space value back to child space.
- log_abs_det_inverse_jacobian(y)[source]
Return the constant affine inverse-Jacobian correction.
- class ExpTransform[source]
Bases:
objectExponential transform y = exp(x), mapping real x to positive y.
- inverse(y)[source]
Map a positive transformed value back to the real line.
- log_abs_det_inverse_jacobian(y)[source]
Return the log inverse-Jacobian correction for
log(y).
- class LogTransform[source]
Bases:
objectLog transform y = log(x), mapping positive x to real y.
- forward(x)[source]
Map a positive child value to the real line.
- inverse(y)[source]
Map a real transformed value back to the positive scale.
- log_abs_det_inverse_jacobian(y)[source]
Return the log inverse-Jacobian correction for
exp(y).
- class LogitTransform[source]
Bases:
objectLogistic transform y = 1 / (1 + exp(-x)), mapping real x to (0, 1).
- forward(x)[source]
Map a real value into the open unit interval.
- inverse(y)[source]
Map a unit-interval value back to the real line.
- log_abs_det_inverse_jacobian(y)[source]
Return the log inverse-Jacobian correction for the logit map.
- class LDADistribution(topics, alpha, len_dist=NullDistribution(), gamma_threshold=1.0e-8, max_gamma_iter=100, fit_diagnostics=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLatent Dirichlet allocation model for documents given as bags of weighted values.
Data type: Sequence[Tuple[T, float]], where T is the data type of the topic distributions and each (value, count) pair gives the count of a value in the document.
- Parameters:
- compute_capabilities()[source]
Return backend capability metadata for this concrete LDA instance.
- compute_declaration()[source]
Return the generated-compute declaration for latent Dirichlet allocation.
- density(x)[source]
Evaluate the density of a single LDA document.
See log_density() for details.
- density_semantics()[source]
Return density semantics for the variational LDA document bound.
- log_density(x)[source]
Evaluate the log-density of a single LDA document.
Note: The returned value is the variational lower bound (ELBO) on the marginal document log-likelihood obtained from the standard LDA mean-field approximation, not the exact (intractable) marginal log-likelihood.
- seq_log_density(x)[source]
Vectorized evaluation of the document log-densities for an encoded corpus x.
- Encoded sequence ‘x’ is a Tuple of length 5 containing:
x[0] (int): Number of documents in corpus. x[1] (np.ndarray): Document id for flattened array of values. x[2] (np.ndarray): Flattened array of counts for each value in each document. x[3] (Optional[np.ndarray]): Optional warm-start gammas (defaults to None). x[4] (E0): Sequence encoded flattened values.
Note: Returns the per-document variational lower bound (ELBO); see log_density(). If a document-length distribution ‘len_dist’ is set, its log-density of the total token count of each document is added to the returned values.
- backend_seq_log_density(x, engine)[source]
Backend-neutral LDA variational lower-bound scoring.
- seq_component_log_density(x)[source]
Vectorized evaluation of the per-topic log-density of each document in encoded corpus x.
- Parameters:
x (tuple[int, ndarray, ndarray, ndarray | None, E0]) – Encoded corpus of LDA documents (see LDADataEncoder.seq_encode()).
- Returns:
2-d numpy array with shape (number of documents, n_topics), where entry (i, l) is the log-density of document i evaluated entirely under topic l.
- Return type:
- backend_seq_component_log_density(x, engine)[source]
Backend-neutral per-topic document scores.
- seq_posterior(x)[source]
Vectorized evaluation of the posterior topic proportions for each document in encoded corpus x.
The variational gammas are computed for each document and normalized to sum to one.
- latent_posterior(doc)[source]
Return the mean-field variational posterior
q(theta, z)for a single document.Runs the per-document Blei-Ng-Jordan variational fixed point and returns a
MeanFieldLDAPosterior:.topic_proportions()(the document-topic mixE[theta]),.marginals()(per-word topic responsibilitiesphi),.sample(rng)(theta, z),.mode()(MAP topic per word), or.entropy().
- posterior_predictive(doc, n_words, seed=None)[source]
Draw
n_wordsnew words conditioned on the documentdoc.Sample the document-topic mix
theta ~ q(theta) = Dir(gamma)from the variational posterior, then generate each new word by drawing a topic~ thetaand a word from that topic – “given this document, generate more words from its inferred topic mixture”.
- sampler(seed=None)[source]
Create a sampler for documents from this distribution.
- Parameters:
seed (Optional[int]) – Seed for the random number generator used in sampling.
- Returns:
Sampler bound to this distribution.
- Return type:
LDASampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this distribution’s topics.
- Parameters:
pseudo_count (Optional[float]) – If passed, used to re-weight sufficient statistics during estimation.
- Returns:
Estimator configured with matching topic and length estimators.
- Return type:
LDAEstimator
- dist_to_encoder()[source]
Return a data encoder for iid LDA documents.
- Return type:
LDADataEncoder
- enumerator()[source]
LDA does not support enumeration.
The document log-density is a variational lower bound (ELBO) over latent topic assignments rather than an exact density, so an enumeration satisfying log_prob == log_density over a well-defined support cannot be constructed.
- Raises:
EnumerationError – Always.
- Return type:
DistributionEnumerator
- class LDAEstimator(estimators, len_estimator=NullEstimator(), suff_stat=None, pseudo_count=None, keys=(None, None), fixed_alpha=None, gamma_threshold=1.0e-8, alpha_threshold=1.0e-8, max_gamma_iter=100, max_alpha_iter=1000)[source]
Bases:
ParameterEstimatorEstimate LDA distributions from aggregated variational sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
LDAEstimatorAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an LDA distribution from aggregated sufficient statistics.
suff_statis a six-item tuple containing:suff_stat[0] (Optional[np.ndarray]): Previous Dirichlet parameter estimate. suff_stat[1] (np.ndarray): Aggregated expected log topic proportions. suff_stat[2] (float): Aggregated weighted document count. suff_stat[3] (np.ndarray): Aggregated weighted per-topic value counts. suff_stat[4] (Sequence[SS0]): Sufficient statistics for each topic. suff_stat[5] (Optional[Any]): Sufficient statistics for the document-length distribution.
- Parameters:
nobs (Optional[float]) – Weighted number of observations used in aggregation of suff_stat.
suff_stat – See above for details.
- Returns:
Estimated distribution.
- Return type:
LDADistribution
- class VonMisesFisherDistribution(mu, kappa, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionVon Mises-Fisher distribution on the (p-1)-sphere with mean direction mu and concentration kappa.
Data type: Union[Sequence[float], np.ndarray] (a unit-norm vector in R^p).
- classmethod compute_capabilities()[source]
Declare backend support for von Mises-Fisher generated kernels.
- classmethod compute_declaration()[source]
Return the generated-compute declaration for the von Mises-Fisher distribution.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return row-wise legacy sufficient statistics for resident reductions.
- static backend_log_density_from_params(x, mu, kappa, log_const, engine)[source]
Engine-neutral von Mises-Fisher log-density from fitted parameters.
- density(x)[source]
Density of von Mises-Fisher distribution at observation x.
See log_density() for details.
- log_density(x)[source]
Log-density of von Mises-Fisher distribution at observation x.
The log-density is given by
log(f(x; mu, kappa)) = log(c_p(kappa)) + kappa * dot(mu, x),
for x on the (p-1)-sphere. When kappa = 0 this reduces to the uniform density on the sphere.
- density_cumulative(x)[source]
Exact probability-ordered cumulative
G(x) = P(p(Y) >= p(x))(the HDR mass at x).A coordinate-wise CDF is undefined on the sphere (no total order), but since the density is monotone in the cosine
t = mu . x(p(y) >= p(x)iffmu.y >= mu.xforkappa >= 0), the highest-density-region mass is the upper tail of the cosine marginal, whose density isf(s) proportional to exp(kappa s) (1 - s^2)^((p-3)/2)on[-1, 1].Gis that tail integral (computed by quadrature; theexp(kappa(s-1))shift keeps it stable for large kappa and cancels in the ratio). Returned to density_rank as methodexact-analytic.
- density_quantile(q)[source]
Inverse of
density_cumulative(): a representative unit vector at cumulative-densityq.qis the highest-density-region mass; since the density is monotone in the cosinet = mu . y, the boundary is the cosinet_qwith tail massq, found by bisection on the cosine marginal. The returned representative is a unit vector at that cosine frommu(t_q * mu + sqrt(1 - t_q^2) * perpfor a fixedperporthogonal tomu). Sweepingqenumerates the sphere in descending density (concentric caps aboutmu).
- seq_log_density(x)[source]
Vectorized evaluation of log-density at sequence encoded input x.
- Parameters:
x (np.ndarray) – 2-d numpy array of N unit-norm vectors with p columns.
- Returns:
Numpy array of log-density (float) of length N.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded unit-vector observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for equal-dimensional von Mises-Fisher mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of von Mises-Fisher component log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy
(count, weighted_vector_sum)statistics.
- sampler(seed=None)[source]
Create a sampler from this von Mises-Fisher distribution.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
VonMisesFisherSampler configured from this distribution.
- Return type:
VonMisesFisherSampler
- estimator(pseudo_count=None)[source]
Create an estimator for a von Mises-Fisher distribution.
- Parameters:
pseudo_count (Optional[float]) – Kept for interface consistency (has no effect on estimation).
- Returns:
VonMisesFisherEstimator configured with this distribution’s name and keys.
- Return type:
VonMisesFisherEstimator
- dist_to_encoder()[source]
Return the encoder for von Mises-Fisher observations.
- Return type:
VonMisesFisherDataEncoder
- class GaussianCopulaDistribution(corr, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGaussian copula on
(0,1)^dwith dependence given by a correlation matrix.- property corr: ndarray
Return an owned copy so cached scoring state cannot be desynchronized.
- density(x)[source]
Return the copula density at a single point
uin(0,1)^d.
- log_density(x)[source]
Return the log copula density at a single point
uin(0,1)^d.
- seq_log_density(x)[source]
Vectorized log copula density for sequence-encoded observations (
z = Phi^{-1}(u)rows).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this copula.
- Parameters:
seed (int | None)
- Return type:
GaussianCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator that fits the correlation matrix by the inversion estimator.
- Parameters:
pseudo_count (float | None)
- Return type:
GaussianCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder (stores the normal-score transform
z = Phi^{-1}(u)).- Return type:
GaussianCopulaDataEncoder
- class GaussianCopulaEstimator(dim, min_eig=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorInversion estimator: the correlation of the normal scores
z = Phi^{-1}(u).- accumulator_factory()[source]
Return a factory for Gaussian copula sufficient-statistic accumulators.
- Return type:
GaussianCopulaAccumulatorFactory
- class ClaytonCopulaDistribution(dim, theta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionClayton copula on
(0,1)^dwiththeta >= 0; zero is independence.- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
ClaytonCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
ClaytonCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class ClaytonCopulaEstimator(dim, name=None, keys=None)[source]
Bases:
ParameterEstimatorKendall’s-tau inversion:
theta = 2*tau / (1 - tau)(pair-averaged ford > 2).- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class FrankCopulaDistribution(dim, theta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionFrank copula on
(0,1)^2with dependence parametertheta(any sign; 0 = independence).- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
FrankCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
FrankCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class FrankCopulaEstimator(name=None, keys=None)[source]
Bases:
ParameterEstimator1-D maximum likelihood on
thetaover[-40, 40](golden section on the copula log-likelihood).- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class StudentTCopulaDistribution(corr, df, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionStudent-t copula on
(0,1)^dwith correlationcorrand degrees of freedomdf.- property corr: ndarray
Return an owned copy so cached scoring state cannot be desynchronized.
- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
StudentTCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
StudentTCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class StudentTCopulaEstimator(dim, min_eig=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorInversion for
R(correlation of thet-scores) + profile likelihood overnuon a grid.- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class GumbelCopulaDistribution(dim, theta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGumbel copula on
(0,1)^2with upper-tail dependence parametertheta >= 1.- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
GumbelCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
GumbelCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class GumbelCopulaEstimator(name=None, keys=None)[source]
Bases:
ParameterEstimatorKendall’s-tau inversion:
theta = 1 / (1 - tau)(clamped totheta >= 1).- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class CVineCopulaDistribution(dim, pairs, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA canonical-vine (C-vine) copula on
(0,1)^d:d(d-1)/2bivariate pair copulas in a tree cascade.pairsmaps(tree, position)-> a fitted pair copula,treein1..d-1andpositionin1..d-tree(tree 1 links the root variable to each other; deeper trees link conditionally). Build one by hand, or fit withCVineCopulaEstimator(which selects a family per edge).- Parameters:
- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
CVineCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
CVineCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class CVineCopulaEstimator(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
ParameterEstimatorSequential (stepwise) MLE: fit tree by tree on conditional pseudo-observations, best family per edge.
- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class DVineCopulaDistribution(dim, pairs, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA drawable-vine (D-vine) copula on
(0,1)^d: the second canonical vine, a PATH of pair copulas.Where a C-vine has a star at each tree (one root linked to all), a D-vine has a path: tree 1 couples consecutive variables
(1,2),(2,3),...,(d-1,d); deeper trees couple(i, i+j)given the variables between them. Samed(d-1)/2pair copulas indexed(tree, position); different (path vs star) tree topology. Like the C-vine it is a drop-in dependence core forCopulaDistribution.- Parameters:
- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
DVineCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
DVineCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class DVineCopulaEstimator(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
ParameterEstimatorSequential (stepwise) MLE for a D-vine: fit tree by tree on conditional pseudo-obs, best family per edge.
- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class RVineCopulaDistribution(dim, trees, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA regular-vine copula on
(0,1)^d: an arbitrary tree sequence of bivariate pair copulas.Construct with
RVineCopulaEstimator(Dißmann selection), which picks the tree structure AND a pair-copula family per edge from data.treesis the fitted structure (a list of trees, each a list of_Edge);dimthe number of variables.- Parameters:
- classmethod independence(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Construct an explicit, structurally complete independence R-vine.
- log_density(u)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(u)[source]
Return vectorized log-density values for sequence-encoded observations.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
RVineCopulaSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
RVineCopulaEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
UScoreEncoder
- class RVineCopulaEstimator(dim, candidates=_DEFAULT_CANDIDATES, name=None, keys=None)[source]
Bases:
ParameterEstimatorDißmann selection + sequential MLE: choose the tree structure and per-edge family from data.
- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
BufferedUScoreAccumulatorFactory
- class MatrixNormalDistribution(mean, row_covar, col_covar, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMatrix normal distribution over
(n, p)matrices with row covarianceUand column covarianceV.- Parameters:
- density(x)[source]
Return the matrix-normal density at a single
(n, p)matrix.
- log_density(x)[source]
Return the log-density at a single
(n, p)matrix.
- seq_log_density(x)[source]
Vectorized log-density for a stack of matrices, shape
(N, n, p).
- sampler(seed=None)[source]
Return a sampler for drawing matrices from this distribution.
- Parameters:
seed (int | None)
- Return type:
MatrixNormalSampler
- estimator(pseudo_count=None)[source]
Return a flip-flop MLE estimator for the mean and the two covariance factors.
- Parameters:
pseudo_count (float | None)
- Return type:
MatrixNormalEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
MatrixNormalDataEncoder
- class MatrixNormalEstimator(n, p, max_iter=100, tol=1.0e-9, name=None, keys=None)[source]
Bases:
ParameterEstimatorFlip-flop maximum-likelihood estimator for the matrix-normal parameters.
- accumulator_factory()[source]
Return a factory for matrix-normal sufficient-statistic accumulators.
- Return type:
MatrixNormalAccumulatorFactory
- exception MatrixNormalFitError[source]
Bases:
RuntimeErrorRaised when a matrix-normal MLE is invalid or non-identifiable.
- class WatsonDistribution(mu, kappa, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionWatson distribution on the unit sphere
S^{p-1}with axismuand concentrationkappa.- density(x)[source]
Return the density at a single unit vector
x.
- log_density(x)[source]
Return the log-density at a single unit vector
x.
- seq_log_density(x)[source]
Vectorized log-density for a stack of unit vectors, shape
(N, p).
- classmethod compute_capabilities()[source]
Describe backend support for generated Watson scoring kernels.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for
(N, p)unit vectors.
- sampler(seed=None)[source]
Return an exact rejection sampler for this Watson distribution.
- Parameters:
seed (int | None)
- Return type:
WatsonSampler
- estimator(pseudo_count=None)[source]
Return a maximum-likelihood estimator (scatter eigenvector + Kummer-ratio kappa solve).
- Parameters:
pseudo_count (float | None)
- Return type:
WatsonEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
WatsonDataEncoder
- class WatsonEstimator(dim, name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator: scatter eigenvector for the axis, Kummer-ratio solve for kappa.
- accumulator_factory()[source]
Return an accumulator factory for Watson scatter statistics.
- Return type:
WatsonAccumulatorFactory
- exception WatsonFitError[source]
Bases:
RuntimeErrorRaised when Watson moments have no certified finite fit.
- exception WatsonSamplingError(accepted, proposed, kappa, dim)[source]
Bases:
RuntimeErrorRaised when exact Watson rejection sampling exhausts its proposal budget.
- class WishartDistribution(df, scale, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionWishart distribution with
dfdegrees of freedom and scale matrixscale(p, p).- density(x)[source]
Return the density at a single
(p, p)SPD matrix.
- log_density(x)[source]
Return the log-density at a single
(p, p)SPD matrix (-infif not symmetric or not positive definite).Mirrors
seq_log_density()’s routines exactly rather than merely approximately: usesbatched_pd_logdet()(the same eigenvalue-based check) instead ofcholesky_logdet()for positive-definiteness/log-determinant, and the sameeinsumtrace contraction instead oftrace(A @ B). Near the positive-definiteness boundary a Cholesky factorization and an eigendecomposition can round differently and even disagree on whether a matrix is PD at all, and a full matrix product summed viatraceaccumulates in a different order than the directeinsumcontraction – both previously made this scalar path and the vectorized path diverge (in value, and occasionally in support) on the same input.
- seq_log_density(x)[source]
Vectorized log-density for a stack of SPD matrices, shape
(N, p, p)(-infper row that is not symmetric or not positive definite).
- sampler(seed=None)[source]
Return a sampler for drawing SPD matrices from this distribution.
- Parameters:
seed (int | None)
- Return type:
WishartSampler
- estimator(pseudo_count=None)[source]
Return a closed-form estimator for the scale at the fixed degrees of freedom
df.- Parameters:
pseudo_count (float | None)
- Return type:
WishartEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
WishartDataEncoder
- class WishartEstimator(dim, df=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorClosed-form scale estimator (
V = mean(X)/df);df=Nonealso fits the degrees of freedom by MLE.With a fixed
dfthe estimator returns only the closed-form scale (E[X] = df V). Withdf=Noneit additionally estimates the degrees of freedom fromsum_i w_i log det(X_i)with a bracketed, certified root of the profile score (_solve_wishart_df()).- accumulator_factory()[source]
Return a factory for Wishart sufficient-statistic accumulators.
- Return type:
WishartAccumulatorFactory
- exception WishartFitError[source]
Bases:
RuntimeErrorRaised when a Wishart fit has no valid, certified optimum.
- class LKJDistribution(dim, eta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLKJ distribution over
dim x dimcorrelation matrices with concentrationeta > 0.- density(x)[source]
Return the probability density at a correlation matrix
x.
- log_density(x)[source]
Return the log-density at a
dim x dimcorrelation matrix (-infifxis the wrong size, not symmetric, does not have a unit diagonal, or is not positive definite).
- seq_log_density(x)[source]
Return vectorized log density for dimension-bound encoded LKJ data.
Invalid rows remain
-infregardless of eta, including at eta=1 where direct multiplication by their-infsentinel would be NaN.
- sampler(seed=None)[source]
Return an onion-method sampler for correlation matrices.
- Parameters:
seed (int | None)
- Return type:
LKJSampler
- estimator(pseudo_count=None)[source]
Return a maximum-likelihood estimator for the concentration
eta(dimfixed).- Parameters:
pseudo_count (float | None)
- Return type:
LKJEstimator
- dist_to_encoder()[source]
Return the data encoder (a correlation matrix is encoded as its log-determinant).
- Return type:
LKJDataEncoder
- class LKJEstimator(dim, eta_bounds=(0.05, 1.0e4), name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood estimator for the concentration
etaat fixed dimensiondim.- accumulator_factory()[source]
Return a factory for LKJ sufficient-statistic accumulators.
- Return type:
LKJAccumulatorFactory
- exception LKJFitError[source]
Bases:
RuntimeErrorRaised when an LKJ concentration fit has no certified solution.
- class KentDistribution(gamma, kappa, beta, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionKent (FB5) distribution on
S^2with orientationgamma(3x3), concentration and ovalness.- density(x)[source]
Return the Kent density at one unit 3-vector.
- log_density(x)[source]
Return the log-density at a unit 3-vector
x.
- seq_log_density(x)[source]
Return vectorized log-density for a sequence-encoded
(n, 3)array of unit vectors.
- classmethod compute_capabilities()[source]
Declare NumPy/Torch scoring capabilities for Kent log-density kernels.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for
(N, 3)unit vectors.
- sampler(seed=None)[source]
Return an exact rejection sampler for this Kent distribution.
- Parameters:
seed (int | None)
- Return type:
KentSampler
- estimator(pseudo_count=None)[source]
Return Kent’s moment/ML estimator for orientation, concentration, and ovalness.
- Parameters:
pseudo_count (float | None)
- Return type:
KentEstimator
- dist_to_encoder()[source]
Return the unit-vector encoder used by vectorized methods.
- Return type:
KentDataEncoder
- class KentEstimator(name=None, keys=None)[source]
Bases:
ParameterEstimatorKent’s moment estimator for the orientation, with an ML refinement of
(kappa, beta).- accumulator_factory()[source]
Return a factory for Kent sufficient-statistic accumulators.
- Return type:
KentAccumulatorFactory
- exception KentFitError[source]
Bases:
RuntimeErrorRaised when Kent moments have no certified finite fit.
- exception KentSamplingError(accepted, proposed, kappa, beta)[source]
Bases:
RuntimeErrorRaised when Kent rejection sampling exhausts its proposal budget.
- class BinghamDistribution(m, z, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBingham distribution on
S^2with orientationm(3x3) and concentrationsz(length 3).- density(x)[source]
Return the Bingham density at one unit 3-vector.
- log_density(x)[source]
Return the log-density at a unit 3-vector
x(the same value atxand-x).
- seq_log_density(x)[source]
Return vectorized log-density for a sequence-encoded
(n, 3)array of unit vectors.
- classmethod compute_capabilities()[source]
Declare NumPy/Torch scoring capabilities for Bingham log-density kernels.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for
(N, 3)unit vectors.
- sampler(seed=None)[source]
Return an exact rejection sampler for this Bingham distribution.
- Parameters:
seed (int | None)
- Return type:
BinghamSampler
- estimator(pseudo_count=None)[source]
Return a maximum-likelihood estimator for Bingham orientation and concentration.
- Parameters:
pseudo_count (float | None)
- Return type:
BinghamEstimator
- dist_to_encoder()[source]
Return the unit-vector encoder used by vectorized methods.
- Return type:
BinghamDataEncoder
- class BinghamEstimator(name=None, keys=None)[source]
Bases:
ParameterEstimatorMaximum-likelihood Bingham fit: scatter eigenbasis + concave concentration moment-matching.
- estimate(nobs, suff_stat)[source]
Estimate orientation and concentrations from scatter statistics.
- accumulator_factory()[source]
Return a factory for Bingham sufficient-statistic accumulators.
- Return type:
BinghamAccumulatorFactory
- exception BinghamFitError[source]
Bases:
RuntimeErrorRaised when Bingham moments have no certified finite fit.
- exception BinghamSamplingError(accepted, proposed, concentrations)[source]
Bases:
RuntimeErrorRaised when Bingham rejection sampling exhausts its proposal budget.
- class InverseWishartDistribution(df, scale, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionInverse-Wishart distribution with
dfdegrees of freedom and scale matrixscale(p, p).- density(x)[source]
Return the density at a single
(p, p)SPD matrix.
- log_density(x)[source]
Return the log-density at a single
(p, p)SPD matrix (-infif not symmetric or not positive definite).Mirrors
seq_log_density()’s routines exactly rather than merely approximately: usesbatched_pd_logdet()(the same eigenvalue-based check) instead ofcholesky_logdet()for positive-definiteness/log-determinant, and the sameeinsumtrace contraction instead oftrace(A @ B). Near the positive-definiteness boundary a Cholesky factorization and an eigendecomposition can round differently and even disagree on whether a matrix is PD at all, and a full matrix product summed viatraceaccumulates in a different order than the directeinsumcontraction – both previously made this scalar path and the vectorized path diverge (in value, and occasionally in support) on the same input.
- seq_log_density(x)[source]
Vectorized log-density for a stack of SPD matrices, shape
(N, p, p)(-infper row that is not symmetric or not positive definite).np.linalg.inv, likenp.linalg.cholesky(seebatched_pd_logdet()’s docstring), raisesLinAlgErrorfor the WHOLE batch if even one matrix is singular – singular is just the not-positive-definite boundary case, already scored-infbelow viais_valid, so its inverse is never actually used. Substitute the identity for invalid rows before inverting so the call always succeeds, mirroring how the scalarlog_density()path never callsinvon a matrix it is about to reject.
- sampler(seed=None)[source]
Return a sampler for drawing SPD matrices from this distribution.
- Parameters:
seed (int | None)
- Return type:
InverseWishartSampler
- estimator(pseudo_count=None)[source]
Return the fixed-df mean-moment estimator when that moment exists.
- Parameters:
pseudo_count (float | None)
- Return type:
InverseWishartMeanMomentEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
InverseWishartDataEncoder
- InverseWishartEstimator
alias of
InverseWishartMeanMomentEstimator
- class InverseWishartMeanMomentEstimator(dim, df, name=None, keys=None)[source]
Bases:
ParameterEstimatorFixed-df method-of-moments estimator based on the inverse-Wishart mean.
This is not a likelihood MLE. It is defined only for
df > p + 1, whereE[X] = Psi / (df-p-1)exists.- accumulator_factory()[source]
Return an accumulator factory for estimating the fixed-df scale matrix.
- Return type:
InverseWishartAccumulatorFactory
- exception InverseWishartMomentFitError[source]
Bases:
RuntimeErrorRaised when the inverse-Wishart mean-moment fit is undefined.
- class VonMisesFisherEstimator(dim=None, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator for the VonMisesFisherDistribution using the Banerjee et al. approximation for kappa.
- accumulator_factory()[source]
Return a factory for von Mises-Fisher accumulators.
- estimate(nobs, suff_stat)[source]
Estimate a VonMisesFisherDistribution from sufficient statistics.
The mean direction is the normalized weighted vector sum. The concentration solves
A_p(kappa) = rhatusing a finite bracket and Brent root certificate. Boundary resultants withrhat=1have only an infinite-concentration MLE and raise a typed fit error.
- exception VonMisesFisherFitError[source]
Bases:
RuntimeErrorRaised when vMF sufficient statistics have no finite identifiable fit.
- class MultivariateStudentTDistribution(dof, loc, shape, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultivariate Student’s t distribution with degrees of freedom dof, location mu, and scale Sigma.
- Parameters:
- classmethod compute_capabilities()[source]
Describe backend support for generated multivariate Student-t kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for multivariate Student-t distributions.
- static backend_log_density_from_params(x, mu, inv_shape, log_const, dof, dim, engine)[source]
Engine-neutral multivariate Student’s t log-density from fitted parameters.
- condition(observed)[source]
Return the conditional distribution over the unobserved dimensions given
observed.The conditional of a multivariate Student-t is again a multivariate Student-t. With observed dimensions
o(Mahalanobisd_o) and unobservedu:dof' = dof + |o|, mu' = mu_u + S_uo S_oo^{-1} (x_o - mu_o), shape' = (dof + d_o)/(dof + |o|) * (S_uu - S_uo S_oo^{-1} S_ou),
i.e. the location shifts like the Gaussian conditional but the scale is inflated by how far the observed coordinates fall in the tails (
given=-style conditional sampling). Raises if no dimension is left unobserved.
- marginal(keep)[source]
Return the marginal over the dimensions
keep:MVT(dof, mu[keep], shape[keep, keep]).A multivariate Student-t marginal keeps the same degrees of freedom and simply restricts the location and shape to the kept coordinates (order preserved).
- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for equal-dimensional multivariate Student’s t mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of multivariate Student’s t component log densities.
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
MultivariateStudentTSampler
- estimator(pseudo_count=None)[source]
Return an EM estimator that keeps dof fixed at this distribution’s value.
- Parameters:
pseudo_count (float | None)
- Return type:
MultivariateStudentTEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
MultivariateStudentTDataEncoder
- class MultivariateStudentTEstimator(dof=5.0, dim=None, pseudo_count=None, min_ridge=_MIN_RIDGE, name=None, keys=None)[source]
Bases:
ParameterEstimatorFixed-dof EM estimator for the multivariate Student’s t location and scale matrix.
The scale matrix is formed from shift-anchored statistics whenever the accumulated sufficient statistics carry that payload (see
MultivariateStudentTAccumulator), which makes the fit SHIFT-EQUIVARIANT: estimating onx + creturnsloc + cwith the scale matrix unchanged, for any constantcthe data can carry – epoch seconds (~1.7e9) and 2**31 included. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, andestimatewarns rather than returning a scale matrix it cannot stand behind.Residual limit, and it is representational rather than algorithmic. One M-step is shift-equivariant to ~1e-15, but a full EM run is not exactly so: the latent reweighting
u_i = (nu + p)/(nu + delta_i)is a function ofx_i - mu, andmuis a float64 at the data’s own magnitude, so it can only be placed on that grid – 1.2e-4 apart at offset 1e12. Snapping the un-shifted fit’smuonto exactly that grid reproduces the shifted fit to 3e-14, which is what identifies the mechanism. The effect on the fitted scale matrix is bounded by roughlyulp(abs(mu)) / spreadper iteration: 4e-8 at epoch seconds, 1e-7 at 2**31, 7e-5 at 1e12. Every consumer of a fitted location faces the same granularity, so there is no more precise answer to return; subtract a constant origin before fitting if a tighter one is needed.- Parameters:
- accumulator_factory()[source]
Return an accumulator factory for fixed-dof Student-t EM statistics.
- Return type:
MultivariateStudentTAccumulatorFactory
- class WeightedDistribution(dist, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionDistribution wrapper that attaches observation weights to a base distribution.
- Parameters:
- dist
Base distribution for the observed values.
- Type:
SequenceEncodableProbabilityDistribution
- name
Optional distribution name.
- Type:
Optional[str]
- compute_capabilities()[source]
Delegate generated-compute support to the wrapped value distribution.
- compute_declaration()[source]
Return the generated-compute declaration for the weighted wrapper.
- density(x)[source]
Density of the base distribution at a weighted observation’s value.
- Parameters:
x (D) – Observation value (weight excluded).
- Returns:
Density of the base distribution at x.
- Return type:
- log_density(x)[source]
Log-density of the base distribution at a weighted observation’s value.
The observation weight does not enter the likelihood, so this is simply the base distribution’s log-density evaluated on the value.
- Parameters:
x (D) – Observation value (weight excluded).
- Returns:
Log-density of the base distribution at x.
- Return type:
- seq_log_density(x)[source]
Vectorized log-density of the base distribution on encoded values.
- Parameters:
x (Tuple[E, np.ndarray]) – Sequence encoded values and weights from WeightedDataEncoder.
- Returns:
Numpy array of base-distribution log-densities.
- Return type:
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density delegated to the value distribution.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked child parameters for homogeneous weighted-wrapper mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of child log densities, ignoring attached weights.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Decline resident accumulation until its nested effective-count layout is representable.
- dist_to_encoder()[source]
Returns a WeightedDataEncoder for encoding sequences of (value, weight) observations.
- Return type:
WeightedDataEncoder
- to_fisher(**kwargs)[source]
Fisher view for the weighted wrapper.
- estimator(pseudo_count=None)[source]
Create a WeightedEstimator wrapping the base distribution’s estimator.
- Parameters:
pseudo_count (Optional[float]) – Passed through to the base distribution’s estimator.
- Returns:
WeightedEstimator object.
- Return type:
WeightedEstimator
- sampler(seed=None)[source]
Create a WeightedSampler producing (value, weight) pairs.
- Parameters:
seed (Optional[int]) – Used to set seed in random sampler.
- Returns:
WeightedSampler object.
- Return type:
WeightedSampler
- enumerator()[source]
Enumerate canonical
(value, 1.0)observations in child-probability order.- Return type:
DistributionEnumerator
- class WeightedEstimator(estimator, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimator for a weighted distribution from weighted observations.
- Parameters:
- estimator
Estimator for the base distribution.
- Type:
ParameterEstimator
- name
Optional name assigned to the estimated distribution.
- Type:
Optional[str]
- accumulator_factory()[source]
Returns a WeightedAccumulatorFactory wrapping the base estimator’s factory.
- Return type:
WeightedAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a WeightedDistribution from the base distribution’s sufficient statistics.
- Parameters:
nobs (Optional[float]) – Weighted number of observations.
suff_stat (SS) – Sufficient statistics of the base accumulator.
- Returns:
WeightedDistribution wrapping the estimated base distribution.
- Return type:
WeightedDistribution
- class WeightedObservation(value, weight)[source]
Bases:
NamedTupleA child value plus non-random, non-negative estimation-weight metadata.
- value: Any
Alias for field number 0
- weight: float
Alias for field number 1
- class WeightedStatistics(child, effective_weight)[source]
Bases:
NamedTupleChild sufficient statistics plus their effective attached-times-external weight.
- child: Any
Alias for field number 0
- effective_weight: float
Alias for field number 1
- class WeightedEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate one canonical metadata representation for every child support value.
- Parameters:
dist (WeightedDistribution)
- class ErdosRenyiGraphDistribution(p, directed=False, self_loops=False, num_nodes=None, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionIndependent Bernoulli distribution over binary graph edges.
- Parameters:
- classmethod compute_capabilities()[source]
Return backend capabilities for Bernoulli graph scoring.
- classmethod compute_declaration()[source]
Return the structured declaration for the Erdos-Renyi graph family.
- classmethod from_model(model)[source]
Create a distribution wrapper from an Erdos-Renyi model.
- Parameters:
model (Any)
- Return type:
ErdosRenyiGraphDistribution
- to_model()[source]
Convert this distribution to the corresponding random-graph model.
- Return type:
- density(x)[source]
Return the probability mass of one graph observation.
- log_density(x)[source]
Return the Bernoulli edge log probability of one graph.
- seq_log_density(x)[source]
Score a batch of graph observations.
- Parameters:
x (Sequence[GraphObservation])
- Return type:
np.ndarray
- backend_seq_log_density(x, engine)[source]
Engine-routed Bernoulli edge log-likelihood.
Per-graph edge opportunities/successes are extracted host-side (the graphs are ragged object data), but the Bernoulli reduction runs on the active engine, so the model’s scoring math is engine-native (and differentiable in
pon torch).- Parameters:
x (Sequence[GraphObservation])
engine (Any)
- Return type:
Any
- edge_probability(i=None, j=None, context=None)[source]
Return the common edge probability
p.
- edge_marginals(num_nodes=None)[source]
Return the matrix of marginal edge probabilities for
num_nodes.
- posterior(x)[source]
Return edge opportunities, observed edge count, and fitted probability for
x.
- sampler(seed=None)[source]
Return a sampler for Erdos-Renyi graph observations.
- Parameters:
seed (int | None)
- Return type:
ErdosRenyiGraphSampler
- enumerator()[source]
Enumerate binary graphs in descending probability order (requires
num_nodes).The edges are independent Bernoulli(p) over the free positions
_edge_indices(n, directed, self_loops), so the graph distribution is a product of edge factors and enumerates by best-first over the per-edge supports – exactly like a composite of Bernoullis, with the combined value assembled into an adjacency matrix (mirrored for the undirected case). Each graph carries its exactlog_density.num_nodesmust be set so the edge set is finite.- Return type:
DistributionEnumerator
- estimator(pseudo_count=None)[source]
Return the edge-count estimator for this graph family.
- Parameters:
pseudo_count (float | None)
- Return type:
ErdosRenyiGraphEstimator
- dist_to_encoder()[source]
Return the graph encoder used by vectorized scoring and fitting.
- Return type:
GraphDataEncoder
- class ErdosRenyiGraphEstimator(directed=False, self_loops=False, pseudo_count=None, prior_p=0.5, num_nodes=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate an Erdos-Renyi graph distribution from edge counts.
- Parameters:
- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
ErdosRenyiGraphAccumulatorFactory
- class TemporalGraphGrammarDistribution(motif_weights, edge_rate=1.0, node_rate=0.0, remove_weights=None, edge_remove_rate=0.0, motif=None, directed=False, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionDistribution over dynamic graphs (sequences of adjacency snapshots) under a motif-edit grammar.
- Parameters:
- transition_components(prev, cur)[source]
The PARAMETER-INDEPENDENT decomposition of a transition:
(new_nodes, add_bins, add_cand, rem_bins, rem_cand, valid). Depends only on the graph pair and the motif, NOT on the grammar’s weights/rates – so K regimes sharing a motif can compute the (expensive A@A) decomposition ONCE and score it K times viascore_components().validis False for an impossible node removal.
- score_components(components)[source]
Score a precomputed
transition_components()decomposition under THIS grammar’s parameters.
- log_density(x)[source]
Log-density of one dynamic graph: the sum of transition log-densities over the snapshot chain.
xis a sequence of binary adjacency matrices – densendarrayorscipy.sparse(large graphs). The initial graph is taken as given (its marginal is not modelled, matching how the static grammars treat their start symbol).
- seq_encode(x)[source]
Return dynamic graph sequences unchanged for sequence scoring.
- seq_log_density(x)[source]
Score a batch of dynamic graph sequences.
- sampler(seed=None)[source]
Return a sampler for dynamic graph sequences.
- Parameters:
seed (int | None)
- Return type:
TemporalGraphGrammarSampler
- estimator(pseudo_count=None)[source]
Return the closed-form estimator for this motif grammar.
- Parameters:
pseudo_count (float | None)
- Return type:
TemporalGraphGrammarEstimator
- dist_to_encoder()[source]
Return the pass-through data encoder for graph sequences.
- Return type:
TemporalGraphGrammarDataEncoder
- class TemporalGraphGrammarEstimator(motif=None, pseudo_count=None, name=None)[source]
Bases:
ParameterEstimatorLearn the motif distribution (rule weights) + edge/node rates from observed dynamic graphs.
- accumulator_factory()[source]
Return the accumulator factory used by the estimator.
- Return type:
TemporalGraphGrammarAccumulatorFactory
- class CommonNeighbourMotif(bins=(0, 1, 2, 3), directed=False)[source]
Bases:
objectA motif rule keyed by how many common neighbours a candidate edge has (triangles it would close).
binsis an increasing list of thresholds; binbcovers common-neighbour counts in[bins[b], bins[b+1])with the last bin open-ended. The default[0, 1, 2, 3]gives the interpretable {bridge, closes-1, closes-2, closes-3+} partition. A non-edge falls in exactly one bin, so the motifs partition every candidate edge.- property num_motifs: int
Number of mutually exclusive motif bins.
- assign(adj, on_edges=False)[source]
Motif bin of every candidate pair (and -1 on non-candidates / diagonal).
The common-neighbour count of a pair (i, j) is
(A @ A)[i, j]– for a non-edge, how many triangles adding it would CLOSE; for an existing edge, how many triangles it is PART of. Binning byself.binsgives its motif. Withon_edges=Falsethe candidates are the non-edges (addition); withon_edges=Truethey are the existing edges (removal). Non-candidates and the diagonal -> -1.
- counts_and_binner(adj, on_edges)[source]
Return (candidate_counts[M], lookup(i, j) -> motif index) WITHOUT forming the n*n bin matrix.
Sparse-scalable: only the existing edges (O(m)) and the non-edges that close a triangle (O(wedges) =
A @ A’s nonzeros) are ever enumerated; the bridge count (cn=0 non-edges) is the analytic remainderpairs - edges - wedge_non_edges. The lookup reads(A @ A)[i, j]for the handful of observed edges. (For graphs with mega-hubs the wedge set itself is large – the documented limit.)
- class LabeledTemporalGraphGrammarDistribution(structure, node_dist=None, edge_dist=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA dynamic graph whose nodes and edges carry attributes.
Composes a structural
TemporalGraphGrammarDistribution(the topology over time) with two ordinary mixle distributions:node_distover per-node attribute records (location, name, age, … – typically aCompositeDistributionof leaves or a mixture) andedge_distover per-edge attribute records (communication counts, channel, weight, …). An observation is(snapshots, node_features, edge_features): the adjacency chain, one attribute record per final node index, and one edge-record group per transition containing one record per added edge in canonical_edge_difforder. The likelihood factorises – structure x node attributes x edge attributes – so the attribute models are fit (and scored) with the full mixle distribution machinery (mixtures, fusion, all leaf families).- Parameters:
structure (TemporalGraphGrammarDistribution)
node_dist (SequenceEncodableProbabilityDistribution | None)
edge_dist (SequenceEncodableProbabilityDistribution | None)
name (str | None)
- log_density(x)[source]
Score one attributed dynamic graph observation.
- seq_encode(x)[source]
Validate and encode a batch of event-aligned attributed observations.
- seq_log_density(x)[source]
Score a batch of attributed dynamic graph observations.
- sampler(seed=None)[source]
Return a sampler for attributed dynamic graph observations.
- Parameters:
seed (int | None)
- Return type:
LabeledTemporalGraphGrammarSampler
- estimator(**kw)[source]
Return the estimator for structure, node attributes, and edge attributes.
- Parameters:
kw (Any)
- Return type:
LabeledTemporalGraphGrammarEstimator
- dist_to_encoder()[source]
Return the event-aligned attributed graph encoder.
- Return type:
LabeledTemporalGraphGrammarDataEncoder
- class LabeledTemporalGraphGrammarEstimator(structure_estimator, node_estimator=None, edge_estimator=None, *, structure, node_encoder=None, edge_encoder=None, name=None)[source]
Bases:
ParameterEstimatorEstimator for attributed temporal graph grammars.
- Parameters:
structure_estimator (Any)
node_estimator (Any)
edge_estimator (Any)
structure (TemporalGraphGrammarDistribution)
node_encoder (Any)
edge_encoder (Any)
name (str | None)
- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
LabeledTemporalGraphGrammarAccumulatorFactory
- class HomophilyTemporalGraphGrammarDistribution(rate, type_weights, node_rate=0.0, motif=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA growth grammar whose edge formation depends on node ATTRIBUTES, not just structure (homophily).
Each node carries a categorical
type(community / location-bucket / …). The per-step number of new edges of motifmbetween an (unordered) type pair (a, b) isPoisson(rate[m, a, b]), placed uniformly among the candidate non-edges of that motif and type pair. Makingrate[m, a, a]larger thanrate[m, a, b]is homophily (“similar nodes connect more”); the rate tensor is the learnable coupling between attributes and topology. New nodes draw their type fromtype_weights.Observation:
(snapshots, node_types)– the adjacency chain plus an int type per node. Exact and closed-form: the rate tensor is just edge counts per (motif, type-pair) over steps, and the type distribution is node-type counts. (Phase: growth-only, dense; add+remove and sparse compose with the machinery above and are the natural extensions.)- Parameters:
- log_density(x)[source]
Score one homophily dynamic graph observation.
- seq_encode(x)[source]
Validate and encode homophily observations.
- seq_log_density(x)[source]
Score a batch of homophily dynamic graph observations.
- sampler(seed=None)[source]
Return a sampler for homophily dynamic graph observations.
- Parameters:
seed (int | None)
- Return type:
HomophilyTemporalGraphGrammarSampler
- estimator(pseudo_count=None)[source]
Return the estimator for homophily rates and node-type weights.
- Parameters:
pseudo_count (float | None)
- Return type:
HomophilyTemporalGraphGrammarEstimator
- dist_to_encoder()[source]
Return the validated homophily encoder.
- Return type:
HomophilyTemporalGraphGrammarDataEncoder
- class HomophilyTemporalGraphGrammarEstimator(M, K, motif=None, pseudo_count=None, name=None)[source]
Bases:
ParameterEstimatorEstimator for homophily temporal graph grammars.
- Parameters:
- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
HomophilyTemporalGraphGrammarAccumulatorFactory
- class ChurningTemporalGraphGrammarDistribution(edit_grammar, node_remove_rate=0.0, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionDynamic graph where nodes both JOIN and LEAVE, tracked by stable identity.
Each snapshot is
(adjacency, node_ids)–node_ids[i]is the persistent identity of row i. A transition first removes nodes (those whose id disappears; count ~ Poisson(node_remove_rate), chosen uniformly, their edges vanishing with them), then runs the wrapped edit grammar on the surviving subgraph (which also appends new nodes + adds/removes edges). So churn is a thin wrapper: identity alignment + a node-removal Poisson term on top of all the existing motif/edge machinery. Scoring and fitting accept dense orscipy.sparseadjacencies (the id alignment slices either); the sampler is dense.- Parameters:
- log_density(x)[source]
Score one identity-tracked churning graph sequence.
- seq_encode(x)[source]
Validate and encode identity-tracked graph observations.
- seq_log_density(x)[source]
Score a batch of churning graph observations.
- sampler(seed=None)[source]
Return a sampler for churning graph observations.
- Parameters:
seed (int | None)
- Return type:
ChurningTemporalGraphGrammarSampler
- estimator(pseudo_count=None)[source]
Return the estimator for the wrapped edit grammar and node churn rate.
- Parameters:
pseudo_count (float | None)
- Return type:
ChurningTemporalGraphGrammarEstimator
- dist_to_encoder()[source]
Return the validated identity-tracked graph encoder.
- Return type:
ChurningTemporalGraphGrammarDataEncoder
- class ChurningTemporalGraphGrammarEstimator(edit_estimator, edit_grammar=None, name=None)[source]
Bases:
ParameterEstimatorEstimator for identity-tracked churning temporal graph grammars.
- Parameters:
edit_estimator (Any)
edit_grammar (TemporalGraphGrammarDistribution | None)
name (str | None)
- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
ChurningTemporalGraphGrammarAccumulatorFactory
- class LatentTemporalGraphGrammarDistribution(states, initial_probs=None, transition_matrix=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA dynamic graph whose edit grammar is governed by a hidden, time-evolving REGIME.
A latent state z_t (a Markov chain:
initial_probspi,transition_matrixA) selects which of K edit grammars governs transition t. So the graph can switch regimes over time – e.g. a bursty growth / densification phase, then a fragmentation / decay phase – dynamics a single grammar cannot express. The sequence likelihood marginalises the regime path by the forward algorithm; emissions are the per- transition edit log-densities of each regime’s grammar, so this is an HMM whose emission models are the graph-edit grammars and EM reuses each grammar’s weighted accumulator for the M-step.Observation = a plain list of adjacency snapshots (same as the base grammar) – the regime is latent.
decodereturns the most likely regime active at each transition (Viterbi).- Parameters:
- log_density(x)[source]
Score one dynamic graph sequence with regimes marginalized out.
- decode(x)[source]
Viterbi: the most likely regime governing each transition.
- seq_encode(x)[source]
Validate and encode latent-regime graph observations.
- seq_log_density(x)[source]
Score a batch of latent-regime graph observations.
- sampler(seed=None)[source]
Return a sampler for latent-regime graph sequences.
- Parameters:
seed (int | None)
- Return type:
LatentTemporalGraphGrammarSampler
- estimator(pseudo_count=None)[source]
Return the Baum-Welch estimator for the latent-regime grammar.
- Parameters:
pseudo_count (float | None)
- Return type:
LatentTemporalGraphGrammarEstimator
- dist_to_encoder()[source]
Return the validated graph encoder.
- Return type:
TemporalGraphGrammarDataEncoder
- class LatentTemporalGraphGrammarEstimator(state_estimators, pseudo_count=None, name=None)[source]
Bases:
ParameterEstimatorEM (Baum-Welch) for the regime-switching grammar: forward-backward E-step, per-regime weighted M-step.
- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
LatentTemporalGraphGrammarAccumulatorFactory
- class LatentAttributedTemporalGraphGrammarDistribution(structures, node_dists=None, edge_dists=None, initial_probs=None, transition_matrix=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA regime-switching dynamic graph where the hidden regime drives the STRUCTURE and the ATTRIBUTES.
Each of K regimes carries a full edit grammar plus (optionally) a node-attribute distribution and an edge-attribute distribution, all switched by one latent Markov state z_t. So a single regime change can densify the topology AND spike communication volume / shift node properties together – e.g. an “active” phase with bursty triadic closure and high message counts, vs a “quiet” phase. The per-transition emission under regime k is
structure_k(transition) + node_attrs_k(nodes added this step) + edge_attrs_k(edges added this step); the sequence likelihood marginalises the regime path by the forward algorithm and EM does forward-backward + a per-regime weighted M-step over each piece.Observation =
(snapshots, node_features, edge_features)wherenode_features[t]/edge_features[t]are the attribute records of the nodes / edges that appear at transition t (lists, length = #transitions).- Parameters:
- log_density(x)[source]
Score one attributed graph sequence with regimes marginalized out.
- decode(x)[source]
Viterbi: the most likely regime governing each transition (jointly explaining structure+attrs).
- seq_encode(x)[source]
Validate and encode attributed latent-regime observations.
- seq_log_density(x)[source]
Score a batch of attributed latent-regime observations.
- sampler(seed=None)[source]
Return a sampler for attributed latent-regime graph sequences.
- Parameters:
seed (int | None)
- Return type:
LatentAttributedTemporalGraphGrammarSampler
- estimator(pseudo_count=None)[source]
Return the EM estimator for structure and attribute regime models.
- Parameters:
pseudo_count (float | None)
- Return type:
LatentAttributedTemporalGraphGrammarEstimator
- dist_to_encoder()[source]
Return the event-aligned latent attributed encoder.
- Return type:
LatentAttributedTemporalGraphGrammarDataEncoder
- class LatentAttributedTemporalGraphGrammarEstimator(structure_estimators, node_estimators=None, edge_estimators=None, *, structures, node_encoders=None, edge_encoders=None, pseudo_count=None, name=None)[source]
Bases:
ParameterEstimator- Parameters:
- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
LatentAttributedTemporalGraphGrammarAccumulatorFactory
- class LatentChurningTemporalGraphGrammarDistribution(states, node_remove_rates=None, initial_probs=None, transition_matrix=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA regime-switching dynamic graph where the hidden regime also governs NODE TURNOVER.
Combines the latent regime HMM with identity-tracked node churn: each of K regimes carries a full edit grammar AND its own node-removal rate, so the graph can switch between e.g. a stable phase (slow turnover, triadic growth) and a churn phase (fast member departure, fragmentation). Each snapshot is
(adjacency, node_ids); per transition the active regime first removes nodes (those whose id disappears) then edits the surviving subgraph, and the per-transition emission under regime k isnode_removal_k(#removed) + grammar_k(edit on the aligned surviving subgraph). The sequence likelihood marginalises the regime path by the forward algorithm; EM does forward-backward then a per-regime weighted M-step over both the grammar and the turnover rate.decoderecovers the active regime.Observation =
(snapshots, node_ids)wherenode_idsis a list of per-snapshot id arrays. Dense.- Parameters:
- log_density(x)[source]
Score one identity-tracked sequence with regimes marginalized out.
- decode(x)[source]
Return the most likely churn/edit regime for each transition.
- seq_encode(x)[source]
Validate and encode latent churning observations.
- seq_log_density(x)[source]
Score a batch of latent churning graph observations.
- sampler(seed=None)[source]
Return a sampler for latent churning graph sequences.
- Parameters:
seed (int | None)
- Return type:
LatentChurningTemporalGraphGrammarSampler
- estimator(pseudo_count=None)[source]
Return the EM estimator for regime-specific edit grammars and churn rates.
- Parameters:
pseudo_count (float | None)
- Return type:
LatentChurningTemporalGraphGrammarEstimator
- dist_to_encoder()[source]
Return the validated identity-tracked graph encoder.
- Return type:
ChurningTemporalGraphGrammarDataEncoder
- class LatentChurningTemporalGraphGrammarEstimator(state_estimators, *, states=None, pseudo_count=None, name=None)[source]
Bases:
ParameterEstimator- Parameters:
- accumulator_factory()[source]
Return the accumulator factory used to collect this estimator’s sufficient statistics.
- Return type:
LatentChurningTemporalGraphGrammarAccumulatorFactory
- class StochasticBlockGraphDistribution(block_probs, block_assignments=None, block_prior=None, directed=False, self_loops=False, include_assignment_prior=None, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionBernoulli stochastic block graph distribution.
The distribution can be used conditionally on observed block assignments, or as a population model that samples assignments from
block_priorfor new graphs. Exact marginal likelihood over unknown assignments is intentionally not implied.- Parameters:
- classmethod compute_capabilities()[source]
Return backend capabilities for block-structured Bernoulli graph scoring.
- classmethod from_model(model, block_prior=None, include_assignment_prior=False)[source]
Create a distribution wrapper from a random-graph SBM model.
- to_model()[source]
Convert this distribution to the corresponding random-graph model.
- Return type:
- density(x)[source]
Return the probability mass of one graph observation.
- log_density(x)[source]
Return the conditional block-model log probability of one graph.
- seq_log_density(x)[source]
Score a batch of graph observations.
- Parameters:
x (Sequence[GraphObservation])
- Return type:
np.ndarray
- backend_seq_log_density(x, engine)[source]
Engine-routed block-structured Bernoulli edge log-likelihood.
Each graph’s edges are flattened host-side into per-edge (value, block-pair probability) arrays with a graph-segment id; the Bernoulli terms and the segment reduction run on the active engine (differentiable in
block_probson torch). The optional assignment prior is added per graph.- Parameters:
x (Sequence[GraphObservation])
engine (Any)
- Return type:
Any
- link_probability(i, j, block_assignments=None)[source]
Return the marginal or assignment-conditional edge probability for node pair
(i, j).
- edge_marginals(block_assignments=None, num_nodes=None)[source]
Return the matrix of edge probabilities under fixed or prior-predictive assignments.
- block_marginals(x=None)[source]
Return empirical block proportions for
xor the model block prior.
- posterior(x)[source]
Return block counts, block proportions, and edge marginals for an observed graph.
- sampler(seed=None)[source]
Return a sampler for SBM graph observations.
- Parameters:
seed (int | None)
- Return type:
StochasticBlockGraphSampler
- enumerator()[source]
Enumerate binary graphs in descending probability order, for FIXED block assignments.
With the node block assignments fixed (
block_assignmentsset on the distribution), each edge(i, j)is an independent Bernoulli with its own probabilityblock_probs[a_i, a_j], so the graph distribution is a product of edge factors – enumerated by best-first over the per-edge supports and assembled into an adjacency matrix (mirrored when undirected).Marginalizing over UNKNOWN assignments is intentionally not modeled by this family, so enumeration requires fixed assignments; otherwise EnumerationError.
- Return type:
DistributionEnumerator
- estimator(pseudo_count=None)[source]
Return an estimator for observed-assignment SBM fitting.
- Parameters:
pseudo_count (float | None)
- Return type:
StochasticBlockGraphEstimator
- dist_to_encoder()[source]
Return the graph encoder used by vectorized scoring and fitting.
- Return type:
GraphDataEncoder
- class StochasticBlockGraphEstimator(num_blocks=None, block_assignments=None, directed=False, self_loops=False, pseudo_count=None, prior_p=0.5, block_prior=None, estimate_block_prior=True, include_assignment_prior=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate an SBM from graphs with observed block assignments.
- Parameters:
- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- Return type:
StochasticBlockGraphAccumulatorFactory
- class StochasticBlockGraphStatistics(schema_version, successes, totals, block_counts, total_nodes, num_graphs, directed, self_loops)[source]
Bases:
NamedTupleVersioned, configuration-bound sufficient statistics for an SBM.
- Parameters:
- schema_version: int
Alias for field number 0
- successes: ndarray
Alias for field number 1
- totals: ndarray
Alias for field number 2
- block_counts: ndarray
Alias for field number 3
- total_nodes: float
Alias for field number 4
- num_graphs: float
Alias for field number 5
- directed: bool
Alias for field number 6
- self_loops: bool
Alias for field number 7
- class LatentAPIEntry(name, source, status, lazy=True)[source]
Bases:
objectOne immutable entry in the reviewed latent-package export manifest.
- latent_api_manifest()[source]
Return the immutable, ordered latent-package export manifest.
- Return type:
tuple[LatentAPIEntry, …]
- class EffectiveSampleReceipt(declared_mass, assigned_mass, unassigned_mass, allows_unassigned, schema_version=1, contract='mixle.latent_effective_sample/v1')[source]
Bases:
objectValidated relationship between declared and assigned effective mass.
- validated_positive_integer(value, label)[source]
Return a positive exact non-boolean integer.
- validated_observation_weight(value, label='observation weight')[source]
Return one finite non-negative, non-boolean observation weight.
- validated_observation_weights(values, rows, label='observation weights')[source]
Return an owned finite non-negative weight vector with exact row geometry.
- validated_count_array(values, shape, label='sufficient-statistic counts')[source]
Return an owned finite non-negative count array with exact geometry.
- validated_statistic_tuple(values, arity, label)[source]
Return a statistic tuple only when its public schema arity is exact.
- validate_effective_sample_mass(declared_mass, assigned_mass, *, label, allow_unassigned=False)[source]
Validate declared outer mass against mass assigned to latent children.
declared_mass=Nonemeans the caller did not provide outer-mass metadata. Otherwise exact agreement is required, except that families whose documented impossible-evidence policy assigns zero responsibility may setallow_unassigned=True. Assigned mass may never exceed declared mass.
- validated_weighted_responsibilities(values, weights, components, *, label, allow_unassigned=False)[source]
Validate an owned
(rows, components)matrix of assigned posterior mass.
- class GatedMixtureStatistics(component_statistics, covariates, responsibilities, buffer_receipt, component_counts, schema_version=1)[source]
-
Versioned gated-mixture statistics with backward four-slot iteration.
- class GaussianMixtureDistribution(mu, sig2, w=MISSING, name=None, weights=MISSING)[source]
Bases:
MixtureDistributionFinite mixture of full-covariance multivariate Gaussian components.
The constructor packs each
(mu[k], sig2[k])pair into aMultivariateGaussianDistribution. Density, posterior responsibility, and vectorized scoring behavior are inherited fromMixtureDistribution.- Parameters:
mu (Sequence[Sequence[float]] | ndarray) – Component means with shape
(K, d).sig2 (Sequence[Any] | ndarray) – Component covariance matrices with shape
(K, d, d)or diagonal variances with shape(K, d).w (Sequence[float] | ndarray) – Mixture weights with length
K.name (str | None) – Optional diagnostic name.
- mu
Component means as a
(K, d)NumPy array.
- sig2
Component covariance matrices as a
(K, d, d)NumPy array.
- dim
Observation dimension.
- density_semantics()[source]
Return exact-or-approximate density semantics joined from Gaussian components.
- sampler(seed=None)[source]
Return a sampler that draws vectors from this Gaussian mixture.
- Parameters:
seed (int | None) – Optional seed for reproducible component and Gaussian draws.
- Returns:
GaussianMixtureSamplerbound to this distribution.- Return type:
GaussianMixtureSampler
- estimator(pseudo_count=None)[source]
Return an estimator with matching Gaussian component structure.
- Parameters:
pseudo_count (float | None) – Optional smoothing mass for mixture weights.
- Returns:
GaussianMixtureEstimatorsuitable for fitting length-d vectors.- Return type:
GaussianMixtureEstimator
- dist_to_encoder()[source]
Return the Gaussian mixture encoder for iid vector observations.
- Return type:
GaussianMixtureDataEncoder
- class GaussianMixtureEstimator(estimators, name=None, conj_prior_params=None, suff_stat=None, pseudo_count=None, keys=(None, None), robust=False, init=None)[source]
Bases:
MixtureEstimatorEM estimator for a multivariate Gaussian mixture.
The weight M-step and robustness options are inherited from
MixtureEstimator. The specialization repacks fitted Gaussian components into(mu, sig2, w)arrays for aGaussianMixtureDistribution.- Parameters:
estimators (Sequence[ParameterEstimator]) – Component estimators whose fitted components carry a mean vector and a covariance (
muandcovar) – typicallyMultivariateGaussianEstimatororDiagonalGaussianEstimator. The univariateGaussianEstimatoris refused at construction (its fitted component has no covariance to pack); spell a univariate Gaussian mixtureMixtureEstimator([GaussianEstimator(), ...]).name (str | None) – Optional diagnostic name.
conj_prior_params (Any | None) – Reserved compatibility slot.
suff_stat (ndarray | None) – Optional prior component-count vector used with
pseudo_count.pseudo_count (float | None) – Optional smoothing mass for mixture weights.
keys (tuple[str | None, str | None]) – Optional shared-statistic keys for weights and components.
robust (bool) – Enable the robust weight floor, as on
MixtureEstimator.init (str | None) – Initialization strategy, one of
MIXTURE_INIT_STRATEGIES;Noneselects the default"kmeans++".
- accumulator_factory()[source]
Return a Gaussian mixture accumulator factory.
- Return type:
GaussianMixtureEstimatorAccumulatorFactory
- accumulatorFactory()[source]
Deprecated alias for
accumulator_factory().New code should call
accumulator_factory. The camelCase name remains available for older callers and returns the same factory, but now emits aDeprecationWarning(seedocs/support-policy.rst).- Return type:
GaussianMixtureEstimatorAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a Gaussian mixture from aggregated EM sufficient statistics.
The component M-step and weight estimate reuse the generic mixture estimator path. The fitted component means and covariances are then repacked into a
GaussianMixtureDistribution.
- class PCFGTerminationCertificate(proper, reachable_nonterminals, progeny_spectral_radius, critical_singular_classes, reason)[source]
Bases:
objectFinite certificate that the start-symbol branching process dies out almost surely.
- class HeterogeneousPCFGStatistics(terminal_counts, binary_counts, emission_statistics, observation_mass, schema_version=1)[source]
-
Mass-aware PCFG statistics with backward three-slot iteration.
- class HeterogeneousPCFGFisherView(dist)[source]
Bases:
FixedFisherViewInside-outside Fisher view for heterogeneous PCFGs.
Coordinates are expected complete-data rule counts followed by terminal emission sufficient statistics gated by the posterior probability of the corresponding terminal rule at each token. For finite enumerable PCFGs, the model Fisher is the exact observed Fisher covariance of these posterior-expected complete-data statistics under the model distribution. Recursive or infinite-support grammars should use observed_fisher_* on data.
- Parameters:
dist (Any)
- fisher_information(stats=None, diagonal=False, ridge=1.0e-8, **kwargs)[source]
Return model Fisher information, falling back to observed statistics.
- fisher_vectors(stats=None, metric='diagonal', center=None, fisher=None, ridge=1.0e-8, **kwargs)[source]
Whiten PCFG statistics under the requested Fisher metric.
- class HiddenAssociationStatistics(conditional, given, size, conditional_mass, observation_mass, schema_version=1)[source]
-
Mass-aware statistics with backward three-child iteration.
- class HiddenAssociationEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate hidden-association support pairs in best-first order.
- Parameters:
dist (HiddenAssociationDistribution)
- hmm_dirichlet_default_prior(num_states)[source]
Returns the default
(init_prior, row_priors)pair of unit-parameter Dirichlets.- Parameters:
num_states (int) – Number of hidden states S.
- Returns:
Tuple
(DirichletDistribution, list of S DirichletDistribution).
- terminal_forward_loglik(log_w, log_a, log_b, term_mask)[source]
Log-likelihood of a terminal-state HMM sequence (length is a stopping time at the first terminal state).
log_bis the per-position, per-state emission log-density(L, K). The forward only transitions from non-terminal states and the likelihood sums the final position over terminal states. Shared by every HMM variant whose forward is a linear state trellis (base, lookback, …).
- terminal_forward_backward(log_w, log_a, log_b, term_mask)[source]
Terminal-state forward-backward; returns
(loglik, gamma (L,K), xi (L-1,K,K))(gamma/xi None if 0-prob).The backward pass mirrors the forward: only the final position may be terminal, and only non-terminal states have a future. Responsibilities are normalized by the sequence likelihood.
- class HiddenMarkovFisherView(dist)[source]
Bases:
FixedFisherViewObserved Fisher view for HMMs via forward-backward statistics.
The per-observation vectors are posterior-expected complete-data sufficient statistics: initial-state counts, transition counts, per-state emission statistics, optional length statistics, and state occupancies when the model accumulator exposes them. For finite enumerable HMMs, the full model Fisher is the exact observed covariance of these statistics under the model distribution. For continuous or otherwise non-enumerable HMMs, diagonal model moments remain available; use observed_fisher_information() for empirical full covariance on data.
- Parameters:
dist (Any)
- structured_statistics(x, estimate=None, weight=1.0)[source]
Return Baum-Welch sufficient statistics for one weighted sequence.
- fisher_information(stats=None, diagonal=False, ridge=1.0e-8, **kwargs)[source]
Return HMM Fisher information, using exact finite-support moments when available.
- fisher_vectors(stats=None, metric='diagonal', center=None, fisher=None, ridge=1.0e-8, **kwargs)[source]
Return Fisher-normalized HMM sufficient statistics.
Full Fisher normalization is available when the model has finite enumerable support or when an explicit Fisher matrix is supplied. Otherwise callers should use the diagonal metric or observed Fisher routes.
- class HierarchicalNormalDistribution(mu, tau, sigma, name=None, keys=None, fit_diagnostics=None)[source]
Bases:
SequenceEncodableProbabilityDistributionTwo-level normal hierarchy over groups:
y[g,i] ~ N(theta[g], sigma^2),theta[g] ~ N(mu, tau^2).Each observation is one group (a sequence of values).
muis the population mean,tauthe between-group sd andsigmathe within-group sd. The latent group mean is marginalized out, so a group’s likelihood is the multivariate normalN(mu*1, sigma^2 I + tau^2 11^T)(computed in closed form).group_posterior/shrinkagegive the partial-pooling estimates.- Parameters:
- log_density(group)[source]
Marginal log-likelihood of one group (latent group mean integrated out).
- Return type:
- seq_log_density(x)[source]
Return vectorized marginal log likelihoods for encoded groups.
- Return type:
- group_posterior(ybar, n)[source]
Posterior
(mean, sd)of a group’s true mean given its sample meanybarand sizen.The shrinkage estimate
mu + shrink*(ybar - mu)withshrink = tau^2/(tau^2 + sigma^2/n).
- shrinkage(n)[source]
The shrinkage weight for a size-
ngroup (0 = full pooling tomu, 1 = its own mean).
- sampler(seed=None)[source]
Return a sampler for grouped observations from this hierarchy.
- Parameters:
seed (int | None)
- Return type:
HierarchicalNormalSampler
- estimator(pseudo_count=None)[source]
Return an empirical-Bayes EM estimator for the hierarchy.
- Parameters:
pseudo_count (float | None)
- Return type:
HierarchicalNormalEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution.
- Return type:
HierarchicalNormalDataEncoder
- class HierarchicalNormalEstimator(max_iter=500, tol=1e-9, max_group_sizes=_DEFAULT_MAX_GROUP_SIZES, name=None, keys=None)[source]
Bases:
ParameterEstimatorWeighted empirical-Bayes EM over size-bucketed group sufficient statistics.
- accumulator_factory()[source]
Return an accumulator factory for bounded size-bucketed statistics.
- Return type:
StatisticAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Fit
mu,tau, andsigmawith a weighted EM receipt.- Return type:
HierarchicalNormalDistribution
- class HierarchicalNormalFitDiagnostics(converged, identifiable, iterations, termination_reason, objective_trace, final_parameter_delta, n_group_sizes, total_group_weight, total_observation_weight)[source]
Bases:
objectMachine-readable receipt for the empirical-Bayes EM fit.
- determinize_quantized_terminal(dist, max_states=1 << 16)[source]
Determinize a terminal-value quantized HMM into a
DeterminizedSequenceDistribution.Raises EnumerationError if the HMM has no terminal_values, or if the belief expansion exceeds
max_states(the twins property fails – not finitely determinizable).- Parameters:
max_states (int)
- determinize_terminal_hmm(dist, max_states=1 << 16, max_denominator=10**9)[source]
Determinize a GENERAL terminal-value HMM (any transitions/initial, finite-discrete emissions).
Belief equality must be decidable, so each row of the model’s float probabilities is first rationalized (
Fraction(p).limit_denominator(max_denominator)) and then normalized exactly. Determinization is exact on that stochastic rational model, which approximates the source to the requested rationalization precision. Requires terminal_values and enumerable finite emissions. Raises EnumerationError if not finitely determinizable withinmax_statesor if an emission support is not finite/enumerable.
- class DeterminizedSequenceDistribution(trans, accept, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA deterministic weighted machine over terminal-ended sequences (one path per sequence).
trans[q][x] = (log_weight, next_state)for a non-terminal symbol;accept[q][x] = log_weightfor a terminal symbol that completes the sequence.log_density(x)is the unique path’s summed log-weight (== the original HMM’s exact marginal); enumeration yields exact, duplicate-free n-best-strings.- Parameters:
name (str | None)
- log_density(x)[source]
Return the unique deterministic path log-weight for a sequence.
- Return type:
- seq_log_density(x)[source]
Return log-densities for a batch of encoded sequences.
- Return type:
- dist_to_encoder()[source]
Return the passthrough sequence encoder for determinized machines.
- Return type:
DeterminizedDataEncoder
- enumerator()[source]
Return an exact descending-probability enumerator.
- Return type:
DeterminizedEnumerator
- quantized_count_index(quantizer, max_fine_bucket)[source]
Structural count index over the deterministic machine -> sub-linear exact seek/rank.
The machine is deterministic (one path per sequence), so a forward reach DP over states counts each sequence exactly once at its (floored) cost: reach_by_len[t][q] is the count histogram of length-t non-terminal prefixes reaching state q; an accept edge then completes a length-(t+1) sequence. Unranking walks the reach DP backward through the (precomputed) incoming edges. Exact up to quantization tie granularity; no path over-count (the determinization already removed it).
- Parameters:
max_fine_bucket (int)
- class DeterminizedEnumerator(dist)[source]
Bases:
DistributionEnumeratorExact descending-probability enumeration of sequences over the deterministic machine (n-best strings). Best-first with an admissible per-state best-completion bound (Viterbi over the machine).
- Parameters:
dist (DeterminizedSequenceDistribution)
- seek(index)[source]
Sub-linear exact seek over the deterministic machine (no prefix enumeration).
Deepens the structural count index until
indexis covered or the support is provably exhausted (the count-DP’s reliabletruncatedflag), then unranks within the located fine bucket. Robust to gaps in the cost spectrum, unlike the shared total-growth deepening heuristic.- Parameters:
index (int)
- class IndianBuffetProcessFisherView(dist)[source]
Bases:
FixedFisherViewFixed Fisher view whose statistics are the binary feature indicators.
- Parameters:
dist (Any)
- class IndianBuffetProcessEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate finite IBP feature rows in descending plug-in probability order.
- Parameters:
dist (IndianBuffetProcessDistribution)
- class IntegerHiddenAssociationStatistics(initial_counts, weight_counts, state_counts, previous, size, observation_mass, schema_version=1)[source]
-
Mass-aware statistics with backward five-slot iteration.
- class IntegerHiddenAssociationEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate integer hidden-association support pairs in best-first order.
- Parameters:
dist (IntegerHiddenAssociationDistribution)
- class IntegerPLSIEncodedData(value_ids, counts, entry_doc_ids, row_ids, totals, doc_ids, num_vals, num_docs)[source]
Bases:
objectOwned, validated flattened representation of canonical integer PLSI bags.
- class IntegerProbabilisticLatentSemanticIndexingEnumerator(dist)[source]
Bases:
DistributionEnumeratorBest-first enumerator for document-labelled integer PLSI bag observations.
- Parameters:
dist (IntegerProbabilisticLatentSemanticIndexingDistribution)
- multinomial_bag_stream(log_p_vec, min_val, len_dist, combine)[source]
Enumerate normalized integer count-vector bags in descending probability order.
Each fixed-size stream includes
log(n!) - sum_w log(c_w!). A real length law is required because a conditional multinomial law for every possible length has infinite total mass when joined without length probabilities.
- bag_stream(element_stream, len_dist, combine)[source]
Enumerate bags (multisets) drawn from a sorted element stream, in descending bag-score order.
element_streamis a descending(value, log_prob)iterator over the element distribution (any enumerable element distribution – a fixed categorical, or e.g. a per-document/per-given mixture). A bag scores by the sum of its elements’ log-probs pluslog P_len(n)fromlen_dist; bags enumerate by the per-size multiset best-first search (MultisetProductEnumerator) under a length frontier. Whenlen_distis Null there is no length term and a syntheticn*log p_maxfrontier orders the (countably infinite) support by the element term alone.combinemaps the tuple of(value, count)pairs to the emitted bag.
- class JointMixtureFisherView(dist)[source]
Bases:
MixtureFisherViewComplete-data Fisher view for joint mixtures without concrete proxies.
- Parameters:
dist (Any)
- property num_pairs: int
Number of positive-weight component pairs represented by this Fisher view.
- log_density(x)[source]
Evaluate the Fisher-view mixture log-density for one paired observation.
- class LabeledLDADistribution(topics, alphas, set_dist=None, len_dist=None, gamma_threshold=1.0e-8, max_gamma_iter=1000, fit_diagnostics=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLabeled LDA model for documents with label sets.
Compatible with data type Tuple[Sequence[Tuple[T, float]], Sequence[int]], where T is the data type of the topic distributions.
- density(x)[source]
Returns the density (exp of the variational lower bound) for a labeled document x.
- density_semantics()[source]
Return density semantics for the labeled-LDA variational bound.
- log_density(x)[source]
Returns the variational lower bound (ELBO) on the log-density for a labeled document x.
- seq_log_density(x)[source]
Vectorized evaluation of the variational lower bound (ELBO) for encoded documents.
Arg ‘x’ is the output of ‘LabeledLDADataEncoder.seq_encode()’.
- Parameters:
x – Encoded sequence of iid LabeledLDA observations (see LabeledLDADataEncoder.seq_encode()).
- Returns:
Numpy array with one lower-bound value per encoded document.
- seq_encode(x)[source]
Deprecated alias for
dist_to_encoder().seq_encode(): encode iid LabeledLDA observations.Use
dist_to_encoder()andLabeledLDADataEncoder.seq_encode()instead.
- seq_component_log_density(x)[source]
Vectorized per-topic log-density evaluation for encoded documents.
- Parameters:
x – Encoded sequence of iid LabeledLDA observations (see LabeledLDADataEncoder.seq_encode()).
- Returns:
2-d numpy array (num_documents by nTopics) of per-topic document log-densities.
- seq_posterior(x)[source]
Vectorized posterior topic weights for encoded documents.
- Parameters:
x – Encoded sequence of iid LabeledLDA observations (see LabeledLDADataEncoder.seq_encode()).
- Returns:
2-d numpy array (num_documents by nTopics) of normalized posterior topic weights.
- compute_capabilities()[source]
Return backend capability metadata for this concrete LabeledLDA instance.
- backend_seq_log_density(x, engine)[source]
Backend-neutral labeled-LDA joint variational lower-bound scoring.
- enumerator()[source]
Not supported: LabeledLDA’s
log_densityis a variational lower bound, not the true marginal.Each document’s score is an ELBO obtained by running per-document variational inference (
seq_posterior), not the exact marginal probability, so enumerating “in descending probability order” is ill-defined – the ELBO ranking need not match the true-probability ranking, and the per-document optimum isn’t a closed-form density over a countable support. Usesampler()and the (approximate)log_densitydirectly.- Return type:
DistributionEnumerator
- sampler(seed=None)[source]
Create a sampler for labeled LDA documents.
Note: Requires ‘set_dist’ and ‘len_dist’ to be set.
- Parameters:
seed (Optional[int]) – Set seed for random sampling.
- Returns:
Sampler bound to this distribution.
- Return type:
LabeledLDASampler
- estimator(pseudo_count=None)[source]
Create an estimator initialized from this labeled LDA distribution.
- Parameters:
pseudo_count (Optional[float]) – Used to re-weight sufficient statistics in estimation.
- Returns:
Estimator configured with matching topic estimators.
- Return type:
LabeledLDAEstimator
- dist_to_encoder()[source]
Return a data encoder for iid labeled LDA observations.
- class LabeledLDALabelSetStats(stats=None)[source]
Bases:
objectSufficient statistics for the coupled alpha update, grouped by distinct document label set.
Maps each distinct label set S (a sorted tuple of unique label indices) to a pair [n_S, m_S], where n_S is the total weight of the documents carrying label set S and m_S is the weighted sum of the per-document expected log topic weights E[log theta] (a vector with one entry per topic) over those documents.
- add(label_set, weight, sum_log_p)[source]
Accumulate document weight and summed expected log topic weights for one label set.
- combine(other)[source]
Merge the statistics of another LabeledLDALabelSetStats instance into this instance.
- Parameters:
other (LabeledLDALabelSetStats) – Statistics to merge in (left unmodified).
- Returns:
LabeledLDALabelSetStats object (self).
- copy()[source]
Returns a deep copy of the LabeledLDALabelSetStats instance.
- arrays()[source]
Returns the statistics as parallel arrays in sorted label-set order.
- Returns:
Tuple of the sorted label-set tuples (List[Tuple[int, …]]), the per-set weights n_S (1-d numpy array), and the per-set summed expected log topic weights m_S (2-d numpy array with one row per label set).
- class LabeledLDAEstimator(estimators, num_alphas, suff_stat=None, pseudo_count=None, keys=(None, None), fixed_alpha=None, gamma_threshold=1.0e-8, alpha_threshold=1.0e-8, max_gamma_iter=1000, max_alpha_iter=2000, set_dist=None, len_dist=None)[source]
Bases:
ParameterEstimatorEstimate labeled LDA distributions from aggregated sufficient statistics.
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- accumulatorFactory()[source]
Deprecated alias for accumulator_factory().
- estimate(nobs, suff_stat)[source]
Estimate a labeled LDA distribution from aggregated sufficient statistics.
suff_statis a tuple containing:suff_stat[0] (Optional[np.ndarray]): Previous alphas matrix. suff_stat[1] (LabeledLDALabelSetStats): Per-label-set expected log topic weights and counts. suff_stat[2] (Union[float, np.ndarray]): Per-label weighted document counts. suff_stat[3] (np.ndarray): Label-allocated weighted topic counts. suff_stat[4] (Sequence): Sufficient statistics for the topic distribution accumulators.
If ‘fixed_alpha’ is None, the alphas matrix is re-estimated by maximizing the coupled objective over all label rows (see ‘update_alpha_coupled()’). When every document carries exactly one label the objective decouples and the per-row fixed-point updates are used (see ‘update_alpha()’). Otherwise the alphas matrix is set to ‘fixed_alpha’.
- Parameters:
nobs (Optional[float]) – Number of observations used in estimation.
suff_stat – See above for details.
- Returns:
Estimated distribution.
- Return type:
LabeledLDADistribution
- doc_label_sets(nbx, nbcnt)[source]
Returns the sorted label-set tuple of each encoded document.
- Parameters:
nbx (np.ndarray) – Flattened array of label indices over all documents (document-contiguous).
nbcnt (np.ndarray) – Number of labels for each document.
- Returns:
List of sorted label-index tuples, one per document.
- coupled_alpha_objective(alpha, label_sets, set_counts, set_mean_logs)[source]
Coupled multi-label alpha objective (terms independent of alpha dropped).
F(alpha) = sum_S n_S * [ log Gamma(sum_k a_Sk) - sum_k log Gamma(a_Sk) + sum_k a_Sk * mbar_Sk ], where a_S = mean_{l in S} alpha[l], n_S = set_counts[S], and mbar_S = set_mean_logs[S] are the per-set mean expected log topic weights.
- Parameters:
alpha (np.ndarray) – Alphas matrix (num_alphas by num_topics).
label_sets (Sequence[Tuple[int, ...]]) – Label-set tuples.
set_counts (np.ndarray) – Per-set document weights n_S.
set_mean_logs (np.ndarray) – Per-set mean expected log topic weights mbar_S (one row per set).
- Returns:
Objective value F(alpha).
- coupled_alpha_gradient(alpha, label_sets, set_counts, set_mean_logs)[source]
Gradient of the coupled multi-label alpha objective with respect to alpha.
dF/d alpha[l,k] = sum_{S contains l} (n_S/|S|) * [ psi(sum_j a_Sj) - psi(a_Sk) + mbar_Sk ], with one term per occurrence of l in S.- Parameters:
alpha (np.ndarray) – Alphas matrix (num_alphas by num_topics).
label_sets (Sequence[Tuple[int, ...]]) – Label-set tuples.
set_counts (np.ndarray) – Per-set document weights n_S.
set_mean_logs (np.ndarray) – Per-set mean expected log topic weights mbar_S (one row per set).
- Returns:
Numpy 2-d array with the same shape as alpha.
- update_alpha_coupled(current_alpha, label_sets, set_counts, set_mean_logs, alpha_threshold, max_its=2000, *, return_diagnostics=False)[source]
Maximize the validated coupled label-row objective with bounded ascent.
- class LDAOptimizationDiagnostics(algorithm, converged, iterations, max_iterations, termination_reason, final_residual, objective_trace=(), residual_trace=(), impossible_documents=())[source]
Bases:
objectSerializable termination record for an LDA inner optimization.
- exception LDAConvergenceError(diagnostics)[source]
Bases:
RuntimeErrorRaised when an LDA inner optimization cannot meet its declared contract.
- Parameters:
diagnostics (LDAOptimizationDiagnostics)
- class LookbackHiddenMarkovModelDistribution(topics, w=MISSING, transitions=MISSING, lag=0, init_dist=None, len_dist=NullDistribution(), name=None, weights=MISSING, terminal_states=None, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionHidden Markov model whose state emissions condition on the previous
lagobservations.- Parameters:
- get_prior()[source]
Returns the chain conjugate prior in
(init_prior, row_priors)form (or None).Per-state emission/init component priors are owned by those distributions themselves – mirrors
get_prior().
- set_prior(prior)[source]
Set the conjugate Dirichlet chain prior over w/transitions and flag
has_conj_prior.Mirrors
set_prior()exactly (no digamma-expectation caching: this class has noexpected_log_densitycounterpart to feed).prior=Noneleaves the distribution a plain point model.- Parameters:
prior –
(init_prior, row_priors)tuple or None.- Return type:
None
- density(x)[source]
Evaluate the density of the distribution at sequence x.
- Parameters:
x (Sequence[T]) – Observed sequence.
- Returns:
Density at x.
- Return type:
- log_density(x)[source]
Evaluate the log-density of the distribution at sequence x.
Marginalizes the hidden state path with a scaled forward pass. The initial segment x[:lag] is scored by init_dist, each window x[t-lag:t+1] by the topic distributions, and the number of hidden positions by len_dist. When lag == 0 there is no initial segment: the first state emits the window x[0:1] directly (ordinary HMM).
- Parameters:
x (Sequence[T]) – Observed sequence with len(x) >= lag.
- Returns:
Log-density at x.
- Return type:
- viterbi_sequence(x)[source]
Compute the most likely hidden state sequence for observed sequence x.
- Parameters:
x (Sequence[T]) – Observed sequence with len(x) >= lag.
- Returns:
- Integer array of len(x) - lag + 1 (len(x) when lag == 0) most likely hidden
state indices.
- Return type:
np.ndarray
- seq_log_density(x)[source]
Vectorized evaluation of the log-density at encoded sequences x.
- Parameters:
x – Encoded sequence data produced by seq_encode() / dist_to_encoder().
- Returns:
Log-density value for each encoded sequence.
- Return type:
np.ndarray
- compute_capabilities()[source]
Return backend capability metadata for this concrete lookback-HMM instance.
- backend_seq_log_density(x, engine)[source]
Engine-neutral lookback-HMM scoring via the shared HMM forward pass.
- seq_posterior(x)[source]
Compute posterior hidden state probabilities for encoded sequences x.
- Parameters:
x – Encoded sequence data produced by seq_encode() / dist_to_encoder().
- Returns:
- For each sequence, an array of per-position posterior state
probabilities with shape (num_windows, num_states).
- Return type:
List[np.ndarray]
- density_semantics()[source]
Return exact-or-approximate density semantics joined from child models.
- sampler(seed=None)[source]
Create a LookbackHiddenMarkovModelSampler for this distribution.
- Parameters:
seed (Optional[int]) – Seed for random number generator.
- Returns:
Sampler object (requires a non-null len_dist).
- Return type:
LookbackHiddenMarkovModelSampler
- enumerator()[source]
Not supported: lookback emissions condition on the previous
lagobservations.Unlike the standard / segmental HMM, each emission depends on the preceding
lagsymbols, so the effective state is(hidden_state, last lag observations). Best-first enumeration over that augmented (and, for large/continuous alphabets, unbounded) state space is not implemented; usesampler()or the exactlog_density/viterbi_sequenceinstead.- Return type:
DistributionEnumerator
- estimator(pseudo_count=None)[source]
Create a LookbackHiddenMarkovModelEstimator from this distribution.
- Parameters:
pseudo_count (Optional[float]) – Regularize the initial-state and transition estimates.
- Returns:
- Estimator built from the topic, initial-segment, and
length distributions, preserving the lag.
- Return type:
LookbackHiddenMarkovModelEstimator
- seq_encode(x)[source]
Encode a sequence of observed sequences for vectorized
seq_calls.- Parameters:
x (Sequence[Sequence[T]]) – Sequence of iid observed sequences.
- Returns:
Encoded data consistent with seq_log_density(), seq_posterior(), and seq_update().
- dist_to_encoder()[source]
Return a LookbackHiddenMarkovModelDataEncoder for encoding sequences of iid observations.
- Returns:
- Encoder built from the topic, initial, and length
distributions of this instance.
- Return type:
LookbackHiddenMarkovModelDataEncoder
- class LookbackHiddenMarkovModelEstimator(estimators, lag=0, init_estimators=None, len_estimator=NullEstimator(), suff_stat=None, pseudo_count=(None, None), name=None, keys=(None, None, None), terminal_states=None, prior=None)[source]
Bases:
ParameterEstimatorEstimator for a lookback hidden Markov model from aggregated sufficient statistics.
- Parameters:
- get_prior()[source]
Returns the chain conjugate prior in
(init_prior, row_priors)form (or None).Mirrors
get_prior().
- set_prior(prior)[source]
Set the conjugate Dirichlet chain prior and flag whether it admits the conjugate update.
Mirrors
set_prior()exactly.- Parameters:
prior –
(init_prior, row_priors)tuple or None; has_conj_prior is set when both the initial-state prior and all row priors are Dirichlet.- Return type:
None
- model_log_density(model)[source]
Log-density of the model parameters under the priors (ELBO global term).
Sums the Dirichlet log-densities of the initial-state and transition probabilities (when a conjugate chain prior is set) plus each topic/init-segment estimator’s own
model_log_densityof its fitted distribution. Mirrorsmodel_log_density()(which does not include its ownlen_estimatoreither – kept at parity here rather than widening scope beyond the sibling class).- Parameters:
model (LookbackHiddenMarkovModelDistribution) – Model to score.
- Returns:
Prior log-density of the model parameters.
- Return type:
- accumulator_factory()[source]
Create a LookbackHiddenMarkovModelEstimatorAccumulatorFactory from the member estimators.
- Returns:
- Factory for accumulators consistent
with this estimator.
- Return type:
LookbackHiddenMarkovModelEstimatorAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a LookbackHiddenMarkovModelDistribution from aggregated sufficient statistics.
- Parameters:
nobs (Optional[float]) – Weighted number of observations (passed to the length estimator).
suff_stat (Tuple) – Sufficient statistics in the format returned by LookbackHiddenMarkovModelEstimatorAccumulator.value().
- Returns:
M-step estimate of the distribution.
- Return type:
LookbackHiddenMarkovModelDistribution
- validated_state_ids(values, n_states, *, context, field)[source]
Return exact in-range state IDs without lossy integer coercion.
- validated_terminal_states(values, n_states, *, context)[source]
Return exact in-range terminal state IDs without lossy integer coercion.
- validated_terminal_values(values, *, context)[source]
Return an owned non-empty set of terminal emissions.
- validate_terminal_reachability(initial, transitions, terminal_states, *, context)[source]
Require every initially reachable state to have a positive-probability path to termination.
- validated_terminal_step_cap(value)[source]
Return an exact positive stopping-time sampling bound.
- require_terminal_reached(reached, *, mode, max_steps, last_state=None)[source]
Raise the typed bounded-sampling failure when the stop event was not reached.
- class MixtureFisherView(dist)[source]
Bases:
FixedFisherViewComplete-data Fisher view for finite mixture distributions.
Coordinates are component assignment indicators followed by each component’s sufficient statistics gated by that assignment. Observed data map to posterior-expected complete-data statistics.
- Parameters:
dist (Any)
- class ProbabilisticCircuitStatistics(sum_counts, leaf_statistics, leaf_counts, observation_mass, schema_version=1)[source]
-
Mass-aware circuit statistics with backward two-slot iteration.
- leaf(scope, dist)[source]
A leaf node: an existing mixle
distover the variable indicesscope(an int or a tuple).
- prod(children)[source]
A product node over children with PAIRWISE-DISJOINT scopes (the decomposability requirement).
- Parameters:
children (list[_Node])
- Return type:
_Node
- summ(children, w=None)[source]
A sum (mixture) node over children that share ONE scope (smoothness);
ware mixing weights.
- class ProbabilisticCircuitDistribution(root, num_vars, lns_step=None)[source]
Bases:
SequenceEncodableProbabilityDistributionA sum-product network density; build with
leaf()/prod()/summ()then pass the root.- log_density(x)[source]
Return the log-density of one full observation by an upward circuit pass.
- seq_log_density(x)[source]
Return vectorized log-densities for encoded observations.
- dist_to_encoder()[source]
Return the encoder that projects observations into each leaf scope.
- Return type:
ProbabilisticCircuitEncoder
- sampler(seed=None)[source]
Return an ancestral sampler for this fixed circuit.
- Parameters:
seed (int | None)
- Return type:
ProbabilisticCircuitSampler
- estimator(pseudo_count=None)[source]
Return an EM estimator for this fixed circuit structure.
- class ProbabilisticCircuitEncoder(leaf_dists, leaf_scope)[source]
Bases:
DataSequenceEncoderEncode each leaf’s projected columns once with the leaf’s own encoder (shared across EM iterations).
- seq_encode(x)[source]
Encode a batch for every leaf distribution using its projected scope.
- class ProbabilisticCircuitEstimator(dist, pseudo_count=None)[source]
Bases:
ParameterEstimatorFits a fixed-structure circuit by EM: renormalize each sum node’s weights to its expected child counts, and re-estimate each leaf from its responsibility-weighted sufficient statistic.
- Parameters:
dist (ProbabilisticCircuitDistribution)
pseudo_count (float | None)
- accumulator_factory()[source]
Return a factory for circuit-flow sufficient-statistic accumulators.
- Return type:
ProbabilisticCircuitAccumulatorFactory
- class QuantizedHMMFitDiagnostics(converged, fixed_theta, theta, objective, iterations_per_start, converged_starts, termination_reasons, selected_start, selected_start_converged, scalar_optimizer_evaluations, split_count, schema_version=1, algorithm='multistart_coordinate_ascent')[source]
Bases:
objectImmutable convergence and provenance record for one quantized M-step.
- exception QuantizedHMMOptimizationError(message, diagnostics)[source]
Bases:
RuntimeErrorRaised when the quantized coordinate or scalar optimization fails.
- Parameters:
message (str)
diagnostics (QuantizedHMMFitDiagnostics)
- Return type:
None
- class PhaseSchedule[source]
Bases:
objectMaps a position
tin a length-Lsequence to a phase index in[0, n_phases).- phase(t, length)[source]
Return the phase index for position
tin a sequence oflength.
- to_dict()[source]
Serialize the schedule to a JSON-compatible dictionary.
- class SemiSupervisedHiddenMarkovModelDistribution(topics, transitions, len_dist=None, name=None, keys=None, use_numba=None, terminal_states=None)[source]
Bases:
SequenceEncodableProbabilityDistributionHMM with shared emissions/transitions where each observation may carry a per-position state prior.
- compute_capabilities()[source]
Declare the legacy NumPy execution path for semi-supervised HMM inference.
- density(x)[source]
Return the probability of one semi-supervised HMM observation.
- Return type:
- log_density(x)[source]
Return the log-likelihood of one
(emissions, state_prior)observation.- Return type:
- seq_log_density(x)[source]
Return vectorized log-likelihoods for encoded semi-supervised HMM observations.
- Return type:
- density_semantics()[source]
Return the joined density semantics of emission and optional length distributions.
- sampler(seed=None)[source]
Return a sampler for emission sequences with no external state priors.
- estimator(pseudo_count=None)[source]
Return a Baum-Welch estimator for transitions, emissions, and optional length.
- dist_to_encoder()[source]
Return the encoder for emission sequences, priors, and optional lengths.
- class SemiSupervisedHiddenMarkovEstimator(estimators, len_estimator=None, pseudo_count=None, name=None, keys=(None, None), terminal_states=None)[source]
Bases:
ParameterEstimatorEstimate transitions, emissions, and optional length from semi-supervised HMM statistics.
- accumulator_factory()[source]
Return a factory for semi-supervised HMM sufficient-statistic accumulators.
- estimate(nobs, suff_stat)[source]
Estimate the HMM transition matrix and child distributions from accumulated statistics.
- SemiSupervisedHiddenMarkovModelEstimator
alias of
SemiSupervisedHiddenMarkovEstimator
- class SparseScore(lower, upper, exact, n_scored)[source]
Bases:
objectA certified bracket on a mixture’s
log p(x)from scoring only the top components.lower <= log p(x) <= upperalways holds;exactis True when the bracket collapsed (all components scored, ormax_componentscovered the support).n_scoredcomponents were exactly evaluated. Whenexact,lower == upper == log p(x).
- log_density_sup(dist)[source]
Maximum
log p(x)of a single distribution, orNoneif unbounded / unknown.A finite value certifies the component can contribute at most this much, which is what makes the dropped-tail bound sound.
None(unbounded density or an unrecognized family) forces the exact path.
- sparse_mixture_score(mixture, x, max_components)[source]
Score
mixture.log_density(x)exactly on the topmax_componentsand certify the rest.Ranks components by the low-cost upper bound
log w_k + sup_k(x-independent), scores the exact contribution of only the top ones, and bounds the dropped tail by the remaining upper bounds. Returns aSparseScorebracket. If any positive-weight component’s density is unbounded (log_density_supisNone), falls back to exact full scoring (lower == upper, no speedup).
- collapse_identical(mixture)[source]
Merge components that are identical (same family + parameters) by summing their weights – EXACT.
A fitted huge mixture often carries duplicate components; pooling exact duplicates leaves
log p(x)unchanged while shrinking K. Identity requires the same fully qualified family and canonical serialized state. A component that cannot produce that representation is conservatively left separate. ‘Blend a mixture of closed forms’ with zero approximation.
- collapse_gaussian_mixture(mixture, max_components)[source]
Reduce an all-Gaussian mixture to
<= max_componentsby moment-matching the nearest pair.Greedily merges the two closest components (by mean) into the single Gaussian preserving their combined weight, mean, and variance, until
max_componentsremain. Approximate (it widens), but it preserves the OVERALL mixture mean and variance exactly – the analytic ‘collapse a huge mixture of closed forms’ that lets scoring/sampling scale.
- class FinalStateEnumeration(hmm, len_dist)[source]
Bases:
objectResult of
_final_state_enumerate():top_k(k)-> [(sequence, log_prob), …] descending.- top_k(k)[source]
Return the top
kfinal-state-constrained sequences.
- class IOHMMEstimator(emission_estimators, transition_protos, name=None)[source]
Bases:
ParameterEstimatorEstimator (M-step) for an
InputOutputHMM: re-estimates pi, one transition operator per input symbol (from the per-input expected counts), and each state’s emission.- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- estimate(nobs, suff_stat)[source]
Estimate an IOHMM from Baum-Welch sufficient statistics.
- class EDHMMEstimator(emission_estimators, k, d, name=None)[source]
Bases:
ParameterEstimatorEstimator (M-step) for an
ExplicitDurationHMM: re-estimates pi, the zero-diagonal transition, the per-state DURATION distributions, and each state’s emission from the segment-posterior statistics.- accumulator_factory()[source]
Return the accumulator factory used by this estimator.
- estimate(nobs, suff_stat)[source]
Estimate an explicit-duration HMM from segment posterior statistics.
- chunked_state_posteriors(hmm, seq, *, chunk, overlap)[source]
State posteriors gamma for one long sequence via overlapping chunks, each run INDEPENDENTLY (embarrassingly parallel). The first chunk uses the model’s pi; interior chunks start from the uniform belief and the
overlapcontext lets the chain forget that wrong boundary – so the kept interior matches the exact forward-backward up to an error that decays at the mixing rate inoverlap.
- fit_chunked(hmm, seqs, *, chunk, overlap, max_its=50, workers=0, tol=1e-6, weights=None)[source]
Baum-Welch where each long sequence’s forward-backward is split into overlapping chunks run in PARALLEL (the forgetting property bounds the boundary error).
workers>0runs the per-chunk E-steps on a thread pool (NumPy releases the GIL in its array kernels);workers=0runs them serially. The interior suff-statistics are accumulated exactly as inStructuredHMM.fit(); this only changes how the E-step is computed, trading a small, overlap-controlled approximation for intra-sequence parallelism. The returnedHMMFitResultremains unpackable as(fitted_hmm, loglik_trace)and marks the receipt’s objective as approximate.
- find_level(parents)[source]
Find the level in the tree for nodes, given an array of parents.
- level_state_prob(levels, num_states, tr_mat, init_prob, out)[source]
Numba kernel: marginal state probabilities per tree level, out[k] = init_prob @ tr_mat^k.
- closure(x, total=1.0)[source]
Normalize strictly positive finite rows to a positive finite total.
- clr(x)[source]
Return centered logratios for strictly positive finite compositions.
- clr_inv(y)[source]
Map finite clr-coordinate rows to the unit simplex.
- ilr(x, basis=None)[source]
Map strictly positive
D-part rows toD-1ilr coordinates.
- ilr_inv(y, basis=None)[source]
Map finite
D-1ilr rows to strictly positive unit compositions.
- ilr_basis(d)[source]
Return the Helmert
(D, D-1)orthonormal contrast basis.
- class AitchisonNormalDistribution(mean, cov, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionLogratio-normal density on ordinary unit-simplex coordinates.
- property mean: ndarray
Return the Gaussian mean in ilr coordinates.
- property cov: ndarray
Return the Gaussian covariance in ilr coordinates.
- density(x)[source]
Return ordinary-coordinate simplex density.
- log_density(x)[source]
Return density relative to the first
D-1simplex coordinates.
- seq_log_density(x)[source]
Score an encoded
(ilr coordinates, log Jacobian)payload.
- sampler(seed=None)[source]
Return a push-forward sampler from the ilr Gaussian.
- Parameters:
seed (int | None)
- Return type:
AitchisonNormalSampler
- estimator(pseudo_count=None)[source]
Return an estimator preserving keys and optional current-model smoothing.
- Parameters:
pseudo_count (float | None)
- Return type:
AitchisonNormalEstimator
- dist_to_encoder()[source]
Return a fixed-width composition encoder.
- Return type:
AitchisonNormalDataEncoder
- class AitchisonNormalEstimator(dim=None, pseudo_count=None, suff_stat=(None, None), name=None, keys=None)[source]
Bases:
ParameterEstimatorFit a Gaussian in ilr coordinates with explicit smoothing and keys.
- Parameters:
- accumulator_factory()[source]
Return a keyed accumulator factory delegated to the Gaussian estimator.
- Return type:
StatisticAccumulatorFactory
- class MultinomialEncodedData(indices, inverse_totals, nonzero_totals, encoded_values, encoded_lengths, counts, totals, len_normalized)[source]
Bases:
objectValidated sparse multinomial batch representation.
- class MultinomialFisherView(dist)[source]
Bases:
SequenceFisherViewFisher view for bag/count observations with a count-weighted child model.
The model Fisher uses the canonical multinomial/count sufficient-statistic moments that match estimation. The multinomial coefficient is a base-measure term, not an accumulator statistic.
- Parameters:
dist (Any)
- class DirichletMultinomialEnumerator(dist, *, max_recurrence_cells=_DEFAULT_MAX_RECURRENCE_CELLS, max_frontier_entries=_DEFAULT_MAX_FRONTIER_ENTRIES)[source]
Bases:
DistributionEnumeratorEnumerate Dirichlet-multinomial count vectors in descending probability order, lazily (A* best-first).
The log-mass separates per category:
log P(x) = log_const + sum_k f_k(x_k)withf_k(c) = gammaln(c + alpha_k) - gammaln(alpha_k) - gammaln(c + 1), and eachf_kis monotone inc(increasing foralpha_k > 1, decreasing foralpha_k < 1), so a prefix assignment(x_1..x_j)withmtrials left admits the admissible completion boundsum_{k>j} max(f_k(0), f_k(m)). A* on the exact prefix score plus that bound streams count vectors in exact descending order without materializing theC(n+K-1, K-1)support.
- class DirichletMultinomialFitReceipt(algorithm, converged, identifiable, iterations, objective_history, max_delta, regularized_categories, concentration_floor)[source]
Bases:
objectMachine-readable evidence about a concentration fixed-point fit.
- exception DirichletMultinomialResourceError[source]
Bases:
RuntimeErrorRaised before a configured enumeration or fitting resource budget is exceeded.
- class DiagonalGaussianFisherView(dist)[source]
Bases:
FixedFisherViewFisher view over per-dimension first and second moments for a diagonal Gaussian.
- Parameters:
dist (Any)
- class MultivariateGaussianFisherView(dist)[source]
Bases:
FixedFisherViewFisher view over first and upper-triangular second moments for a full Gaussian.
- Parameters:
dist (Any)
- exception VinePairFitError[source]
Bases:
RuntimeErrorRaised when no requested pair-copula family can be fitted on an edge.
- class PairCandidateEvidence(family, parameter_count, weighted_log_likelihood, aic, fit_error)[source]
Bases:
objectOne candidate’s training evidence and complexity-adjusted AIC value.
- class PairSelectionReceipt(schema_version, criterion, edge_context, selected_family, total_weight, evidence)[source]
Bases:
objectAuditable per-edge model-selection receipt.
- LogNormalDistribution
alias of
LogGaussianDistribution
- LogNormalEstimator
alias of
LogGaussianEstimator