mixle.contracts module

mixle.contracts — every contract (ABC / Protocol) in one import.

The capability vocabulary was correct but spread across several modules (capability, pdist, relations, engines.base, planner, utils.em, doe._contracts). This module gathers them so the whole contract surface has one home:

from mixle.contracts import Distribution, Enumerable, Conditionable, Relation, ComputeEngine, Surrogate, EMStrategy

The light contracts (the object cast + the capability protocols) are imported eagerly; the heavier subsystem roles are resolved lazily (PEP 562 __getattr__) so this stays a lightweight leaf import with no cycles. See docs/ARCHITECTURE.md.

Distribution

alias of SequenceEncodableProbabilityDistribution

class DistributionSampler(dist, seed=None, *, rng=None)[source]

Bases: ABC

Draws iid observations from a distribution using a seeded RandomState.

sample(size=None) returns a single observation of the distribution’s data type; sample(size=n) returns a length-n collection of observations.

Parameters:
  • dist (SequenceEncodableProbabilityDistribution)

  • seed (int | None)

  • rng (RandomState | None)

new_seed()[source]

Return a fresh random seed drawn from this sampler’s RandomState.

Return type:

int

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

Draw observations.

Combinator samplers (mixture/sequence/…) accept batched. With batched=True (the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independent RandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path. batched=False forces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.

Parameters:
Return type:

Any

class ConditionalSampler[source]

Bases: ABC

Sampler mixin for conditional draws: sample_given(x) draws from P(. | x).

abstractmethod sample_given(x)[source]

Draw a sample from the conditional distribution given x.

class DistributionEnumerator(dist)[source]

Bases: ABC

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

Parameters:

k (int)

Return type:

list[tuple[Any, float]]

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.95 gives a 95%-coverage support set – the discrete analogue of nucleus sampling). Accumulation stops as soon as the cumulative probability reaches p.

max_items caps 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-compatible NucleusResult reports whether the target was reached, the accumulated mass, and whether a cap stopped the search.

Parameters:
  • p (float) – Target cumulative probability in [0, 1].

  • max_items (Optional[int]) – Hard cap on the number of values pulled.

Returns:

A list-compatible nucleus result with termination provenance.

Return type:

NucleusResult

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.

Parameters:
  • max_bits (float) – Maximum information content in bits to index.

  • bin_width_bits (float) – Width of each quantized probability bin in bits.

Returns:

mixle.enumeration.algorithms.QuantizedEnumerationIndex.

rank(value)[source]

Rank and cumulative probability of value in the descending-probability order.

Returns a DensityRankResult with .rank (0-based count of strictly-more-probable outcomes; None if 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 of rank().

Returns a CountDPSeekResult carrying 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 index with 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’s tropical_displacement_bits and divides out the component over-count, so the returned MarginalSeekResult [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 with seek().

Parameters:

index (int)

cumulative(value)[source]

G(value) = P(p(Y) >= p(value)) – total mass of outcomes at least as probable as value.

Returns a CumulativeProbabilityResult with .probability plus 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 CountDPTopPResult with 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 structural start.

Yields the same stream as iterating a fresh enumerator but beginning at index start (and ending before stop if given). A fresh underlying enumeration is used, so this does not consume self. (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.)

Parameters:
  • start (int)

  • stop (int | None)

class ParameterEstimator[source]

Bases: ABC, Generic[SS]

Estimates a distribution from accumulated sufficient statistics.

accumulator_factory() supplies accumulators that gather sufficient statistics of type SS, and estimate(nobs, suff_stat) maps those statistics (plus optional regularization configured on the estimator) to a new distribution.

to_dict()[source]

Return a safe JSON-compatible representation of this estimator.

Return type:

dict[str, Any]

classmethod from_dict(payload)[source]

Reconstruct an estimator from to_dict output.

Parameters:

payload (dict[str, Any])

Return type:

ParameterEstimator

to_json(**kwargs)[source]

Serialize this estimator as safe strict JSON.

Parameters:

kwargs (Any)

Return type:

str

classmethod from_json(text)[source]

Deserialize an estimator from to_json output.

Parameters:

text (str)

Return type:

ParameterEstimator

abstractmethod estimate(nobs, suff_stat)[source]

Estimate a distribution from accumulated sufficient statistics.

Parameters:
  • nobs (float | None)

  • suff_stat (SS)

Return type:

SequenceEncodableProbabilityDistribution

abstractmethod accumulator_factory()[source]

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

Return type:

StatisticAccumulatorFactory

resident_accumulation_supported()[source]

Return whether engine-resident (fixed-width) sufficient statistics suffice for estimate.

Most exponential-family M-steps consume only the resident sufficient statistics, so the default is True. Estimators whose M-step needs more than that (e.g. a full count histogram for the negative-binomial dispersion solve) override this to False so stacked/generated kernels fall back to the host accumulator, keeping every backend’s fixed point identical.

Return type:

bool

get_prior()[source]

Return the parameter prior configured on this estimator, if any.

The unified estimation contract treats the prior as the single regularization concept: None gives maximum likelihood, a conjugate prior gives the Bayesian posterior update inside estimate. The default reads the prior attribute (None when unset).

Return type:

ProbabilityDistribution | None

model_log_density(model)[source]

Return the prior log-density of model’s parameters (the ELBO global term).

Used by the variational/MAP objective in fit. The default is 0.0 (no prior); conjugate estimators override this to evaluate their prior at the model’s parameters, mapping to the prior’s parameterization first.

Parameters:

model (ProbabilityDistribution)

Return type:

float

class StatisticAccumulator[source]

Bases: ABC, Generic[SS]

Accumulates weighted sufficient statistics of type SS from observations.

update(x, weight, estimate) adds one observation (estimate is the previous model, used for E-step posteriors; it may be None during initialization). Accumulators merge across partitions via combine(suff_stat) / value() / from_value(), and key_merge / key_replace pool statistics shared across model components through a stats_dict keyed by the accumulator’s key.

update(x, weight, estimate)[source]

Accumulate one weighted observation under an optional current estimate.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize sufficient statistics from one weighted observation.

Parameters:
Return type:

None

abstractmethod combine(suff_stat)[source]

Merge serialized sufficient statistics into this accumulator.

Parameters:

suff_stat (SS)

Return type:

StatisticAccumulator

abstractmethod value()[source]

Return this accumulator’s serialized sufficient statistics.

Return type:

SS

abstractmethod from_value(x)[source]

Restore this accumulator from serialized sufficient statistics.

Parameters:

x (SS)

Return type:

SequenceEncodableStatisticAccumulator

scale(c)[source]

Scale linear sufficient statistics in-place by c.

The structural default is correct for ordinary weighted sums, nested tuples/lists/dicts, and numeric arrays. Families whose value() payload includes non-linear metadata such as support bounds must override this method and leave that metadata unscaled.

Parameters:

c (float)

Return type:

StatisticAccumulator

key_merge(stats_dict)[source]

Pool this accumulator’s statistics into stats_dict under its merge key.

The structural default implements the common single-key pattern: store the accumulator under self.keys the first time the key is seen, else combine into the one already there. Accumulators whose key does not cover their whole state (several named keys, a wrapped child accumulator, a non-accumulator payload) override this – and ONLY those: as of 2026-07-14 every whole-state family uses this default, after a sweep found sixteen hand-rolled copies that had drifted into three broken shapes. If you are tempted to reimplement this per family, don’t; extend the base or override with super() calls. A keys of None (the default) is a no-op.

Why this exact shape is correct – and the drifted shapes are not: the POOL must live in the dict. Combining INTO the dict-held accumulator (below) mutates the pool in place, so after all sites merge, the dict entry holds everyone’s statistics and key_replace hands that pool to every site. The observed broken variants each violate one half: pulling the dict’s stats into self without writing back (the dict keeps the FIRST site only – later sites’ data silently discarded); merging only when the key is already present (nobody ever inserts: both passes are no-ops and tying does nothing); and replacing by pushing self INTO the dict (the LAST site overwrites the pool). The keyed-protocol sweep (keyed_protocol_sweep_test.py) enforces this behaviorally for every catalog family.

Parameters:

stats_dict (dict[str, Any])

Return type:

None

key_replace(stats_dict)[source]

Replace this accumulator’s statistics from the pooled stats_dict entry (see key_merge).

Parameters:

stats_dict (dict[str, Any])

Return type:

None

class SequenceEncodableStatisticAccumulator[source]

Bases: StatisticAccumulator[SS]

StatisticAccumulator with vectorized updates on encoded data sequences.

seq_update / seq_initialize consume the output of the matching DataSequenceEncoder’s seq_encode() (obtained via acc_to_encoder()) together with a per-observation weight vector.

get_seq_lambda()[source]

Return optional low-level sequence-update kernels used by generated code.

abstractmethod seq_update(x, weights, estimate)[source]

Accumulate weighted sufficient statistics from sequence-encoded observations.

Parameters:

weights (ndarray)

Return type:

None

abstractmethod seq_initialize(x, weights, rng)[source]

Initialize sufficient statistics from sequence-encoded observations.

Parameters:
Return type:

None

abstractmethod acc_to_encoder()[source]

Return a sequence encoder compatible with this accumulator.

Return type:

DataSequenceEncoder

class StatisticAccumulatorFactory[source]

Bases: ABC

Factory whose make() returns a fresh, zeroed accumulator for one estimator.

abstractmethod make()[source]

Create a fresh accumulator instance.

Return type:

SequenceEncodableStatisticAccumulator

class DataSequenceEncoder[source]

Bases: ABC

Encodes an iid data sequence into the vectorized form used by seq_* methods.

seq_encode(x) transforms a sequence of observations into the encoding consumed by seq_log_density / seq_update / seq_initialize. Encoders must define __eq__ (so equivalent encoders are interchangeable when batching) and a readable __str__.

seq_encode(x)[source]

Encode the iid observation sequence x for vectorized evaluation.

Parameters:

x (Any)

Return type:

Any

nbytes(x)[source]

Return the approximate in-memory byte size of an encoded payload.

Parameters:

x (Any)

Return type:

int

row_count(x)[source]

Return the number of observations represented by x.

The default covers simple array/list encodings and structurally aligned tuples/dicts. Encoders with flattened, ragged, or otherwise specialized layouts must override this method so metadata wrappers can verify counts instead of trusting a caller assertion.

Parameters:

x (Any)

Return type:

int

class Enumerable[source]

Bases: PredicateCapability

Its support can be iterated in descending-probability order (enumerator() works).

classmethod check(obj)[source]

Return whether obj exposes a supported enumerator.

Parameters:

obj (Any)

Return type:

bool

class FiniteSupport[source]

Bases: PredicateCapability

Has a finite number of distinct support points (support_size() is an int).

classmethod check(obj)[source]

Return whether obj reports a finite, non-negative support size.

A Boolean is not a support count even though bool subclasses int: support_size() returning True used to certify a one-point support, so an object answering a yes/no question was routed as an enumerable finite distribution.

Parameters:

obj (Any)

Return type:

bool

class RankableByIndex[source]

Bases: PredicateCapability

Supports random access by integer rank (unranking) via the count-budget seek index.

Finite-support enumerables are rankable by index through the count-DP semiring; the implication edge finite ==> enumerable ==> rankable is exactly this composition. (Decomposable combinators over infinite-but-countable children are also rankable structurally; this conservative check covers the finite-leaf case used by the dispatch layers.)

classmethod check(obj)[source]

Return whether obj can be unranked by finite support index.

Parameters:

obj (Any)

Return type:

bool

class ExponentialFamily[source]

Bases: PredicateCapability

Declares an exponential-family form (generated stacked kernels + conjugate estimation).

classmethod check(obj)[source]

Return whether obj declares an exponential-family form.

Parameters:

obj (Any)

Return type:

bool

class ConjugateUpdatable[source]

Bases: PredicateCapability

Has a closed-form conjugate Bayesian update (the top tier of the inference ladder).

supports(x, ConjugateUpdatable) is True iff conjugate_posterior(x, data) returns an exact closed-form posterior; otherwise Bayesian inference falls back to the numerical fitters (MAP / Laplace / MCMC / VI). Detection is the single conjugate_posterior registry.

classmethod check(obj)[source]

Return whether obj has a registered closed-form conjugate update.

Parameters:

obj (Any)

Return type:

bool

class Conditionable(*args, **kwargs)[source]

Bases: Protocol

Supports conditioning on a subset of coordinates: condition(observed) -> distribution.

condition(observed)[source]

Return the conditional distribution after fixing the indexed coordinates in observed.

Parameters:

observed (dict[int, float])

Return type:

Any

class Marginalizable(*args, **kwargs)[source]

Bases: Protocol

Supports marginalising to a subset of coordinates: marginal(keep) -> distribution.

marginal(keep)[source]

Return the distribution over the coordinates or fields identified by keep.

Parameters:

keep (Any)

Return type:

Any

class LatentStructured(*args, **kwargs)[source]

Bases: Protocol

Exposes an explicit latent posterior q(z|x): latent_posterior(x) -> LatentPosterior.

latent_posterior(x)[source]

Return the inferred latent-state posterior for observation x.

Parameters:

x (Any)

Return type:

Any

class PosteriorPredictive(*args, **kwargs)[source]

Bases: Protocol

Can draw/score new data conditioned on an observation’s inferred latent state.

posterior_predictive(*args, **kwargs)[source]

Return the posterior-predictive distribution or sample representation for the supplied context.

Parameters:
Return type:

Any

class TemporalPointProcess(*args, **kwargs)[source]

Bases: Protocol

An event-time point process exposing its conditional intensity and compensator.

intensity(t, times, marks=None) is the conditional rate lambda(t) given the history; the univariate Hawkes / inhomogeneous-Poisson leaves return a float, the multivariate variant a per-mark vector. expected_count(t_start, t_end, times, marks=None) is the integrated intensity (compensator) over the window. (Birth-death is a population process, not an intensity-based point process, and is intentionally excluded.)

intensity(t, times, marks=None)[source]

Return the conditional event intensity at time t given the observed history.

Parameters:
Return type:

Any

expected_count(t_start, t_end, times, marks=None)[source]

Return the integrated intensity over [t_start, t_end] given the observed history.

Parameters:
Return type:

Any

class SetValued[source]

Bases: PredicateCapability

A distribution over sets with forced/required membership (required / num_required).

classmethod check(obj)[source]

Return whether obj exposes set-valued membership metadata.

Parameters:

obj (Any)

Return type:

bool

class Neutral[source]

Bases: PredicateCapability

The identity / no-op element of a combinator (a Null distribution, accumulator, or encoder).

classmethod check(obj)[source]

Return whether obj is a recognized null or identity value.

Parameters:

obj (Any)

Return type:

bool

class Transform(*args, **kwargs)[source]

Bases: Protocol

A contract-declared invertible change of variables with a tractable Jacobian.

forward(x)[source]

Map values from the base space into the transformed space.

Parameters:

x (Any)

Return type:

Any

inverse(y)[source]

Map values from the transformed space back into the base space.

Parameters:

y (Any)

Return type:

Any

log_abs_det_inverse_jacobian(y)[source]

Return log |det d inverse(y) / dy| for density correction.

Parameters:

y (Any)

Return type:

float

invalid_inverse_value()[source]

Return an in-domain fill value used to encode rejected observations safely.

Return type:

Any

class EngineResidentEStep(*args, **kwargs)[source]

Bases: Protocol

An accumulator that can run its E-step on the active compute engine without leaving it.

seq_update_engine(enc, weights, estimate, engine)[source]

Update sufficient statistics from encoded data resident on engine.

Parameters:
Return type:

None

class SupportsBackendScoring(*args, **kwargs)[source]

Bases: Protocol

A distribution that can score a batch directly on the active engine (backend_seq_log_density).

backend_seq_log_density(x, engine)[source]

Return per-row log densities for encoded data already resident on engine.

Parameters:
Return type:

Any

class SupportsBackendComponentScoring(*args, **kwargs)[source]

Bases: Protocol

A distribution that exposes per-component engine scoring (backend_seq_component_log_density).

backend_seq_component_log_density(x, engine)[source]

Return per-row, per-component log densities on engine.

Parameters:
Return type:

Any

class SupportsStackedBackend(*args, **kwargs)[source]

Bases: Protocol

A component type that can score/parameterise a homogeneous stack on the engine.

backend_stacked_params(dists, engine)[source]

Pack homogeneous component parameters into an engine-native stacked representation.

Parameters:
Return type:

Any

backend_stacked_log_density(x, params, engine)[source]

Score encoded data against a stacked parameter representation on engine.

Parameters:
Return type:

Any

class PredicateCapability[source]

Bases: object

Base for capabilities determined by inspecting the object rather than a method name.

classmethod check(obj)[source]

Return whether obj satisfies this capability predicate.

Parameters:

obj (Any)

Return type:

bool

class Relation[source]

Bases: ABC

A constraint over a structured space whose members are enumerated ranked by a residual.

Subclasses implement enumerator() (yielding Solution items); solve(), top() and iteration come for free. sense is "min" (residual minimized, members out in increasing cost) or "max" (residual maximized, members out in decreasing score).

abstractmethod enumerator(k=None)[source]

Lazily yield Solution items best-first; at most k if given (None = all).

Parameters:

k (int | None)

Return type:

Iterator[Solution]

solve()[source]

The single optimal Solution, or None if the problem is infeasible.

Return type:

Solution | None

top(k)[source]

The k best solutions as a list.

k is an exact non-negative count: top(0) used to return ONE solution and top(2.9) three, because the engines counted emissions after yielding and compared against the raw float (MXR-080-1903).

Parameters:

k (int)

Return type:

list[Solution]

sampler(seed=None, *, temperature=1.0, k=None, uniform=False, rng=None)[source]

Return a RelationSampler that draws members under a Gibbs measure over the objective.

A relation is a specification of a structured space, not itself a random object; sampling it means imposing a distribution over its members, which needs an RNG and a temperature. So – like every other mixle object – it hands back a sampler (relation.sampler(seed).sample(size)) that owns the stream and the Gibbs measure, rather than being sampled directly.

Each enumerated member is weighted exp(-objective / temperature) when sense == "min" (low cost favoured) or exp(objective / temperature) when sense == "max". temperature -> 0 concentrates on the optimum; -> inf (or uniform=True) is uniform. The draw is an exact Gibbs sample only when the relation is finite and fully enumerated (k=None); pass k to truncate an infinite/large relation to its k best (the dropped tail is the lowest-weight mass – a good low-temperature approximation, and k is required if infinite).

Parameters:
  • seed (int | None) – scalar seed for the sampler’s RandomState (ignored if rng is given).

  • temperature (float) – Gibbs temperature (default 1.0).

  • k (int | None) – enumerate at most this many members (None = all; required if infinite).

  • uniform (bool) – ignore objectives and sample uniformly over the enumerated members.

  • rng – a shared numpy.random.RandomState (takes precedence over seed).

Return type:

RelationSampler

class ComputeEngine[source]

Bases: ABC

Small array-backend interface for numpy/torch/etc.

Engines own arithmetic policy: array library, device, dtype, and optional compilation. Distribution and kernel code should depend only on this surface when it wants backend-neutral arrays.

is_concrete(x)[source]

Return whether x holds real values now, so host-side inspection of it is meaningful.

Every eager backend answers True. A tracing backend (JAX under jit) answers False for a traced value: its contents are not available in Python, so to_numpy raises and any control flow branching on them is impossible by construction. Shared code that wants to run an optional host-side diagnostic – scanning for NaN rows to name them in an exception, say – asks first and skips the diagnostic while tracing; the engine math itself is unaffected either way.

Parameters:

x (Any)

Return type:

bool

constant(value)[source]

Return value in this engine’s scalar representation (identity for numeric engines).

Parameters:

value (Any)

Return type:

Any

property accumulator_dtype: Any

High-precision dtype for sufficient-statistic reductions, or None when not applicable.

Numeric engines override this with their float64 accumulator so a reduced-precision fit does not drift on large N (see NumpyEngine/TorchEngine). The base returns None: meaning “no separate accumulator dtype”, which is the correct policy for engines that never drive the numeric accumulate path (e.g. the symbolic engine, where reductions are exact expression trees). None is also a valid dtype= argument to sum (NumPy’s default).

property precision: str

Return the engine dtype policy as a stable user-facing name.

with_precision(precision)[source]

Return an equivalent engine with a different floating-point policy.

Parameters:

precision (Any)

Return type:

ComputeEngine

abstractmethod asarray(x, dtype=None)[source]

Convert x into this engine’s array/tensor representation.

Parameters:
Return type:

Any

abstractmethod zeros(shape, dtype=None)[source]

Allocate a zero-filled array on this engine.

Parameters:
Return type:

Any

abstractmethod empty(shape, dtype=None)[source]

Allocate an uninitialized array on this engine.

Parameters:
Return type:

Any

abstractmethod arange(*args, **kwargs)[source]

Return an evenly spaced one-dimensional array on this engine.

Parameters:
Return type:

Any

abstractmethod to_numpy(x)[source]

Move an engine array back to a NumPy/host representation.

Parameters:

x (Any)

Return type:

Any

abstractmethod stack(arrays, axis=0)[source]

Stack a sequence of arrays along axis.

Parameters:
Return type:

Any

abstractmethod concatenate(arrays, axis=0)[source]

Join a sequence of arrays along an existing axis.

Parameters:
Return type:

Any

requires_grad(x)[source]

Return whether x participates in this engine’s autograd graph.

Parameters:

x (Any)

Return type:

bool

compile(fn)[source]

Optionally compile fn; engines without a compiler return it unchanged.

Parameters:

fn (Callable)

Return type:

Callable

replicate(x)[source]

Return x in the engine’s replicated placement, when applicable.

Parameters:

x (Any)

Return type:

Any

place_component_axis(x, axis=0)[source]

Return x with a component-axis placement, when the engine supports it.

Parameters:
Return type:

Any

class Kernel[source]

Bases: ABC

Evaluation kernel for a fitted distribution.

abstractmethod score(enc)[source]

Return per-row log densities for an encoded observation batch.

Parameters:

enc (Any)

Return type:

Any

component_scores(enc)[source]

Return per-row, per-component log densities where meaningful.

Parameters:

enc (Any)

Return type:

Any

abstractmethod accumulate(enc, weights)[source]

Return sufficient statistics in the legacy estimator format.

Parameters:
Return type:

Any

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

Factory that builds a Kernel for a distribution and engine.

abstractmethod build(dist, engine, estimator=None)[source]

Return a kernel for dist on engine.

estimator is 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 DecomposableSemiring[source]

Bases: ABC

A witness-retaining semiring over which a likelihood reduction is evaluated.

zero/one are the additive/multiplicative identities; plus pools mutually exclusive alternatives (e.g. different sequence lengths or Markov end-states); times composes independent factors (whose log-probabilities add); product is n-ary times. leaf lifts a single scored atom into the carrier. Implementations choose the carrier E; for counting it is CountIndex, whose per-bucket structure is the witness needed to unrank.

abstractmethod zero()[source]

Return the additive identity.

Return type:

E

abstractmethod one()[source]

Return the multiplicative identity.

Return type:

E

abstractmethod leaf(value, log_prob, quantizer)[source]

Lift one scored atom into the semiring carrier.

Parameters:
  • value (Any)

  • log_prob (float)

  • quantizer (Quantizer)

Return type:

E

abstractmethod plus(a, b)[source]

Combine mutually exclusive alternatives.

Parameters:
  • a (E)

  • b (E)

Return type:

E

abstractmethod times(a, b, quantizer, max_fine_bucket)[source]

Compose independent factors.

Parameters:
  • a (E)

  • b (E)

  • quantizer (Quantizer)

  • max_fine_bucket (int)

Return type:

E

product(elements, quantizer, max_fine_bucket)[source]

n-ary times. Default folds times; carriers may override for efficiency/order.

Parameters:
  • elements (Sequence[E])

  • quantizer (Quantizer)

  • max_fine_bucket (int)

Return type:

E

class EMStrategy(*args, **kwargs)[source]

Bases: Protocol

Structural contract for an EM-family strategy consumed by run_em().

Every strategy object in this module (StandardEM, PosteriorTransformEM, AnnealedEM, …) satisfies this Protocol structurally by exposing a step(...) -> EMStepResult method. run_em and _em_step_fn dispatch on it polymorphically; membership is decided by isinstance().

step(enc_data, estimator, model, engine=..., objective=...)[source]

Run one EM-style update and return the resulting model and objective metadata.

Parameters:
  • enc_data (Any)

  • estimator (ParameterEstimator)

  • model (SequenceEncodableProbabilityDistribution)

  • engine (Any | None)

  • objective (Callable[[Any], float] | None)

Return type:

EMStepResult

class EncodedFold(*args, **kwargs)[source]

Bases: Protocol

Structural contract for the parallel/distributed fold consumed by mixle.stats.

This formalizes the duck-typed orchestrator contract that the concrete EncodedDataHandle base class documents. Local, multiprocessing, MPI, Spark, dask, Ray, Lightning, or additional worker handles satisfy this Protocol structurally without sharing inheritance. Membership is decided by isinstance() against the four pysp_seq_*/pysp_stream_* methods.

pysp_seq_log_density_sum(estimate)[source]

Return total observation count and summed log-density for the encoded data.

Parameters:

estimate (Any)

Return type:

tuple[float, float]

pysp_seq_estimate(estimator, prev_estimate)[source]

Estimate a model from encoded data and a previous estimate.

Parameters:
  • estimator (Any)

  • prev_estimate (Any)

Return type:

Any

pysp_seq_initialize(estimator, rng, p)[source]

Initialize an estimate from encoded data using Bernoulli subsampling.

Parameters:
Return type:

Any

pysp_stream_accumulate(estimator, model)[source]

Accumulate streaming sufficient statistics for encoded data.

Parameters:
Return type:

tuple[float, Any]

class Surrogate(*args, **kwargs)[source]

Bases: Protocol

The GP-surrogate contract passed as gp= to the Bayesian-optimization loops.

A surrogate is fit to the observed (x, y) and queried for the posterior predictive moments at new candidate points. The call convention is the one used by mixle.models.gaussian_process.GaussianProcessRegressor: fit trains in place (it may return diagnostics, which the loops ignore), and predict takes the training data alongside the query points, returning the posterior mean (return_cov=False) or (mean, cov) pair (return_cov=True).

fit(x, y, **kwargs)[source]

Fit or update the surrogate from observed design points x and responses y.

Parameters:
Return type:

Any

predict(x_train, y_train, x_new, return_cov=...)[source]

Return predictive moments at x_new using the observed training data.

Parameters:
Return type:

Any

class Acquisition(*args, **kwargs)[source]

Bases: Protocol

The acquisition-function contract registered via register_acquisition (EI/PI/UCB).

An acquisition scores candidate points from their surrogate posterior moments and returns a merit array that the proposal loop maximizes over the candidate set. It is called as fn(mean, std, best, *, maximize, **params) where mean / std are the predictive mean and standard deviation at the candidates, best is the incumbent objective value, maximize selects the optimization sense, and **params carries per-acquisition knobs (e.g. xi for EI/PI, kappa for UCB). Built-ins mixle.doe.bayesopt.expected_improvement(), probability_of_improvement(), and upper_confidence_bound() satisfy this contract.

class Criterion(*args, **kwargs)[source]

Bases: Protocol

The optimality-criterion contract registered via register_criterion (D/A/I-optimality).

A criterion maps the information matrix M = F.T @ F to a scalar merit that mixle.doe.optimal.optimal_design() maximizes over candidate designs. It is called as fn(info, *, ref) where ref is an optional reference model matrix (used by I-optimality). Built-ins mixle.doe.optimal.d_criterion(), a_criterion(), and i_criterion() satisfy this contract.