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:
ABCDraws 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:
- abstractmethod sample(size=None, *, batched=True)[source]
Draw observations.
Combinator samplers (mixture/sequence/…) accept
batched. Withbatched=True(the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independentRandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path.batched=Falseforces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.
- class ConditionalSampler[source]
Bases:
ABCSampler 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:
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.)
- class ParameterEstimator[source]
-
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.
- classmethod from_dict(payload)[source]
Reconstruct an estimator from
to_dictoutput.
- to_json(**kwargs)[source]
Serialize this estimator as safe strict JSON.
- classmethod from_json(text)[source]
Deserialize an estimator from
to_jsonoutput.- 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 toFalseso stacked/generated kernels fall back to the host accumulator, keeping every backend’s fixed point identical.- Return type:
- 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:
Nonegives maximum likelihood, a conjugate prior gives the Bayesian posterior update insideestimate. The default reads thepriorattribute (Nonewhen 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 is0.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:
- class StatisticAccumulator[source]
-
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.
- initialize(x, weight, rng)[source]
Initialize sufficient statistics from one weighted observation.
- Parameters:
x (Any)
weight (float)
rng (RandomState)
- 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_dictunder its merge key.The structural default implements the common single-key pattern: store the accumulator under
self.keysthe first time the key is seen, elsecombineinto 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 withsuper()calls. AkeysofNone(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_replacehands that pool to every site. The observed broken variants each violate one half: pulling the dict’s stats intoselfwithout 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 pushingselfINTO the dict (the LAST site overwrites the pool). The keyed-protocol sweep (keyed_protocol_sweep_test.py) enforces this behaviorally for every catalog family.
- 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.
- supported_rows(x)[source]
Encoded rows this accumulator can be fitted on, or
Nonewhen every row qualifies.Support-limited laws admit out-of-support observations at encode time so that a mixture can encode one batch against every component (P02-F03) – the component that does not own a value scores it -inf, and the E-step gives it no responsibility for that row. Initialization draws responsibilities before any model exists, so a latent model asks each component for this mask first and never seeds a component from a row it could not be fitted on.
- Return type:
ndarray | None
- 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:
weights (ndarray)
rng (RandomState)
- Return type:
None
- abstractmethod acc_to_encoder()[source]
Return a sequence encoder compatible with this accumulator.
- Return type:
DataSequenceEncoder
- class StatisticAccumulatorFactory[source]
Bases:
ABCFactory 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:
ABCEncodes 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.
- nbytes(x)[source]
Return the approximate in-memory byte size of an encoded payload.
- 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.
- class Enumerable[source]
Bases:
PredicateCapabilityIts support can be iterated in descending-probability order (
enumerator()works).
- class FiniteSupport[source]
Bases:
PredicateCapabilityHas a finite number of distinct support points (
support_size()is an int).- classmethod check(obj)[source]
Return whether
objreports a finite, non-negative support size.A Boolean is not a support count even though
boolsubclassesint:support_size()returningTrueused to certify a one-point support, so an object answering a yes/no question was routed as an enumerable finite distribution.
- class RankableByIndex[source]
Bases:
PredicateCapabilitySupports 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 ==> rankableis 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.)
- class ExponentialFamily[source]
Bases:
PredicateCapabilityDeclares an exponential-family form (generated stacked kernels + conjugate estimation).
- class ConjugateUpdatable[source]
Bases:
PredicateCapabilityHas a closed-form conjugate Bayesian update (the top tier of the inference ladder).
supports(x, ConjugateUpdatable)is True iffconjugate_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 singleconjugate_posteriorregistry.
- class Conditionable(*args, **kwargs)[source]
Bases:
ProtocolSupports conditioning on a subset of coordinates:
condition(observed) -> distribution.
- class Marginalizable(*args, **kwargs)[source]
Bases:
ProtocolSupports marginalising to a subset of coordinates:
marginal(keep) -> distribution.
- class LatentStructured(*args, **kwargs)[source]
Bases:
ProtocolExposes an explicit latent posterior q(z|x):
latent_posterior(x) -> LatentPosterior.
- class PosteriorPredictive(*args, **kwargs)[source]
Bases:
ProtocolCan draw/score new data conditioned on an observation’s inferred latent state.
- class TemporalPointProcess(*args, **kwargs)[source]
Bases:
ProtocolAn 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
tgiven the observed history.
- class SetValued[source]
Bases:
PredicateCapabilityA distribution over sets with forced/required membership (
required/num_required).
- class Neutral[source]
Bases:
PredicateCapabilityThe identity / no-op element of a combinator (a Null distribution, accumulator, or encoder).
- class Transform(*args, **kwargs)[source]
Bases:
ProtocolA contract-declared invertible change of variables with a tractable Jacobian.
- forward(x)[source]
Map values from the base space into the transformed space.
- inverse(y)[source]
Map values from the transformed space back into the base space.
- log_abs_det_inverse_jacobian(y)[source]
Return
log |det d inverse(y) / dy|for density correction.
- class EngineResidentEStep(*args, **kwargs)[source]
Bases:
ProtocolAn accumulator that can run its E-step on the active compute engine without leaving it.
- class SupportsBackendScoring(*args, **kwargs)[source]
Bases:
ProtocolA distribution that can score a batch directly on the active engine (
backend_seq_log_density).
- class SupportsBackendComponentScoring(*args, **kwargs)[source]
Bases:
ProtocolA distribution that exposes per-component engine scoring (
backend_seq_component_log_density).
- class SupportsStackedBackend(*args, **kwargs)[source]
Bases:
ProtocolA 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.
- class PredicateCapability[source]
Bases:
objectBase for capabilities determined by inspecting the object rather than a method name.
- class Relation[source]
Bases:
ABCA constraint over a structured space whose members are enumerated ranked by a residual.
Subclasses implement
enumerator()(yieldingSolutionitems);solve(),top()and iteration come for free.senseis"min"(residual minimized, members out in increasing cost) or"max"(residual maximized, members out in decreasing score).- abstractmethod enumerator(k=None)[source]
Lazily yield
Solutionitems best-first; at mostkif given (None= all).
- solve()[source]
The single optimal
Solution, orNoneif the problem is infeasible.- Return type:
Solution | None
- top(k)[source]
The
kbest solutions as a list.kis an exact non-negative count:top(0)used to return ONE solution andtop(2.9)three, because the engines counted emissions after yielding and compared against the raw float (MXR-080-1903).
- sampler(seed=None, *, temperature=1.0, k=None, uniform=False, rng=None)[source]
Return a
RelationSamplerthat 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)whensense == "min"(low cost favoured) orexp(objective / temperature)whensense == "max".temperature -> 0concentrates on the optimum;-> inf(oruniform=True) is uniform. The draw is an exact Gibbs sample only when the relation is finite and fully enumerated (k=None); passkto truncate an infinite/large relation to itskbest (the dropped tail is the lowest-weight mass – a good low-temperature approximation, andkis required if infinite).- Parameters:
seed (int | None) – scalar seed for the sampler’s RandomState (ignored if
rngis 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 overseed).
- Return type:
RelationSampler
- class ComputeEngine[source]
Bases:
ABCSmall 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
xholds 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, soto_numpyraises 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.
- constant(value)[source]
Return
valuein this engine’s scalar representation (identity for numeric engines).
- property accumulator_dtype: Any
High-precision dtype for sufficient-statistic reductions, or
Nonewhen 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 returnsNone: 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).Noneis also a validdtype=argument tosum(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
xinto this engine’s array/tensor representation.
- abstractmethod zeros(shape, dtype=None)[source]
Allocate a zero-filled array on this engine.
- abstractmethod empty(shape, dtype=None)[source]
Allocate an uninitialized array on this engine.
- abstractmethod arange(*args, **kwargs)[source]
Return an evenly spaced one-dimensional array on this engine.
- abstractmethod to_numpy(x)[source]
Move an engine array back to a NumPy/host representation.
- abstractmethod stack(arrays, axis=0)[source]
Stack a sequence of arrays along
axis.
- abstractmethod concatenate(arrays, axis=0)[source]
Join a sequence of arrays along an existing
axis.
- requires_grad(x)[source]
Return whether
xparticipates in this engine’s autograd graph.
- compile(fn)[source]
Optionally compile
fn; engines without a compiler return it unchanged.
- replicate(x)[source]
Return
xin the engine’s replicated placement, when applicable.
- 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 DecomposableSemiring[source]
Bases:
ABCA witness-retaining semiring over which a likelihood reduction is evaluated.
zero/oneare the additive/multiplicative identities;pluspools mutually exclusive alternatives (e.g. different sequence lengths or Markov end-states);timescomposes independent factors (whose log-probabilities add);productis n-arytimes.leaflifts a single scored atom into the carrier. Implementations choose the carrierE; for counting it isCountIndex, 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.
- abstractmethod plus(a, b)[source]
Combine mutually exclusive alternatives.
- Parameters:
a (E)
b (E)
- Return type:
E
- class EMStrategy(*args, **kwargs)[source]
Bases:
ProtocolStructural 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 astep(...) -> EMStepResultmethod.run_emand_em_step_fndispatch on it polymorphically; membership is decided byisinstance().- step(enc_data, estimator, model, engine=..., objective=...)[source]
Run one EM-style update and return the resulting model and objective metadata.
- class EncodedFold(*args, **kwargs)[source]
Bases:
ProtocolStructural contract for the parallel/distributed fold consumed by
mixle.stats.This formalizes the duck-typed orchestrator contract that the concrete
EncodedDataHandlebase class documents. Local, multiprocessing, MPI, Spark, dask, Ray, Lightning, or additional worker handles satisfy this Protocol structurally without sharing inheritance. Membership is decided byisinstance()against the fourpysp_seq_*/pysp_stream_*methods.- pysp_seq_log_density_sum(estimate)[source]
Return total observation count and summed log-density for the encoded data.
- pysp_seq_estimate(estimator, prev_estimate)[source]
Estimate a model from encoded data and a previous estimate.
- pysp_seq_initialize(estimator, rng, p)[source]
Initialize an estimate from encoded data using Bernoulli subsampling.
- Parameters:
estimator (Any)
rng (RandomState)
p (float)
- Return type:
- class Surrogate(*args, **kwargs)[source]
Bases:
ProtocolThe 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 bymixle.models.gaussian_process.GaussianProcessRegressor:fittrains in place (it may return diagnostics, which the loops ignore), andpredicttakes 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
xand responsesy.
- class Acquisition(*args, **kwargs)[source]
Bases:
ProtocolThe 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)wheremean/stdare the predictive mean and standard deviation at the candidates,bestis the incumbent objective value,maximizeselects the optimization sense, and**paramscarries per-acquisition knobs (e.g.xifor EI/PI,kappafor UCB). Built-insmixle.doe.bayesopt.expected_improvement(),probability_of_improvement(), andupper_confidence_bound()satisfy this contract.
- class Criterion(*args, **kwargs)[source]
Bases:
ProtocolThe optimality-criterion contract registered via
register_criterion(D/A/I-optimality).A criterion maps the information matrix
M = F.T @ Fto a scalar merit thatmixle.doe.optimal.optimal_design()maximizes over candidate designs. It is called asfn(info, *, ref)whererefis an optional reference model matrix (used by I-optimality). Built-insmixle.doe.optimal.d_criterion(),a_criterion(), andi_criterion()satisfy this contract.