Skip to content

API

posterior implements immutable provenance/target/numerical references and a guarded provenance JSON loader, plus coordinate-aware native posterior samples. forward attaches that shared provenance to immutable output references. The optional ArviZ adapter implements guarded DataTree/netCDF snapshots. rng implements versioned task stream addresses and default parameter/simulation separation; its optional adapters lower to native JAX keys and validated Torch CPU generator banks. priors, observe and simulation implement the bounded catalog of independent scalar or fixed-shaped iid priors and iid observation laws described in the statistical-model guide. General transforms, hierarchy, dependence and integrated likelihood interfaces remain planned. The optional NumPyro adapter implements a bounded native NUTS fit with shared posterior records and raw diagnostic outcomes. calibrate implements rank-based SBC aggregation (ordinary and randomized-rank PIT, Benjamini-Hochberg multiplicity, power floors, failed-replicate accounting and contraction), plus study-extra central-coverage summaries with marginal Wilson intervals (see Rank-based calibration). The native sbi adapter adds masked-cohort NPE and seed ensembles. Prespecified scalar gate criteria and records are available from gates and re-exported by calibrate. Other estimator adapters and the reserved advanced statistical interfaces listed in the capability guide remain planned. sbc schedules replayable fixed banks and design composes held-out refits with aligned unit-score contrasts from compare. See implemented capabilities for the current scope and extras.

params

Parameter spaces and transforms.

Status: planned (no public API yet). See docs/design/proposal.md and the issue tracker.

Scope: Named, shaped parameters with support constraints; flatten/unflatten to vectors or pytrees in any Array-API backend; non-centred hierarchical declarations; gauge-pinned parameters recorded as fixed; bijectors (log, logit, softplus, interval, simplex) with log-Jacobians; analysis coordinates for identifiability.

priors

Immutable scalar distribution declarations and independently addressed priors.

Native lowerings wrap SciPy, NumPyro and Torch distributions. The first catalog is independent Normal, LogNormal, Uniform, Gamma(shape/rate) and Beta; hierarchy, correlated blocks and automatic coordinate changes are explicitly outside it.

Beta

Bases: _Distribution

Beta law with mean concentration1/(concentration1 + concentration0).

Source code in src/op_infer/priors.py
160
161
162
163
164
165
class Beta(_Distribution):
    """Beta law with mean concentration1/(concentration1 + concentration0)."""

    family: Literal["beta"] = "beta"
    concentration1: _Positive
    concentration0: _Positive

Gamma

Bases: _Distribution

Gamma shape/rate law, with mean concentration/rate.

Source code in src/op_infer/priors.py
152
153
154
155
156
157
class Gamma(_Distribution):
    """Gamma shape/rate law, with mean concentration/rate."""

    family: Literal["gamma"] = "gamma"
    concentration: _Positive
    rate: _Positive

JointPrior

Bases: _Record

Ordered independent declarations, their stable identity and native sites.

Shapes are event axes; sample_shape adds leading independent draws. Sampling never retries or drops a draw. Native distributions own their sampling APIs; no cross-backend bitwise replay is claimed.

Examples:

>>> prior = JointPrior(
...     parameters=(
...         PriorParameter(
...             name="rate", distribution=Gamma(concentration=2.0, rate=3.0)
...         ),
...     )
... )
>>> key = RandomKey(seed=2026, stream="parameters")
>>> prior.sample(key)["rate"] == prior.sample(key)["rate"]
np.True_
Source code in src/op_infer/priors.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
class JointPrior(_Record):
    """Ordered independent declarations, their stable identity and native sites.

    Shapes are event axes; ``sample_shape`` adds leading independent draws.
    Sampling never retries or drops a draw. Native distributions own their
    sampling APIs; no cross-backend bitwise replay is claimed.

    Examples:
        >>> prior = JointPrior(
        ...     parameters=(
        ...         PriorParameter(
        ...             name="rate", distribution=Gamma(concentration=2.0, rate=3.0)
        ...         ),
        ...     )
        ... )
        >>> key = RandomKey(seed=2026, stream="parameters")
        >>> prior.sample(key)["rate"] == prior.sample(key)["rate"]
        np.True_
    """

    schema_version: Literal[1] = 1
    parameters: tuple[PriorParameter, ...]

    @field_validator("schema_version", mode="before")
    @classmethod
    def _integer_version(cls, value: object) -> object:
        if type(value) is not int:
            msg = "schema_version must be an integer"
            raise ValueError(msg)
        return value

    @model_validator(mode="after")
    def _unique(self) -> Self:
        names = self.parameter_names
        if not names or len(set(names)) != len(names):
            msg = "Declare nonempty unique prior parameter names"
            raise ValueError(msg)
        return self

    @property
    def parameter_names(self) -> tuple[str, ...]:
        """Return the semantic parameter order."""
        return tuple(parameter.name for parameter in self.parameters)

    @property
    def reference(self) -> ArtifactReference:
        """Identify the ordered declaration with canonical JSON."""
        payload = json.dumps(
            self.model_dump(mode="json"),
            sort_keys=True,
            separators=(",", ":"),
            allow_nan=False,
        )
        return ArtifactReference.from_bytes(
            payload.encode(), kind="independent-joint-prior-v1"
        )

    def sample(
        self, key: RandomKey, *, sample_shape: tuple[int, ...] = ()
    ) -> dict[str, np.ndarray[Any, Any]]:
        """Draw NumPy arrays using per-name streams and native SciPy sampling.

        Adding/reordering another parameter does not change an existing name's
        draws. Changes to a distribution or shape still change prior identity.
        """
        _validate_sample_shape(sample_shape)
        RandomKey.model_validate(key)
        result = {}
        for parameter in self.parameters:
            address = key.model_copy(
                update={"stream": f"{key.stream}/prior/{parameter.name}"}
            )
            result[parameter.name] = np.asarray(
                parameter.distribution.scipy().rvs(
                    size=sample_shape + parameter.shape,
                    random_state=address.numpy_generator(),
                )
            )
        return result

    def log_prob(self, values: Mapping[str, Any]) -> Any:  # noqa: ANN401
        """Sum event axes while retaining leading native batch axes and graphs.

        NumPy/SciPy, JAX/NumPyro and Torch are the qualified namespaces. A mixed
        namespace, wrong names or mismatched event/batch shapes fails explicitly.
        """
        if set(values) != set(self.parameter_names):
            msg = "Prior values must contain exactly the declared names"
            raise ValueError(msg)
        xp = array_namespace(*(values[name] for name in self.parameter_names))
        backend = _backend(xp)
        result = None
        batch_shape = None
        for parameter in self.parameters:
            value = values[parameter.name]
            if not xp.isdtype(value.dtype, "real floating"):
                msg = "Prior coordinates must have real floating dtype"
                raise TypeError(msg)
            event_ndim = len(parameter.shape)
            if event_ndim and tuple(value.shape[-event_ndim:]) != parameter.shape:
                msg = "Prior event shape differs from its declaration"
                raise ValueError(msg)
            batch = (
                tuple(value.shape[:-event_ndim]) if event_ndim else tuple(value.shape)
            )
            if batch_shape is not None and batch != batch_shape:
                msg = "Prior batch shapes must match exactly"
                raise ValueError(msg)
            batch_shape = batch
            density = _log_density(parameter.distribution, value, xp, backend)
            if event_ndim:
                density = xp.sum(
                    density, axis=tuple(range(density.ndim - event_ndim, density.ndim))
                )
            result = density if result is None else result + density
        return result

    def numpyro_sites(self) -> dict[str, Any]:
        """Return named native laws, with shaped coordinates declared as events."""
        return {
            p.name: p.distribution.numpyro().expand(p.shape).to_event(len(p.shape))
            for p in self.parameters
        }

    def torch_sites(self, *, dtype: Any = None, device: Any = "cpu") -> dict[str, Any]:  # noqa: ANN401
        """Return native named laws, with shaped coordinates declared as events."""
        distributions = importlib.import_module("torch.distributions")
        return {
            p.name: distributions.Independent(
                p.distribution.torch(dtype=dtype, device=device).expand(p.shape),
                len(p.shape),
            )
            for p in self.parameters
        }

    def torch_normal_vector(self, *, dtype: Any = None, device: Any = "cpu") -> Any:  # noqa: ANN401
        """Lower scalar Normal sites to one real-vector law for existing sbi NPE.

        Other supports and automatic coordinate transforms are refused. Parameter
        order is the declared order and is not inferred from a training bank.
        """
        torch = importlib.import_module("torch")
        if any(
            not isinstance(p.distribution, Normal) or p.shape for p in self.parameters
        ):
            msg = "The NPE vector lowering requires scalar Normal coordinates"
            raise ValueError(msg)
        normals = [
            p.distribution
            for p in self.parameters
            if isinstance(p.distribution, Normal)
        ]
        loc = torch.tensor([p.loc for p in normals], dtype=dtype, device=device)
        scale = torch.tensor([p.scale for p in normals], dtype=dtype, device=device)
        return torch.distributions.Independent(
            torch.distributions.Normal(loc, scale), 1
        )

parameter_names property

Return the semantic parameter order.

reference property

Identify the ordered declaration with canonical JSON.

log_prob(values)

Sum event axes while retaining leading native batch axes and graphs.

NumPy/SciPy, JAX/NumPyro and Torch are the qualified namespaces. A mixed namespace, wrong names or mismatched event/batch shapes fails explicitly.

Source code in src/op_infer/priors.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def log_prob(self, values: Mapping[str, Any]) -> Any:  # noqa: ANN401
    """Sum event axes while retaining leading native batch axes and graphs.

    NumPy/SciPy, JAX/NumPyro and Torch are the qualified namespaces. A mixed
    namespace, wrong names or mismatched event/batch shapes fails explicitly.
    """
    if set(values) != set(self.parameter_names):
        msg = "Prior values must contain exactly the declared names"
        raise ValueError(msg)
    xp = array_namespace(*(values[name] for name in self.parameter_names))
    backend = _backend(xp)
    result = None
    batch_shape = None
    for parameter in self.parameters:
        value = values[parameter.name]
        if not xp.isdtype(value.dtype, "real floating"):
            msg = "Prior coordinates must have real floating dtype"
            raise TypeError(msg)
        event_ndim = len(parameter.shape)
        if event_ndim and tuple(value.shape[-event_ndim:]) != parameter.shape:
            msg = "Prior event shape differs from its declaration"
            raise ValueError(msg)
        batch = (
            tuple(value.shape[:-event_ndim]) if event_ndim else tuple(value.shape)
        )
        if batch_shape is not None and batch != batch_shape:
            msg = "Prior batch shapes must match exactly"
            raise ValueError(msg)
        batch_shape = batch
        density = _log_density(parameter.distribution, value, xp, backend)
        if event_ndim:
            density = xp.sum(
                density, axis=tuple(range(density.ndim - event_ndim, density.ndim))
            )
        result = density if result is None else result + density
    return result

numpyro_sites()

Return named native laws, with shaped coordinates declared as events.

Source code in src/op_infer/priors.py
298
299
300
301
302
303
def numpyro_sites(self) -> dict[str, Any]:
    """Return named native laws, with shaped coordinates declared as events."""
    return {
        p.name: p.distribution.numpyro().expand(p.shape).to_event(len(p.shape))
        for p in self.parameters
    }

sample(key, *, sample_shape=())

Draw NumPy arrays using per-name streams and native SciPy sampling.

Adding/reordering another parameter does not change an existing name's draws. Changes to a distribution or shape still change prior identity.

Source code in src/op_infer/priors.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def sample(
    self, key: RandomKey, *, sample_shape: tuple[int, ...] = ()
) -> dict[str, np.ndarray[Any, Any]]:
    """Draw NumPy arrays using per-name streams and native SciPy sampling.

    Adding/reordering another parameter does not change an existing name's
    draws. Changes to a distribution or shape still change prior identity.
    """
    _validate_sample_shape(sample_shape)
    RandomKey.model_validate(key)
    result = {}
    for parameter in self.parameters:
        address = key.model_copy(
            update={"stream": f"{key.stream}/prior/{parameter.name}"}
        )
        result[parameter.name] = np.asarray(
            parameter.distribution.scipy().rvs(
                size=sample_shape + parameter.shape,
                random_state=address.numpy_generator(),
            )
        )
    return result

torch_normal_vector(*, dtype=None, device='cpu')

Lower scalar Normal sites to one real-vector law for existing sbi NPE.

Other supports and automatic coordinate transforms are refused. Parameter order is the declared order and is not inferred from a training bank.

Source code in src/op_infer/priors.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def torch_normal_vector(self, *, dtype: Any = None, device: Any = "cpu") -> Any:  # noqa: ANN401
    """Lower scalar Normal sites to one real-vector law for existing sbi NPE.

    Other supports and automatic coordinate transforms are refused. Parameter
    order is the declared order and is not inferred from a training bank.
    """
    torch = importlib.import_module("torch")
    if any(
        not isinstance(p.distribution, Normal) or p.shape for p in self.parameters
    ):
        msg = "The NPE vector lowering requires scalar Normal coordinates"
        raise ValueError(msg)
    normals = [
        p.distribution
        for p in self.parameters
        if isinstance(p.distribution, Normal)
    ]
    loc = torch.tensor([p.loc for p in normals], dtype=dtype, device=device)
    scale = torch.tensor([p.scale for p in normals], dtype=dtype, device=device)
    return torch.distributions.Independent(
        torch.distributions.Normal(loc, scale), 1
    )

torch_sites(*, dtype=None, device='cpu')

Return native named laws, with shaped coordinates declared as events.

Source code in src/op_infer/priors.py
305
306
307
308
309
310
311
312
313
314
def torch_sites(self, *, dtype: Any = None, device: Any = "cpu") -> dict[str, Any]:  # noqa: ANN401
    """Return native named laws, with shaped coordinates declared as events."""
    distributions = importlib.import_module("torch.distributions")
    return {
        p.name: distributions.Independent(
            p.distribution.torch(dtype=dtype, device=device).expand(p.shape),
            len(p.shape),
        )
        for p in self.parameters
    }

LogNormal

Bases: _Distribution

Exp(Normal(loc, scale)); parameters are on the logarithmic scale.

Source code in src/op_infer/priors.py
129
130
131
132
133
134
class LogNormal(_Distribution):
    """Exp(Normal(loc, scale)); parameters are on the logarithmic scale."""

    family: Literal["lognormal"] = "lognormal"
    loc: _Finite = 0.0
    scale: _Positive = 1.0

Normal

Bases: _Distribution

Normal law with location and positive standard deviation.

Source code in src/op_infer/priors.py
121
122
123
124
125
126
class Normal(_Distribution):
    """Normal law with location and positive standard deviation."""

    family: Literal["normal"] = "normal"
    loc: _Finite = 0.0
    scale: _Positive = 1.0

PriorParameter

Bases: _Record

Name an independent scalar or fixed-shaped array of iid coordinates.

Source code in src/op_infer/priors.py
173
174
175
176
177
178
class PriorParameter(_Record):
    """Name an independent scalar or fixed-shaped array of iid coordinates."""

    name: _Name
    distribution: Distribution
    shape: tuple[Annotated[int, Field(ge=1)], ...] = ()

Uniform

Bases: _Distribution

Uniform law on low <= x < high, consistently across density adapters.

Source code in src/op_infer/priors.py
137
138
139
140
141
142
143
144
145
146
147
148
149
class Uniform(_Distribution):
    """Uniform law on low <= x < high, consistently across density adapters."""

    family: Literal["uniform"] = "uniform"
    low: _Finite = 0.0
    high: _Finite = 1.0

    @model_validator(mode="after")
    def _ordered(self) -> Self:
        if self.low >= self.high:
            msg = "Uniform requires low < high"
            raise ValueError(msg)
        return self

observe

Native iid observation laws shared by simulation and likelihood evaluation.

Latent means/log-locations/probabilities remain separate from random measurements. Array operations preserve NumPy, JAX or Torch execution; native distributions own sampling and density kernels. Correlated observations are not silently iid.

BinnedNormalObservation

Bases: _Record

Record a Normal measurement as an interval code on a fixed partition.

With K finite, strictly increasing cutpoints, codes 0, ..., K denote (-inf, c[0]), [c[0], c[1]), ..., [c[K-1], inf). Cutpoints use measurement coordinates, whose Normal mean is offset + slope * latent and standard deviation is scale. Codes are labels, not interval midpoints or numerical measurements.

Sampling quantizes the existing native Normal sampler. Scoring returns interval probability mass, including both open tails. Invalid codes or nonfinite means score as impossible; masked cells contribute zero even when missing values are NaN. A common partition applies to every cell. Per-cell partitions, correlated errors and explicit curvature interfaces are outside this law.

Examples:

>>> import numpy as np
>>> sensor = BinnedNormalObservation(cutpoints=(-1.0, 1.0))
>>> np.exp(sensor.log_prob(np.array(0.0), np.arange(3))).round(6)
array([0.158655, 0.682689, 0.158655])
Source code in src/op_infer/observe.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
class BinnedNormalObservation(_Record):
    """Record a Normal measurement as an interval code on a fixed partition.

    With ``K`` finite, strictly increasing cutpoints, codes ``0, ..., K``
    denote ``(-inf, c[0])``, ``[c[0], c[1])``, ..., ``[c[K-1], inf)``.
    Cutpoints use measurement coordinates, whose Normal mean is
    ``offset + slope * latent`` and standard deviation is ``scale``.
    Codes are labels, not interval midpoints or numerical measurements.

    Sampling quantizes the existing native Normal sampler. Scoring returns
    interval probability mass, including both open tails. Invalid codes or
    nonfinite means score as impossible; masked cells contribute zero even
    when missing values are NaN. A common partition applies to every cell.
    Per-cell partitions, correlated errors and explicit curvature interfaces
    are outside this law.

    Examples:
        >>> import numpy as np
        >>> sensor = BinnedNormalObservation(cutpoints=(-1.0, 1.0))
        >>> np.exp(sensor.log_prob(np.array(0.0), np.arange(3))).round(6)
        array([0.158655, 0.682689, 0.158655])
    """

    cutpoints: Annotated[tuple[_Finite, ...], Field(min_length=1)]
    scale: _Positive = 1.0
    offset: _Finite = 0.0
    slope: _Finite = 1.0

    @model_validator(mode="after")
    def _ordered_cutpoints(self) -> Self:
        if any(a >= b for a, b in itertools.pairwise(self.cutpoints)):
            msg = "Normal bin cutpoints must be strictly increasing"
            raise ValueError(msg)
        return self

    @property
    def reference(self) -> ArtifactReference:
        """Identify the partition, boundary convention, affine map and noise."""
        data = {
            "schema_version": 1,
            "family": "normal",
            "dependence": "iid",
            "mask": "true-is-observed",
            "observation": "zero-based-bin-code",
            "intervals": "left-closed-right-open-with-infinite-end-tails",
            "parameters": self.model_dump(mode="json"),
        }
        payload = json.dumps(
            data, sort_keys=True, separators=(",", ":"), allow_nan=False
        )
        return ArtifactReference.from_bytes(
            payload.encode(), kind="binned-normal-observation-v1"
        )

    def log_prob(self, latent: Any, observed: Any, *, mask: Any = None) -> Any:  # noqa: ANN401
        """Score integer-valued bin codes with native tail-stable probabilities.

        Integer and real floating code arrays are accepted; fractional,
        negative, nonfinite and out-of-range codes receive ``-inf``. Masks
        must be native boolean arrays with exactly the broadcast shape.
        Native JAX/Torch derivatives are with respect to the latent input.
        Choose precision that resolves cutpoints, standardized separation and
        log-CDF differences. Very narrow intervals can lose relative accuracy;
        differences that collapse in that precision have zero computed mass.
        """
        xp = array_namespace(latent, observed)
        backend = _backend(xp)
        if not xp.isdtype(latent.dtype, "real floating"):
            msg = "Observation latent values must have real floating dtype"
            raise TypeError(msg)
        if not xp.isdtype(observed.dtype, ("integral", "real floating")):
            msg = "Normal bin codes must have integer or real floating dtype"
            raise TypeError(msg)
        mean, code = xp.broadcast_arrays(self.offset + self.slope * latent, observed)
        selected = xp.ones_like(mean, dtype=xp.bool) if mask is None else mask
        if (
            array_namespace(selected).__name__ != xp.__name__
            or selected.dtype != xp.bool
            or tuple(selected.shape) != tuple(mean.shape)
        ):
            msg = "Observation mask must be native boolean with the broadcast shape"
            raise ValueError(msg)
        valid = xp.isfinite(mean)
        mean = xp.where(selected & valid, mean, xp.zeros_like(mean))
        code = xp.where(selected, code, xp.zeros_like(code))
        valid = (
            valid
            & xp.isfinite(code)
            & (code >= 0)
            & (code <= len(self.cutpoints))
            & (code == xp.floor(code))
        )
        interior = valid & (code > 0) & (code < len(self.cutpoints))
        lower, upper = -xp.ones_like(mean), xp.ones_like(mean)
        for index, (left, right) in enumerate(
            itertools.pairwise(self.cutpoints), start=1
        ):
            lower = xp.where(code == index, xp.full_like(mean, left), lower)
            upper = xp.where(code == index, xp.full_like(mean, right), upper)
        center = xp.where(interior, mean, xp.zeros_like(mean))
        lower = (lower - center) / self.scale
        upper = (upper - center) / self.scale
        # Reflect right-tail intervals before subtraction; never subtract CDFs
        # rounded to one. Inactive open tails retain finite dummy endpoints.
        reflected = lower > 0
        low = xp.where(reflected, -upper, lower)
        high = xp.where(reflected, -lower, upper)
        special = importlib.import_module(
            {
                "numpy": "scipy.special",
                "jax": "jax.scipy.special",
                "torch": "torch.special",
            }[backend]
        )
        log_high = special.log_ndtr(high)
        # For intervals crossing the mean, a lower tail below -40 standard
        # deviations has less mass than float64 can represent. Do not evaluate
        # its native backward kernel: its undefined derivative can otherwise
        # contaminate an exactly saturated interval through zero times infinity.
        negligible_lower_tail = (low < -40) & (high >= 0)
        safe_low = xp.where(negligible_lower_tail, xp.zeros_like(low), low)
        difference = special.log_ndtr(safe_low) - log_high
        resolved = difference < 0
        safe_difference = xp.where(resolved, difference, -xp.ones_like(mean))
        density = xp.where(
            resolved, log_high + xp.log(-xp.expm1(safe_difference)), -xp.inf
        )
        density = xp.where(negligible_lower_tail, log_high, density)
        left_mean = xp.where(code == 0, mean, xp.full_like(mean, self.cutpoints[0]))
        right_mean = xp.where(
            code == len(self.cutpoints),
            mean,
            xp.full_like(mean, self.cutpoints[-1]),
        )
        density = xp.where(
            code == 0,
            special.log_ndtr((self.cutpoints[0] - left_mean) / self.scale),
            density,
        )
        density = xp.where(
            code == len(self.cutpoints),
            special.log_ndtr((right_mean - self.cutpoints[-1]) / self.scale),
            density,
        )
        return xp.where(selected, xp.where(valid, density, -xp.inf), 0.0)

    def sample(
        self,
        latent: Any,  # noqa: ANN401
        key: Any,  # noqa: ANN401
        *,
        sample_shape: tuple[int, ...] = (),
    ) -> Any:  # noqa: ANN401
        """Quantize addressed native Normal draws, returning latent float dtype.

        A draw exactly on a cutpoint enters the higher bin. Replay, leading
        sample axes and local-generator semantics are those of IIDObservation.
        Nonfinite underlying draws remain NaN, never valid-looking bin codes.
        """
        draws = IIDObservation(
            family="normal", scale=self.scale, offset=self.offset, slope=self.slope
        ).sample(latent, key, sample_shape=sample_shape)
        xp = array_namespace(draws)
        codes = xp.zeros_like(draws)
        for cutpoint in self.cutpoints:
            codes = codes + xp.astype(draws >= cutpoint, draws.dtype)
        return xp.where(xp.isfinite(draws), codes, xp.full_like(draws, xp.nan))

reference property

Identify the partition, boundary convention, affine map and noise.

log_prob(latent, observed, *, mask=None)

Score integer-valued bin codes with native tail-stable probabilities.

Integer and real floating code arrays are accepted; fractional, negative, nonfinite and out-of-range codes receive -inf. Masks must be native boolean arrays with exactly the broadcast shape. Native JAX/Torch derivatives are with respect to the latent input. Choose precision that resolves cutpoints, standardized separation and log-CDF differences. Very narrow intervals can lose relative accuracy; differences that collapse in that precision have zero computed mass.

Source code in src/op_infer/observe.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def log_prob(self, latent: Any, observed: Any, *, mask: Any = None) -> Any:  # noqa: ANN401
    """Score integer-valued bin codes with native tail-stable probabilities.

    Integer and real floating code arrays are accepted; fractional,
    negative, nonfinite and out-of-range codes receive ``-inf``. Masks
    must be native boolean arrays with exactly the broadcast shape.
    Native JAX/Torch derivatives are with respect to the latent input.
    Choose precision that resolves cutpoints, standardized separation and
    log-CDF differences. Very narrow intervals can lose relative accuracy;
    differences that collapse in that precision have zero computed mass.
    """
    xp = array_namespace(latent, observed)
    backend = _backend(xp)
    if not xp.isdtype(latent.dtype, "real floating"):
        msg = "Observation latent values must have real floating dtype"
        raise TypeError(msg)
    if not xp.isdtype(observed.dtype, ("integral", "real floating")):
        msg = "Normal bin codes must have integer or real floating dtype"
        raise TypeError(msg)
    mean, code = xp.broadcast_arrays(self.offset + self.slope * latent, observed)
    selected = xp.ones_like(mean, dtype=xp.bool) if mask is None else mask
    if (
        array_namespace(selected).__name__ != xp.__name__
        or selected.dtype != xp.bool
        or tuple(selected.shape) != tuple(mean.shape)
    ):
        msg = "Observation mask must be native boolean with the broadcast shape"
        raise ValueError(msg)
    valid = xp.isfinite(mean)
    mean = xp.where(selected & valid, mean, xp.zeros_like(mean))
    code = xp.where(selected, code, xp.zeros_like(code))
    valid = (
        valid
        & xp.isfinite(code)
        & (code >= 0)
        & (code <= len(self.cutpoints))
        & (code == xp.floor(code))
    )
    interior = valid & (code > 0) & (code < len(self.cutpoints))
    lower, upper = -xp.ones_like(mean), xp.ones_like(mean)
    for index, (left, right) in enumerate(
        itertools.pairwise(self.cutpoints), start=1
    ):
        lower = xp.where(code == index, xp.full_like(mean, left), lower)
        upper = xp.where(code == index, xp.full_like(mean, right), upper)
    center = xp.where(interior, mean, xp.zeros_like(mean))
    lower = (lower - center) / self.scale
    upper = (upper - center) / self.scale
    # Reflect right-tail intervals before subtraction; never subtract CDFs
    # rounded to one. Inactive open tails retain finite dummy endpoints.
    reflected = lower > 0
    low = xp.where(reflected, -upper, lower)
    high = xp.where(reflected, -lower, upper)
    special = importlib.import_module(
        {
            "numpy": "scipy.special",
            "jax": "jax.scipy.special",
            "torch": "torch.special",
        }[backend]
    )
    log_high = special.log_ndtr(high)
    # For intervals crossing the mean, a lower tail below -40 standard
    # deviations has less mass than float64 can represent. Do not evaluate
    # its native backward kernel: its undefined derivative can otherwise
    # contaminate an exactly saturated interval through zero times infinity.
    negligible_lower_tail = (low < -40) & (high >= 0)
    safe_low = xp.where(negligible_lower_tail, xp.zeros_like(low), low)
    difference = special.log_ndtr(safe_low) - log_high
    resolved = difference < 0
    safe_difference = xp.where(resolved, difference, -xp.ones_like(mean))
    density = xp.where(
        resolved, log_high + xp.log(-xp.expm1(safe_difference)), -xp.inf
    )
    density = xp.where(negligible_lower_tail, log_high, density)
    left_mean = xp.where(code == 0, mean, xp.full_like(mean, self.cutpoints[0]))
    right_mean = xp.where(
        code == len(self.cutpoints),
        mean,
        xp.full_like(mean, self.cutpoints[-1]),
    )
    density = xp.where(
        code == 0,
        special.log_ndtr((self.cutpoints[0] - left_mean) / self.scale),
        density,
    )
    density = xp.where(
        code == len(self.cutpoints),
        special.log_ndtr((right_mean - self.cutpoints[-1]) / self.scale),
        density,
    )
    return xp.where(selected, xp.where(valid, density, -xp.inf), 0.0)

sample(latent, key, *, sample_shape=())

Quantize addressed native Normal draws, returning latent float dtype.

A draw exactly on a cutpoint enters the higher bin. Replay, leading sample axes and local-generator semantics are those of IIDObservation. Nonfinite underlying draws remain NaN, never valid-looking bin codes.

Source code in src/op_infer/observe.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def sample(
    self,
    latent: Any,  # noqa: ANN401
    key: Any,  # noqa: ANN401
    *,
    sample_shape: tuple[int, ...] = (),
) -> Any:  # noqa: ANN401
    """Quantize addressed native Normal draws, returning latent float dtype.

    A draw exactly on a cutpoint enters the higher bin. Replay, leading
    sample axes and local-generator semantics are those of IIDObservation.
    Nonfinite underlying draws remain NaN, never valid-looking bin codes.
    """
    draws = IIDObservation(
        family="normal", scale=self.scale, offset=self.offset, slope=self.slope
    ).sample(latent, key, sample_shape=sample_shape)
    xp = array_namespace(draws)
    codes = xp.zeros_like(draws)
    for cutpoint in self.cutpoints:
        codes = codes + xp.astype(draws >= cutpoint, draws.dtype)
    return xp.where(xp.isfinite(draws), codes, xp.full_like(draws, xp.nan))

IIDObservation

Bases: _Record

Independent measurements on an affine map of one named latent output.

Normal uses a physical mean and standard deviation; LogNormal uses a log-location and log-standard deviation. NB2 has variance mu + mu**2 / k, where concentration=k. Beta-binomial uses probability p and concentration k, hence alpha=pk and beta=(1-p)k. Bernoulli sensitivity/specificity map a true probability to the probability of a positive measurement.

Optional Normal clipping records left/right censoring as probability mass at the limit. Missing cells contribute zero and can contain NaNs. Values outside support contribute -inf. Families with other censoring or dependence require another explicitly qualified ObservationModel.

Examples:

>>> import numpy as np
>>> model = IIDObservation(family="normal", scale=0.5)
>>> model.log_prob(np.array([0.0]), np.array([0.0])).round(6)
array([-0.225791])
Source code in src/op_infer/observe.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
class IIDObservation(_Record):
    """Independent measurements on an affine map of one named latent output.

    Normal uses a physical mean and standard deviation; LogNormal uses a
    log-location and log-standard deviation. NB2 has variance mu + mu**2 / k,
    where ``concentration=k``. Beta-binomial uses probability p and concentration
    k, hence alpha=p*k and beta=(1-p)*k. Bernoulli sensitivity/specificity map a
    true probability to the probability of a positive measurement.

    Optional Normal clipping records left/right censoring as probability mass
    at the limit. Missing cells contribute zero and can contain NaNs. Values
    outside support contribute -inf. Families with other censoring or dependence
    require another explicitly qualified ObservationModel.

    Examples:
        >>> import numpy as np
        >>> model = IIDObservation(family="normal", scale=0.5)
        >>> model.log_prob(np.array([0.0]), np.array([0.0])).round(6)
        array([-0.225791])
    """

    family: _Family
    scale: _Positive = 1.0
    concentration: _Positive = 1.0
    trials: Annotated[int, Field(ge=0)] = 1
    sensitivity: _Probability = 1.0
    specificity: _Probability = 1.0
    offset: _Finite = 0.0
    slope: _Finite = 1.0
    lower_limit: _Finite | None = None
    upper_limit: _Finite | None = None

    @model_validator(mode="after")
    def _limits(self) -> Self:
        if (
            self.lower_limit is not None or self.upper_limit is not None
        ) and self.family != "normal":
            msg = "Censoring is qualified only for Normal measurements"
            raise ValueError(msg)
        if (
            self.lower_limit is not None
            and self.upper_limit is not None
            and self.lower_limit >= self.upper_limit
        ):
            msg = "Censoring limits require lower_limit < upper_limit"
            raise ValueError(msg)
        return self

    @property
    def reference(self) -> ArtifactReference:
        """Return stable versioned observation-law identity."""
        data = {
            "schema_version": 1,
            "dependence": "iid",
            "mask": "true-is-observed",
            "parameters": self.model_dump(mode="json"),
        }
        payload = json.dumps(
            data, sort_keys=True, separators=(",", ":"), allow_nan=False
        )
        return ArtifactReference.from_bytes(payload.encode(), kind="iid-observation-v1")

    def log_prob(self, latent: Any, observed: Any, *, mask: Any = None) -> Any:  # noqa: ANN401
        """Score measurements per cell, retaining graphs and leading batch axes.

        The latent input must be a native floating array. Observed arrays share
        its namespace. Masks must be boolean and match the broadcast result;
        excluded values are replaced before density evaluation, preventing
        missing NaNs from contaminating gradients.
        """
        xp = array_namespace(latent, observed)
        backend = _backend(xp)
        if not xp.isdtype(latent.dtype, "real floating"):
            msg = "Observation latent values must have real floating dtype"
            raise TypeError(msg)
        mean, value = xp.broadcast_arrays(self.offset + self.slope * latent, observed)
        selected = xp.ones_like(mean, dtype=xp.bool) if mask is None else mask
        if (
            array_namespace(selected).__name__ != xp.__name__
            or selected.dtype != xp.bool
            or tuple(selected.shape) != tuple(mean.shape)
        ):
            msg = "Observation mask must be native boolean with the broadcast shape"
            raise ValueError(msg)
        safe_mean, valid = self._safe_mean(mean, xp)
        placeholder = 1.0 if self.family == "lognormal" else 0.0
        value = xp.where(selected, value, xp.full_like(mean, placeholder))
        law = self._native(safe_mean, backend)
        if backend == "numpy":
            density = (
                law.logpmf(value)
                if self.family
                in {"poisson", "nb2", "binomial", "beta_binomial", "bernoulli"}
                else law.logpdf(value)
            )
        elif self.family == "beta_binomial":
            density = self._beta_binomial_density(safe_mean, value, xp)
        else:
            support = (
                law.support(value) if backend == "jax" else law.support.check(value)
            )
            safe_value = xp.where(support, value, xp.full_like(mean, placeholder))
            density = xp.where(support, law.log_prob(safe_value), -xp.inf)
        if self.family in {"binomial", "bernoulli"}:
            probability = (
                (1 - self.specificity)
                + (self.sensitivity + self.specificity - 1) * mean
                if self.family == "bernoulli"
                else mean
            )
            trials = 1 if self.family == "bernoulli" else self.trials
            density = xp.where(
                probability == 0, xp.where(value == 0, 0.0, -xp.inf), density
            )
            density = xp.where(
                probability == 1, xp.where(value == trials, 0.0, -xp.inf), density
            )
        if self.family in {"poisson", "nb2"}:
            density = xp.where(mean == 0, xp.where(value == 0, 0.0, -xp.inf), density)
        density = xp.where(valid, density, -xp.inf)
        if self.lower_limit is not None or self.upper_limit is not None:
            special = importlib.import_module(
                {
                    "numpy": "scipy.special",
                    "jax": "jax.scipy.special",
                    "torch": "torch.special",
                }[backend]
            )
            if self.lower_limit is not None:
                z = (self.lower_limit - safe_mean) / self.scale
                density = xp.where(
                    value == self.lower_limit,
                    special.log_ndtr(z),
                    xp.where(value < self.lower_limit, -xp.inf, density),
                )
            if self.upper_limit is not None:
                z = (safe_mean - self.upper_limit) / self.scale
                density = xp.where(
                    value == self.upper_limit,
                    special.log_ndtr(z),
                    xp.where(value > self.upper_limit, -xp.inf, density),
                )
        density = xp.where(xp.isnan(value), xp.full_like(mean, xp.nan), density)
        return xp.where(selected, density, 0.0)

    def _safe_mean(self, mean: Any, xp: Any) -> tuple[Any, Any]:  # noqa: ANN401
        valid = xp.isfinite(mean)
        if self.family in {"poisson", "nb2"}:
            valid = valid & (mean >= 0)
        elif self.family in {"binomial", "bernoulli", "beta_binomial"}:
            valid = valid & (mean >= 0) & (mean <= 1)
            if self.family == "beta_binomial":
                valid = valid & (mean > 0) & (mean < 1)
        safe = xp.where(valid, mean, xp.full_like(mean, 0.5))
        if self.family in {"poisson", "nb2"}:
            safe = xp.where(mean == 0, xp.ones_like(mean), safe)
        return safe, valid

    def _native(self, mean: Any, backend: str) -> Any:  # noqa: ANN401, PLR0911, C901
        if backend == "numpy":
            stats = importlib.import_module("scipy.stats")
            if self.family == "normal":
                return stats.norm(loc=mean, scale=self.scale)
            if self.family == "lognormal":
                return stats.lognorm(
                    s=self.scale, scale=importlib.import_module("numpy").exp(mean)
                )
            if self.family == "poisson":
                return stats.poisson(mu=mean)
            if self.family == "nb2":
                return stats.nbinom(
                    n=self.concentration,
                    p=self.concentration / (self.concentration + mean),
                )
            if self.family == "beta_binomial":
                return stats.betabinom(
                    n=self.trials,
                    a=mean * self.concentration,
                    b=(1 - mean) * self.concentration,
                )
            probability = (
                (1 - self.specificity)
                + (self.sensitivity + self.specificity - 1) * mean
                if self.family == "bernoulli"
                else mean
            )
            return stats.binom(
                n=1 if self.family == "bernoulli" else self.trials, p=probability
            )
        distributions = importlib.import_module(
            "numpyro.distributions" if backend == "jax" else "torch.distributions"
        )
        if self.family in {"normal", "lognormal"}:
            return getattr(
                distributions, "Normal" if self.family == "normal" else "LogNormal"
            )(mean, self.scale, validate_args=False)
        if self.family == "poisson":
            return distributions.Poisson(mean, validate_args=False)
        if self.family == "nb2":
            if backend == "jax":
                return distributions.NegativeBinomial2(
                    mean, self.concentration, validate_args=False
                )
            return distributions.NegativeBinomial(
                self.concentration,
                probs=mean / (mean + self.concentration),
                validate_args=False,
            )
        if self.family == "beta_binomial":
            return (
                distributions.BetaBinomial(
                    mean * self.concentration,
                    (1 - mean) * self.concentration,
                    total_count=self.trials,
                    validate_args=False,
                )
                if backend == "jax"
                else None
            )
        probability = (
            (1 - self.specificity) + (self.sensitivity + self.specificity - 1) * mean
            if self.family == "bernoulli"
            else mean
        )
        return distributions.Binomial(
            total_count=1 if self.family == "bernoulli" else self.trials,
            probs=probability,
            validate_args=False,
        )

    def _beta_binomial_density(self, mean: Any, value: Any, xp: Any) -> Any:  # noqa: ANN401
        backend = _backend(xp)
        special = importlib.import_module(
            "jax.scipy.special" if backend == "jax" else "torch"
        )
        a = mean * self.concentration
        b = (1 - mean) * self.concentration
        valid = (value >= 0) & (value <= self.trials) & (value == xp.floor(value))
        safe = xp.where(valid, value, xp.zeros_like(mean))
        log_gamma = special.gammaln if backend == "jax" else special.lgamma
        n = xp.full_like(mean, float(self.trials))
        density = (
            log_gamma(n + 1)
            - log_gamma(safe + 1)
            - log_gamma(n - safe + 1)
            + log_gamma(safe + a)
            + log_gamma(n - safe + b)
            - log_gamma(n + a + b)
            - log_gamma(a)
            - log_gamma(b)
            + log_gamma(a + b)
        )
        return xp.where(valid, density, -xp.inf)

    def sample(
        self,
        latent: Any,  # noqa: ANN401
        key: Any,  # noqa: ANN401
        *,
        sample_shape: tuple[int, ...] = (),
    ) -> Any:  # noqa: ANN401
        """Draw native measurements; RandomKey lowering happens outside tracing.

        JAX accepts a native key for jitted/vmapped sampling. Torch accepts a
        local device-matched Generator; RandomKey creates one without seeding
        global state. Scoped Torch CUDA sampling uses float32/64. Returned counts
        use latent float dtype, matching native Torch count distributions.
        """
        _validate_sample_shape(sample_shape)
        xp = array_namespace(latent)
        backend = _backend(xp)
        if not xp.isdtype(latent.dtype, "real floating"):
            msg = "Observation latent values must have real floating dtype"
            raise TypeError(msg)
        mean = self.offset + self.slope * latent
        shape = sample_shape + tuple(mean.shape)
        if backend == "numpy":
            numpy_generator = RandomKey.model_validate(key).numpy_generator()
            result = xp.asarray(
                self._native(mean, backend).rvs(
                    size=shape, random_state=numpy_generator
                ),
                dtype=latent.dtype,
            )
        elif backend == "jax":
            from op_infer.adapters.rng import jax_key  # noqa: PLC0415

            native_key = jax_key(key) if isinstance(key, RandomKey) else key
            result = (
                self._native(mean, backend)
                .sample(native_key, sample_shape=sample_shape)
                .astype(latent.dtype)
            )
        else:
            from op_infer.adapters.rng import torch_generators  # noqa: PLC0415

            if latent.device.type not in {"cpu", "cuda"}:
                msg = "Observation Torch sampling is qualified only on CPU and CUDA"
                raise ValueError(msg)
            if latent.device.type == "cuda" and latent.dtype not in {
                xp.float32,
                xp.float64,
            }:
                msg = "CUDA observation sampling requires float32 or float64"
                raise TypeError(msg)
            generator = (
                torch_generators((key,), device=latent.device)[0]
                if isinstance(key, RandomKey)
                else key
            )
            if getattr(generator, "device", None) != latent.device:
                msg = "Torch observation generator device must match the latent device"
                raise ValueError(msg)
            result = self._torch_sample(mean, generator, shape)
        if self.lower_limit is not None:
            result = xp.maximum(result, xp.full_like(result, self.lower_limit))
        if self.upper_limit is not None:
            result = xp.minimum(result, xp.full_like(result, self.upper_limit))
        return result

    def _torch_sample(self, mean: Any, generator: Any, shape: tuple[int, ...]) -> Any:  # noqa: ANN401
        torch = importlib.import_module("torch")
        mean = mean.expand(shape)
        options = {"dtype": mean.dtype, "device": mean.device, "generator": generator}
        if self.family in {"normal", "lognormal"}:
            result = mean + self.scale * torch.randn(shape, **options)
            return torch.exp(result) if self.family == "lognormal" else result
        if self.family == "poisson":
            return torch.poisson(mean, generator=generator)
        if self.family == "nb2":
            concentration = torch.full_like(mean, self.concentration)
            rate = (
                torch._standard_gamma(concentration, generator=generator)  # noqa: SLF001
                * mean
                / self.concentration
            )
            return torch.poisson(rate, generator=generator)
        if self.family == "beta_binomial":
            a = torch._standard_gamma(  # noqa: SLF001
                mean * self.concentration, generator=generator
            )
            b = torch._standard_gamma(  # noqa: SLF001 -- native primitive takes a local generator
                (1 - mean) * self.concentration, generator=generator
            )
            probability = a / (a + b)
        else:
            probability = (
                (1 - self.specificity)
                + (self.sensitivity + self.specificity - 1) * mean
                if self.family == "bernoulli"
                else mean
            )
        return torch.binomial(
            torch.full_like(mean, 1 if self.family == "bernoulli" else self.trials),
            probability,
            generator=generator,
        )

reference property

Return stable versioned observation-law identity.

log_prob(latent, observed, *, mask=None)

Score measurements per cell, retaining graphs and leading batch axes.

The latent input must be a native floating array. Observed arrays share its namespace. Masks must be boolean and match the broadcast result; excluded values are replaced before density evaluation, preventing missing NaNs from contaminating gradients.

Source code in src/op_infer/observe.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
def log_prob(self, latent: Any, observed: Any, *, mask: Any = None) -> Any:  # noqa: ANN401
    """Score measurements per cell, retaining graphs and leading batch axes.

    The latent input must be a native floating array. Observed arrays share
    its namespace. Masks must be boolean and match the broadcast result;
    excluded values are replaced before density evaluation, preventing
    missing NaNs from contaminating gradients.
    """
    xp = array_namespace(latent, observed)
    backend = _backend(xp)
    if not xp.isdtype(latent.dtype, "real floating"):
        msg = "Observation latent values must have real floating dtype"
        raise TypeError(msg)
    mean, value = xp.broadcast_arrays(self.offset + self.slope * latent, observed)
    selected = xp.ones_like(mean, dtype=xp.bool) if mask is None else mask
    if (
        array_namespace(selected).__name__ != xp.__name__
        or selected.dtype != xp.bool
        or tuple(selected.shape) != tuple(mean.shape)
    ):
        msg = "Observation mask must be native boolean with the broadcast shape"
        raise ValueError(msg)
    safe_mean, valid = self._safe_mean(mean, xp)
    placeholder = 1.0 if self.family == "lognormal" else 0.0
    value = xp.where(selected, value, xp.full_like(mean, placeholder))
    law = self._native(safe_mean, backend)
    if backend == "numpy":
        density = (
            law.logpmf(value)
            if self.family
            in {"poisson", "nb2", "binomial", "beta_binomial", "bernoulli"}
            else law.logpdf(value)
        )
    elif self.family == "beta_binomial":
        density = self._beta_binomial_density(safe_mean, value, xp)
    else:
        support = (
            law.support(value) if backend == "jax" else law.support.check(value)
        )
        safe_value = xp.where(support, value, xp.full_like(mean, placeholder))
        density = xp.where(support, law.log_prob(safe_value), -xp.inf)
    if self.family in {"binomial", "bernoulli"}:
        probability = (
            (1 - self.specificity)
            + (self.sensitivity + self.specificity - 1) * mean
            if self.family == "bernoulli"
            else mean
        )
        trials = 1 if self.family == "bernoulli" else self.trials
        density = xp.where(
            probability == 0, xp.where(value == 0, 0.0, -xp.inf), density
        )
        density = xp.where(
            probability == 1, xp.where(value == trials, 0.0, -xp.inf), density
        )
    if self.family in {"poisson", "nb2"}:
        density = xp.where(mean == 0, xp.where(value == 0, 0.0, -xp.inf), density)
    density = xp.where(valid, density, -xp.inf)
    if self.lower_limit is not None or self.upper_limit is not None:
        special = importlib.import_module(
            {
                "numpy": "scipy.special",
                "jax": "jax.scipy.special",
                "torch": "torch.special",
            }[backend]
        )
        if self.lower_limit is not None:
            z = (self.lower_limit - safe_mean) / self.scale
            density = xp.where(
                value == self.lower_limit,
                special.log_ndtr(z),
                xp.where(value < self.lower_limit, -xp.inf, density),
            )
        if self.upper_limit is not None:
            z = (safe_mean - self.upper_limit) / self.scale
            density = xp.where(
                value == self.upper_limit,
                special.log_ndtr(z),
                xp.where(value > self.upper_limit, -xp.inf, density),
            )
    density = xp.where(xp.isnan(value), xp.full_like(mean, xp.nan), density)
    return xp.where(selected, density, 0.0)

sample(latent, key, *, sample_shape=())

Draw native measurements; RandomKey lowering happens outside tracing.

JAX accepts a native key for jitted/vmapped sampling. Torch accepts a local device-matched Generator; RandomKey creates one without seeding global state. Scoped Torch CUDA sampling uses float32/64. Returned counts use latent float dtype, matching native Torch count distributions.

Source code in src/op_infer/observe.py
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def sample(
    self,
    latent: Any,  # noqa: ANN401
    key: Any,  # noqa: ANN401
    *,
    sample_shape: tuple[int, ...] = (),
) -> Any:  # noqa: ANN401
    """Draw native measurements; RandomKey lowering happens outside tracing.

    JAX accepts a native key for jitted/vmapped sampling. Torch accepts a
    local device-matched Generator; RandomKey creates one without seeding
    global state. Scoped Torch CUDA sampling uses float32/64. Returned counts
    use latent float dtype, matching native Torch count distributions.
    """
    _validate_sample_shape(sample_shape)
    xp = array_namespace(latent)
    backend = _backend(xp)
    if not xp.isdtype(latent.dtype, "real floating"):
        msg = "Observation latent values must have real floating dtype"
        raise TypeError(msg)
    mean = self.offset + self.slope * latent
    shape = sample_shape + tuple(mean.shape)
    if backend == "numpy":
        numpy_generator = RandomKey.model_validate(key).numpy_generator()
        result = xp.asarray(
            self._native(mean, backend).rvs(
                size=shape, random_state=numpy_generator
            ),
            dtype=latent.dtype,
        )
    elif backend == "jax":
        from op_infer.adapters.rng import jax_key  # noqa: PLC0415

        native_key = jax_key(key) if isinstance(key, RandomKey) else key
        result = (
            self._native(mean, backend)
            .sample(native_key, sample_shape=sample_shape)
            .astype(latent.dtype)
        )
    else:
        from op_infer.adapters.rng import torch_generators  # noqa: PLC0415

        if latent.device.type not in {"cpu", "cuda"}:
            msg = "Observation Torch sampling is qualified only on CPU and CUDA"
            raise ValueError(msg)
        if latent.device.type == "cuda" and latent.dtype not in {
            xp.float32,
            xp.float64,
        }:
            msg = "CUDA observation sampling requires float32 or float64"
            raise TypeError(msg)
        generator = (
            torch_generators((key,), device=latent.device)[0]
            if isinstance(key, RandomKey)
            else key
        )
        if getattr(generator, "device", None) != latent.device:
            msg = "Torch observation generator device must match the latent device"
            raise ValueError(msg)
        result = self._torch_sample(mean, generator, shape)
    if self.lower_limit is not None:
        result = xp.maximum(result, xp.full_like(result, self.lower_limit))
    if self.upper_limit is not None:
        result = xp.minimum(result, xp.full_like(result, self.upper_limit))
    return result

ObservationModel

Bases: Protocol

Expose one statistical target for sampling, scoring and artifact identity.

Source code in src/op_infer/observe.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class ObservationModel(Protocol):
    """Expose one statistical target for sampling, scoring and artifact identity."""

    @property
    def reference(self) -> ArtifactReference:
        """Identify family, parameterization, support and censoring semantics."""
        ...

    def log_prob(self, latent: Any, observed: Any, *, mask: Any = None) -> Any:  # noqa: ANN401
        """Return per-cell density/mass with True meaning observed."""
        ...

    def sample(
        self,
        latent: Any,  # noqa: ANN401
        key: Any,  # noqa: ANN401
        *,
        sample_shape: tuple[int, ...] = (),
    ) -> Any:  # noqa: ANN401
        """Draw addressed native measurements without changing global RNG state."""
        ...

reference property

Identify family, parameterization, support and censoring semantics.

log_prob(latent, observed, *, mask=None)

Return per-cell density/mass with True meaning observed.

Source code in src/op_infer/observe.py
40
41
42
def log_prob(self, latent: Any, observed: Any, *, mask: Any = None) -> Any:  # noqa: ANN401
    """Return per-cell density/mass with True meaning observed."""
    ...

sample(latent, key, *, sample_shape=())

Draw addressed native measurements without changing global RNG state.

Source code in src/op_infer/observe.py
44
45
46
47
48
49
50
51
52
def sample(
    self,
    latent: Any,  # noqa: ANN401
    key: Any,  # noqa: ANN401
    *,
    sample_shape: tuple[int, ...] = (),
) -> Any:  # noqa: ANN401
    """Draw addressed native measurements without changing global RNG state."""
    ...

forward

Forward models, designs and simulators.

Status: immutable forward-run references, a named-output protocol and a guarded plain-callable adapter are implemented. Optional numerical adapters live outside the core. See docs/design/numerical-provenance.md.

Scope: ForwardModel protocol (theta, design, key) -> latent outputs, with adapters for op_system CompiledRhs + op_engine solvers and plain callables; Simulator = forward + observation + prior, compatible with trade_study.Simulator; Design objects with sampling schedules, limits, controlled covariates and a design hash; compile-once kernels with data passed as traced inputs.

CallableForward dataclass

Adapt an explicitly identified callable without optional numerical libraries.

Callbacks receive the original native parameter/design inputs and simulation key. Use SimulationStreams to draw parameters on its separate parameter stream. The caller declares a model manifest; this adapter never hashes callable repr, bytecode, globals or closure contents.

Attributes:

Name Type Description
function Callable[[Mapping[str, object], object, RandomKey], Mapping[str, object]]

(theta, design.inputs, key) -> named native latent outputs.

parameter_names tuple[str, ...]

Complete ordered parameter names, including initial-state and observable-only parameters used by this callable.

output_names tuple[str, ...]

Complete ordered latent output names.

provenance Provenance

Schema-2 shared provenance, with declared model content.

Source code in src/op_infer/forward.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
@dataclass(frozen=True, slots=True)
class CallableForward:
    """Adapt an explicitly identified callable without optional numerical libraries.

    Callbacks receive the original native parameter/design
    inputs and simulation key. Use ``SimulationStreams`` to draw parameters on
    its separate parameter stream. The caller declares a model manifest; this
    adapter never hashes callable repr, bytecode, globals or closure contents.

    Attributes:
        function: ``(theta, design.inputs, key) -> named native latent outputs``.
        parameter_names: Complete ordered parameter names, including initial-state
            and observable-only parameters used by this callable.
        output_names: Complete ordered latent output names.
        provenance: Schema-2 shared provenance, with declared model content.
    """

    function: Callable[
        [Mapping[str, object], object, RandomKey], Mapping[str, object]
    ] = field(repr=False, compare=False)
    parameter_names: tuple[str, ...]
    output_names: tuple[str, ...]
    provenance: Provenance

    def __post_init__(self) -> None:
        """Validate declarations before invoking a consumer callback.

        Raises:
            ValueError: Layouts or structural provenance are incomplete.
            TypeError: The supplied callback is not callable.
        """
        Provenance.model_validate(self.provenance)
        if self.provenance.schema_version != 2:
            msg = "Forward adapters require schema-2 structural model provenance"
            raise ValueError(msg)
        for names in (self.parameter_names, self.output_names):
            if (
                not isinstance(names, tuple)
                or not names
                or any(not isinstance(name, str) or not name.strip() for name in names)
                or len(set(names)) != len(names)
            ):
                msg = "Forward parameter/output layouts must be nonempty unique tuples"
                raise ValueError(msg)
        if not callable(self.function):
            msg = "Forward function must be callable"
            raise TypeError(msg)

    def __call__(
        self, theta: Mapping[str, object], design: ForwardDesign, key: RandomKey
    ) -> Mapping[str, object]:
        """Check static identity/layout, then preserve native callback outputs.

        Args:
            theta: Complete named parameters; values are borrowed, never converted.
            design: Independently supplied expected physical design and inputs.
            key: Explicit simulation stream address, separate from parameter draws.

        Returns:
            Named native outputs in the declared order, without array copies.

        Raises:
            ValueError: Design, parameter names or output names differ.
            TypeError: The callback does not return named outputs.
        """
        if design.reference != self.provenance.design:
            msg = "Forward design identity mismatch"
            raise ValueError(msg)
        if set(theta) != set(self.parameter_names):
            msg = "Forward parameter names differ from the declared binding layout"
            raise ValueError(msg)
        RandomKey.model_validate(key)
        outputs = self.function(theta, design.inputs, key)
        if not isinstance(outputs, Mapping):
            msg = "Forward callback must return a mapping of named outputs"
            raise TypeError(msg)
        if tuple(outputs) != self.output_names:
            msg = "Forward output names/order differ from the declared layout"
            raise ValueError(msg)
        return outputs

__call__(theta, design, key)

Check static identity/layout, then preserve native callback outputs.

Parameters:

Name Type Description Default
theta Mapping[str, object]

Complete named parameters; values are borrowed, never converted.

required
design ForwardDesign

Independently supplied expected physical design and inputs.

required
key RandomKey

Explicit simulation stream address, separate from parameter draws.

required

Returns:

Type Description
Mapping[str, object]

Named native outputs in the declared order, without array copies.

Raises:

Type Description
ValueError

Design, parameter names or output names differ.

TypeError

The callback does not return named outputs.

Source code in src/op_infer/forward.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def __call__(
    self, theta: Mapping[str, object], design: ForwardDesign, key: RandomKey
) -> Mapping[str, object]:
    """Check static identity/layout, then preserve native callback outputs.

    Args:
        theta: Complete named parameters; values are borrowed, never converted.
        design: Independently supplied expected physical design and inputs.
        key: Explicit simulation stream address, separate from parameter draws.

    Returns:
        Named native outputs in the declared order, without array copies.

    Raises:
        ValueError: Design, parameter names or output names differ.
        TypeError: The callback does not return named outputs.
    """
    if design.reference != self.provenance.design:
        msg = "Forward design identity mismatch"
        raise ValueError(msg)
    if set(theta) != set(self.parameter_names):
        msg = "Forward parameter names differ from the declared binding layout"
        raise ValueError(msg)
    RandomKey.model_validate(key)
    outputs = self.function(theta, design.inputs, key)
    if not isinstance(outputs, Mapping):
        msg = "Forward callback must return a mapping of named outputs"
        raise TypeError(msg)
    if tuple(outputs) != self.output_names:
        msg = "Forward output names/order differ from the declared layout"
        raise ValueError(msg)
    return outputs

__post_init__()

Validate declarations before invoking a consumer callback.

Raises:

Type Description
ValueError

Layouts or structural provenance are incomplete.

TypeError

The supplied callback is not callable.

Source code in src/op_infer/forward.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def __post_init__(self) -> None:
    """Validate declarations before invoking a consumer callback.

    Raises:
        ValueError: Layouts or structural provenance are incomplete.
        TypeError: The supplied callback is not callable.
    """
    Provenance.model_validate(self.provenance)
    if self.provenance.schema_version != 2:
        msg = "Forward adapters require schema-2 structural model provenance"
        raise ValueError(msg)
    for names in (self.parameter_names, self.output_names):
        if (
            not isinstance(names, tuple)
            or not names
            or any(not isinstance(name, str) or not name.strip() for name in names)
            or len(set(names)) != len(names)
        ):
            msg = "Forward parameter/output layouts must be nonempty unique tuples"
            raise ValueError(msg)
    if not callable(self.function):
        msg = "Forward function must be callable"
        raise TypeError(msg)

ForwardDesign dataclass

Keep physical design identity beside native inputs without copying arrays.

The reference is an independently supplied content claim, not an automatic digest or authenticity/integrity check of inputs. Treat borrowed inputs as immutable; retain their graphs and device placement. Design objects use identity equality; compare reference explicitly.

Attributes:

Name Type Description
reference ArtifactReference

Physical design/data/layout identity expected by provenance.

inputs object

Consumer-defined native design inputs, passed through unchanged.

Examples:

>>> inputs = {"sampling_times": (0.0, 1.0)}
>>> reference = ArtifactReference.from_bytes(b"times=0,1", kind="design-v1")
>>> design = ForwardDesign(reference, inputs)
>>> design.inputs is inputs
True
Source code in src/op_infer/forward.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass(frozen=True, slots=True, eq=False)
class ForwardDesign:
    """Keep physical design identity beside native inputs without copying arrays.

    The reference is an independently supplied content
    claim, not an automatic digest or authenticity/integrity check of ``inputs``.
    Treat borrowed inputs as immutable; retain their graphs and device placement.
    Design objects use identity equality; compare ``reference`` explicitly.

    Attributes:
        reference: Physical design/data/layout identity expected by provenance.
        inputs: Consumer-defined native design inputs, passed through unchanged.

    Examples:
        >>> inputs = {"sampling_times": (0.0, 1.0)}
        >>> reference = ArtifactReference.from_bytes(b"times=0,1", kind="design-v1")
        >>> design = ForwardDesign(reference, inputs)
        >>> design.inputs is inputs
        True
    """

    reference: ArtifactReference
    inputs: object

    def __post_init__(self) -> None:
        """Validate immutable metadata without examining native inputs."""
        ArtifactReference.model_validate(self.reference)

__post_init__()

Validate immutable metadata without examining native inputs.

Source code in src/op_infer/forward.py
51
52
53
def __post_init__(self) -> None:
    """Validate immutable metadata without examining native inputs."""
    ArtifactReference.model_validate(self.reference)

ForwardModel

Bases: Protocol

Named latent outputs from explicit parameters, design and simulation key.

Statistical sampling and log density are separate. Implementations expose ordered parameter/output layouts and the shared provenance contract; backend/JIT/derivative support is adapter-specific.

Source code in src/op_infer/forward.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class ForwardModel(Protocol):
    """Named latent outputs from explicit parameters, design and simulation key.

    Statistical sampling and log density are separate.
    Implementations expose ordered parameter/output layouts and the shared
    provenance contract; backend/JIT/derivative support is adapter-specific.
    """

    @property
    def parameter_names(self) -> tuple[str, ...]:
        """Return the declared parameter binding order."""
        ...

    @property
    def output_names(self) -> tuple[str, ...]:
        """Return the declared latent output order."""
        ...

    @property
    def provenance(self) -> Provenance:
        """Return shared structural/design/numerical/runtime identity."""
        ...

    def __call__(
        self, theta: Mapping[str, object], design: ForwardDesign, key: RandomKey
    ) -> Mapping[str, object]:
        """Evaluate native outputs without implicitly drawing parameters or noise."""
        ...

output_names property

Return the declared latent output order.

parameter_names property

Return the declared parameter binding order.

provenance property

Return shared structural/design/numerical/runtime identity.

__call__(theta, design, key)

Evaluate native outputs without implicitly drawing parameters or noise.

Source code in src/op_infer/forward.py
79
80
81
82
83
def __call__(
    self, theta: Mapping[str, object], design: ForwardDesign, key: RandomKey
) -> Mapping[str, object]:
    """Evaluate native outputs without implicitly drawing parameters or noise."""
    ...

ForwardRunReference

Bases: BaseModel

Attach shared provenance to numerical outputs.

This is metadata for immutable outputs, not an array container or solver adapter.

Attributes:

Name Type Description
outputs ArtifactReference

Reference to numerical output bytes, including dtype/shape/layout.

provenance Provenance

Shared target/numerical identity used by posterior artifacts.

Source code in src/op_infer/forward.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
class ForwardRunReference(BaseModel):
    """Attach shared provenance to numerical outputs.

    This is metadata for immutable outputs, not an array container or solver adapter.

    Attributes:
        outputs: Reference to numerical output bytes, including dtype/shape/layout.
        provenance: Shared target/numerical identity used by posterior artifacts.
    """

    model_config = ConfigDict(
        frozen=True, extra="forbid", strict=True, revalidate_instances="always"
    )

    outputs: ArtifactReference
    provenance: Provenance

    @model_validator(mode="after")
    def _require_numerical_execution(self) -> Self:
        if self.provenance.numerical is None:
            msg = "Numerical forward references require an execution contract"
            raise ValueError(msg)
        return self

op

Optional compiler/fixed-engine adapter with observation-only retention.

Numerical stages and namespace loop operations are owned by op_engine. This adapter binds named parameters and evaluates existing compiled latent observables; it adds neither integration methods nor noise.

FixedForwardSettings

Bases: BaseModel

Static bounded deterministic solver and stored-observation-time choices.

Attributes:

Name Type Description
times tuple[float, ...]

Start time followed by requested observation times; no interpolation.

method Literal['euler', 'heun', 'rk4', 'dopri5']

Existing engine fixed explicit method.

dtype Literal['float32', 'float64']

Declared native state precision, checked without converting arrays.

max_step float

Maximum internal step between stored observation times.

fixed_loop Literal['auto', 'scan', 'unroll']

Eager stepping or namespace-native scan selection.

checkpoint bool

Rematerialize a forced scan's body during reverse mode.

max_internal_steps int

Hard setup limit on the complete fixed partition.

Examples:

>>> settings = FixedForwardSettings(times=(0.0, 1.0), max_step=0.1)
>>> settings.method, settings.fixed_loop
('rk4', 'auto')
Source code in src/op_infer/adapters/op.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class FixedForwardSettings(BaseModel):
    """Static bounded deterministic solver and stored-observation-time choices.

    Attributes:
        times: Start time followed by requested observation times; no interpolation.
        method: Existing engine fixed explicit method.
        dtype: Declared native state precision, checked without converting arrays.
        max_step: Maximum internal step between stored observation times.
        fixed_loop: Eager stepping or namespace-native scan selection.
        checkpoint: Rematerialize a forced scan's body during reverse mode.
        max_internal_steps: Hard setup limit on the complete fixed partition.

    Examples:
        >>> settings = FixedForwardSettings(times=(0.0, 1.0), max_step=0.1)
        >>> settings.method, settings.fixed_loop
        ('rk4', 'auto')
    """

    model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
    times: tuple[float, ...]
    method: Literal["euler", "heun", "rk4", "dopri5"] = "rk4"
    dtype: Literal["float32", "float64"] = "float64"
    max_step: float = Field(default=0.1, gt=0, allow_inf_nan=False)
    fixed_loop: Literal["auto", "scan", "unroll"] = "auto"
    checkpoint: bool = False
    max_internal_steps: int = Field(default=100_000, ge=1)

    @model_validator(mode="after")
    def _static_grid(self) -> Self:
        if (
            not self.times
            or not all(math.isfinite(t) for t in self.times)
            or any(right <= left for left, right in pairwise(self.times))
        ):
            msg = "Forward times must be finite, nonempty and strictly increasing"
            raise ValueError(msg)
        if self.checkpoint and self.fixed_loop != "scan":
            msg = "Forward checkpointing requires fixed_loop='scan'"
            raise ValueError(msg)
        return self

compiled_forward(compiled, *, settings, initial_state, parameter_names, output_names, provenance)

Bind compiled latent observables to existing functional fixed-step kernels.

The native carry contains current state/FSAL only; scan outputs are None. At requested times, existing engine observation adapters evaluate selected compiler observables. Only those latent series are stacked. Reverse-mode AD may retain its own residuals; checkpointing does not promise a memory bound. The returned callable is reused with dynamic parameters/initial states.

Parameters:

Name Type Description Default
compiled Any

Natural-coordinate model without operators, history, tables or scheduled state maps.

required
settings FixedForwardSettings

Static fixed partition, output grid and explicit work bound.

required
initial_state Callable[[Mapping[str, object], object], object]

Native flat state factory, given parameters/design inputs.

required
parameter_names tuple[str, ...]

Complete binding layout, including observable/initial inputs.

required
output_names tuple[str, ...]

Selected compiled observable names in returned order.

required
provenance Provenance

Schema-2 identity with matching model, solver, mesh and observation references. Source/runtime and statistical qualification remain explicit.

required

Returns:

Type Description
CallableForward

A callable satisfying the core forward protocol. Qualified CPU cases use

CallableForward

NumPy, JAX JIT/vmap/AD and Torch AD; other devices need separate evidence.

Raises:

Type Description
ValueError

Identity, layout, settings or declared work limits disagree.

NotImplementedError

Operators, history, tables, scheduled state maps or gauge-fixed execution need a separately qualified adapter.

Source code in src/op_infer/adapters/op.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def compiled_forward(  # noqa: C901, PLR0913, PLR0915 - static binding and one native evaluator
    compiled: Any,  # noqa: ANN401 - optional compiler boundary
    *,
    settings: FixedForwardSettings,
    initial_state: Callable[[Mapping[str, object], object], object],
    parameter_names: tuple[str, ...],
    output_names: tuple[str, ...],
    provenance: Provenance,
) -> CallableForward:
    """Bind compiled latent observables to existing functional fixed-step kernels.

    The native carry contains current state/FSAL only; scan outputs are ``None``.
    At requested times, existing engine observation adapters evaluate selected
    compiler observables. Only those latent series are stacked. Reverse-mode AD
    may retain its own residuals; checkpointing does not promise a memory bound.
    The returned callable is reused with dynamic parameters/initial states.

    Args:
        compiled: Natural-coordinate model without operators, history, tables or
            scheduled state maps.
        settings: Static fixed partition, output grid and explicit work bound.
        initial_state: Native flat state factory, given parameters/design inputs.
        parameter_names: Complete binding layout, including observable/initial inputs.
        output_names: Selected compiled observable names in returned order.
        provenance: Schema-2 identity with matching model, solver, mesh and observation
            references. Source/runtime and statistical qualification remain explicit.

    Returns:
        A callable satisfying the core forward protocol. Qualified CPU cases use
        NumPy, JAX JIT/vmap/AD and Torch AD; other devices need separate evidence.

    Raises:
        ValueError: Identity, layout, settings or declared work limits disagree.
        NotImplementedError: Operators, history, tables, scheduled state maps or
            gauge-fixed execution need a separately qualified adapter.
    """
    identity, solver_module, model_module, observations, loops = _modules()
    del identity
    settings = FixedForwardSettings.model_validate(settings)
    provenance = Provenance.model_validate(provenance)
    structural = structural_model_reference(compiled)
    if provenance.schema_version != 2 or provenance.structural_model != structural:
        msg = "Compiled forward structural model identity mismatch"
        raise ValueError(msg)
    if (
        getattr(compiled, "impulses", ())
        or getattr(compiled, "impulse_times", ())
        or compiled.meta.get("impulse_times")
        or compiled.meta.get("op_system_impulses_ir")
    ):
        msg = "Compiled forward does not execute scheduled state maps (impulses)"
        raise NotImplementedError(msg)
    if (
        compiled.operators
        or compiled.history_requirements
        or compiled.meta.get("time_varying_params")
        or compiled.meta.get("forcing_breakpoints")
        or compiled.gauge_fix is not None
    ):
        msg = (
            "Compiled forward supports natural fixed explicit models without "
            "operators/history/tables/gauge fixing"
        )
        raise NotImplementedError(msg)
    partitions = _partition(settings)
    numerical = provenance.numerical
    if (
        numerical is None
        or numerical.solver != fixed_forward_settings_reference(settings)
        or numerical.time_mesh != fixed_forward_mesh_reference(settings)
        or numerical.observation
        != compiled_observation_reference(compiled, output_names)
    ):
        msg = "Compiled forward numerical settings/mesh/observation identity mismatch"
        raise ValueError(msg)
    if not output_names or any(
        name not in compiled.observables for name in output_names
    ):
        msg = "Compiled forward requires declared compiled latent observables"
        raise ValueError(msg)
    specs = tuple(
        observations.observation_from_compiled(compiled.observables[name])
        for name in output_names
    )
    rhs_names = tuple(
        dict.fromkeys(
            (
                *compiled.param_names,
                *(name for name, _axes in compiled.meta.get("shaped_params", ())),
            )
        )
    )
    required = set(rhs_names) | {
        name for spec in specs for name, _shape in spec.metadata.parameter_shapes
    }
    if not required <= set(parameter_names):
        msg = "Compiled forward parameter layout omits RHS/observable inputs"
        raise ValueError(msg)
    size = len(compiled.state_names)
    core = model_module.ModelCore(
        size,
        1,
        np.asarray(settings.times),
        options=model_module.ModelCoreOptions(
            store_history=False, dtype=settings.dtype
        ),
    )
    solver = solver_module.CoreSolver(core)

    def evaluate(  # noqa: C901 - bounded output loop and existing namespace stepping
        theta: Mapping[str, object], design: object, key: RandomKey
    ) -> Mapping[str, object]:
        del key  # Deterministic latent execution consumes no simulation randomness.
        initial = initial_state(theta, design)
        xp = array_namespace(initial)
        if getattr(initial, "shape", None) != (size,) or not xp.isdtype(
            getattr(initial, "dtype", None), "real floating"
        ):
            msg = (
                "Compiled forward initial state must be a native "
                "real floating flat state"
            )
            raise ValueError(msg)
        if getattr(initial, "dtype", None) != getattr(xp, settings.dtype):
            msg = "Compiled forward initial-state dtype differs from numerical settings"
            raise ValueError(msg)
        state = xp.reshape(initial, (size, 1))
        adapter = (
            None if settings.fixed_loop == "unroll" else loops.get_loop_adapter(xp)
        )
        if settings.fixed_loop == "scan" and adapter is None:
            msg = "Compiled forward forced scan has no namespace loop adapter"
            raise ValueError(msg)
        if settings.checkpoint and (adapter is None or adapter.checkpoint is None):
            msg = "Compiled forward namespace adapter has no checkpoint operation"
            raise ValueError(msg)
        rhs_params = {name: theta[name] for name in rhs_names}

        def rhs(time: object, values: object) -> object:
            return xp.reshape(
                compiled.eval_fn(time, xp.reshape(values, (-1,)), **rhs_params),
                (size, 1),
            )

        observation_params = {name: theta[name] for name in required}

        def observe(time: object, current: object) -> tuple[object, ...]:
            values = []
            for spec in specs:
                value = spec.eval_fn(time, current, **observation_params)
                if (
                    array_namespace(value) is not xp
                    or getattr(value, "dtype", None) != state.dtype
                ):
                    msg = (
                        "Compiled observations must preserve native namespace and dtype"
                    )
                    raise TypeError(msg)
                if getattr(value, "shape", None) != spec.metadata.output_shape:
                    msg = "Compiled observation shape differs from its metadata"
                    raise ValueError(msg)
                values.append(value)
            return tuple(values)

        def advance(carry: Any, step: Any) -> tuple[Any, None]:  # noqa: ANN401
            values, first_stage = carry
            time, dt = step
            next_values, next_stage = solver.fixed_explicit_step(
                rhs,
                method=settings.method,
                t=time,
                dt=dt,
                y=values,
                first_stage=first_stage,
            )
            return (next_values, next_stage), None

        if adapter is not None:
            body = adapter.checkpoint(advance) if settings.checkpoint else advance
            outputs = _scan_outputs(
                adapter,
                xp,
                body,
                (state, None),
                times=settings.times,
                partitions=partitions,
                observe=observe,
            )
        else:
            rows = [[value] for value in observe(settings.times[0], state)]
            carry = (state, None)
            for (start, end), steps in zip(
                pairwise(settings.times), partitions, strict=True
            ):
                starts = tuple(accumulate(steps, initial=start))[:-1]
                for time, dt in zip(starts, steps, strict=True):
                    carry, _ = advance(carry, (time, dt))
                for row, value in zip(rows, observe(end, carry[0]), strict=True):
                    row.append(value)
            outputs = tuple(xp.stack(row, axis=0) for row in rows)
        return dict(zip(output_names, outputs, strict=True))

    return CallableForward(evaluate, parameter_names, output_names, provenance)

compiled_observation_reference(compiled, output_names)

Reference the selected ordered latent outputs on stored solver nodes.

Source code in src/op_infer/adapters/op.py
190
191
192
193
194
195
196
197
198
199
200
201
def compiled_observation_reference(
    compiled: object, output_names: tuple[str, ...]
) -> ArtifactReference:
    """Reference the selected ordered latent outputs on stored solver nodes."""
    return _reference(
        {
            "model": structural_model_reference(compiled).model_dump(mode="json"),
            "output_names": output_names,
            "evaluation": "stored-nodes-no-interpolation",
        },
        kind="op-compiled-latent-observation-v1",
    )

fixed_forward_mesh_reference(settings)

Reference actual engine-planned steps and requested observation times.

Source code in src/op_infer/adapters/op.py
182
183
184
185
186
187
def fixed_forward_mesh_reference(settings: FixedForwardSettings) -> ArtifactReference:
    """Reference actual engine-planned steps and requested observation times."""
    return _reference(
        {"times": settings.times, "steps": _partition(settings)},
        kind="op-fixed-forward-mesh-v1",
    )

fixed_forward_settings_reference(settings)

Return the solver/settings reference required by numerical provenance.

Source code in src/op_infer/adapters/op.py
147
148
149
150
151
152
153
def fixed_forward_settings_reference(
    settings: FixedForwardSettings,
) -> ArtifactReference:
    """Return the solver/settings reference required by numerical provenance."""
    return _reference(
        settings.model_dump(mode="json"), kind="op-fixed-forward-settings-v1"
    )

structural_model_reference(compiled)

Reuse the compiler's exact schema-1 manifest digest.

Parameters:

Name Type Description Default
compiled object

Unmodified compiler-produced model, without runtime bindings.

required

Returns:

Type Description
ArtifactReference

Existing generic artifact reference, not a second model identity scheme.

Source code in src/op_infer/adapters/op.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def structural_model_reference(compiled: object) -> ArtifactReference:
    """Reuse the compiler's exact schema-1 manifest digest.

    Args:
        compiled: Unmodified compiler-produced model, without runtime bindings.

    Returns:
        Existing generic artifact reference, not a second model identity scheme.
    """
    try:
        identity = importlib.import_module("op_system.identity")
    except ImportError as error:
        msg = (
            "Install the op extra with an op_system revision "
            "providing structural identity"
        )
        raise ImportError(msg) from error
    reference = identity.StructuralModelIdentity.from_compiled(compiled)
    return ArtifactReference(
        kind=f"op-system-structural-model-v{reference.schema_version}",
        digest=reference.digest,
    )

likelihood

Log-densities and per-unit integrated likelihoods.

Status: planned (no public API yet). See docs/design/proposal.md and the issue tracker.

Scope: LogDensity protocol (log prior + sum over units); per-unit integrals over unit latents by Laplace, Laplace importance sampling (Levenberg-Marquardt with Gauss-Newton curvature, moment-matched t, defensive mixture, Pareto k-hat) and prior Monte Carlo (reference only), with a validation harness against high-sample references.

Inference adapters and per-unit likelihood/comparison workflows follow the target and adequacy contract in docs/design/likelihood-targets.md. Frozen common random numbers define an approximation; an exact pseudo-marginal claim requires a qualified augmented target. Unbiasedness concerns the likelihood, not its logarithm, including the joint product over units. Importance diagnostics and target validity are separate requirements.

estimators

Adapters to mature inference libraries.

Status: a bounded optional native NumPyro NUTS adapter is implemented in op_infer.adapters.numpyro. A bounded CPU masked-cohort NPE adapter is implemented in op_infer.adapters.sbi. Other adapters and the registry remain planned. See docs/numpyro.md and docs/design/proposal.md.

Scope: A registry of thin adapters, each an optional extra: numpyro NUTS/SVI/Predictive, blackjax SMC/MCLMC, sbi NPE/NLE/MNLE/NRE/BNRE (with a masked set embedding and seed ensembles), pyabc ABC-SMC, scipy MAP/Laplace, pseudo-marginal NUTS. Every adapter returns a Posterior with estimator stage and provenance; non-flow posteriors carry per-replicate MCMC adequacy. Samplers are never reimplemented.

posterior

Posterior containers and provenance.

Status: native posterior containers and immutable provenance are implemented. Optional ArviZ snapshots live in op_infer.adapters.arviz; shard merging remains planned.

Scope: Posterior (draws per chain or seed, sample statistics, per-unit log-likelihoods, estimator stage) converting to and from ArviZ 1.x and netCDF; Provenance (prior hash, design hash, simulator version, estimator settings, backend versions, commit); guarded loading and shard merging that refuse mismatches, gaps and overlaps.

Required target identity and approximation/auxiliary-state provenance are specified in docs/design/likelihood-targets.md. Future loaders must check expected identities and preserve unknown legacy claims as unknown. Posterior snapshots and fitting adapters use the shared references below. Numerical qualification is evidence for its recorded scope, not automatic proof or a universal error bound.

ArtifactReference

Bases: _Record

Identify immutable artifact bytes.

Attributes:

Name Type Description
kind _Text

Semantic artifact type, including its format/version where applicable.

digest _Digest

SHA-256 of the exact referenced bytes. Payload availability, semantics and authenticity require separate verification by the consumer.

Source code in src/op_infer/posterior.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class ArtifactReference(_Record):
    """Identify immutable artifact bytes.

    Attributes:
        kind: Semantic artifact type, including its format/version where applicable.
        digest: SHA-256 of the exact referenced bytes. Payload availability, semantics
            and authenticity require separate verification by the consumer.
    """

    kind: _Text
    digest: _Digest

    @classmethod
    def from_bytes(cls, payload: bytes, *, kind: str) -> Self:
        """Hash exact artifact bytes without reading external data.

        Args:
            payload: Immutable serialized content; canonicalization is the writer's
                responsibility, including dtype, shape and ordering for arrays.
            kind: Semantic artifact type.

        Returns:
            A content reference, without storing or authenticating the payload.

        Examples:
            >>> ref = ArtifactReference.from_bytes(
            ...     b'{"method":"rk4"}', kind="solver-v1"
            ... )
            >>> ref.digest.startswith("sha256:")
            True
        """
        return cls(kind=kind, digest=f"sha256:{hashlib.sha256(payload).hexdigest()}")

from_bytes(payload, *, kind) classmethod

Hash exact artifact bytes without reading external data.

Parameters:

Name Type Description Default
payload bytes

Immutable serialized content; canonicalization is the writer's responsibility, including dtype, shape and ordering for arrays.

required
kind str

Semantic artifact type.

required

Returns:

Type Description
Self

A content reference, without storing or authenticating the payload.

Examples:

>>> ref = ArtifactReference.from_bytes(
...     b'{"method":"rk4"}', kind="solver-v1"
... )
>>> ref.digest.startswith("sha256:")
True
Source code in src/op_infer/posterior.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
@classmethod
def from_bytes(cls, payload: bytes, *, kind: str) -> Self:
    """Hash exact artifact bytes without reading external data.

    Args:
        payload: Immutable serialized content; canonicalization is the writer's
            responsibility, including dtype, shape and ordering for arrays.
        kind: Semantic artifact type.

    Returns:
        A content reference, without storing or authenticating the payload.

    Examples:
        >>> ref = ArtifactReference.from_bytes(
        ...     b'{"method":"rk4"}', kind="solver-v1"
        ... )
        >>> ref.digest.startswith("sha256:")
        True
    """
    return cls(kind=kind, digest=f"sha256:{hashlib.sha256(payload).hexdigest()}")

BackendVersion

Bases: _Record

Record one numerical/backend dependency.

Source code in src/op_infer/posterior.py
277
278
279
280
281
class BackendVersion(_Record):
    """Record one numerical/backend dependency."""

    name: _Text
    version: _Text

Coordinate

Bases: _Record

Immutable ordered coordinate labels , not a physical-unit claim.

Attributes:

Name Type Description
name _Text

Portable dimension name.

labels tuple[int | float | str, ...]

Nonempty unique, homogeneous strings, signed 64-bit integers or finite floats. Order is preserved; no automatic sorting/alignment.

Examples:

>>> Coordinate(name="unit", labels=("u3", "u1")).labels
('u3', 'u1')
Source code in src/op_infer/posterior.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
class Coordinate(_Record):
    """Immutable ordered coordinate labels , not a physical-unit claim.

    Attributes:
        name: Portable dimension name.
        labels: Nonempty unique, homogeneous strings, signed 64-bit integers or
            finite floats. Order is preserved; no automatic sorting/alignment.

    Examples:
        >>> Coordinate(name="unit", labels=("u3", "u1")).labels
        ('u3', 'u1')
    """

    name: _Text
    labels: tuple[int | float | str, ...]

    @model_validator(mode="after")
    def _check_labels(self) -> Self:
        _portable_name(self.name)
        if not self.labels or len(set(self.labels)) != len(self.labels):
            msg = "Coordinate labels must be nonempty and unique"
            raise ValueError(msg)
        if len({type(label) for label in self.labels}) != 1:
            msg = "Coordinate labels must have one scalar type"
            raise ValueError(msg)
        for label in self.labels:
            if (
                (isinstance(label, float) and not math.isfinite(label))
                or (type(label) is int and not -(2**63) <= label < 2**63)
                or (isinstance(label, str) and (not label or "\0" in label))
                or isinstance(label, bool)
            ):
                msg = "Coordinate labels must be finite, portable scalar identities"
                raise ValueError(msg)
        return self

DerivativeContract

Bases: _Record

Identify the differentiated map with explicit graph-portability limits.

Attributes:

Name Type Description
mode Literal['none', 'finite_difference', 'discrete_autodiff', 'continuous_sensitivity', 'implicit', 'custom']

Derivative method, or none for a value-only evaluation.

parameters tuple[_Text, ...]

Ordered differentiation coordinates, including their transforms.

adaptive_path Literal['not_applicable', 'frozen_replay', 'differentiate_controller', 'unqualified']

Whether replay is fixed or controller choices differentiated.

graph_scope ArtifactReference

Backend, transforms, geometry treatment and transfer boundaries.

qualification Qualification

Independent derivative checks and their supported domain.

Source code in src/op_infer/posterior.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
class DerivativeContract(_Record):
    """Identify the differentiated map with explicit graph-portability limits.

    Attributes:
        mode: Derivative method, or none for a value-only evaluation.
        parameters: Ordered differentiation coordinates, including their transforms.
        adaptive_path: Whether replay is fixed or controller choices differentiated.
        graph_scope: Backend, transforms, geometry treatment and transfer boundaries.
        qualification: Independent derivative checks and their supported domain.
    """

    mode: Literal[
        "none",
        "finite_difference",
        "discrete_autodiff",
        "continuous_sensitivity",
        "implicit",
        "custom",
    ]
    parameters: tuple[_Text, ...]
    adaptive_path: Literal[
        "not_applicable", "frozen_replay", "differentiate_controller", "unqualified"
    ]
    graph_scope: ArtifactReference
    qualification: Qualification

    @model_validator(mode="after")
    def _check_parameters(self) -> Self:
        if (self.mode == "none") != (not self.parameters):
            msg = "Value-only modes need no coordinates; other modes need coordinates"
            raise ValueError(msg)
        if len(set(self.parameters)) != len(self.parameters):
            msg = "Derivative coordinates must be unique"
            raise ValueError(msg)
        return self

ErrorComponent

Bases: _Record

Keep error controls distinct with settings distinct from achieved error bounds.

Attributes:

Name Type Description
kind _ErrorKind

One of seven separately recorded numerical/statistical components.

status Literal['specified', 'not_applicable', 'unqualified']

Settings specified, not applicable, or explicitly unqualified.

reason _Text

Applicability or qualification limitation.

controls ArtifactReference | None

Settings artifact; required when specified, absent when inapplicable.

evidence ArtifactReference | None

Optional achieved-error/uncertainty evidence with its own scope.

Source code in src/op_infer/posterior.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class ErrorComponent(_Record):
    """Keep error controls distinct with settings distinct from achieved error bounds.

    Attributes:
        kind: One of seven separately recorded numerical/statistical components.
        status: Settings specified, not applicable, or explicitly unqualified.
        reason: Applicability or qualification limitation.
        controls: Settings artifact; required when specified, absent when inapplicable.
        evidence: Optional achieved-error/uncertainty evidence with its own scope.
    """

    kind: _ErrorKind
    status: Literal["specified", "not_applicable", "unqualified"]
    reason: _Text
    controls: ArtifactReference | None
    evidence: ArtifactReference | None

    @model_validator(mode="after")
    def _check_controls(self) -> Self:
        if self.status == "specified" and self.controls is None:
            msg = "Specified error components require control settings"
            raise ValueError(msg)
        if self.status == "not_applicable" and self.controls is not None:
            msg = "Inapplicable error components cannot declare control settings"
            raise ValueError(msg)
        return self

LikelihoodTargetReference

Bases: _Record

Preserve the intended and evaluated likelihood-target contract.

Attributes:

Name Type Description
kind Literal['analytic', 'deterministic_approximation', 'frozen_random_approximation', 'augmented_pseudo_marginal']

Evaluated target category, not an exactness certificate.

intended ArtifactReference

Prior/model/data/unit/measure identities of the intended target.

evaluated ArtifactReference

Full approximation/settings/support/randomness identity of the evaluated target.

qualification Qualification

Exactness/approximation evidence and limitations for its scope.

Source code in src/op_infer/posterior.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
class LikelihoodTargetReference(_Record):
    """Preserve the intended and evaluated likelihood-target contract.

    Attributes:
        kind: Evaluated target category, not an exactness certificate.
        intended: Prior/model/data/unit/measure identities of the intended target.
        evaluated: Full approximation/settings/support/randomness identity of the
            evaluated target.
        qualification: Exactness/approximation evidence and limitations for its scope.
    """

    kind: Literal[
        "analytic",
        "deterministic_approximation",
        "frozen_random_approximation",
        "augmented_pseudo_marginal",
    ]
    intended: ArtifactReference
    evaluated: ArtifactReference
    qualification: Qualification

NumericalExecution

Bases: _Record

Reference the evaluated numerical behavior.

Attributes:

Name Type Description
solver ArtifactReference

Method, tolerance, precision, solver/library version and settings.

time_mesh ArtifactReference

Time discretization and output coordinates.

spatial_mesh ArtifactReference | None

Spatial/quadrature coordinates and measures, or explicit absence.

topology ArtifactReference | None

Fixed connectivity identity; required with a spatial mesh.

geometry Literal['frozen', 'learnable_fixed_topology']

Frozen geometry or learnable coordinates with fixed topology.

replay ArtifactReference | None

Accepted replay artifact, or explicit absence.

mesh_policy ArtifactReference

Refresh/reuse rules defining one consistent evaluated likelihood.

observation ArtifactReference

Physical observation definition, evaluation and aggregation.

field_prior ArtifactReference

State representation, basis, measures and prior interpretation.

derivative DerivativeContract

Differentiated map and qualification scope.

errors tuple[ErrorComponent, ...]

Exactly one record for each of the seven error/uncertainty components.

qualification Qualification

Refinement/reference results for this execution's scope.

Source code in src/op_infer/posterior.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
class NumericalExecution(_Record):
    """Reference the evaluated numerical behavior.

    Attributes:
        solver: Method, tolerance, precision, solver/library version and settings.
        time_mesh: Time discretization and output coordinates.
        spatial_mesh: Spatial/quadrature coordinates and measures, or explicit absence.
        topology: Fixed connectivity identity; required with a spatial mesh.
        geometry: Frozen geometry or learnable coordinates with fixed topology.
        replay: Accepted replay artifact, or explicit absence.
        mesh_policy: Refresh/reuse rules defining one consistent evaluated likelihood.
        observation: Physical observation definition, evaluation and aggregation.
        field_prior: State representation, basis, measures and prior interpretation.
        derivative: Differentiated map and qualification scope.
        errors: Exactly one record for each of the seven error/uncertainty components.
        qualification: Refinement/reference results for this execution's scope.
    """

    solver: ArtifactReference
    time_mesh: ArtifactReference
    spatial_mesh: ArtifactReference | None
    topology: ArtifactReference | None
    geometry: Literal["frozen", "learnable_fixed_topology"]
    replay: ArtifactReference | None
    mesh_policy: ArtifactReference
    observation: ArtifactReference
    field_prior: ArtifactReference
    derivative: DerivativeContract
    errors: tuple[ErrorComponent, ...]
    qualification: Qualification

    @model_validator(mode="after")
    def _check_mesh_and_errors(self) -> Self:
        if (self.spatial_mesh is None) != (self.topology is None):
            msg = "Spatial meshes and their fixed topology must be recorded together"
            raise ValueError(msg)
        if self.geometry == "learnable_fixed_topology" and self.topology is None:
            msg = "Learnable geometry requires a spatial mesh and fixed topology"
            raise ValueError(msg)
        kinds = [component.kind for component in self.errors]
        if len(kinds) != len(_ERROR_KINDS) or set(kinds) != _ERROR_KINDS:
            msg = "Record each of the seven error components exactly once"
            raise ValueError(msg)
        if self.replay is None and self.derivative.adaptive_path == "frozen_replay":
            msg = "Frozen-replay derivatives require a replay artifact"
            raise ValueError(msg)
        return self

Posterior dataclass

Coordinate-aware native samples , with shared provenance.

This container neither fits nor certifies a posterior. Non-finite values remain present; downstream adequacy/comparison policies must count their outcomes.

Attributes:

Name Type Description
draws tuple[SampledVariable[ArrayT], ...]

Nonempty parameter variables; no warmup is implicitly discarded.

coordinates tuple[Coordinate, ...]

Every used dimension, including member/draw coordinates.

provenance Provenance

Existing complete target, numerical and estimator-stage identity.

sample_axis Literal['chain', 'seed']

Independent chains or training seeds; seeds are not MCMC chains.

sample_stats tuple[SampledVariable[ArrayT], ...]

Optional sampled diagnostics, with the same member/draw ordering.

log_likelihood tuple[SampledVariable[ArrayT], ...]

Optional real floating per-unit log likelihoods, with exactly one event dimension named unit. Integration semantics are declared in target provenance, not inferred or certified from the shape.

Source code in src/op_infer/posterior.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
@dataclass(frozen=True, slots=True, eq=False)
class Posterior[ArrayT]:
    """Coordinate-aware native samples , with shared provenance.

    This container neither fits nor certifies a posterior. Non-finite values remain
    present; downstream adequacy/comparison policies must count their outcomes.

    Attributes:
        draws: Nonempty parameter variables; no warmup is implicitly discarded.
        coordinates: Every used dimension, including member/draw coordinates.
        provenance: Existing complete target, numerical and estimator-stage identity.
        sample_axis: Independent chains or training seeds; seeds are not MCMC chains.
        sample_stats: Optional sampled diagnostics, with the same member/draw ordering.
        log_likelihood: Optional real floating per-unit log likelihoods, with exactly
            one event dimension named ``unit``. Integration semantics are declared in
            target provenance, not inferred or certified from the shape.
    """

    draws: tuple[SampledVariable[ArrayT], ...]
    coordinates: tuple[Coordinate, ...]
    provenance: Provenance
    sample_axis: Literal["chain", "seed"] = "chain"
    sample_stats: tuple[SampledVariable[ArrayT], ...] = ()
    log_likelihood: tuple[SampledVariable[ArrayT], ...] = ()

    def __post_init__(self) -> None:
        """Validate the complete layout; see :meth:`validate`."""
        self.validate()

    @property
    def estimator_stage(self) -> str:
        """Return the shared provenance stage without duplicating its identity."""
        return self.provenance.estimator_stage

    def validate(self) -> None:
        """Check current array shapes/backend and immutable coordinate metadata.

        Call this before reuse or snapshotting, because native
        arrays may have been mutated after construction. Data values and gradients are
        not evaluated, copied, filtered or promoted. Arrays require one native backend.

        Raises:
            TypeError: A collection is mutable, a record is invalid, or backends differ.
            ValueError: Names, dimensions, coordinate lengths or sample layouts differ.
        """
        groups = (self.draws, self.sample_stats, self.log_likelihood)
        if any(not isinstance(group, tuple) for group in (*groups, self.coordinates)):
            msg = "Posterior collections must be immutable tuples"
            raise TypeError(msg)
        if not self.draws or self.sample_axis not in {"chain", "seed"}:
            msg = "Nonempty draws and an explicit chain/seed sample axis are required"
            raise ValueError(msg)
        Provenance.model_validate(self.provenance)
        for coordinate in self.coordinates:
            Coordinate.model_validate(coordinate)
        coords = {coordinate.name: coordinate.labels for coordinate in self.coordinates}
        if len(coords) != len(self.coordinates):
            msg = "Coordinate dimension names must be unique"
            raise ValueError(msg)
        used: set[str] = set()
        for group in groups:
            used.update(_group_dimensions(group, coords, self.sample_axis))
        if used != coords.keys():
            msg = "Unused coordinates are not silently retained or discarded"
            raise ValueError(msg)
        array_namespace(*(variable.values for group in groups for variable in group))
        for variable in self.log_likelihood:
            xp = array_namespace(variable.values)
            if variable.dims != ("unit",) or not xp.isdtype(
                getattr(variable.values, "dtype", None), "real floating"
            ):
                msg = "Log likelihoods need floating values and one 'unit' dimension"
                raise ValueError(msg)

estimator_stage property

Return the shared provenance stage without duplicating its identity.

__post_init__()

Validate the complete layout; see :meth:validate.

Source code in src/op_infer/posterior.py
587
588
589
def __post_init__(self) -> None:
    """Validate the complete layout; see :meth:`validate`."""
    self.validate()

validate()

Check current array shapes/backend and immutable coordinate metadata.

Call this before reuse or snapshotting, because native arrays may have been mutated after construction. Data values and gradients are not evaluated, copied, filtered or promoted. Arrays require one native backend.

Raises:

Type Description
TypeError

A collection is mutable, a record is invalid, or backends differ.

ValueError

Names, dimensions, coordinate lengths or sample layouts differ.

Source code in src/op_infer/posterior.py
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
def validate(self) -> None:
    """Check current array shapes/backend and immutable coordinate metadata.

    Call this before reuse or snapshotting, because native
    arrays may have been mutated after construction. Data values and gradients are
    not evaluated, copied, filtered or promoted. Arrays require one native backend.

    Raises:
        TypeError: A collection is mutable, a record is invalid, or backends differ.
        ValueError: Names, dimensions, coordinate lengths or sample layouts differ.
    """
    groups = (self.draws, self.sample_stats, self.log_likelihood)
    if any(not isinstance(group, tuple) for group in (*groups, self.coordinates)):
        msg = "Posterior collections must be immutable tuples"
        raise TypeError(msg)
    if not self.draws or self.sample_axis not in {"chain", "seed"}:
        msg = "Nonempty draws and an explicit chain/seed sample axis are required"
        raise ValueError(msg)
    Provenance.model_validate(self.provenance)
    for coordinate in self.coordinates:
        Coordinate.model_validate(coordinate)
    coords = {coordinate.name: coordinate.labels for coordinate in self.coordinates}
    if len(coords) != len(self.coordinates):
        msg = "Coordinate dimension names must be unique"
        raise ValueError(msg)
    used: set[str] = set()
    for group in groups:
        used.update(_group_dimensions(group, coords, self.sample_axis))
    if used != coords.keys():
        msg = "Unused coordinates are not silently retained or discarded"
        raise ValueError(msg)
    array_namespace(*(variable.values for group in groups for variable in group))
    for variable in self.log_likelihood:
        xp = array_namespace(variable.values)
        if variable.dims != ("unit",) or not xp.isdtype(
            getattr(variable.values, "dtype", None), "real floating"
        ):
            msg = "Log likelihoods need floating values and one 'unit' dimension"
            raise ValueError(msg)

Provenance

Bases: _Record

Versioned shared artifact identity.

Attributes:

Name Type Description
schema_version Literal[1, 2]

Required format version; unknown/missing versions are refused.

prior ArtifactReference

Prior definition and parameter interpretation.

design ArtifactReference

Physical design and data/unit manifest.

simulator ArtifactReference

Simulator implementation/version and observation definition.

target LikelihoodTargetReference

Intended and evaluated likelihood identity and qualification.

numerical NumericalExecution | None

Numerical execution, or explicit absence for an analytic calculation.

estimator_stage _Text

Distinct training, fitting, calibration or reporting stage.

estimator_settings ArtifactReference

Full estimator settings and randomness policy.

backend_versions tuple[BackendVersion, ...]

Unique dependency names and exact versions in canonical order.

commit ArtifactReference

Code content identity, normally an immutable commit/source manifest.

structural_model ArtifactReference | None

Schema-2 compiler or explicitly declared callable content reference, separate from runtime/prior/design/estimator identity.

Source code in src/op_infer/posterior.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
class Provenance(_Record):
    """Versioned shared artifact identity.

    Attributes:
        schema_version: Required format version; unknown/missing versions are refused.
        prior: Prior definition and parameter interpretation.
        design: Physical design and data/unit manifest.
        simulator: Simulator implementation/version and observation definition.
        target: Intended and evaluated likelihood identity and qualification.
        numerical: Numerical execution, or explicit absence for an analytic calculation.
        estimator_stage: Distinct training, fitting, calibration or reporting stage.
        estimator_settings: Full estimator settings and randomness policy.
        backend_versions: Unique dependency names and exact versions in canonical order.
        commit: Code content identity, normally an immutable commit/source manifest.
        structural_model: Schema-2 compiler or explicitly declared callable content
            reference, separate from runtime/prior/design/estimator identity.
    """

    schema_version: Literal[1, 2]
    prior: ArtifactReference
    design: ArtifactReference
    simulator: ArtifactReference
    target: LikelihoodTargetReference
    numerical: NumericalExecution | None
    estimator_stage: _Text
    estimator_settings: ArtifactReference
    backend_versions: tuple[BackendVersion, ...]
    commit: ArtifactReference
    structural_model: ArtifactReference | None = Field(
        default=None, exclude_if=lambda value: value is None
    )

    @field_validator("schema_version", mode="before")
    @classmethod
    def _strict_schema_version(cls, value: object) -> object:
        if type(value) is not int:
            msg = "Schema version must be an integer, not a boolean or float"
            raise ValueError(msg)
        return value

    @model_validator(mode="after")
    def _check_versions(self) -> Self:
        names = tuple(backend.name for backend in self.backend_versions)
        if not names or names != tuple(sorted(set(names))):
            msg = "Record nonempty, unique backend versions sorted by name"
            raise ValueError(msg)
        return self

    @model_validator(mode="after")
    def _check_structural_model(self) -> Self:
        if self.schema_version == 1 and self.structural_model is not None:
            msg = "Structural model references require provenance schema 2"
            raise ValueError(msg)
        if self.schema_version == 2 and self.structural_model is None:
            msg = "Provenance schema 2 requires an explicit structural model reference"
            raise ValueError(msg)
        if self.structural_model is not None:
            kind = self.structural_model.kind
            if (
                kind.startswith("op-system-structural-model-")
                and kind != "op-system-structural-model-v1"
            ):
                msg = "Unsupported op_system structural model identity schema"
                raise ValueError(msg)
        return self

    def with_structural_model(self, model: ArtifactReference) -> Self:
        """Explicitly create schema-2 provenance from an independently supplied model.

        This does not upgrade old artifacts or verify that their producing code
        used the supplied model. Consumers must supply expectations independently.
        All native fitting/bank/posterior records reuse this
        provenance rather than another artifact identity hierarchy.

        Args:
            model: Compiler manifest reference or a declared callable model manifest.

        Returns:
            Validated schema-2 provenance, leaving this record unchanged.
        """
        return type(self).model_validate(
            {**self.model_dump(), "schema_version": 2, "structural_model": model}
        )

    @property
    def identity(self) -> str:
        """Return deterministic complete-record identity."""
        payload = json.dumps(
            self.model_dump(mode="json"),
            sort_keys=True,
            separators=(",", ":"),
            ensure_ascii=True,
            allow_nan=False,
        ).encode("utf-8")
        return f"sha256:{hashlib.sha256(payload).hexdigest()}"

    def require_match(self, expected: Self) -> None:
        """Refuse behavior/provenance changes.

        Args:
            expected: Complete expected provenance, including qualification evidence.

        Raises:
            ValueError: Any required field differs. Payload authenticity and semantic
                compatibility require separate verification; equality is conservative.
        """
        if self != expected:
            msg = (
                "Provenance mismatch: artifact differs from expected behavior identity"
            )
            raise ValueError(msg)

    @classmethod
    def load_json(cls, payload: str, *, expected: Self) -> Self:
        """Validate and guard provenance JSON before artifact reuse.

        Args:
            payload: Serialized provenance; this loader does not load referenced data.
            expected: Required identity, supplied independently by the caller.

        Returns:
            Validated immutable provenance matching the caller's expectation.

        Raises:
            ValueError: Invalid, missing, unknown-schema or mismatched provenance.
        """
        result = cls.model_validate_json(payload)
        result.require_match(expected)
        return result

identity property

Return deterministic complete-record identity.

load_json(payload, *, expected) classmethod

Validate and guard provenance JSON before artifact reuse.

Parameters:

Name Type Description Default
payload str

Serialized provenance; this loader does not load referenced data.

required
expected Self

Required identity, supplied independently by the caller.

required

Returns:

Type Description
Self

Validated immutable provenance matching the caller's expectation.

Raises:

Type Description
ValueError

Invalid, missing, unknown-schema or mismatched provenance.

Source code in src/op_infer/posterior.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
@classmethod
def load_json(cls, payload: str, *, expected: Self) -> Self:
    """Validate and guard provenance JSON before artifact reuse.

    Args:
        payload: Serialized provenance; this loader does not load referenced data.
        expected: Required identity, supplied independently by the caller.

    Returns:
        Validated immutable provenance matching the caller's expectation.

    Raises:
        ValueError: Invalid, missing, unknown-schema or mismatched provenance.
    """
    result = cls.model_validate_json(payload)
    result.require_match(expected)
    return result

require_match(expected)

Refuse behavior/provenance changes.

Parameters:

Name Type Description Default
expected Self

Complete expected provenance, including qualification evidence.

required

Raises:

Type Description
ValueError

Any required field differs. Payload authenticity and semantic compatibility require separate verification; equality is conservative.

Source code in src/op_infer/posterior.py
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def require_match(self, expected: Self) -> None:
    """Refuse behavior/provenance changes.

    Args:
        expected: Complete expected provenance, including qualification evidence.

    Raises:
        ValueError: Any required field differs. Payload authenticity and semantic
            compatibility require separate verification; equality is conservative.
    """
    if self != expected:
        msg = (
            "Provenance mismatch: artifact differs from expected behavior identity"
        )
        raise ValueError(msg)

with_structural_model(model)

Explicitly create schema-2 provenance from an independently supplied model.

This does not upgrade old artifacts or verify that their producing code used the supplied model. Consumers must supply expectations independently. All native fitting/bank/posterior records reuse this provenance rather than another artifact identity hierarchy.

Parameters:

Name Type Description Default
model ArtifactReference

Compiler manifest reference or a declared callable model manifest.

required

Returns:

Type Description
Self

Validated schema-2 provenance, leaving this record unchanged.

Source code in src/op_infer/posterior.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def with_structural_model(self, model: ArtifactReference) -> Self:
    """Explicitly create schema-2 provenance from an independently supplied model.

    This does not upgrade old artifacts or verify that their producing code
    used the supplied model. Consumers must supply expectations independently.
    All native fitting/bank/posterior records reuse this
    provenance rather than another artifact identity hierarchy.

    Args:
        model: Compiler manifest reference or a declared callable model manifest.

    Returns:
        Validated schema-2 provenance, leaving this record unchanged.
    """
    return type(self).model_validate(
        {**self.model_dump(), "schema_version": 2, "structural_model": model}
    )

Qualification

Bases: _Record

Record scoped evidence status without certifying a claim.

Attributes:

Name Type Description
status Literal['qualified', 'failed', 'unqualified']

Explicit qualified, failed or unqualified outcome.

scope ArtifactReference

Referenced domain, physical quantities, transforms and tested setup.

reason _Text

Human-readable outcome or limitation.

evidence tuple[ArtifactReference, ...]

Immutable qualification artifacts; required for a qualified claim.

Source code in src/op_infer/posterior.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class Qualification(_Record):
    """Record scoped evidence status without certifying a claim.

    Attributes:
        status: Explicit qualified, failed or unqualified outcome.
        scope: Referenced domain, physical quantities, transforms and tested setup.
        reason: Human-readable outcome or limitation.
        evidence: Immutable qualification artifacts; required for a qualified claim.
    """

    status: Literal["qualified", "failed", "unqualified"]
    scope: ArtifactReference
    reason: _Text
    evidence: tuple[ArtifactReference, ...]

    @model_validator(mode="after")
    def _require_evidence(self) -> Self:
        if self.status == "qualified" and not self.evidence:
            msg = "Qualified claims require scoped evidence references"
            raise ValueError(msg)
        return self

SampledVariable dataclass

Named native values without host transfer or graph detachment.

Attributes:

Name Type Description
name str

Portable name, unique within its group.

values ArrayT

Native array with member and draw axes first, then event dimensions. Arrays retain backend mutability; frozen metadata is not a payload hash.

dims tuple[str, ...]

Ordered event dimensions only; sample dimensions belong to the posterior.

Examples:

>>> import numpy as np
>>> variable = SampledVariable("theta", np.ones((2, 3)))
>>> variable.values.shape, variable.dims
((2, 3), ())
Source code in src/op_infer/posterior.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
@dataclass(frozen=True, slots=True, eq=False)
class SampledVariable[ArrayT]:
    """Named native values without host transfer or graph detachment.

    Attributes:
        name: Portable name, unique within its group.
        values: Native array with member and draw axes first, then event dimensions.
            Arrays retain backend mutability; frozen metadata is not a payload hash.
        dims: Ordered event dimensions only; sample dimensions belong to the posterior.

    Examples:
        >>> import numpy as np
        >>> variable = SampledVariable("theta", np.ones((2, 3)))
        >>> variable.values.shape, variable.dims
        ((2, 3), ())
    """

    name: str
    values: ArrayT
    dims: tuple[str, ...] = ()

    def __post_init__(self) -> None:
        """Check names and rank without evaluating native data.

        Raises:
            TypeError: Dimensions are mutable or values are not native real arrays.
            ValueError: Names, event dimensions or array rank are invalid.
        """
        _portable_name(self.name)
        if not isinstance(self.dims, tuple):
            msg = "Event dimensions must be an immutable tuple"
            raise TypeError(msg)
        for name in self.dims:
            _portable_name(name)
        if len(set(self.dims)) != len(self.dims) or len(
            _array_shape(self.values)
        ) != 2 + len(self.dims):
            msg = "Values need two sample axes and unique declared event dimensions"
            raise ValueError(msg)

__post_init__()

Check names and rank without evaluating native data.

Raises:

Type Description
TypeError

Dimensions are mutable or values are not native real arrays.

ValueError

Names, event dimensions or array rank are invalid.

Source code in src/op_infer/posterior.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
def __post_init__(self) -> None:
    """Check names and rank without evaluating native data.

    Raises:
        TypeError: Dimensions are mutable or values are not native real arrays.
        ValueError: Names, event dimensions or array rank are invalid.
    """
    _portable_name(self.name)
    if not isinstance(self.dims, tuple):
        msg = "Event dimensions must be an immutable tuple"
        raise TypeError(msg)
    for name in self.dims:
        _portable_name(name)
    if len(set(self.dims)) != len(self.dims) or len(
        _array_shape(self.values)
    ) != 2 + len(self.dims):
        msg = "Values need two sample axes and unique declared event dimensions"
        raise ValueError(msg)

arviz

Optional ArviZ snapshots and named MCMC diagnostics, using shared provenance.

No consumer model/data or inference library is imported here. Only op_infer-authored snapshots are accepted; arbitrary sampler trees need an explicit adapter with independently supplied provenance. Full authenticated artifact loading, publication and shard merging remain planned.

DiagnosticComponent

Bases: _Record

One event element, indexed in its original named event dimensions.

Source code in src/op_infer/adapters/arviz.py
372
373
374
375
376
377
378
379
class DiagnosticComponent(_Record):
    """One event element, indexed in its original named event dimensions."""

    index: tuple[int, ...]
    nonfinite_values: Annotated[int, Field(ge=0)] | None
    rank_rhat: DiagnosticValue
    bulk_ess: DiagnosticValue
    tail_ess: DiagnosticValue

DiagnosticQuantity

Bases: _Record

A selected variable with every event element retained, including failures.

content hashes the copied host input in its original host dtype before float64 diagnostic calculation. It is unavailable if host conversion failed. The caller's definition reference identifies reported/aligned transformations.

Source code in src/op_infer/adapters/arviz.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
class DiagnosticQuantity(_Record):
    """A selected variable with every event element retained, including failures.

    ``content`` hashes the copied host input in its original host dtype before
    float64 diagnostic calculation. It is unavailable if host conversion failed.
    The caller's definition reference identifies reported/aligned transformations.
    """

    name: str
    dims: tuple[str, ...]
    source_dtype: str
    host_dtype: str | None
    content: ArtifactReference | None
    components: tuple[DiagnosticComponent, ...]

DiagnosticValue

Bases: _Record

A named ArviZ method result or an explicit unavailable/undefined outcome.

Available values are finite and positive; ESS is absolute and can exceed the number of draws for antithetic samples. No adequacy threshold is applied.

Examples:

>>> result = DiagnosticValue(
...     method="rank",
...     value=None,
...     status="unavailable",
...     reason="single_original_chain",
... )
>>> result.status, result.value
('unavailable', None)
Source code in src/op_infer/adapters/arviz.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class DiagnosticValue(_Record):
    """A named ArviZ method result or an explicit unavailable/undefined outcome.

    Available values are finite and positive; ESS is absolute and can exceed the
    number of draws for antithetic samples. No adequacy threshold is applied.

    Examples:
        >>> result = DiagnosticValue(
        ...     method="rank",
        ...     value=None,
        ...     status="unavailable",
        ...     reason="single_original_chain",
        ... )
        >>> result.status, result.value
        ('unavailable', None)
    """

    method: Literal["rank", "bulk", "tail"]
    value: Annotated[float, Field(gt=0, allow_inf_nan=False)] | None
    status: Literal["available", "unavailable", "undefined"]
    reason: Annotated[str, Field(min_length=1, pattern=r"\S")] | None = None

    @model_validator(mode="after")
    def _outcome(self) -> Self:
        if (self.status == "available") != (self.value is not None) or (
            (self.reason is None) != (self.status == "available")
        ):
            msg = "Available diagnostics need a value; other outcomes need a reason"
            raise ValueError(msg)
        return self

MCMCDiagnostics

Bases: _Record

Versioned named diagnostic values, with original axes and provenance.

Rank R-hat is ArviZ's maximum of rank-normalized split and folded R-hat. Tail ESS uses quantiles 0.05 and 0.95. Values do not imply sampler adequacy; thresholds, divergences and combined-gate qualification remain separate.

Source code in src/op_infer/adapters/arviz.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
class MCMCDiagnostics(_Record):
    """Versioned named diagnostic values, with original axes and provenance.

    Rank R-hat is ArviZ's maximum of rank-normalized split and folded R-hat.
    Tail ESS uses quantiles 0.05 and 0.95. Values do not imply sampler adequacy;
    thresholds, divergences and combined-gate qualification remain separate.
    """

    schema_version: Literal[1] = 1
    provenance: Provenance
    definition: ArtifactReference
    implementation_reference: ArtifactReference
    coordinates: tuple[Coordinate, ...]
    sample_axis: Literal["chain", "seed"]
    backend_versions: tuple[BackendVersion, ...]
    quantities: tuple[DiagnosticQuantity, ...]
    implementation: Literal["arviz_stats.base.array_stats"] = (
        "arviz_stats.base.array_stats"
    )
    diagnostic_dtype: Literal["float64"] = "float64"
    tail_probabilities: tuple[float, float] = (0.05, 0.95)
    relative_ess: Literal[False] = False

    @field_validator("schema_version", mode="before")
    @classmethod
    def _version(cls, value: object) -> object:
        if type(value) is not int:
            msg = "Diagnostic schema version must be an integer"
            raise ValueError(msg)
        return value

    @model_validator(mode="after")
    def _layout(self) -> Self:
        if self.tail_probabilities != (0.05, 0.95):
            msg = "Tail ESS is defined at quantiles 0.05 and 0.95"
            raise ValueError(msg)
        coords = {c.name: c.labels for c in self.coordinates}
        names = tuple(q.name for q in self.quantities)
        if (
            not names
            or len(set(names)) != len(names)
            or len(coords) != len(self.coordinates)
            or not {self.sample_axis, "draw"} <= coords.keys()
        ):
            msg = "Diagnostics need distinct quantities and sample coordinates"
            raise ValueError(msg)
        for quantity in self.quantities:
            if (
                len(set(quantity.dims)) != len(quantity.dims)
                or not set(quantity.dims) <= coords.keys()
                or {self.sample_axis, "draw"}.intersection(quantity.dims)
            ):
                msg = "Diagnostic dimensions need their original coordinates"
                raise ValueError(msg)
            expected = tuple(np.ndindex(*(len(coords[d]) for d in quantity.dims)))
            if tuple(c.index for c in quantity.components) != expected:
                msg = "Every event component must remain in original coordinate order"
                raise ValueError(msg)
            for component in quantity.components:
                if (
                    component.rank_rhat.method,
                    component.bulk_ess.method,
                    component.tail_ess.method,
                ) != ("rank", "bulk", "tail"):
                    msg = "Diagnostic method names do not match their fields"
                    raise ValueError(msg)
                available = any(
                    value.status == "available"
                    for value in (
                        component.rank_rhat,
                        component.bulk_ess,
                        component.tail_ess,
                    )
                )
                if available and (
                    self.sample_axis != "chain"
                    or len(coords["draw"]) < 4
                    or component.nonfinite_values != 0
                    or quantity.host_dtype is None
                    or quantity.content is None
                ):
                    msg = "Available diagnostics require finite original MCMC inputs"
                    raise ValueError(msg)
                if (
                    component.rank_rhat.status == "available"
                    and len(coords[self.sample_axis]) < 2
                ):
                    msg = "Rank R-hat requires two original chains"
                    raise ValueError(msg)
        return self

    @property
    def n_components(self) -> int:
        """Return the complete selected scalar-quantity denominator."""
        return sum(len(q.components) for q in self.quantities)

    @property
    def n_incomplete(self) -> int:
        """Count elements with any unavailable or undefined required diagnostic."""
        return sum(
            any(v.status != "available" for v in (c.rank_rhat, c.bulk_ess, c.tail_ess))
            for q in self.quantities
            for c in q.components
        )

    @property
    def adequacy_status(self) -> Literal["not_assessed"]:
        """Keep raw diagnostics distinct from a prespecified adequacy decision."""
        return "not_assessed"

    @classmethod
    def load_json(
        cls, payload: str, *, expected: Provenance, definition: ArtifactReference
    ) -> Self:
        """Load a report only with independently supplied context and definition.

        Returns:
            The validated immutable report; self-recorded hashes are not authentication.

        Raises:
            ValueError: Schema, layout, provenance or quantity definition differs.
        """
        result = cls.model_validate_json(payload)
        result.provenance.require_match(expected)
        if result.definition != definition:
            msg = "Reported-quantity definition differs"
            raise ValueError(msg)
        return result

adequacy_status property

Keep raw diagnostics distinct from a prespecified adequacy decision.

n_components property

Return the complete selected scalar-quantity denominator.

n_incomplete property

Count elements with any unavailable or undefined required diagnostic.

load_json(payload, *, expected, definition) classmethod

Load a report only with independently supplied context and definition.

Returns:

Type Description
Self

The validated immutable report; self-recorded hashes are not authentication.

Raises:

Type Description
ValueError

Schema, layout, provenance or quantity definition differs.

Source code in src/op_infer/adapters/arviz.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
@classmethod
def load_json(
    cls, payload: str, *, expected: Provenance, definition: ArtifactReference
) -> Self:
    """Load a report only with independently supplied context and definition.

    Returns:
        The validated immutable report; self-recorded hashes are not authentication.

    Raises:
        ValueError: Schema, layout, provenance or quantity definition differs.
    """
    result = cls.model_validate_json(payload)
    result.provenance.require_match(expected)
    if result.definition != definition:
        msg = "Reported-quantity definition differs"
        raise ValueError(msg)
    return result

diagnose_mcmc(posterior, *, quantities, definition, to_numpy=None)

Calculate named rank R-hat and absolute bulk/tail ESS using ArviZ Stats.

Active consumer: Sheep_Immune's named reported/aligned quantity diagnostics. No estimator is reimplemented. Every selected scalar/event element remains present, including constants, nonfinite data and unsupported inputs.

Parameters:

Name Type Description Default
posterior Posterior[ArrayT]

Original post-warmup chain/draw container. Seed members are retained with unavailable MCMC diagnostics, never relabeled as chains.

required
quantities Sequence[str]

Explicit nonempty variable names in posterior.draws, in reporting order. Derived/aligned quantities must be supplied there with their original sample axes and declared event coordinates.

required
definition ArtifactReference

Content reference to the reporting/transformation definition, including data-dependent alignment and sample selection when used.

required
to_numpy Callable[[ArrayT], NDArray[generic]] | None

Explicit host-transfer/detachment callback for native arrays. Without it only unmasked supported NumPy arrays are read. Conversion must preserve shape/order; it does not authorize a new transformation.

None

Returns:

Type Description
MCMCDiagnostics

Immutable values/reasons, complete event denominator, dependency versions,

MCMCDiagnostics

original coordinates, host input digests and shared provenance. Calculation

MCMCDiagnostics

uses float64; source/host dtypes are recorded. No thresholds or pass label.

Raises:

Type Description
ImportError

Install the diagnostics extra for ArviZ Stats.

ValueError

Selection is empty, duplicated, unknown, or layout is invalid.

TypeError

The original layout/backend is invalid or selection is a string.

Source code in src/op_infer/adapters/arviz.py
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
def diagnose_mcmc[ArrayT](
    posterior: Posterior[ArrayT],
    *,
    quantities: Sequence[str],
    definition: ArtifactReference,
    to_numpy: Callable[[ArrayT], NDArray[np.generic]] | None = None,
) -> MCMCDiagnostics:
    """Calculate named rank R-hat and absolute bulk/tail ESS using ArviZ Stats.

    Active consumer: Sheep_Immune's named reported/aligned quantity diagnostics.
    No estimator is reimplemented. Every selected scalar/event element remains
    present, including constants, nonfinite data and unsupported inputs.

    Args:
        posterior: Original post-warmup chain/draw container. Seed members are
            retained with unavailable MCMC diagnostics, never relabeled as chains.
        quantities: Explicit nonempty variable names in ``posterior.draws``, in
            reporting order. Derived/aligned quantities must be supplied there
            with their original sample axes and declared event coordinates.
        definition: Content reference to the reporting/transformation definition,
            including data-dependent alignment and sample selection when used.
        to_numpy: Explicit host-transfer/detachment callback for native arrays.
            Without it only unmasked supported NumPy arrays are read. Conversion
            must preserve shape/order; it does not authorize a new transformation.

    Returns:
        Immutable values/reasons, complete event denominator, dependency versions,
        original coordinates, host input digests and shared provenance. Calculation
        uses float64; source/host dtypes are recorded. No thresholds or pass label.

    Raises:
        ImportError: Install the diagnostics extra for ArviZ Stats.
        ValueError: Selection is empty, duplicated, unknown, or layout is invalid.
        TypeError: The original layout/backend is invalid or selection is a string.
    """
    posterior.validate()
    if isinstance(quantities, str):
        msg = "Select distinct nonempty names as a sequence, not one string"
        raise TypeError(msg)
    names = tuple(quantities)
    variables = {variable.name: variable for variable in posterior.draws}
    if not names or len(set(names)) != len(names) or not set(names) <= variables.keys():
        msg = "Select distinct nonempty names from posterior.draws"
        raise ValueError(msg)
    try:
        stats = importlib.import_module("arviz_stats.base").array_stats
    except ImportError as error:
        msg = "Install op_infer[diagnostics] for named MCMC diagnostics"
        raise ImportError(msg) from error
    results = []
    coords = {
        coordinate.name: coordinate.labels for coordinate in posterior.coordinates
    }
    # Avoid contextual tuple inference through NumPy 2.0's indexing overloads.
    sample_slices = (slice(None), slice(None))
    for name in names:
        variable = variables[name]
        shape = tuple(
            len(coords[d]) for d in (posterior.sample_axis, "draw", *variable.dims)
        )
        indices = tuple(np.ndindex(*shape[2:]))
        host = None
        reason = None
        if posterior.sample_axis != "chain":
            reason = "seed_axis_is_not_mcmc_chains"
        else:
            try:
                supplied = (
                    variable.values if to_numpy is None else to_numpy(variable.values)
                )
                host = _diagnostic_host(supplied, shape)
            except Exception as error:  # noqa: BLE001 - retain unsupported selected quantities
                reason = f"unsupported_input:{type(error).__name__}:{error}"
                host = None
        components = tuple(
            _unavailable_component(index, reason or "unavailable_input")
            if host is None
            else _diagnose_component(host[sample_slices + index], index, stats)
            for index in indices
        )
        results.append(
            DiagnosticQuantity(
                name=name,
                dims=variable.dims,
                source_dtype=str(getattr(variable.values, "dtype", None)),
                host_dtype=None if host is None else host.dtype.str,
                content=None if host is None else _content(host),
                components=components,
            )
        )
    versions = {
        name: importlib.metadata.version(name)
        for name in ("op_infer", "arviz-stats", "numpy", "scipy")
    }
    versions["python"] = platform.python_version()
    return MCMCDiagnostics(
        provenance=posterior.provenance,
        definition=definition,
        implementation_reference=ArtifactReference.from_bytes(
            Path(__file__).read_bytes(), kind="op-infer-arviz-adapter-source-v1"
        ),
        coordinates=posterior.coordinates,
        sample_axis=posterior.sample_axis,
        quantities=tuple(results),
        backend_versions=tuple(
            BackendVersion(name=name, version=value)
            for name, value in sorted(versions.items())
        ),
    )

from_arviz(tree, *, expected)

Restore an op_infer-authored snapshot, checking expected provenance first.

Parameters:

Name Type Description Default
tree DataTree

DataTree produced by :func:to_arviz, possibly read from netCDF.

required
expected Provenance

Independently supplied complete provenance required for reuse.

required

Returns:

Type Description
Posterior[NDArray[generic]]

Detached NumPy samples, with all original unit entries and seed/chain meaning.

Raises:

Type Description
ValueError

Missing/unknown schema, provenance mismatch, undeclared data or inconsistent layout/content. Self-recorded digests detect corruption; they do not authenticate a header or verify referenced scientific claims.

Source code in src/op_infer/adapters/arviz.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def from_arviz(
    tree: DataTree, *, expected: Provenance
) -> Posterior[NDArray[np.generic]]:
    """Restore an op_infer-authored snapshot, checking expected provenance first.

    Args:
        tree: DataTree produced by :func:`to_arviz`, possibly read from netCDF.
        expected: Independently supplied complete provenance required for reuse.

    Returns:
        Detached NumPy samples, with all original unit entries and seed/chain meaning.

    Raises:
        ValueError: Missing/unknown schema, provenance mismatch, undeclared data or
            inconsistent layout/content. Self-recorded digests detect corruption;
            they do not authenticate a header or verify referenced scientific claims.
    """
    payload = tree.attrs.get(_HEADER)
    if payload is None:
        msg = "Missing op_infer snapshot header; legacy trees need an adapter"
        raise ValueError(msg)
    if not isinstance(payload, str):
        msg = "Snapshot header must be JSON text"
        raise TypeError(msg)
    header = _Header.model_validate_json(payload)
    header.provenance.require_match(expected)
    names = tuple(group.name for group in header.groups)
    if (
        "posterior" not in names
        or len(set(names)) != len(names)
        or set(tree.groups) != {"/", *(f"/{name}" for name in names)}
        or tree.data_vars
        or tree.coords
    ):
        msg = "Snapshot contains missing, duplicate or undeclared groups/root data"
        raise ValueError(msg)
    groups = {
        group.name: _restore_group(tree, group, header) for group in header.groups
    }
    return Posterior(
        draws=groups["posterior"],
        coordinates=header.coordinates,
        provenance=header.provenance,
        sample_axis=header.sample_axis,
        sample_stats=groups.get("sample_stats", ()),
        log_likelihood=groups.get("log_likelihood", ()),
    )

load_netcdf(path, *, expected)

Guard a netCDF snapshot before eagerly copying its sample arrays.

Parameters:

Name Type Description Default
path str | Path

Local file written from :func:to_arviz using netCDF4.

required
expected Provenance

Independently supplied complete provenance required for reuse.

required

Returns:

Type Description
Posterior[NDArray[generic]]

Detached NumPy container; no lazy arrays or open file handles escape.

Raises:

Type Description
ImportError

The optional arviz extra is unavailable.

OSError

The file cannot be read.

ValueError

The guarded snapshot contract is violated.

Source code in src/op_infer/adapters/arviz.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def load_netcdf(
    path: str | Path, *, expected: Provenance
) -> Posterior[NDArray[np.generic]]:
    """Guard a netCDF snapshot before eagerly copying its sample arrays.

    Args:
        path: Local file written from :func:`to_arviz` using netCDF4.
        expected: Independently supplied complete provenance required for reuse.

    Returns:
        Detached NumPy container; no lazy arrays or open file handles escape.

    Raises:
        ImportError: The optional ``arviz`` extra is unavailable.
        OSError: The file cannot be read.
        ValueError: The guarded snapshot contract is violated.
    """
    import xarray as xr  # noqa: PLC0415

    with xr.open_datatree(
        path, engine="netcdf4", mask_and_scale=False, decode_times=False
    ) as tree:
        return from_arviz(tree, expected=expected)

to_arviz(posterior)

Take an independent host snapshot using ArviZ 1.x's DataTree conventions.

Parameters:

Name Type Description Default
posterior Posterior[ArrayT]

Valid native container whose values were explicitly transferred to NumPy. Live arrays are copied; later mutations do not change the tree.

required

Returns:

Type Description
DataTree

An xarray DataTree with versioned layout/shared provenance and array digests.

DataTree

Use its standard to_netcdf(path, engine="netcdf4") for file writing.

Raises:

Type Description
ImportError

Install op_infer[arviz] to use this optional integration.

TypeError

Values have not crossed the explicit host/storage boundary.

ValueError

The current posterior layout is invalid.

Source code in src/op_infer/adapters/arviz.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def to_arviz[ArrayT](posterior: Posterior[ArrayT]) -> DataTree:
    """Take an independent host snapshot using ArviZ 1.x's DataTree conventions.

    Args:
        posterior: Valid native container whose values were explicitly transferred
            to NumPy. Live arrays are copied; later mutations do not change the tree.

    Returns:
        An xarray DataTree with versioned layout/shared provenance and array digests.
        Use its standard ``to_netcdf(path, engine="netcdf4")`` for file writing.

    Raises:
        ImportError: Install ``op_infer[arviz]`` to use this optional integration.
        TypeError: Values have not crossed the explicit host/storage boundary.
        ValueError: The current posterior layout is invalid.
    """
    posterior.validate()
    for group in (posterior.draws, posterior.sample_stats, posterior.log_likelihood):
        for variable in group:
            _host(variable.values)

    import arviz_base as az  # noqa: PLC0415
    import xarray as xr  # noqa: PLC0415

    datasets: dict[str, xr.Dataset] = {}
    descriptors: list[_Group] = []
    variables = (posterior.draws, posterior.sample_stats, posterior.log_likelihood)
    for name, group in zip(_GROUPS, variables, strict=True):
        if not group:
            continue
        arrays = {
            variable.name: np.array(_host(variable.values), copy=True)
            for variable in group
        }
        records = tuple(
            _Variable(
                name=variable.name,
                dims=variable.dims,
                shape=arrays[variable.name].shape,
                dtype=arrays[variable.name].dtype.str,
                content=_content(arrays[variable.name]),
            )
            for variable in group
        )
        descriptors.append(
            _Group(
                name=cast(
                    "Literal['posterior', 'sample_stats', 'log_likelihood']", name
                ),
                variables=records,
            )
        )
        dimensions = {
            posterior.sample_axis,
            "draw",
            *(dim for variable in group for dim in variable.dims),
        }
        converted = az.from_dict(
            {name: arrays},
            sample_dims=[posterior.sample_axis, "draw"],
            coords={
                coordinate.name: list(coordinate.labels)
                for coordinate in posterior.coordinates
                if coordinate.name in dimensions
            },
            dims={variable.name: list(variable.dims) for variable in group},
        )
        dataset = converted[name].to_dataset()
        # ArviZ 1.0 does not automatically retain this attribute. Record the
        # explicit contract on every version rather than relying on rcParams.
        dataset.attrs["sample_dims"] = [posterior.sample_axis, "draw"]
        for stored in dataset.variables.values():
            stored.encoding["_FillValue"] = None
        datasets[name] = dataset
    header = _Header(
        schema_version=1,
        provenance=posterior.provenance,
        sample_axis=posterior.sample_axis,
        coordinates=posterior.coordinates,
        groups=tuple(descriptors),
    )
    datasets["/"] = xr.Dataset(attrs={_HEADER: header.model_dump_json()})
    return xr.DataTree.from_dict(datasets)

rng

Lazy native RNG lowerings for explicit task addresses.

The shared RandomKey supplies the host identity; arrays and generators stay native after lowering. CPU and scoped CUDA sampling are qualified separately; this module implements no distributions.

jax_key(key)

Lower a task address to an explicit typed Threefry key.

The first two uint32 SeedSequence state words become Threefry2x32 key data. Lower on the host before tracing; the resulting key is a native JIT/vmap input. No global default PRNG implementation is consulted.

Parameters:

Name Type Description Default
key RandomKey

Validated, recorded stream address.

required

Returns:

Type Description
Array

A scalar typed JAX key using threefry2x32.

Raises:

Type Description
ImportError

The optional JAX dependency is unavailable.

Source code in src/op_infer/adapters/rng.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def jax_key(key: RandomKey) -> Array:
    """Lower a task address to an explicit typed Threefry key.

    The first two uint32 SeedSequence state words become Threefry2x32 key data.
    Lower on the host before tracing; the resulting key is a native JIT/vmap
    input. No global default PRNG implementation is consulted.

    Args:
        key: Validated, recorded stream address.

    Returns:
        A scalar typed JAX key using ``threefry2x32``.

    Raises:
        ImportError: The optional JAX dependency is unavailable.
    """
    words = key.seed_sequence().generate_state(2, dtype=np.uint32)
    try:
        random = importlib.import_module("jax.random")
        xp = importlib.import_module("jax.numpy")
    except ImportError as exc:
        msg = "Install op_infer[jax] to lower a JAX random key"
        raise ImportError(msg) from exc
    return cast(
        "Array",
        random.wrap_key_data(xp.asarray(words, dtype=xp.uint32), impl="threefry2x32"),
    )

torch_generators(keys, *, device='cpu')

Lower a complete task bank to local Torch CPU or CUDA generators.

Torch's CPU MT19937 seed uses only 32 effective bits. Version 1 uses the first uint32 SeedSequence word explicitly on both devices and refuses duplicate seeds, including repeated addresses, before creating any generator. Pass all simultaneously independent tasks together; separate calls cannot check collisions against earlier banks. Deliberate replay uses a separate call.

Parameters:

Name Type Description Default
keys tuple[RandomKey, ...]

Immutable ordered bank of addresses; an empty bank is permitted.

required
device str | device

Explicit CPU or CUDA device; the default preserves CPU streams.

'cpu'

Returns:

Type Description
tuple[Generator, ...]

Fresh device-local generators, without seeding global state.

Raises:

Type Description
TypeError

The bank is not a tuple of RandomKey records.

ValueError

Addresses are invalid or effective seeds collide.

ImportError

The optional Torch dependency is unavailable.

Source code in src/op_infer/adapters/rng.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def torch_generators(
    keys: tuple[RandomKey, ...], *, device: str | torch_device = "cpu"
) -> tuple[Generator, ...]:
    """Lower a complete task bank to local Torch CPU or CUDA generators.

    Torch's CPU MT19937 seed uses only 32 effective bits. Version 1 uses the
    first uint32 SeedSequence word explicitly on both devices and refuses duplicate
    seeds, including repeated addresses, before creating any generator. Pass
    all simultaneously independent tasks together; separate calls cannot check
    collisions against earlier banks. Deliberate replay uses a separate call.

    Args:
        keys: Immutable ordered bank of addresses; an empty bank is permitted.
        device: Explicit CPU or CUDA device; the default preserves CPU streams.

    Returns:
        Fresh device-local generators, without seeding global state.

    Raises:
        TypeError: The bank is not a tuple of RandomKey records.
        ValueError: Addresses are invalid or effective seeds collide.
        ImportError: The optional Torch dependency is unavailable.
    """
    if not isinstance(keys, tuple) or any(
        not isinstance(key, RandomKey) for key in keys
    ):
        msg = "Torch generator banks require a tuple of RandomKey records"
        raise TypeError(msg)
    seeds = [
        int(key.seed_sequence().generate_state(1, dtype=np.uint32)[0]) for key in keys
    ]
    if len(set(seeds)) != len(seeds):
        msg = (
            "Torch effective seeds collide; use a new recorded root seed or "
            "stream namespace for the complete bank"
        )
        raise ValueError(msg)
    try:
        torch = importlib.import_module("torch")
    except ImportError as exc:
        msg = "Install op_infer[torch] to lower Torch generators"
        raise ImportError(msg) from exc
    target = torch.device(device)
    if target.type not in {"cpu", "cuda"}:
        msg = "Torch RNG lowering is qualified only for CPU and CUDA"
        raise ValueError(msg)
    return tuple(
        cast("Generator", torch.Generator(device=target).manual_seed(seed))
        for seed in seeds
    )

numpyro

Thin optional NumPyro NUTS adapter for native posterior fitting.

Run native NUTS and preserve grouped samples and per-fit diagnostics. No sampler or adequacy gate is implemented here. SVI and predictive/report adapters remain planned.

NutsResult dataclass

Preserve the common posterior and native fit.

Attributes:

Name Type Description
posterior Posterior[Array]

Native JAX samples/statistics, with complete shared provenance.

diagnostics tuple[ParameterDiagnostics, ...]

Host diagnostic arrays; no nonfinite site is discarded.

divergences_per_chain tuple[int, ...]

Counts over every retained transition in each chain.

nonfinite_values int

Count of nonfinite scalar entries over all returned sites.

native MCMC

Original MCMC instance; advanced native inspection remains available.

Source code in src/op_infer/adapters/numpyro.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
@dataclass(frozen=True, slots=True, eq=False)
class NutsResult:
    """Preserve the common posterior and native fit.

    Attributes:
        posterior: Native JAX samples/statistics, with complete shared provenance.
        diagnostics: Host diagnostic arrays; no nonfinite site is discarded.
        divergences_per_chain: Counts over every retained transition in each chain.
        nonfinite_values: Count of nonfinite scalar entries over all returned sites.
        native: Original MCMC instance; advanced native inspection remains available.
    """

    posterior: Posterior[Array]
    diagnostics: tuple[ParameterDiagnostics, ...]
    divergences_per_chain: tuple[int, ...]
    nonfinite_values: int
    native: MCMC

    @property
    def adequacy_status(self) -> Literal["not_assessed"]:
        """Keep raw diagnostics distinct from prespecified adequacy gates."""
        return "not_assessed"

adequacy_status property

Keep raw diagnostics distinct from prespecified adequacy gates.

NutsSettings

Bases: _Record

Declare a CPU run and its estimator-settings identity.

Native defaults are tied to recorded versions.

Attributes:

Name Type Description
schema_version Literal[1]

Adapter format; unknown versions are refused.

key RandomKey

Explicit fitting stream address.

sites tuple[SiteLayout, ...]

Every native returned sample/deterministic site, with event dimensions.

coordinates tuple[Coordinate, ...]

Ordered event labels; chain/draw labels are generated separately.

num_warmup Annotated[int, Field(ge=1)]

Adaptation iterations per chain, excluded from returned samples.

num_samples Annotated[int, Field(ge=4)]

Retained transitions per chain, with thinning fixed at one.

num_chains Annotated[int, Field(ge=1)]

Sequential CPU chains; a single chain has unavailable R-hat.

target_accept_prob Annotated[float, Field(gt=0, lt=1, allow_inf_nan=False)]

Native target acceptance probability.

max_tree_depth Annotated[int, Field(ge=1)]

Native NUTS tree-depth limit.

dense_mass bool

Native full versus diagonal mass adaptation.

enable_x64 bool

Required JAX precision setting, checked without changing globals.

Examples:

>>> config = NutsSettings(
...     key=RandomKey(seed=2026, stream="fit"),
...     sites=(SiteLayout(name="theta"),),
... )
>>> config.reference.kind
'numpyro-nuts-settings-v1'
Source code in src/op_infer/adapters/numpyro.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
class NutsSettings(_Record):
    """Declare a CPU run and its estimator-settings identity.

    Native defaults are tied to recorded versions.

    Attributes:
        schema_version: Adapter format; unknown versions are refused.
        key: Explicit fitting stream address.
        sites: Every native returned sample/deterministic site, with event dimensions.
        coordinates: Ordered event labels; chain/draw labels are generated separately.
        num_warmup: Adaptation iterations per chain, excluded from returned samples.
        num_samples: Retained transitions per chain, with thinning fixed at one.
        num_chains: Sequential CPU chains; a single chain has unavailable R-hat.
        target_accept_prob: Native target acceptance probability.
        max_tree_depth: Native NUTS tree-depth limit.
        dense_mass: Native full versus diagonal mass adaptation.
        enable_x64: Required JAX precision setting, checked without changing globals.

    Examples:
        >>> config = NutsSettings(
        ...     key=RandomKey(seed=2026, stream="fit"),
        ...     sites=(SiteLayout(name="theta"),),
        ... )
        >>> config.reference.kind
        'numpyro-nuts-settings-v1'
    """

    schema_version: Literal[1] = 1
    key: RandomKey
    sites: tuple[SiteLayout, ...]
    coordinates: tuple[Coordinate, ...] = ()
    num_warmup: Annotated[int, Field(ge=1)] = 500
    num_samples: Annotated[int, Field(ge=4)] = 500
    num_chains: Annotated[int, Field(ge=1)] = 2
    target_accept_prob: Annotated[float, Field(gt=0, lt=1, allow_inf_nan=False)] = 0.8
    max_tree_depth: Annotated[int, Field(ge=1)] = 10
    dense_mass: bool = False
    enable_x64: bool = False

    @field_validator("schema_version", mode="before")
    @classmethod
    def _integer_version(cls, value: object) -> object:
        if type(value) is not int:
            msg = "schema_version must be an integer"
            raise ValueError(msg)
        return value

    @model_validator(mode="after")
    def _complete_layout(self) -> Self:
        names = [site.name for site in self.sites]
        coords = [coordinate.name for coordinate in self.coordinates]
        used = {dim for site in self.sites for dim in site.dims}
        if not names or len(set(names)) != len(names):
            msg = "Declare nonempty unique native sample sites"
            raise ValueError(msg)
        if (
            len(set(coords)) != len(coords)
            or set(coords) & {"chain", "draw", "seed", *_EXTRA_FIELDS}
            or set(names) & {*coords, "chain", "draw"}
            or used != set(coords)
            or any(len(set(site.dims)) != len(site.dims) for site in self.sites)
        ):
            msg = "Event coordinates must be unique, fully used and distinct from sites"
            raise ValueError(msg)
        return self

    def manifest_json(self) -> str:
        """Serialize the exact resolved settings payload for fit artifacts.

        Returns:
            Canonical JSON containing inputs and the fixed native adapter policy.
            Store these bytes with the shared estimator-settings reference.
        """
        settings = NutsSettings.model_validate(self)
        payload = {
            "settings": settings.model_dump(mode="json"),
            "adapter": "numpyro-nuts-cpu-v1",
            "chain_method": "sequential",
            "thinning": 1,
            "progress_bar": False,
            "initialization": "init_to_uniform(radius=2.0)",
            "extra_fields": _EXTRA_FIELDS,
            "remaining_defaults": "recorded numpyro version",
        }
        return json.dumps(
            payload, sort_keys=True, separators=(",", ":"), allow_nan=False
        )

    @property
    def reference(self) -> ArtifactReference:
        """Hash the exact fit manifest using the shared artifact reference.

        The reference alone does not store/authenticate payload or model identities.
        """
        return ArtifactReference.from_bytes(
            self.manifest_json().encode(), kind="numpyro-nuts-settings-v1"
        )

reference property

Hash the exact fit manifest using the shared artifact reference.

The reference alone does not store/authenticate payload or model identities.

manifest_json()

Serialize the exact resolved settings payload for fit artifacts.

Returns:

Type Description
str

Canonical JSON containing inputs and the fixed native adapter policy.

str

Store these bytes with the shared estimator-settings reference.

Source code in src/op_infer/adapters/numpyro.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def manifest_json(self) -> str:
    """Serialize the exact resolved settings payload for fit artifacts.

    Returns:
        Canonical JSON containing inputs and the fixed native adapter policy.
        Store these bytes with the shared estimator-settings reference.
    """
    settings = NutsSettings.model_validate(self)
    payload = {
        "settings": settings.model_dump(mode="json"),
        "adapter": "numpyro-nuts-cpu-v1",
        "chain_method": "sequential",
        "thinning": 1,
        "progress_bar": False,
        "initialization": "init_to_uniform(radius=2.0)",
        "extra_fields": _EXTRA_FIELDS,
        "remaining_defaults": "recorded numpyro version",
    }
    return json.dumps(
        payload, sort_keys=True, separators=(",", ":"), allow_nan=False
    )

ParameterDiagnostics dataclass

Retain NumPyro's raw host diagnostics without asserting sampler adequacy.

Attributes:

Name Type Description
name str

Same native site as the posterior variable.

dims tuple[str, ...]

Same ordered event dimensions, without chain/draw axes.

ess NDArray[float64]

Native NumPyro ESS, with nonfinite entries retained (not bulk/tail ESS).

split_r_hat NDArray[float64] | None

Classic NumPyro split R-hat; absent for a single original chain. This is not rank-normalized R-hat. Undefined values remain nonfinite.

Source code in src/op_infer/adapters/numpyro.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
@dataclass(frozen=True, slots=True, eq=False)
class ParameterDiagnostics:
    """Retain NumPyro's raw host diagnostics without asserting sampler adequacy.

    Attributes:
        name: Same native site as the posterior variable.
        dims: Same ordered event dimensions, without chain/draw axes.
        ess: Native NumPyro ESS, with nonfinite entries retained (not bulk/tail ESS).
        split_r_hat: Classic NumPyro split R-hat; absent for a single original chain.
            This is not rank-normalized R-hat. Undefined values remain nonfinite.
    """

    name: str
    dims: tuple[str, ...]
    ess: NDArray[np.float64]
    split_r_hat: NDArray[np.float64] | None

SiteLayout

Bases: _Record

Declare one complete native output layout.

Attributes:

Name Type Description
name _Name

Portable native NumPyro site name; no implicit renaming or filtering.

dims tuple[_Name, ...]

Event dimensions only, in native array order.

Source code in src/op_infer/adapters/numpyro.py
67
68
69
70
71
72
73
74
75
76
class SiteLayout(_Record):
    """Declare one complete native output layout.

    Attributes:
        name: Portable native NumPyro site name; no implicit renaming or filtering.
        dims: Event dimensions only, in native array order.
    """

    name: _Name
    dims: tuple[_Name, ...] = ()

fit_nuts(model, *, settings, provenance, model_args=(), model_kwargs=None)

Run native NUTS and retain the fitted posterior.

The caller supplies matching prior/model/data/target identities; their scientific truth is not inferred from hashes. All native returned sites need declared layouts. Models receive dynamic arguments without closure conversion. Failures propagate; no posterior or successful gate is fabricated.

Parameters:

Name Type Description Default
model Callable[..., object]

Trusted native NumPyro model callable.

required
settings NutsSettings

Immutable CPU run, RNG and complete output layout.

required
provenance Provenance

Shared identity with matching settings and installed versions.

required
model_args tuple[object, ...]

Dynamic positional model inputs, owned by the caller.

()
model_kwargs Mapping[str, object] | None

Dynamic named inputs; native run-control names are reserved.

None

Returns:

Type Description
NutsResult

Common native posterior, raw diagnostics and original NumPyro fit.

Raises:

Type Description
ImportError

The optional NumPyro/JAX dependencies are unavailable.

TypeError

The model or positional input collection is invalid.

ValueError

Settings/provenance/layout/precision/backend are incompatible, an augmented target is requested, or native fitting fails.

RuntimeError

Native initialization or execution fails.

Source code in src/op_infer/adapters/numpyro.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def fit_nuts(
    model: Callable[..., object],
    *,
    settings: NutsSettings,
    provenance: Provenance,
    model_args: tuple[object, ...] = (),
    model_kwargs: Mapping[str, object] | None = None,
) -> NutsResult:
    """Run native NUTS and retain the fitted posterior.

    The caller supplies matching prior/model/data/target identities; their
    scientific truth is not inferred from hashes. All native returned sites
    need declared layouts. Models receive dynamic arguments without closure
    conversion. Failures propagate; no posterior or successful gate is fabricated.

    Args:
        model: Trusted native NumPyro model callable.
        settings: Immutable CPU run, RNG and complete output layout.
        provenance: Shared identity with matching settings and installed versions.
        model_args: Dynamic positional model inputs, owned by the caller.
        model_kwargs: Dynamic named inputs; native run-control names are reserved.

    Returns:
        Common native posterior, raw diagnostics and original NumPyro fit.

    Raises:
        ImportError: The optional NumPyro/JAX dependencies are unavailable.
        TypeError: The model or positional input collection is invalid.
        ValueError: Settings/provenance/layout/precision/backend are incompatible,
            an augmented target is requested, or native fitting fails.
        RuntimeError: Native initialization or execution fails.
    """
    settings = NutsSettings.model_validate(settings)
    provenance = Provenance.model_validate(provenance)
    if not callable(model) or not isinstance(model_args, tuple):
        msg = "Supply a native model callable and a tuple of positional model inputs"
        raise TypeError(msg)
    kwargs = dict(model_kwargs or {})
    if set(kwargs) & {"extra_fields", "init_params", "rng_key"}:
        msg = "Model kwargs cannot override native run controls"
        raise ValueError(msg)
    if provenance.estimator_settings != settings.reference:
        msg = "Estimator settings provenance mismatch"
        raise ValueError(msg)
    if provenance.target.kind == "augmented_pseudo_marginal":
        msg = (
            "Augmented pseudo-marginal targets require the separately qualified "
            "#16 adapter"
        )
        raise ValueError(msg)
    declared = {item.name: item.version for item in provenance.backend_versions}
    if any(
        declared.get(item.name) != item.version for item in numpyro_backend_versions()
    ):
        msg = "Backend versions provenance mismatch"
        raise ValueError(msg)
    try:
        jax = importlib.import_module("jax")
        infer = importlib.import_module("numpyro.infer")
    except ImportError as exc:
        msg = "Install op_infer[numpyro] to use the NumPyro NUTS adapter"
        raise ImportError(msg) from exc
    if jax.default_backend() != "cpu":
        msg = "This NUTS adapter is qualified for the default CPU backend only"
        raise ValueError(msg)
    if bool(jax.config.jax_enable_x64) != settings.enable_x64:
        msg = "JAX precision differs from the recorded enable_x64 setting"
        raise ValueError(msg)
    kernel = infer.NUTS(
        model,
        target_accept_prob=settings.target_accept_prob,
        max_tree_depth=settings.max_tree_depth,
        dense_mass=settings.dense_mass,
        init_strategy=infer.init_to_uniform(radius=2.0),
    )
    native = cast(
        "MCMC",
        infer.MCMC(
            kernel,
            num_warmup=settings.num_warmup,
            num_samples=settings.num_samples,
            num_chains=settings.num_chains,
            chain_method="sequential",
            thinning=1,
            progress_bar=False,
        ),
    )
    native.run(jax_key(settings.key), *model_args, extra_fields=_EXTRA_FIELDS, **kwargs)
    samples = cast("dict[str, Array]", native.get_samples(group_by_chain=True))
    stats = cast("dict[str, Array]", native.get_extra_fields(group_by_chain=True))
    if set(samples) != {site.name for site in settings.sites}:
        msg = "Declare every returned native site; no site is silently omitted"
        raise ValueError(msg)
    posterior = Posterior(
        draws=tuple(
            SampledVariable(site.name, samples[site.name], site.dims)
            for site in settings.sites
        ),
        coordinates=(
            Coordinate(name="chain", labels=tuple(range(settings.num_chains))),
            Coordinate(name="draw", labels=tuple(range(settings.num_samples))),
            *settings.coordinates,
        ),
        provenance=provenance,
        sample_stats=tuple(
            SampledVariable(name, stats[name]) for name in _EXTRA_FIELDS
        ),
    )
    summaries = _summaries(posterior)
    return NutsResult(
        posterior=posterior,
        diagnostics=summaries,
        divergences_per_chain=tuple(
            int(np.count_nonzero(chain)) for chain in np.asarray(stats["diverging"])
        ),
        nonfinite_values=sum(
            int(np.count_nonzero(~np.isfinite(np.asarray(variable.values))))
            for variable in posterior.draws
        ),
        native=native,
    )

numpyro_backend_versions()

Collect exact fit dependencies for shared fit provenance before running.

Returns:

Type Description
tuple[BackendVersion, ...]

Sorted dependency/Python versions; no backend is imported by this helper.

Raises:

Type Description
ImportError

A required optional distribution is not installed.

Source code in src/op_infer/adapters/numpyro.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def numpyro_backend_versions() -> tuple[BackendVersion, ...]:
    """Collect exact fit dependencies for shared fit provenance before running.

    Returns:
        Sorted dependency/Python versions; no backend is imported by this helper.

    Raises:
        ImportError: A required optional distribution is not installed.
    """
    try:
        versions = {
            name: importlib.metadata.version(name)
            for name in (
                "array-api-compat",
                "jax",
                "jaxlib",
                "numpy",
                "numpyro",
                "op_infer",
                "pydantic",
                "scipy",
            )
        }
    except importlib.metadata.PackageNotFoundError as exc:
        msg = "Install op_infer[numpyro] to use the NumPyro NUTS adapter"
        raise ImportError(msg) from exc
    versions["python"] = platform.python_version()
    return tuple(
        BackendVersion(name=name, version=version)
        for name, version in sorted(versions.items())
    )

calibrate

Rank-based simulation-based calibration (SBC): PITs, aggregation, gate.

Scope: the rank half of the calibration layer. Ordinary and randomized-rank PIT, Benjamini-Hochberg multiplicity, power floors, failed-replicate accounting and contraction, aggregated from one JSON file per replicate. The study extra adds central-interval coverage summaries with Wilson intervals. Fixed coverage-rule planning is re-exported from op_infer.coverage; optional reference TARP curves live in op_infer.adapters.tarp. The module is estimator independent: any method that can draw a posterior for a simulated truth (NUTS, SVI, NPE, Laplace) writes the files. The bounded runner lives in op_infer.sbc. The masked-unit runner and raw width comparisons live in op_infer.masked_sbc. Prespecified scalar Gate/GateSet records live in op_infer.gates and are re-exported here. There is no plotting layer; the ledger carries the data for rank histograms.

Estimator adapters use the same replicate schema, so one aggregator can read their calibration records.

Replicate JSON schema (one *.json file per replicate)::

{
  "<estimand>": {"pit": 0.37, "contraction": 0.41},
  "<estimand 2>": {"pit": 0.92},
  "_fit_diag": {"rhat_max": 1.01, "ess_min": 850}
}

contraction (posterior SD over prior SD) is optional. A key that starts with _ is a diagnostic, not an estimand; _fit_diag values are collected per key. A replicate that failed (non-convergence, timeout, solver error) is written as {"_failed": true}. Failures are counted, kept in the denominator and reported; more than 10% failed fails the gate. A replicate that lacks an estimand without _failed is an error, and so is a non-finite PIT: nothing is dropped silently.

Rules encoded here (see docs/calibration.md):

  • a pass below power_floor replicates is an "underpowered pass" and is not a calibration claim; a failure counts at any number of replicates;
  • quantities with atoms (peak week, point masses at zero) need the randomized PIT (atoms=True);
  • flagging uses the Benjamini-Hochberg q-value across the estimand set, never the raw p-value;
  • before reading any rank, assert that the simulated data differ from the observed data (assert_simulated_differs);
  • report contraction beside the ranks, because a posterior equal to the prior is uniform.

Examples:

>>> import numpy as np
>>> pit([1.0, 2.0, 2.0, 3.0], 2.0)
0.5
>>> rng = np.random.default_rng(0)
>>> 0.25 <= pit([1.0, 2.0, 2.0, 3.0], 2.0, rng=rng, atoms=True) <= 0.75
True
>>> benjamini_hochberg([0.01, 0.04, 0.03, 0.005]).round(3).tolist()
[0.02, 0.04, 0.04, 0.02]

Command line (exit status 1 on a gate failure)::

python -m op_infer.calibrate aggregate DIR --out LEDGER.json \
    [--max-flagged 1] [--must-pass a,b]

CoverageRule

Bases: BaseModel

One inclusive empirical-coverage range, declared before a fixed bank.

name identifies an estimand/nominal-level criterion. Its calibrated coverage probability is nominal; this assumption needs independent replicates, an appropriate PIT/atom rule and sufficient posterior resolution. Bounds may be asymmetric but must contain the nominal probability.

Examples:

>>> rule = CoverageRule(
...     name="theta_50", nominal=0.5, lower=0.45, upper=0.55
... )
>>> rule.lower, rule.upper
(0.45, 0.55)
Source code in src/op_infer/coverage.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class CoverageRule(BaseModel):
    """One inclusive empirical-coverage range, declared before a fixed bank.

    ``name`` identifies an estimand/nominal-level criterion. Its calibrated
    coverage probability is ``nominal``; this assumption needs independent
    replicates, an appropriate PIT/atom rule and sufficient posterior resolution.
    Bounds may be asymmetric but must contain the nominal probability.

    Examples:
        >>> rule = CoverageRule(
        ...     name="theta_50", nominal=0.5, lower=0.45, upper=0.55
        ... )
        >>> rule.lower, rule.upper
        (0.45, 0.55)
    """

    model_config = ConfigDict(
        frozen=True, strict=True, extra="forbid", revalidate_instances="always"
    )

    name: Annotated[str, Field(min_length=1, pattern=r"\S")]
    nominal: Annotated[float, Field(gt=0, lt=1, allow_inf_nan=False)]
    lower: Annotated[float, Field(ge=0, le=1, allow_inf_nan=False)]
    upper: Annotated[float, Field(ge=0, le=1, allow_inf_nan=False)]

    @model_validator(mode="after")
    def _bounds(self) -> Self:
        if not self.lower <= self.nominal <= self.upper:
            msg = "Coverage bounds must contain their nominal probability"
            raise ValueError(msg)
        return self

Gate

Bases: _Record

One inclusive scalar criterion, with a separately named input metric.

adequacy criteria govern whether results are readable, including sampler diagnostics, replicate floors and failure limits. decision criteria govern the substantive reading. At least one finite bound is required. Missing/nonfinite values are unavailable and cannot pass.

Examples:

>>> criterion = Gate(
...     name="bias",
...     metric="mean_pit_error",
...     role="decision",
...     lower=-0.05,
...     upper=0.05,
... )
>>> criterion.lower, criterion.upper
(-0.05, 0.05)
Source code in src/op_infer/gates.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Gate(_Record):
    """One inclusive scalar criterion, with a separately named input metric.

    ``adequacy`` criteria govern whether results are readable, including sampler
    diagnostics, replicate floors and failure limits. ``decision`` criteria
    govern the substantive reading. At least one finite bound is required.
    Missing/nonfinite values are unavailable and cannot pass.

    Examples:
        >>> criterion = Gate(
        ...     name="bias",
        ...     metric="mean_pit_error",
        ...     role="decision",
        ...     lower=-0.05,
        ...     upper=0.05,
        ... )
        >>> criterion.lower, criterion.upper
        (-0.05, 0.05)
    """

    name: _Text
    metric: _Text
    role: Literal["adequacy", "decision"]
    lower: _Finite | None = None
    upper: _Finite | None = None

    @model_validator(mode="after")
    def _bounds(self) -> Self:
        if self.lower is None and self.upper is None:
            msg = "A gate requires at least one bound"
            raise ValueError(msg)
        if (
            self.lower is not None
            and self.upper is not None
            and self.lower > self.upper
        ):
            msg = "Gate lower bound exceeds upper bound"
            raise ValueError(msg)
        return self

GateAmendment

Bases: _Record

Disclose a prospective revision and the evidence already seen.

supersedes identifies the prior saved decision contract. An empty seen_before_amendment explicitly records that no result artifacts were seen. The timestamp and disclosure are supplied by the author; the package cannot authenticate chronology or establish independence of fresh evidence.

Source code in src/op_infer/gates.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class GateAmendment(_Record):
    """Disclose a prospective revision and the evidence already seen.

    ``supersedes`` identifies the prior saved decision contract. An empty
    ``seen_before_amendment`` explicitly records that no result artifacts were
    seen. The timestamp and disclosure are supplied by the author; the package
    cannot authenticate chronology or establish independence of fresh evidence.
    """

    supersedes: ArtifactReference
    recorded_at: datetime
    reason: _Text
    seen_before_amendment: tuple[ArtifactReference, ...]

    @model_validator(mode="after")
    def _timezone(self) -> Self:
        if self.recorded_at.utcoffset() is None:
            msg = "Amendments require a timezone-aware timestamp"
            raise ValueError(msg)
        return self

GateOutcome

Bases: _Record

The scalar read for one criterion; None means unavailable.

Source code in src/op_infer/gates.py
258
259
260
261
262
class GateOutcome(_Record):
    """The scalar read for one criterion; None means unavailable."""

    name: _Text
    value: _Finite | None

GateRecord

Bases: _Record

Immutable criteria and evidence; derive readable/passed on every load.

readable requires all adequacy criteria to pass. passed additionally requires all decision criteria. An unavailable or underpowered reading cannot pass when its requisite evidence/floor is an adequacy criterion. The record retains values for failed and unreadable runs.

Source code in src/op_infer/gates.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
class GateRecord(_Record):
    """Immutable criteria and evidence; derive readable/passed on every load.

    ``readable`` requires all adequacy criteria to pass. ``passed`` additionally
    requires all decision criteria. An unavailable or underpowered reading
    cannot pass when its requisite evidence/floor is an adequacy criterion.
    The record retains values for failed and unreadable runs.
    """

    specification: GateSet
    evidence: ArtifactReference
    outcomes: tuple[GateOutcome, ...]

    @model_validator(mode="after")
    def _names(self) -> Self:
        if tuple(o.name for o in self.outcomes) != tuple(
            g.name for g in self.specification.gates
        ):
            msg = "Outcomes must match every criterion in specification order"
            raise ValueError(msg)
        return self

    def statuses(self) -> tuple[Literal["pass", "fail", "unavailable"], ...]:
        """Return criterion verdicts, preserving unavailable outcomes."""
        statuses: list[Literal["pass", "fail", "unavailable"]] = []
        for gate, outcome in zip(self.specification.gates, self.outcomes, strict=True):
            value = outcome.value
            if value is None:
                statuses.append("unavailable")
            else:
                passed = (gate.lower is None or value >= gate.lower) and (
                    gate.upper is None or value <= gate.upper
                )
                statuses.append("pass" if passed else "fail")
        return tuple(statuses)

    @property
    def readable(self) -> bool:
        """Whether all declared adequacy criteria pass."""
        return all(
            status == "pass"
            for gate, status in zip(
                self.specification.gates, self.statuses(), strict=True
            )
            if gate.role == "adequacy"
        )

    @property
    def passed(self) -> bool:
        """Whether a readable result passes every decision criterion."""
        return self.readable and all(status == "pass" for status in self.statuses())

passed property

Whether a readable result passes every decision criterion.

readable property

Whether all declared adequacy criteria pass.

statuses()

Return criterion verdicts, preserving unavailable outcomes.

Source code in src/op_infer/gates.py
287
288
289
290
291
292
293
294
295
296
297
298
299
def statuses(self) -> tuple[Literal["pass", "fail", "unavailable"], ...]:
    """Return criterion verdicts, preserving unavailable outcomes."""
    statuses: list[Literal["pass", "fail", "unavailable"]] = []
    for gate, outcome in zip(self.specification.gates, self.outcomes, strict=True):
        value = outcome.value
        if value is None:
            statuses.append("unavailable")
        else:
            passed = (gate.lower is None or value >= gate.lower) and (
                gate.upper is None or value <= gate.upper
            )
            statuses.append("pass" if passed else "fail")
    return tuple(statuses)

GateSet

Bases: _Record

Stage-specific criteria saved before invoking a seeded evaluator.

The context reference identifies the estimator/design/prior contract; evidence identifies exact diagnostic inputs. The callback receives a fresh immutable RandomKey on each call. It owns native RNG lowering and must use that key for all stochastic diagnostics. Replaying external mutable state or ignoring the key is outside this bookkeeping contract.

write refuses a different existing specification. evaluate reads and checks that saved specification before calling the evaluator. External version control establishes whether results were unseen at registration.

Examples:

>>> import tempfile
>>> key = RandomKey(seed=7, stream="gates.validation")
>>> context = ArtifactReference.from_bytes(b"toy", kind="design-v1")
>>> criteria = GateSet(
...     name="toy",
...     stage="validation",
...     context=context,
...     key=key,
...     gates=(
...         Gate(
...             name="adequate", metric="ess", role="adequacy", lower=100.0
...         ),
...         Gate(
...             name="error",
...             metric="error",
...             role="decision",
...             lower=-0.05,
...             upper=0.05,
...         ),
...     ),
... )
>>> with tempfile.TemporaryDirectory() as directory:
...     path = Path(directory) / "criteria.json"
...     _ = criteria.write(path)
...     result = criteria.evaluate(
...         path,
...         lambda key: {"ess": 1000.0, "error": 0.01},
...         evidence=context,
...         context=context,
...     )
>>> result.readable, result.passed
(True, True)
>>> restored = GateRecord.model_validate_json(result.model_dump_json())
>>> restored.readable, restored.passed
(True, True)
Source code in src/op_infer/gates.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
class GateSet(_Record):
    """Stage-specific criteria saved before invoking a seeded evaluator.

    The context reference identifies the estimator/design/prior contract;
    evidence identifies exact diagnostic inputs. The callback receives a fresh
    immutable RandomKey on each call. It owns native RNG lowering and must use
    that key for all stochastic diagnostics. Replaying external mutable state
    or ignoring the key is outside this bookkeeping contract.

    ``write`` refuses a different existing specification. ``evaluate`` reads
    and checks that saved specification before calling the evaluator. External
    version control establishes whether results were unseen at registration.

    Examples:
        >>> import tempfile
        >>> key = RandomKey(seed=7, stream="gates.validation")
        >>> context = ArtifactReference.from_bytes(b"toy", kind="design-v1")
        >>> criteria = GateSet(
        ...     name="toy",
        ...     stage="validation",
        ...     context=context,
        ...     key=key,
        ...     gates=(
        ...         Gate(
        ...             name="adequate", metric="ess", role="adequacy", lower=100.0
        ...         ),
        ...         Gate(
        ...             name="error",
        ...             metric="error",
        ...             role="decision",
        ...             lower=-0.05,
        ...             upper=0.05,
        ...         ),
        ...     ),
        ... )
        >>> with tempfile.TemporaryDirectory() as directory:
        ...     path = Path(directory) / "criteria.json"
        ...     _ = criteria.write(path)
        ...     result = criteria.evaluate(
        ...         path,
        ...         lambda key: {"ess": 1000.0, "error": 0.01},
        ...         evidence=context,
        ...         context=context,
        ...     )
        >>> result.readable, result.passed
        (True, True)
        >>> restored = GateRecord.model_validate_json(result.model_dump_json())
        >>> restored.readable, restored.passed
        (True, True)
    """

    schema_version: Literal[1] = 1
    name: _Text
    stage: _Text
    context: ArtifactReference
    key: RandomKey
    gates: tuple[Gate, ...]
    amendment: GateAmendment | None = None

    @field_validator("schema_version", mode="before")
    @classmethod
    def _integer_version(cls, value: object) -> object:
        if type(value) is not int:
            msg = "schema_version must be an integer"
            raise ValueError(msg)
        return value

    @model_validator(mode="after")
    def _criteria(self) -> Self:
        if len({g.name for g in self.gates}) != len(self.gates):
            msg = "Gate names must be unique"
            raise ValueError(msg)
        if {g.role for g in self.gates} != {"adequacy", "decision"}:
            msg = "A GateSet requires adequacy and decision criteria"
            raise ValueError(msg)
        return self

    def reference(self) -> ArtifactReference:
        """Return the content identity of this complete specification."""
        return ArtifactReference.from_bytes(
            self.model_dump_json().encode(), kind="op-infer-gate-set-v1"
        )

    def write(self, path: str | Path) -> ArtifactReference:
        """Atomically save criteria, refusing to replace a different contract.

        Returns:
            The saved specification's content reference.

        Raises:
            ValueError: The destination already contains different bytes.
        """
        write_immutable_json(
            path,
            self.model_dump_json().encode(),
            conflict="Saved gate specification differs; write an amendment separately",
        )
        return self.reference()

    def amend(
        self,
        *,
        gates: tuple[Gate, ...],
        key: RandomKey,
        disclosure: GateAmendment,
    ) -> GateSet:
        """Create revised criteria with an explicit prior-artifact reference.

        Returns:
            A new specification to save separately before fresh evaluation.

        Raises:
            ValueError: The disclosure does not reference this specification.
        """
        if disclosure.supersedes != self.reference():
            msg = "Amendment must reference the specification it supersedes"
            raise ValueError(msg)
        return GateSet(
            name=self.name,
            stage=self.stage,
            context=self.context,
            key=key,
            gates=gates,
            amendment=disclosure,
        )

    def evaluate(
        self,
        path: str | Path,
        evaluator: Callable[[RandomKey], Mapping[str, float | None]],
        *,
        evidence: ArtifactReference,
        context: ArtifactReference,
    ) -> GateRecord:
        """Check saved criteria/context, then evaluate using the declared key.

        Returns:
            A complete record with separate readable and passed decisions.
            Exceptions from the evaluator propagate; they cannot produce a pass.

        Raises:
            ValueError: Saved criteria or evidence context do not match.
            FileNotFoundError: No criteria have been saved at the supplied path.
        """
        saved = GateSet.model_validate_json(Path(path).read_bytes())
        if saved != self or context != self.context:
            msg = "Saved gate specification or evidence context differs"
            raise ValueError(msg)
        values = evaluator(self.key)
        outcomes = []
        for gate in self.gates:
            raw = values.get(gate.metric)
            value = None if raw is None or not math.isfinite(raw) else float(raw)
            outcomes.append(GateOutcome(name=gate.name, value=value))
        return GateRecord(
            specification=self, evidence=evidence, outcomes=tuple(outcomes)
        )

amend(*, gates, key, disclosure)

Create revised criteria with an explicit prior-artifact reference.

Returns:

Type Description
GateSet

A new specification to save separately before fresh evaluation.

Raises:

Type Description
ValueError

The disclosure does not reference this specification.

Source code in src/op_infer/gates.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def amend(
    self,
    *,
    gates: tuple[Gate, ...],
    key: RandomKey,
    disclosure: GateAmendment,
) -> GateSet:
    """Create revised criteria with an explicit prior-artifact reference.

    Returns:
        A new specification to save separately before fresh evaluation.

    Raises:
        ValueError: The disclosure does not reference this specification.
    """
    if disclosure.supersedes != self.reference():
        msg = "Amendment must reference the specification it supersedes"
        raise ValueError(msg)
    return GateSet(
        name=self.name,
        stage=self.stage,
        context=self.context,
        key=key,
        gates=gates,
        amendment=disclosure,
    )

evaluate(path, evaluator, *, evidence, context)

Check saved criteria/context, then evaluate using the declared key.

Returns:

Type Description
GateRecord

A complete record with separate readable and passed decisions.

GateRecord

Exceptions from the evaluator propagate; they cannot produce a pass.

Raises:

Type Description
ValueError

Saved criteria or evidence context do not match.

FileNotFoundError

No criteria have been saved at the supplied path.

Source code in src/op_infer/gates.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def evaluate(
    self,
    path: str | Path,
    evaluator: Callable[[RandomKey], Mapping[str, float | None]],
    *,
    evidence: ArtifactReference,
    context: ArtifactReference,
) -> GateRecord:
    """Check saved criteria/context, then evaluate using the declared key.

    Returns:
        A complete record with separate readable and passed decisions.
        Exceptions from the evaluator propagate; they cannot produce a pass.

    Raises:
        ValueError: Saved criteria or evidence context do not match.
        FileNotFoundError: No criteria have been saved at the supplied path.
    """
    saved = GateSet.model_validate_json(Path(path).read_bytes())
    if saved != self or context != self.context:
        msg = "Saved gate specification or evidence context differs"
        raise ValueError(msg)
    values = evaluator(self.key)
    outcomes = []
    for gate in self.gates:
        raw = values.get(gate.metric)
        value = None if raw is None or not math.isfinite(raw) else float(raw)
        outcomes.append(GateOutcome(name=gate.name, value=value))
    return GateRecord(
        specification=self, evidence=evidence, outcomes=tuple(outcomes)
    )

reference()

Return the content identity of this complete specification.

Source code in src/op_infer/gates.py
176
177
178
179
180
def reference(self) -> ArtifactReference:
    """Return the content identity of this complete specification."""
    return ArtifactReference.from_bytes(
        self.model_dump_json().encode(), kind="op-infer-gate-set-v1"
    )

write(path)

Atomically save criteria, refusing to replace a different contract.

Returns:

Type Description
ArtifactReference

The saved specification's content reference.

Raises:

Type Description
ValueError

The destination already contains different bytes.

Source code in src/op_infer/gates.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def write(self, path: str | Path) -> ArtifactReference:
    """Atomically save criteria, refusing to replace a different contract.

    Returns:
        The saved specification's content reference.

    Raises:
        ValueError: The destination already contains different bytes.
    """
    write_immutable_json(
        path,
        self.model_dump_json().encode(),
        conflict="Saved gate specification differs; write an amendment separately",
    )
    return self.reference()

aggregate(pits, contraction=None, *, bins=20, power_floor=POWER_FLOOR, alpha=0.05, n_failed=0)

Summarize the PITs of every estimand and flag the non-uniform ones.

Parameters:

Name Type Description Default
pits Mapping[str, ArrayLike]

Estimand name to the per-replicate PITs in [0, 1].

required
contraction Mapping[str, ArrayLike] | None

Optional estimand name to per-replicate posterior SD over prior SD.

None
bins int

Number of equal-width bins of the chi-square uniformity test.

20
power_floor int

Replicate count below which the result is underpowered.

POWER_FLOOR
alpha float

Flagging level on the Benjamini-Hochberg q-value.

0.05
n_failed int

Nonnegative integer count of failed replicates; kept as failures (see load_replicates).

0

Returns:

Type Description
dict[str, Any]

The per-estimand table under estimands (n, chi-square p, BH q, mean

dict[str, Any]

and median PIT, coverage50, coverage90, mean contraction or None,

dict[str, Any]

flagged) and the top-level n_replicates (the minimum over estimands),

dict[str, Any]

underpowered, n_flagged, flagged, underpowered_banner (None when

dict[str, Any]

powered), n_failed, n_total, failed_fraction and the settings.

Raises:

Type Description
ValueError

Replicates/PITs are invalid, failed counts are not nonnegative integers, bins are not integers >= 2, the power floor is not a positive integer, alpha is not finite/in (0, 1), or a test is nonfinite.

Examples:

>>> ranks = np.tile((np.arange(20) + 0.5) / 20, 50)
>>> report = aggregate({"theta": ranks}, n_failed=5)
>>> report["n_replicates"], report["n_total"], report["underpowered"]
(1000, 1005, False)
>>> report["n_flagged"]
0
Source code in src/op_infer/calibrate.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
def aggregate(  # noqa: PLR0913 -- one keyword per documented setting
    pits: Mapping[str, ArrayLike],
    contraction: Mapping[str, ArrayLike] | None = None,
    *,
    bins: int = 20,
    power_floor: int = POWER_FLOOR,
    alpha: float = 0.05,
    n_failed: int = 0,
) -> dict[str, Any]:
    """Summarize the PITs of every estimand and flag the non-uniform ones.

    Args:
        pits: Estimand name to the per-replicate PITs in [0, 1].
        contraction: Optional estimand name to per-replicate posterior SD over
            prior SD.
        bins: Number of equal-width bins of the chi-square uniformity test.
        power_floor: Replicate count below which the result is underpowered.
        alpha: Flagging level on the Benjamini-Hochberg q-value.
        n_failed: Nonnegative integer count of failed replicates; kept as failures (see
            ``load_replicates``).

    Returns:
        The per-estimand table under ``estimands`` (n, chi-square p, BH q, mean
        and median PIT, coverage50, coverage90, mean contraction or None,
        flagged) and the top-level n_replicates (the minimum over estimands),
        underpowered, n_flagged, flagged, underpowered_banner (None when
        powered), n_failed, n_total, failed_fraction and the settings.

    Raises:
        ValueError: Replicates/PITs are invalid, failed counts are not nonnegative
            integers, bins are not integers >= 2, the power floor is not a
            positive integer, alpha is not finite/in (0, 1), or a test is nonfinite.

    Examples:
        >>> ranks = np.tile((np.arange(20) + 0.5) / 20, 50)
        >>> report = aggregate({"theta": ranks}, n_failed=5)
        >>> report["n_replicates"], report["n_total"], report["underpowered"]
        (1000, 1005, False)
        >>> report["n_flagged"]
        0
    """
    bins, power_floor, alpha = _rank_settings(bins, power_floor, alpha)
    n_failed = _failed_replicate_count(n_failed)
    if not pits and n_failed == 0:
        msg = "no replicates to aggregate"
        raise ValueError(msg)
    arrays = {name: _as_pits(name, values) for name, values in pits.items()}
    pvals = [
        float(chisquare(np.histogram(x, bins=bins, range=(0.0, 1.0))[0]).pvalue)
        for x in arrays.values()
    ]
    if not np.all(np.isfinite(pvals)):
        msg = "Rank uniformity returned nonfinite p-values; no gate can be read"
        raise ValueError(msg)
    qvals = benjamini_hochberg(pvals)

    table: dict[str, dict[str, Any]] = {}
    for (name, x), p, q in zip(arrays.items(), pvals, qvals, strict=True):
        c = None
        if contraction is not None and name in contraction:
            c = np.asarray(contraction[name], dtype=float)
        table[name] = _estimand_row(x, p, float(q), c, alpha)
    n_rep = min((row["n"] for row in table.values()), default=0)
    underpowered = n_rep < power_floor
    flagged = [name for name, row in table.items() if row["flagged"]]
    n_total = n_rep + n_failed
    banner = (
        f"UNDERPOWERED: {n_rep} replicates < power floor {power_floor}. "
        "A pass means 'not detected', not 'calibrated'; failures count at any n."
    )
    return {
        "estimands": table,
        "n_replicates": n_rep,
        "underpowered": underpowered,
        "n_flagged": len(flagged),
        "flagged": flagged,
        "underpowered_banner": banner if underpowered else None,
        "n_failed": int(n_failed),
        "n_total": n_total,
        "failed_fraction": n_failed / n_total if n_total else 0.0,
        "settings": {"bins": bins, "power_floor": power_floor, "alpha": alpha},
    }

assert_simulated_differs(simulated, observed, mask)

Check that simulated data are not the real data; count the equal cells.

A probabilistic program with an observed site can return the observed array from its predictive. Every replicate then refits the real data against an unrelated prior draw and the ranks look like a result.

Parameters:

Name Type Description Default
simulated ArrayLike

Simulated data of the replicate.

required
observed ArrayLike

The real data.

required
mask ArrayLike

Boolean array, true where the real cell is observed.

required

Returns:

Type Description
int

The number of observed cells where the simulated value equals the real

int

value (record it).

Raises:

Type Description
ValueError

If the shapes differ, no cell is observed, or all observed cells are equal (the replicate refits the real data).

Source code in src/op_infer/calibrate.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def assert_simulated_differs(
    simulated: ArrayLike, observed: ArrayLike, mask: ArrayLike
) -> int:
    """Check that simulated data are not the real data; count the equal cells.

    A probabilistic program with an observed site can return the observed array
    from its predictive. Every replicate then refits the real data against an
    unrelated prior draw and the ranks look like a result.

    Args:
        simulated: Simulated data of the replicate.
        observed: The real data.
        mask: Boolean array, true where the real cell is observed.

    Returns:
        The number of observed cells where the simulated value equals the real
        value (record it).

    Raises:
        ValueError: If the shapes differ, no cell is observed, or all observed
            cells are equal (the replicate refits the real data).
    """
    sim = np.asarray(simulated)
    obs = np.asarray(observed)
    keep = np.asarray(mask, dtype=bool)
    if not sim.shape == obs.shape == keep.shape:
        msg = (
            f"shape mismatch: simulated {sim.shape}, observed {obs.shape}, "
            f"mask {keep.shape}"
        )
        raise ValueError(msg)
    n_obs = int(keep.sum())
    if n_obs == 0:
        msg = "mask has no observed cell"
        raise ValueError(msg)
    n_equal = int(np.sum((sim == obs) & keep))
    if n_equal == n_obs:
        msg = (
            f"all {n_obs} observed cells equal the real data: "
            "the replicate refits the real data"
        )
        raise ValueError(msg)
    return n_equal

benjamini_hochberg(pvalues)

Return Benjamini-Hochberg step-up q-values in the input order.

For ascending p-values p_(1..m) the q-value is min(1, min_{j >= i} p_(j) m / j).

Parameters:

Name Type Description Default
pvalues ArrayLike

Raw p-values in [0, 1].

required

Returns:

Type Description
NDArray[float64]

The q-values, same length and order.

Source code in src/op_infer/calibrate.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def benjamini_hochberg(pvalues: ArrayLike) -> NDArray[np.float64]:
    """Return Benjamini-Hochberg step-up q-values in the input order.

    For ascending p-values ``p_(1..m)`` the q-value is
    ``min(1, min_{j >= i} p_(j) m / j)``.

    Args:
        pvalues: Raw p-values in [0, 1].

    Returns:
        The q-values, same length and order.
    """
    p = np.asarray(pvalues, dtype=float)
    m = p.size
    order = np.argsort(p, kind="stable")
    scaled = p[order] * m / np.arange(1, m + 1)
    q_sorted = np.minimum(1.0, np.minimum.accumulate(scaled[::-1])[::-1])
    q = np.empty(m, dtype=float)
    q[order] = q_sorted
    return q

coverage_operating_characteristics(rules, *, n_replicates, probabilities=None)

Evaluate a fixed coverage family using exact binomial tail probabilities.

All criteria must pass. Replicates are independent within each rule; dependence between rules is unrestricted. The family rejection probability lies between the largest marginal probability and their sum (capped at one). It is not generally equal to either bound.

Parameters:

Name Type Description Default
rules Sequence[CoverageRule]

Complete prespecified criterion family, with unique names.

required
n_replicates int

Fixed number of usable, independent replicates, not attempts.

required
probabilities Mapping[str, float] | None

Actual coverage probability for every rule under an alternative. If absent, use the nominal calibrated probabilities.

None

Returns:

Type Description
dict[str, Any]

JSON-compatible marginal rejection probabilities and family bounds,

dict[str, Any]

inclusive accepted counts, criteria, assumptions and implementation version.

dict[str, Any]

Under calibration these describe false failures; under a specified

dict[str, Any]

alternative they bound rejection power. No sampler/gate certification.

Raises:

Type Description
ValueError

Counts, rules or complete probability mapping are invalid.

Examples:

>>> rule = CoverageRule(name="half", nominal=0.5, lower=0.25, upper=0.75)
>>> result = coverage_operating_characteristics((rule,), n_replicates=4)
>>> result["criteria"][0]["rejection_probability"]
0.125
>>> result["family_rejection_probability"]
{'lower': 0.125, 'upper': 0.125}
Source code in src/op_infer/coverage.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def coverage_operating_characteristics(
    rules: Sequence[CoverageRule],
    *,
    n_replicates: int,
    probabilities: Mapping[str, float] | None = None,
) -> dict[str, Any]:
    """Evaluate a fixed coverage family using exact binomial tail probabilities.

    All criteria must pass. Replicates are independent
    within each rule; dependence between rules is unrestricted. The family
    rejection probability lies between the largest marginal probability and
    their sum (capped at one). It is not generally equal to either bound.

    Args:
        rules: Complete prespecified criterion family, with unique names.
        n_replicates: Fixed number of usable, independent replicates, not attempts.
        probabilities: Actual coverage probability for every rule under an
            alternative. If absent, use the nominal calibrated probabilities.

    Returns:
        JSON-compatible marginal rejection probabilities and family bounds,
        inclusive accepted counts, criteria, assumptions and implementation version.
        Under calibration these describe false failures; under a specified
        alternative they bound rejection power. No sampler/gate certification.

    Raises:
        ValueError: Counts, rules or complete probability mapping are invalid.

    Examples:
        >>> rule = CoverageRule(name="half", nominal=0.5, lower=0.25, upper=0.75)
        >>> result = coverage_operating_characteristics((rule,), n_replicates=4)
        >>> result["criteria"][0]["rejection_probability"]
        0.125
        >>> result["family_rejection_probability"]
        {'lower': 0.125, 'upper': 0.125}
    """
    family = _rules(rules)
    count = _count(n_replicates, "n_replicates")
    supplied = (
        {rule.name: rule.nominal for rule in family}
        if probabilities is None
        else dict(probabilities)
    )
    if set(supplied) != {rule.name for rule in family} or any(
        isinstance(p, (bool, np.bool_)) or not math.isfinite(p) or not 0 <= p <= 1
        for p in supplied.values()
    ):
        msg = "Supply finite coverage probabilities in [0, 1] for every rule"
        raise ValueError(msg)
    counts = np.array([count], dtype=np.int64)
    rows = []
    rejected = []
    for rule in family:
        lower, upper = _accepted_counts(rule, counts)
        probability = float(_rejection(rule, counts, supplied[rule.name])[0])
        rejected.append(probability)
        rows.append(
            {
                "rule": rule.model_dump(mode="json"),
                "coverage_probability": float(supplied[rule.name]),
                "accepted_count_min": int(lower[0]),
                "accepted_count_max": int(upper[0]),
                "rejection_probability": probability,
            }
        )
    return {
        "schema_version": 1,
        "n_replicates": count,
        "criteria": rows,
        "family_rejection_probability": {
            "lower": max(rejected),
            "upper": min(1.0, math.fsum(rejected)),
        },
        "evaluated_under": "nominal calibration"
        if probabilities is None
        else "specified coverage probabilities",
        "decision_rule": "reject_if_any_coverage_outside_inclusive_bounds",
        "sampling": "fixed independent successful replicate bank",
        "dependence_between_rules": "unrestricted",
        "implementation": "scipy.stats.binom.cdf/sf",
        "scipy_version": scipy_version,
        "adequacy_status": "not_assessed",
    }

coverage_summary(pits, *, levels=(0.5, 0.9), confidence=0.95, n_failed=0)

Summarize central posterior coverage with marginal Wilson intervals.

The binomial calculation uses trade-study. Requires the study extra. Each PIT must come from one independent SBC replicate of the same estimator and simulation design, at a fixed size. For atoms use randomized PITs. Finite posterior draws can discretize PITs.

Coverage is conditional on successful fits. Failures remain explicit in the total attempt count and failure fraction; they are not covered draws. An all-failed bank has unavailable coverage, not a zero-width interval. The same successful replicate bank must supply every estimand. Intervals are marginal, without multiple-testing or optional-stopping guarantees. An interval containing its nominal level does not certify calibration.

Parameters:

Name Type Description Default
pits Mapping[str, ArrayLike]

Estimand names to finite PIT vectors in [0, 1].

required
levels Sequence[float]

Distinct nominal central coverage levels in (0, 1).

(0.5, 0.9)
confidence float

Wilson interval confidence in (0, 1).

0.95
n_failed int

Nonnegative integer count of failed attempts in the bank.

0

Returns:

Type Description
dict[str, Any]

JSON-compatible counts, failure fraction and per-estimand coverage

dict[str, Any]

rows. Each row retains its nominal level and complete interval record.

Raises:

Type Description
ValueError

Counts, levels, PITs or the shared bank are invalid.

ImportError

The study extra is not installed.

Examples:

Requires the study extra; the required study job executes this example.

>>> ranks = (np.arange(1000) + 0.5) / 1000
>>> report = coverage_summary(
...     {"theta": ranks}, n_failed=5
... )
>>> report["n_successful"], report["n_total"]
(1000, 1005)
>>> report["estimands"]["theta"][0]["estimate"]
0.5
Source code in src/op_infer/calibrate.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
def coverage_summary(
    pits: Mapping[str, ArrayLike],
    *,
    levels: Sequence[float] = (0.5, 0.9),
    confidence: float = 0.95,
    n_failed: int = 0,
) -> dict[str, Any]:
    """Summarize central posterior coverage with marginal Wilson intervals.

    The binomial calculation uses trade-study.
    Requires the study extra. Each PIT must come from one independent SBC
    replicate of the same estimator and simulation design, at a fixed size.
    For atoms use randomized PITs. Finite posterior draws can discretize PITs.

    Coverage is conditional on successful fits. Failures remain explicit in
    the total attempt count and failure fraction; they are not covered draws.
    An all-failed bank has unavailable coverage, not a zero-width interval.
    The same successful replicate bank must supply every estimand. Intervals
    are marginal, without multiple-testing or optional-stopping guarantees.
    An interval containing its nominal level does not certify calibration.

    Args:
        pits: Estimand names to finite PIT vectors in [0, 1].
        levels: Distinct nominal central coverage levels in (0, 1).
        confidence: Wilson interval confidence in (0, 1).
        n_failed: Nonnegative integer count of failed attempts in the bank.

    Returns:
        JSON-compatible counts, failure fraction and per-estimand coverage
        rows. Each row retains its nominal level and complete interval record.

    Raises:
        ValueError: Counts, levels, PITs or the shared bank are invalid.
        ImportError: The study extra is not installed.

    Examples:
        Requires the study extra; the required study job executes this example.

        >>> ranks = (np.arange(1000) + 0.5) / 1000
        >>> report = coverage_summary(
        ...     {"theta": ranks}, n_failed=5
        ... )  # doctest: +SKIP
        >>> report["n_successful"], report["n_total"]  # doctest: +SKIP
        (1000, 1005)
        >>> report["estimands"]["theta"][0]["estimate"]  # doctest: +SKIP
        0.5
    """
    from trade_study import proportion_interval  # noqa: PLC0415 - optional dependency

    n_failed = _failed_replicate_count(n_failed)
    nominal = tuple(levels)
    if (
        not nominal
        or any(
            isinstance(x, bool) or not np.isfinite(x) or not 0 < x < 1 for x in nominal
        )
        or len(set(nominal)) != len(nominal)
    ):
        msg = "levels must be distinct finite values in (0, 1)"
        raise ValueError(msg)
    # Delegate confidence validation even when the entire bank failed.
    proportion_interval(0, 1, confidence=confidence)
    arrays = {name: _as_pits(name, values) for name, values in pits.items()}
    counts = {x.size for x in arrays.values()}
    if len(counts) > 1 or (not arrays and n_failed == 0):
        msg = "coverage requires one shared nonempty replicate bank"
        raise ValueError(msg)
    successful = int(next(iter(counts), 0))
    total = successful + n_failed
    table = {}
    for name, x in arrays.items():
        rows = []
        for level in nominal:
            tail = (1 - level) / 2
            k = int(np.count_nonzero((x >= tail) & (x <= 1 - tail)))
            interval = proportion_interval(k, successful, confidence=confidence)
            rows.append({"nominal": float(level), **asdict(interval)})
        table[name] = rows
    return {
        "estimands": table,
        "available": bool(successful),
        "n_successful": successful,
        "n_failed": n_failed,
        "n_total": total,
        "failed_fraction": n_failed / total,
        "conditioning": "successful fits",
        "multiplicity": "marginal",
        "sampling": "fixed independent replicate bank",
        "settings": {
            "levels": list(nominal),
            "confidence": confidence,
            "method": "wilson",
        },
    }

format_table(result)

Return the per-estimand table as text.

Parameters:

Name Type Description Default
result Mapping[str, Any]

Output of aggregate.

required

Returns:

Type Description
str

The table, one row per estimand.

Source code in src/op_infer/calibrate.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
def format_table(result: Mapping[str, Any]) -> str:
    """Return the per-estimand table as text.

    Args:
        result: Output of ``aggregate``.

    Returns:
        The table, one row per estimand.
    """
    head = (
        f"{'estimand':<28}{'n':>6}{'chi2 p':>10}{'q_BH':>8}{'meanPIT':>9}"
        f"{'cov50':>7}{'cov90':>7}{'contr.':>8}  flagged"
    )
    lines = [head]
    for name, r in result["estimands"].items():
        contr = "-" if r["mean_contraction"] is None else f"{r['mean_contraction']:.2f}"
        flag = "FLAGGED" if r["flagged"] else "ok"
        lines.append(
            f"{name:<28}{r['n']:>6}{r['p_chisq']:>10.3g}{r['q_bh']:>8.3f}"
            f"{r['mean_pit']:>9.3f}{r['coverage50']:>7.2f}{r['coverage90']:>7.2f}"
            f"{contr:>8}  {flag}"
        )
    return "\n".join(lines)

gate(result, *, max_flagged, must_pass=(), max_failed_fraction=MAX_FAILED_FRACTION)

Apply the pass rule to an aggregated result.

Pass iff at most max_flagged estimands are flagged, none of must_pass is flagged, and no more than max_failed_fraction of the replicates failed. A pass with an underpowered result is labelled "underpowered pass", which is not a claim of calibration; a failure counts at any number of replicates.

Parameters:

Name Type Description Default
result Mapping[str, Any]

Output of aggregate.

required
max_flagged int

Largest number of flagged estimands that still passes.

required
must_pass Sequence[str]

Estimands that must not be flagged.

()
max_failed_fraction float

Largest fraction of failed replicates that passes.

MAX_FAILED_FRACTION

Returns:

Type Description
dict[str, Any]

passed, underpowered, label ("pass", "fail" or "underpowered

dict[str, Any]

pass"), reasons (why it failed), n_failed and

dict[str, Any]

failed_fraction.

Raises:

Type Description
ValueError

A must-pass name is unknown, settings are missing/invalid, max_flagged is not a nonnegative integer or max_failed_fraction is not a finite probability in [0, 1].

Examples:

>>> ranks = np.tile((np.arange(20) + 0.5) / 20, 5)
>>> report = aggregate({"theta": ranks})
>>> verdict = gate(report, max_flagged=0)
>>> verdict["label"]
'underpowered pass'
>>> verdict["underpowered"]
True
Source code in src/op_infer/calibrate.py
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
def gate(
    result: Mapping[str, Any],
    *,
    max_flagged: int,
    must_pass: Sequence[str] = (),
    max_failed_fraction: float = MAX_FAILED_FRACTION,
) -> dict[str, Any]:
    """Apply the pass rule to an aggregated result.

    Pass iff at most ``max_flagged`` estimands are flagged, none of ``must_pass``
    is flagged, and no more than ``max_failed_fraction`` of the replicates
    failed. A pass with an underpowered result is labelled "underpowered pass",
    which is not a claim of calibration; a failure counts at any number of
    replicates.

    Args:
        result: Output of ``aggregate``.
        max_flagged: Largest number of flagged estimands that still passes.
        must_pass: Estimands that must not be flagged.
        max_failed_fraction: Largest fraction of failed replicates that passes.

    Returns:
        ``passed``, ``underpowered``, ``label`` ("pass", "fail" or "underpowered
        pass"), ``reasons`` (why it failed), ``n_failed`` and
        ``failed_fraction``.

    Raises:
        ValueError: A must-pass name is unknown, settings are missing/invalid,
            max_flagged is not a nonnegative integer or max_failed_fraction is
            not a finite probability in [0, 1].

    Examples:
        >>> ranks = np.tile((np.arange(20) + 0.5) / 20, 5)
        >>> report = aggregate({"theta": ranks})
        >>> verdict = gate(report, max_flagged=0)
        >>> verdict["label"]
        'underpowered pass'
        >>> verdict["underpowered"]
        True
    """
    max_flagged = _count_setting(max_flagged, "max_flagged", 0)
    max_failed_fraction = _probability_setting(
        max_failed_fraction, "max_failed_fraction", closed=True
    )
    settings = result.get("settings")
    if (
        not isinstance(settings, Mapping)
        or not {"bins", "power_floor", "alpha"} <= settings.keys()
    ):
        msg = "Gate requires the settings from its aggregate result"
        raise ValueError(msg)
    _rank_settings(settings["bins"], settings["power_floor"], settings["alpha"])
    estimands: Mapping[str, Any] = result["estimands"]
    unknown = [name for name in must_pass if name not in estimands]
    if unknown:
        msg = f"must_pass names not in the result: {unknown}"
        raise ValueError(msg)
    reasons: list[str] = []
    if result["n_flagged"] > max_flagged:
        reasons.append(
            f"{result['n_flagged']} estimands flagged (> {max_flagged}): "
            + ", ".join(result["flagged"])
        )
    reasons += [
        f"must-pass estimand {name!r} is flagged"
        for name in must_pass
        if estimands[name]["flagged"]
    ]
    n_failed = int(result.get("n_failed", 0))
    failed_fraction = float(result.get("failed_fraction", 0.0))
    if failed_fraction > max_failed_fraction:
        reasons.append(
            f"{n_failed} of {result.get('n_total', n_failed)} replicates failed "
            f"({failed_fraction:.1%} > {max_failed_fraction:.0%})"
        )
    passed = not reasons
    underpowered = bool(result["underpowered"])
    label = "fail" if not passed else ("underpowered pass" if underpowered else "pass")
    return {
        "passed": passed,
        "underpowered": underpowered,
        "label": label,
        "reasons": reasons,
        "n_failed": n_failed,
        "failed_fraction": failed_fraction,
    }

load_replicates(directory)

Read the replicate JSON files of a directory.

Parameters:

Name Type Description Default
directory str | Path

Directory with one *.json file per replicate (schema in the module docstring).

required

Returns:

Type Description
dict[str, list[float]]

(pits, contraction, diag): PITs and contractions per estimand over

dict[str, list[float]]

the successful replicates, and diag with n_failed, n_total,

dict[str, Any]

failed_files and fit_diag (the _fit_diag values per key).

Raises:

Type Description
ValueError

If there is no file, a file is malformed, a PIT is not finite, or a replicate that is not marked _failed lacks an estimand that another has.

Source code in src/op_infer/calibrate.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
def load_replicates(
    directory: str | Path,
) -> tuple[dict[str, list[float]], dict[str, list[float]], dict[str, Any]]:
    """Read the replicate JSON files of a directory.

    Args:
        directory: Directory with one ``*.json`` file per replicate (schema in
            the module docstring).

    Returns:
        ``(pits, contraction, diag)``: PITs and contractions per estimand over
        the successful replicates, and ``diag`` with ``n_failed``, ``n_total``,
        ``failed_files`` and ``fit_diag`` (the ``_fit_diag`` values per key).

    Raises:
        ValueError: If there is no file, a file is malformed, a PIT is not
            finite, or a replicate that is not marked ``_failed`` lacks an
            estimand that another has.
    """
    files = sorted(Path(directory).glob("*.json"))
    if not files:
        msg = f"no *.json replicate files in {directory}"
        raise ValueError(msg)
    records = [(f, _read_replicate(f)) for f in files]
    failed = [f.name for f, data in records if data.get("_failed") is True]
    ok = [(f, data) for f, data in records if data.get("_failed") is not True]

    names = list(
        dict.fromkeys(k for _, data in ok for k in data if not k.startswith("_"))
    )
    pits: dict[str, list[float]] = {name: [] for name in names}
    contraction: dict[str, list[float]] = {}
    fit_diag: dict[str, list[Any]] = {}
    for f, data in ok:
        for name in names:
            entry = _pit_entry(f, data, name)
            pits[name].append(float(entry["pit"]))
            if entry.get("contraction") is not None:
                contraction.setdefault(name, []).append(float(entry["contraction"]))
        for key, value in (data.get("_fit_diag") or {}).items():
            fit_diag.setdefault(key, []).append(value)
    diag = {
        "n_failed": len(failed),
        "n_total": len(files),
        "failed_files": failed,
        "fit_diag": fit_diag,
    }
    return pits, contraction, diag

main(argv=None)

Run the aggregate command line.

Parameters:

Name Type Description Default
argv Sequence[str] | None

Arguments (default sys.argv[1:]).

None

Returns:

Type Description
int

The exit status: 0 on a pass or an underpowered pass, 1 on a gate

int

failure.

Source code in src/op_infer/calibrate.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
def main(argv: Sequence[str] | None = None) -> int:
    """Run the ``aggregate`` command line.

    Args:
        argv: Arguments (default ``sys.argv[1:]``).

    Returns:
        The exit status: 0 on a pass or an underpowered pass, 1 on a gate
        failure.
    """
    parser = argparse.ArgumentParser(
        prog="python -m op_infer.calibrate",
        description="Rank-based SBC: aggregate replicate JSON files, apply the gate.",
    )
    sub = parser.add_subparsers(dest="command", required=True)
    agg = sub.add_parser("aggregate", help="aggregate a directory of replicates")
    agg.add_argument("directory", type=Path)
    agg.add_argument("--out", type=Path, required=True, help="ledger JSON to write")
    agg.add_argument("--max-flagged", type=int, default=1, help="gate: flagged allowed")
    agg.add_argument("--must-pass", default="", help="gate: comma-separated estimands")
    agg.add_argument("--bins", type=int, default=20)
    agg.add_argument("--power-floor", type=int, default=POWER_FLOOR)
    agg.add_argument("--alpha", type=float, default=0.05)
    args = parser.parse_args(argv)

    pits, contraction, diag = load_replicates(args.directory)
    result = aggregate(
        pits,
        contraction,
        bins=args.bins,
        power_floor=args.power_floor,
        alpha=args.alpha,
        n_failed=diag["n_failed"],
    )
    must_pass = [name for name in args.must_pass.split(",") if name]
    verdict = gate(result, max_flagged=args.max_flagged, must_pass=must_pass)

    lines = [
        (
            f"# SBC aggregate: {result['n_replicates']} replicates "
            f"({diag['n_failed']} failed) from {args.directory}"
        )
    ]
    if result["underpowered_banner"]:
        lines.append(f"# *** {result['underpowered_banner']} ***")
    lines += [
        format_table(result),
        (
            f"\ngate: {verdict['label']} (max flagged {args.max_flagged}, "
            f"must pass {must_pass or 'none'})"
        ),
        *[f"  - {reason}" for reason in verdict["reasons"]],
    ]
    sys.stdout.write("\n".join(lines) + "\n")

    full = {
        **result,
        "gate": verdict,
        "fit_diag": diag["fit_diag"],
        "failed_files": diag["failed_files"],
    }
    meta = {
        "script": "op_infer.calibrate aggregate",
        "directory": str(args.directory),
        "settings": {
            "bins": args.bins,
            "power_floor": args.power_floor,
            "alpha": args.alpha,
            "max_flagged": args.max_flagged,
            "must_pass": must_pass,
        },
    }
    write_ledger(args.out, full, meta=meta)
    return 0 if verdict["passed"] else 1

pit(draws, truth, *, rng=None, atoms=False)

Return the probability integral transform of truth among draws.

For a continuous quantity the result is (#below + 0.5 #equal) / n. With atoms=True the randomized form p_below + U p_equal with U ~ Uniform(0, 1) is used. It is uniform under calibration for discrete quantities and quantities with point masses; ordinary and mid-ranks are not.

Parameters:

Name Type Description Default
draws ArrayLike

Posterior draws of the quantity.

required
truth float

The simulated true value of the quantity.

required
rng Generator | None

Random generator for the randomization; required when atoms is true. Seed it so the gate is reproducible.

None
atoms bool

Use the randomized PIT for quantities with atoms.

False

Returns:

Type Description
float

The PIT in [0, 1].

Raises:

Type Description
ValueError

If there are no draws, a draw or the truth is not finite, or atoms is set without rng.

Examples:

>>> pit([1.0, 2.0, 3.0], 2.5)
0.6666666666666666
>>> key = np.random.default_rng(3)
>>> 0.25 <= pit([0, 1, 1, 2], 1, atoms=True, rng=key) <= 0.75
True
Source code in src/op_infer/calibrate.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def pit(
    draws: ArrayLike,
    truth: float,
    *,
    rng: np.random.Generator | None = None,
    atoms: bool = False,
) -> float:
    """Return the probability integral transform of ``truth`` among ``draws``.

    For a continuous quantity the result is ``(#below + 0.5 #equal) / n``. With
    ``atoms=True`` the randomized form ``p_below + U p_equal`` with
    ``U ~ Uniform(0, 1)`` is used. It is uniform under calibration for discrete
    quantities and quantities with point masses; ordinary and mid-ranks are not.

    Args:
        draws: Posterior draws of the quantity.
        truth: The simulated true value of the quantity.
        rng: Random generator for the randomization; required when ``atoms`` is
            true. Seed it so the gate is reproducible.
        atoms: Use the randomized PIT for quantities with atoms.

    Returns:
        The PIT in [0, 1].

    Raises:
        ValueError: If there are no draws, a draw or the truth is not finite, or
            ``atoms`` is set without ``rng``.

    Examples:
        >>> pit([1.0, 2.0, 3.0], 2.5)
        0.6666666666666666
        >>> key = np.random.default_rng(3)
        >>> 0.25 <= pit([0, 1, 1, 2], 1, atoms=True, rng=key) <= 0.75
        True
    """
    x = np.asarray(draws, dtype=float).ravel()
    if x.size == 0:
        msg = "no posterior draws"
        raise ValueError(msg)
    if not (np.all(np.isfinite(x)) and np.isfinite(truth)):
        msg = "posterior draws and truth must be finite"
        raise ValueError(msg)
    p_below = float(np.mean(x < truth))
    p_equal = float(np.mean(x == truth))
    if atoms:
        if rng is None:
            msg = "atoms=True needs a numpy Generator in rng"
            raise ValueError(msg)
        return p_below + float(rng.uniform()) * p_equal
    return p_below + 0.5 * p_equal

plan_coverage_replicates(rules, *, max_false_fail, max_replicates)

Find the first fixed bank meeting a conservative family false-failure limit.

Search every integer size, since lattice effects make binomial rejection probabilities nonmonotone. A union bound protects the complete supplied family without assuming independent estimands or coverage levels. The result applies to the exact chosen count, not every larger count.

Parameters:

Name Type Description Default
rules Sequence[CoverageRule]

Complete family of inclusive coverage criteria.

required
max_false_fail float

Explicit maximum family false-failure probability in (0, 1).

required
max_replicates int

Explicit upper search budget for successful replicates.

required

Returns:

Type Description
dict[str, Any]

First qualifying count and its operating-characteristic report, or

dict[str, Any]

available=False and no count when the search budget cannot qualify.

dict[str, Any]

The count sizes only this fixed coverage rule, not failure policies,

dict[str, Any]

sampler diagnostics, other gate criteria or repeated interim looks.

Raises:

Type Description
ValueError

Rules, probability target or budget are invalid.

Examples:

>>> rule = CoverageRule(name="half", nominal=0.5, lower=0.25, upper=0.75)
>>> plan = plan_coverage_replicates(
...     (rule,), max_false_fail=0.125, max_replicates=4
... )
>>> plan["available"], plan["n_replicates"]
(True, 4)
Source code in src/op_infer/coverage.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def plan_coverage_replicates(
    rules: Sequence[CoverageRule],
    *,
    max_false_fail: float,
    max_replicates: int,
) -> dict[str, Any]:
    """Find the first fixed bank meeting a conservative family false-failure limit.

    Search every integer size, since lattice effects make binomial
    rejection probabilities nonmonotone. A union bound protects the complete
    supplied family without assuming independent estimands or coverage levels.
    The result applies to the exact chosen count, not every larger count.

    Args:
        rules: Complete family of inclusive coverage criteria.
        max_false_fail: Explicit maximum family false-failure probability in (0, 1).
        max_replicates: Explicit upper search budget for successful replicates.

    Returns:
        First qualifying count and its operating-characteristic report, or
        ``available=False`` and no count when the search budget cannot qualify.
        The count sizes only this fixed coverage rule, not failure policies,
        sampler diagnostics, other gate criteria or repeated interim looks.

    Raises:
        ValueError: Rules, probability target or budget are invalid.

    Examples:
        >>> rule = CoverageRule(name="half", nominal=0.5, lower=0.25, upper=0.75)
        >>> plan = plan_coverage_replicates(
        ...     (rule,), max_false_fail=0.125, max_replicates=4
        ... )
        >>> plan["available"], plan["n_replicates"]
        (True, 4)
    """
    family = _rules(rules)
    maximum = _count(max_replicates, "max_replicates")
    if (
        isinstance(max_false_fail, (bool, np.bool_))
        or not math.isfinite(max_false_fail)
        or not 0 < max_false_fail < 1
    ):
        msg = "max_false_fail must be finite and in (0, 1)"
        raise ValueError(msg)
    chosen = None
    # Bounded chunks avoid allocating the entire caller's search budget.
    for start in range(1, maximum + 1, 4096):
        counts = np.arange(start, min(start + 4096, maximum + 1), dtype=np.int64)
        upper = np.zeros(counts.size, dtype=np.float64)
        for rule in family:
            upper += _rejection(rule, counts, rule.nominal)
        passing = np.flatnonzero(upper <= max_false_fail)
        if passing.size:
            chosen = int(counts[passing[0]])
            break
    return {
        "schema_version": 1,
        "available": chosen is not None,
        "n_replicates": chosen,
        "max_false_fail": float(max_false_fail),
        "max_replicates": maximum,
        "rules": [rule.model_dump(mode="json") for rule in family],
        "reason": None if chosen is not None else "no_size_within_search_budget",
        "operating_characteristics": None
        if chosen is None
        else coverage_operating_characteristics(family, n_replicates=chosen),
        "sizing_method": "binomial union bound; exhaustive integer search",
        "adequacy_status": "not_assessed",
    }

posterior_contraction(draws, prior_sd)

Return the posterior SD over the prior SD of a quantity.

Parameters:

Name Type Description Default
draws ArrayLike

Posterior draws of the quantity.

required
prior_sd float

Standard deviation of the prior (positive and finite).

required

Returns:

Type Description
float

std(draws) / prior_sd; values near 1 mean the data did not narrow the

float

prior.

Raises:

Type Description
ValueError

If there are no finite draws or prior_sd is not positive and finite.

Source code in src/op_infer/calibrate.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def posterior_contraction(draws: ArrayLike, prior_sd: float) -> float:
    """Return the posterior SD over the prior SD of a quantity.

    Args:
        draws: Posterior draws of the quantity.
        prior_sd: Standard deviation of the prior (positive and finite).

    Returns:
        ``std(draws) / prior_sd``; values near 1 mean the data did not narrow the
        prior.

    Raises:
        ValueError: If there are no finite draws or ``prior_sd`` is not positive
            and finite.
    """
    x = np.asarray(draws, dtype=float).ravel()
    if x.size == 0 or not np.all(np.isfinite(x)):
        msg = "posterior draws must be non-empty and finite"
        raise ValueError(msg)
    if not (np.isfinite(prior_sd) and prior_sd > 0.0):
        msg = "prior_sd must be positive and finite"
        raise ValueError(msg)
    return float(np.std(x, ddof=1) / prior_sd) if x.size > 1 else 0.0

write_failed_replicate(path, reason=None, *, metadata=None)

Write a failed replicate ({"_failed": true}) so it stays counted.

Parameters:

Name Type Description Default
path str | Path

Output *.json file; parent directories are created.

required
reason str | None

Optional short cause (timeout, non-convergence), stored as _reason.

None
metadata Mapping[str, Any] | None

Optional runner/provenance metadata, stored as _meta.

None
Source code in src/op_infer/calibrate.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
def write_failed_replicate(
    path: str | Path,
    reason: str | None = None,
    *,
    metadata: Mapping[str, Any] | None = None,
) -> None:
    """Write a failed replicate (``{"_failed": true}``) so it stays counted.

    Args:
        path: Output ``*.json`` file; parent directories are created.
        reason: Optional short cause (timeout, non-convergence), stored as
            ``_reason``.
        metadata: Optional runner/provenance metadata, stored as ``_meta``.
    """
    payload: dict[str, Any] = {"_failed": True}
    if reason is not None:
        payload["_reason"] = reason
    if metadata is not None:
        payload["_meta"] = dict(metadata)
    _write_json_atomically(path, payload)

write_ledger(path, result, *, meta)

Write the SBC result and its provenance as a JSON ledger.

Parameters:

Name Type Description Default
path str | Path

Output file; parent directories are created.

required
result Mapping[str, Any]

The aggregated result (aggregate, optionally with the gate under gate).

required
meta Mapping[str, Any]

Provenance such as the script name and settings; git_sha (of the current working directory) and timestamp_utc are added unless given.

required
Source code in src/op_infer/calibrate.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
def write_ledger(
    path: str | Path, result: Mapping[str, Any], *, meta: Mapping[str, Any]
) -> None:
    """Write the SBC result and its provenance as a JSON ledger.

    Args:
        path: Output file; parent directories are created.
        result: The aggregated result (``aggregate``, optionally with the gate
            under ``gate``).
        meta: Provenance such as the script name and settings; ``git_sha`` (of
            the current working directory) and ``timestamp_utc`` are added
            unless given.
    """
    full_meta = {
        "git_sha": _git_sha(),
        "timestamp_utc": datetime.now(UTC).isoformat(timespec="seconds"),
        **meta,
    }
    _write_json_atomically(path, {"meta": full_meta, "result": result})

write_replicate(path, pits, *, contraction=None, fit_diag=None, metadata=None)

Write one replicate in the shared schema, atomically.

The file appears complete or not at all, so a runner can resume by skipping existing files and array tasks can write into one directory.

Parameters:

Name Type Description Default
path str | Path

Output *.json file; parent directories are created.

required
pits Mapping[str, float]

Estimand name to the replicate's PIT in [0, 1].

required
contraction Mapping[str, float] | None

Optional estimand name to posterior SD over prior SD.

None
fit_diag Mapping[str, Any] | None

Optional per-replicate fit diagnostics (R-hat, ESS, divergences), stored as _fit_diag.

None
metadata Mapping[str, Any] | None

Optional runner/provenance metadata, stored as _meta.

None

Raises:

Type Description
ValueError

If a PIT is not a finite value in [0, 1] or an estimand name starts with an underscore.

Source code in src/op_infer/calibrate.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def write_replicate(
    path: str | Path,
    pits: Mapping[str, float],
    *,
    contraction: Mapping[str, float] | None = None,
    fit_diag: Mapping[str, Any] | None = None,
    metadata: Mapping[str, Any] | None = None,
) -> None:
    """Write one replicate in the shared schema, atomically.

    The file appears complete or not at all, so a runner can resume by skipping
    existing files and array tasks can write into one directory.

    Args:
        path: Output ``*.json`` file; parent directories are created.
        pits: Estimand name to the replicate's PIT in [0, 1].
        contraction: Optional estimand name to posterior SD over prior SD.
        fit_diag: Optional per-replicate fit diagnostics (R-hat, ESS,
            divergences), stored as ``_fit_diag``.
        metadata: Optional runner/provenance metadata, stored as ``_meta``.

    Raises:
        ValueError: If a PIT is not a finite value in [0, 1] or an estimand name
            starts with an underscore.
    """
    payload: dict[str, Any] = {}
    for name, value in pits.items():
        if name.startswith("_"):
            msg = f"estimand name {name!r} must not start with an underscore"
            raise ValueError(msg)
        _as_pits(name, [value])
        entry: dict[str, float] = {"pit": float(value)}
        if contraction is not None and name in contraction:
            entry["contraction"] = float(contraction[name])
        payload[name] = entry
    if fit_diag is not None:
        payload["_fit_diag"] = dict(fit_diag)
    if metadata is not None:
        payload["_meta"] = dict(metadata)
    _write_json_atomically(path, payload)

coverage

Fixed-tolerance coverage planning through SciPy's binomial probabilities.

This host planning boundary covers an explicit family that rejects on any coverage violation, with unrestricted dependence between rules. It neither runs inference nor qualifies other gates.

CoverageRule

Bases: BaseModel

One inclusive empirical-coverage range, declared before a fixed bank.

name identifies an estimand/nominal-level criterion. Its calibrated coverage probability is nominal; this assumption needs independent replicates, an appropriate PIT/atom rule and sufficient posterior resolution. Bounds may be asymmetric but must contain the nominal probability.

Examples:

>>> rule = CoverageRule(
...     name="theta_50", nominal=0.5, lower=0.45, upper=0.55
... )
>>> rule.lower, rule.upper
(0.45, 0.55)
Source code in src/op_infer/coverage.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class CoverageRule(BaseModel):
    """One inclusive empirical-coverage range, declared before a fixed bank.

    ``name`` identifies an estimand/nominal-level criterion. Its calibrated
    coverage probability is ``nominal``; this assumption needs independent
    replicates, an appropriate PIT/atom rule and sufficient posterior resolution.
    Bounds may be asymmetric but must contain the nominal probability.

    Examples:
        >>> rule = CoverageRule(
        ...     name="theta_50", nominal=0.5, lower=0.45, upper=0.55
        ... )
        >>> rule.lower, rule.upper
        (0.45, 0.55)
    """

    model_config = ConfigDict(
        frozen=True, strict=True, extra="forbid", revalidate_instances="always"
    )

    name: Annotated[str, Field(min_length=1, pattern=r"\S")]
    nominal: Annotated[float, Field(gt=0, lt=1, allow_inf_nan=False)]
    lower: Annotated[float, Field(ge=0, le=1, allow_inf_nan=False)]
    upper: Annotated[float, Field(ge=0, le=1, allow_inf_nan=False)]

    @model_validator(mode="after")
    def _bounds(self) -> Self:
        if not self.lower <= self.nominal <= self.upper:
            msg = "Coverage bounds must contain their nominal probability"
            raise ValueError(msg)
        return self

coverage_operating_characteristics(rules, *, n_replicates, probabilities=None)

Evaluate a fixed coverage family using exact binomial tail probabilities.

All criteria must pass. Replicates are independent within each rule; dependence between rules is unrestricted. The family rejection probability lies between the largest marginal probability and their sum (capped at one). It is not generally equal to either bound.

Parameters:

Name Type Description Default
rules Sequence[CoverageRule]

Complete prespecified criterion family, with unique names.

required
n_replicates int

Fixed number of usable, independent replicates, not attempts.

required
probabilities Mapping[str, float] | None

Actual coverage probability for every rule under an alternative. If absent, use the nominal calibrated probabilities.

None

Returns:

Type Description
dict[str, Any]

JSON-compatible marginal rejection probabilities and family bounds,

dict[str, Any]

inclusive accepted counts, criteria, assumptions and implementation version.

dict[str, Any]

Under calibration these describe false failures; under a specified

dict[str, Any]

alternative they bound rejection power. No sampler/gate certification.

Raises:

Type Description
ValueError

Counts, rules or complete probability mapping are invalid.

Examples:

>>> rule = CoverageRule(name="half", nominal=0.5, lower=0.25, upper=0.75)
>>> result = coverage_operating_characteristics((rule,), n_replicates=4)
>>> result["criteria"][0]["rejection_probability"]
0.125
>>> result["family_rejection_probability"]
{'lower': 0.125, 'upper': 0.125}
Source code in src/op_infer/coverage.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def coverage_operating_characteristics(
    rules: Sequence[CoverageRule],
    *,
    n_replicates: int,
    probabilities: Mapping[str, float] | None = None,
) -> dict[str, Any]:
    """Evaluate a fixed coverage family using exact binomial tail probabilities.

    All criteria must pass. Replicates are independent
    within each rule; dependence between rules is unrestricted. The family
    rejection probability lies between the largest marginal probability and
    their sum (capped at one). It is not generally equal to either bound.

    Args:
        rules: Complete prespecified criterion family, with unique names.
        n_replicates: Fixed number of usable, independent replicates, not attempts.
        probabilities: Actual coverage probability for every rule under an
            alternative. If absent, use the nominal calibrated probabilities.

    Returns:
        JSON-compatible marginal rejection probabilities and family bounds,
        inclusive accepted counts, criteria, assumptions and implementation version.
        Under calibration these describe false failures; under a specified
        alternative they bound rejection power. No sampler/gate certification.

    Raises:
        ValueError: Counts, rules or complete probability mapping are invalid.

    Examples:
        >>> rule = CoverageRule(name="half", nominal=0.5, lower=0.25, upper=0.75)
        >>> result = coverage_operating_characteristics((rule,), n_replicates=4)
        >>> result["criteria"][0]["rejection_probability"]
        0.125
        >>> result["family_rejection_probability"]
        {'lower': 0.125, 'upper': 0.125}
    """
    family = _rules(rules)
    count = _count(n_replicates, "n_replicates")
    supplied = (
        {rule.name: rule.nominal for rule in family}
        if probabilities is None
        else dict(probabilities)
    )
    if set(supplied) != {rule.name for rule in family} or any(
        isinstance(p, (bool, np.bool_)) or not math.isfinite(p) or not 0 <= p <= 1
        for p in supplied.values()
    ):
        msg = "Supply finite coverage probabilities in [0, 1] for every rule"
        raise ValueError(msg)
    counts = np.array([count], dtype=np.int64)
    rows = []
    rejected = []
    for rule in family:
        lower, upper = _accepted_counts(rule, counts)
        probability = float(_rejection(rule, counts, supplied[rule.name])[0])
        rejected.append(probability)
        rows.append(
            {
                "rule": rule.model_dump(mode="json"),
                "coverage_probability": float(supplied[rule.name]),
                "accepted_count_min": int(lower[0]),
                "accepted_count_max": int(upper[0]),
                "rejection_probability": probability,
            }
        )
    return {
        "schema_version": 1,
        "n_replicates": count,
        "criteria": rows,
        "family_rejection_probability": {
            "lower": max(rejected),
            "upper": min(1.0, math.fsum(rejected)),
        },
        "evaluated_under": "nominal calibration"
        if probabilities is None
        else "specified coverage probabilities",
        "decision_rule": "reject_if_any_coverage_outside_inclusive_bounds",
        "sampling": "fixed independent successful replicate bank",
        "dependence_between_rules": "unrestricted",
        "implementation": "scipy.stats.binom.cdf/sf",
        "scipy_version": scipy_version,
        "adequacy_status": "not_assessed",
    }

plan_coverage_replicates(rules, *, max_false_fail, max_replicates)

Find the first fixed bank meeting a conservative family false-failure limit.

Search every integer size, since lattice effects make binomial rejection probabilities nonmonotone. A union bound protects the complete supplied family without assuming independent estimands or coverage levels. The result applies to the exact chosen count, not every larger count.

Parameters:

Name Type Description Default
rules Sequence[CoverageRule]

Complete family of inclusive coverage criteria.

required
max_false_fail float

Explicit maximum family false-failure probability in (0, 1).

required
max_replicates int

Explicit upper search budget for successful replicates.

required

Returns:

Type Description
dict[str, Any]

First qualifying count and its operating-characteristic report, or

dict[str, Any]

available=False and no count when the search budget cannot qualify.

dict[str, Any]

The count sizes only this fixed coverage rule, not failure policies,

dict[str, Any]

sampler diagnostics, other gate criteria or repeated interim looks.

Raises:

Type Description
ValueError

Rules, probability target or budget are invalid.

Examples:

>>> rule = CoverageRule(name="half", nominal=0.5, lower=0.25, upper=0.75)
>>> plan = plan_coverage_replicates(
...     (rule,), max_false_fail=0.125, max_replicates=4
... )
>>> plan["available"], plan["n_replicates"]
(True, 4)
Source code in src/op_infer/coverage.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def plan_coverage_replicates(
    rules: Sequence[CoverageRule],
    *,
    max_false_fail: float,
    max_replicates: int,
) -> dict[str, Any]:
    """Find the first fixed bank meeting a conservative family false-failure limit.

    Search every integer size, since lattice effects make binomial
    rejection probabilities nonmonotone. A union bound protects the complete
    supplied family without assuming independent estimands or coverage levels.
    The result applies to the exact chosen count, not every larger count.

    Args:
        rules: Complete family of inclusive coverage criteria.
        max_false_fail: Explicit maximum family false-failure probability in (0, 1).
        max_replicates: Explicit upper search budget for successful replicates.

    Returns:
        First qualifying count and its operating-characteristic report, or
        ``available=False`` and no count when the search budget cannot qualify.
        The count sizes only this fixed coverage rule, not failure policies,
        sampler diagnostics, other gate criteria or repeated interim looks.

    Raises:
        ValueError: Rules, probability target or budget are invalid.

    Examples:
        >>> rule = CoverageRule(name="half", nominal=0.5, lower=0.25, upper=0.75)
        >>> plan = plan_coverage_replicates(
        ...     (rule,), max_false_fail=0.125, max_replicates=4
        ... )
        >>> plan["available"], plan["n_replicates"]
        (True, 4)
    """
    family = _rules(rules)
    maximum = _count(max_replicates, "max_replicates")
    if (
        isinstance(max_false_fail, (bool, np.bool_))
        or not math.isfinite(max_false_fail)
        or not 0 < max_false_fail < 1
    ):
        msg = "max_false_fail must be finite and in (0, 1)"
        raise ValueError(msg)
    chosen = None
    # Bounded chunks avoid allocating the entire caller's search budget.
    for start in range(1, maximum + 1, 4096):
        counts = np.arange(start, min(start + 4096, maximum + 1), dtype=np.int64)
        upper = np.zeros(counts.size, dtype=np.float64)
        for rule in family:
            upper += _rejection(rule, counts, rule.nominal)
        passing = np.flatnonzero(upper <= max_false_fail)
        if passing.size:
            chosen = int(counts[passing[0]])
            break
    return {
        "schema_version": 1,
        "available": chosen is not None,
        "n_replicates": chosen,
        "max_false_fail": float(max_false_fail),
        "max_replicates": maximum,
        "rules": [rule.model_dump(mode="json") for rule in family],
        "reason": None if chosen is not None else "no_size_within_search_budget",
        "operating_characteristics": None
        if chosen is None
        else coverage_operating_characteristics(family, n_replicates=chosen),
        "sizing_method": "binomial union bound; exhaustive integer search",
        "adequacy_status": "not_assessed",
    }

tarp

Optional TARP curves from the public reference implementation.

This array reporting boundary takes an already sampled bank and explicit reference points. Sampling, coordinate transformation, MCMC adequacy and scientific thresholds belong to the caller.

tarp_coverage(samples, truth, *, references, replicate_ids, quantities, definition, provenance, num_bins, unavailable=None)

Report a TARP curve with explicit coordinates and retained failed rows.

Wraps tarp.get_tarp_coverage with fixed Euclidean distance, no automatic normalization and no bootstrap. All three arrays must already use the same declared coordinates. Reference points are supplied explicitly; their distribution determines diagnostic scope.

Parameters:

Name Type Description Default
samples NDArray[generic]

Unmasked NumPy float32/64 bank, (draw, replicate, quantity). Draws must be appropriate for calibration; this does not check MCMC.

required
truth NDArray[generic]

True reported quantities, (replicate, quantity).

required
references NDArray[generic]

Explicit reference points, with the same shape as truth.

required
replicate_ids Sequence[int]

Complete planned row IDs, including failed-fit placeholders.

required
quantities Sequence[str]

Ordered, distinct names for the selected coordinates.

required
definition ArtifactReference

Reference to coordinate transforms/alignment, reference-point construction and sample-selection rules. Retain its payload separately.

required
provenance Provenance

Shared bank/estimator context, not proof of scientific validity.

required
num_bins int

Explicit positive credibility-grid bin count.

required
unavailable Mapping[int, str] | None

Explicit failed/inadequate fits, keyed by planned row ID. Nonfinite rows are additionally counted; neither outcome is hidden.

None

Returns:

Type Description
dict[str, Any]

JSON-compatible curve, complete row statuses/counts, successful-input

dict[str, Any]

conditioning, input/source digests, method settings and dependency versions.

dict[str, Any]

All-failed banks or reference errors have an unavailable curve. No pass,

dict[str, Any]

p-value, nominal confidence band or automatic adequacy decision is supplied.

Raises:

Type Description
ImportError

Install op_infer[tarp] for the reference implementation.

TypeError

Arrays have not crossed the explicit supported host boundary.

ValueError

Shapes, coordinate IDs, exclusions or bin count are invalid.

Source code in src/op_infer/adapters/tarp.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def tarp_coverage(  # noqa: PLR0913 - explicit bank, coordinates and provenance boundary
    samples: NDArray[np.generic],
    truth: NDArray[np.generic],
    *,
    references: NDArray[np.generic],
    replicate_ids: Sequence[int],
    quantities: Sequence[str],
    definition: ArtifactReference,
    provenance: Provenance,
    num_bins: int,
    unavailable: Mapping[int, str] | None = None,
) -> dict[str, Any]:
    """Report a TARP curve with explicit coordinates and retained failed rows.

    Wraps ``tarp.get_tarp_coverage`` with fixed
    Euclidean distance, no automatic normalization and no bootstrap. All three
    arrays must already use the same declared coordinates. Reference points
    are supplied explicitly; their distribution determines diagnostic scope.

    Args:
        samples: Unmasked NumPy float32/64 bank, ``(draw, replicate, quantity)``.
            Draws must be appropriate for calibration; this does not check MCMC.
        truth: True reported quantities, ``(replicate, quantity)``.
        references: Explicit reference points, with the same shape as truth.
        replicate_ids: Complete planned row IDs, including failed-fit placeholders.
        quantities: Ordered, distinct names for the selected coordinates.
        definition: Reference to coordinate transforms/alignment, reference-point
            construction and sample-selection rules. Retain its payload separately.
        provenance: Shared bank/estimator context, not proof of scientific validity.
        num_bins: Explicit positive credibility-grid bin count.
        unavailable: Explicit failed/inadequate fits, keyed by planned row ID.
            Nonfinite rows are additionally counted; neither outcome is hidden.

    Returns:
        JSON-compatible curve, complete row statuses/counts, successful-input
        conditioning, input/source digests, method settings and dependency versions.
        All-failed banks or reference errors have an unavailable curve. No pass,
        p-value, nominal confidence band or automatic adequacy decision is supplied.

    Raises:
        ImportError: Install ``op_infer[tarp]`` for the reference implementation.
        TypeError: Arrays have not crossed the explicit supported host boundary.
        ValueError: Shapes, coordinate IDs, exclusions or bin count are invalid.
    """
    Provenance.model_validate(provenance)
    ArtifactReference.model_validate(definition)
    bank, targets, points = (_host(value) for value in (samples, truth, references))
    ids = tuple(replicate_ids)
    names = tuple(quantities)
    if (
        bank.ndim != 3
        or targets.ndim != 2
        or targets.shape != bank.shape[1:]
        or points.shape != targets.shape
        or bank.shape[0] < 2
        or min(targets.shape) < 1
        or len(ids) != bank.shape[1]
        or len(names) != bank.shape[2]
        or len(set(ids)) != len(ids)
        or len(set(names)) != len(names)
        or isinstance(quantities, str)
        or any(not isinstance(name, str) or not name.strip() for name in names)
        or any(isinstance(i, bool) or not isinstance(i, Integral) or i < 0 for i in ids)
    ):
        msg = "TARP requires original sample shapes and distinct row/quantity IDs"
        raise ValueError(msg)
    if isinstance(num_bins, bool) or not isinstance(num_bins, Integral) or num_bins < 1:
        msg = "num_bins must be a positive integer"
        raise ValueError(msg)
    ids = tuple(int(i) for i in ids)
    excluded = dict(unavailable or {})
    if not set(excluded) <= set(ids) or any(
        isinstance(i, bool)
        or not isinstance(i, Integral)
        or not isinstance(reason, str)
        or not reason.strip()
        for i, reason in excluded.items()
    ):
        msg = "Unavailable rows need declared IDs and explicit reasons"
        raise ValueError(msg)
    try:
        reference = cast(
            "_Reference", importlib.import_module("tarp").get_tarp_coverage
        )
    except ImportError as error:
        msg = "Install op_infer[tarp] for the TARP reference implementation"
        raise ImportError(msg) from error
    bad = (
        np.count_nonzero(~np.isfinite(bank), axis=(0, 2))
        + np.count_nonzero(~np.isfinite(targets), axis=1)
        + np.count_nonzero(~np.isfinite(points), axis=1)
    )
    keep = np.array(
        [bad[i] == 0 and label not in excluded for i, label in enumerate(ids)]
    )
    rows = [
        {
            "replicate_id": label,
            "status": "available" if keep[i] else "unavailable",
            "nonfinite_values": int(bad[i]),
            "reasons": ([excluded[label]] if label in excluded else [])
            + (["nonfinite_input"] if bad[i] else []),
        }
        for i, label in enumerate(ids)
    ]
    curve = None
    reason = "no_usable_replicates"
    if np.any(keep):
        try:
            ecp, alpha = _curve(
                reference, bank[:, keep], targets[keep], points[keep], int(num_bins)
            )
            curve = {
                "expected_coverage": ecp.tolist(),
                "credibility": alpha.tolist(),
                "max_abs_deviation": float(np.max(np.abs(ecp - alpha))),
            }
            reason = None
        except Exception as error:  # noqa: BLE001 - retain reference failure, not a pass
            reason = f"reference_error:{type(error).__name__}:{error}"
    usable = int(np.count_nonzero(keep))
    return {
        "schema_version": 1,
        "status": "available" if curve is not None else "unavailable",
        "reason": reason,
        "curve": curve,
        "replicates": rows,
        "n_total": len(ids),
        "n_usable": usable,
        "n_failed": len(ids) - usable,
        "failed_fraction": (len(ids) - usable) / len(ids),
        "n_posterior_draws": bank.shape[0],
        "quantities": list(names),
        "conditioning": "usable inputs; failed/inadequate rows excluded and counted",
        "settings": {
            "num_bins": int(num_bins),
            "metric": "euclidean",
            "norm": False,
            "bootstrap": False,
            "reference_seed": 0,
            "credibility_grid": "reference_histogram_edges",
        },
        "implementation": "tarp.get_tarp_coverage",
        "backend_versions": {
            name: importlib.metadata.version(name)
            for name in ("tarp", "numpy", "op_infer")
        }
        | {"python": platform.python_version()},
        "implementation_reference": ArtifactReference.from_bytes(
            Path(__file__).read_bytes(), kind="op-infer-tarp-adapter-source-v1"
        ).model_dump(mode="json"),
        "inputs": {
            "samples": _content(bank),
            "truth": _content(targets),
            "references": _content(points),
        },
        "definition": definition.model_dump(mode="json"),
        "provenance": provenance.model_dump(mode="json"),
        "adequacy_status": "not_assessed",
    }

compare

Unit-level predictive comparison.

Implemented: a bounded paired held-out contrast for DesignStudy. LOO/PSIS recovery and stratified comparisons remain planned.

Scope: Exact leave-one-unit-out (re-conditioning or refit); unit-level PSIS-LOO with explicit adequacy and recovery records; paired contrasts with failure accounting; stratification; three-way outcomes and pre-declared reading rules. Scoring rules and paired bootstraps come from trade_study.

Predictive comparisons follow docs/design/likelihood-targets.md. Raw importance sampling after failed PSIS is diagnostic only until independently qualified; it cannot erase the failure. Future comparison artifacts retain both target identities, excluded and non-finite unit counts, adequacy failures and the conditional paired estimand with its actual denominator. The held-out API below does not implement LOO/PSIS.

PredictiveContrast dataclass

Prespecified paired reading rule, never a certified hypothesis test.

Source code in src/op_infer/compare.py
57
58
59
60
61
62
63
64
65
66
@dataclass(frozen=True)
class PredictiveContrast:
    """Prespecified paired reading rule, never a certified hypothesis test."""

    outcome: Literal["generator", "alternative", "indistinguishable", "failed"]
    mean_delta: float | None
    se_delta: float | None
    n_units: int
    nonfinite_units: int
    reason: str | None = None

ThreeValuedContrast dataclass

A paired contrast read as separated, borderline, tied or not assessable.

tied_bound and separated_bound are the two fixed bounds on the absolute mean difference: at or below tied_bound the contrast is tied, above separated_bound it is separated, and between them it is borderline. Both are None when the contrast is not assessable. favours names the side with the larger mean score for separated and borderline readings.

Source code in src/op_infer/compare.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
@dataclass(frozen=True)
class ThreeValuedContrast:
    """A paired contrast read as separated, borderline, tied or not assessable.

    ``tied_bound`` and ``separated_bound`` are the two fixed bounds on the
    absolute mean difference: at or below ``tied_bound`` the contrast is tied,
    above ``separated_bound`` it is separated, and between them it is
    borderline. Both are ``None`` when the contrast is not assessable.
    ``favours`` names the side with the larger mean score for separated and
    borderline readings.
    """

    reading: Literal["separated", "borderline", "tied", "not_assessable"]
    favours: Literal["generator", "alternative"] | None
    mean_delta: float | None
    se_delta: float | None
    n_units: int
    nonfinite_units: int
    tied_bound: float | None
    separated_bound: float | None
    audited: bool
    reason: str | None = None

UnitPredictiveScores dataclass

Held-out log predictive densities on declared independent units/clusters.

Values come from a proper-scoring callback, not from this module. The target identifies the same held-out observable/window across models and designs. Shared latent parameters and numerical/Monte Carlo approximations belong in the surrounding provenance and qualification.

Source code in src/op_infer/compare.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@dataclass(frozen=True)
class UnitPredictiveScores:
    """Held-out log predictive densities on declared independent units/clusters.

    Values come from a proper-scoring callback, not from this module. The target
    identifies the same held-out observable/window across models and designs.
    Shared latent parameters and numerical/Monte Carlo approximations belong in
    the surrounding provenance and qualification.
    """

    values: ArrayLike
    unit_ids: tuple[str, ...]
    target: ArtifactReference
    unit_kind: Literal["independent_unit", "independent_cluster"]

paired_predictive_contrast(generator, alternative, *, threshold_se=2.0)

Apply a fixed paired ELPD reading rule with explicit failed-unit accounting.

No unit is discarded. A nonfinite unit makes the whole comparison unavailable. The threshold is a decision rule, not a claim of exact testing level; repeated independent cohorts qualify its recovery rate.

Returns:

Type Description
PredictiveContrast

Generator/alternative/indistinguishable, or a failed comparison.

Raises:

Type Description
ValueError

Units, targets, independence assumptions or controls disagree.

Examples:

>>> from op_infer.posterior import ArtifactReference
>>> target = ArtifactReference.from_bytes(
...     b"held-out units", kind="example-v1"
... )
>>> generator = UnitPredictiveScores(
...     [-1.0, -2.0, -3.0], ("a", "b", "c"), target, "independent_unit"
... )
>>> alternative = UnitPredictiveScores(
...     [-5.0, -3.0, -4.0], ("c", "a", "b"), target, "independent_unit"
... )
>>> contrast = paired_predictive_contrast(generator, alternative)
>>> contrast.outcome, contrast.mean_delta, contrast.se_delta
('generator', 2.0, 0.0)
>>> paired_predictive_contrast(generator, generator).outcome
'indistinguishable'
Source code in src/op_infer/compare.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def paired_predictive_contrast(
    generator: UnitPredictiveScores,
    alternative: UnitPredictiveScores,
    *,
    threshold_se: float = 2.0,
) -> PredictiveContrast:
    """Apply a fixed paired ELPD reading rule with explicit failed-unit accounting.

    No unit is discarded. A nonfinite unit makes the whole
    comparison unavailable. The threshold is a decision rule, not a claim of
    exact testing level; repeated independent cohorts qualify its recovery rate.

    Returns:
        Generator/alternative/indistinguishable, or a failed comparison.

    Raises:
        ValueError: Units, targets, independence assumptions or controls disagree.

    Examples:
        >>> from op_infer.posterior import ArtifactReference
        >>> target = ArtifactReference.from_bytes(
        ...     b"held-out units", kind="example-v1"
        ... )
        >>> generator = UnitPredictiveScores(
        ...     [-1.0, -2.0, -3.0], ("a", "b", "c"), target, "independent_unit"
        ... )
        >>> alternative = UnitPredictiveScores(
        ...     [-5.0, -3.0, -4.0], ("c", "a", "b"), target, "independent_unit"
        ... )
        >>> contrast = paired_predictive_contrast(generator, alternative)
        >>> contrast.outcome, contrast.mean_delta, contrast.se_delta
        ('generator', 2.0, 0.0)
        >>> paired_predictive_contrast(generator, generator).outcome
        'indistinguishable'
    """
    if not np.isfinite(threshold_se) or threshold_se <= 0:
        msg = "threshold_se must be finite and positive"
        raise ValueError(msg)
    if (
        generator.target != alternative.target
        or generator.unit_kind != alternative.unit_kind
    ):
        msg = (
            "Predictive comparisons require identical targets and score-unit semantics"
        )
        raise ValueError(msg)
    if generator.unit_kind not in {"independent_unit", "independent_cluster"}:
        msg = "Score-unit independence must be explicitly declared"
        raise ValueError(msg)
    ids = generator.unit_ids
    if (
        not ids
        or len(set(ids)) != len(ids)
        or set(ids) != set(alternative.unit_ids)
        or len(set(alternative.unit_ids)) != len(alternative.unit_ids)
    ):
        msg = "Predictive score units must be distinct and match across models"
        raise ValueError(msg)
    left = np.asarray(generator.values, dtype=float)
    right = np.asarray(alternative.values, dtype=float)
    if left.shape != (len(ids),) or right.shape != (len(ids),):
        msg = "One held-out score is required per declared unit"
        raise ValueError(msg)
    positions = {name: i for i, name in enumerate(alternative.unit_ids)}
    right = right[[positions[name] for name in ids]]
    bad = int(np.sum(~np.isfinite(left) | ~np.isfinite(right)))
    if bad or len(ids) < 2:
        return PredictiveContrast(
            "failed",
            None,
            None,
            len(ids),
            bad,
            "nonfinite units" if bad else "fewer than two score units",
        )
    with np.errstate(over="ignore", invalid="ignore"):
        delta = left - right
        mean = float(delta.mean())
        se = float(delta.std(ddof=1) / np.sqrt(len(delta)))
    if not np.isfinite(mean) or not np.isfinite(se):
        return PredictiveContrast(
            "failed", None, None, len(ids), 0, "nonfinite contrast arithmetic"
        )
    outcome: Literal["generator", "alternative", "indistinguishable"] = (
        "generator"
        if mean > threshold_se * se
        else "alternative"
        if mean < -threshold_se * se
        else "indistinguishable"
    )
    return PredictiveContrast(outcome, mean, se, len(ids), 0)

three_valued_contrast(generator, alternative, *, floor, z_multiplicity, z_base=1.96, stable=None)

Read a paired held-out contrast with a floor and a multiplicity bound.

The mean paired difference d and its standard error se come from paired_predictive_contrast. The reading rule is fixed before the contrast is seen: the contrast is separated when |d| > max(floor, z_multiplicity * se), tied when |d| <= max(floor, z_base * se), and borderline in between. z_multiplicity is the caller's quantile for the number of registered contrasts (for example the two-sided 1 - 0.05 / (2 K) normal quantile for K contrasts), so it must not be smaller than z_base. When floor dominates both products the borderline band is empty.

The normal approximation to a predictive-score difference is poorly calibrated for similar predictions, under misspecification with outliers and for small numbers of units (Sivula, Magnusson, Matamoros and Vehtari 2025, arXiv:2008.10296). Two consequences are built in. A contrast whose Monte Carlo stability check failed (stable=False, for example from op_infer.audit.stability_label), or whose scores are non-finite, or that has fewer than two units, is not assessable: it is never reported as tied, because a failed check carries no evidence of equivalence. Tied means only that the difference is within the fixed bounds, not that the models are equivalent.

Parameters:

Name Type Description Default
generator UnitPredictiveScores

Held-out unit scores of the generating-model side.

required
alternative UnitPredictiveScores

Held-out unit scores of the alternative on the same units.

required
floor float

Smallest absolute mean difference worth reading, in score units (nonnegative).

required
z_multiplicity float

Multiplicity-adjusted standard-error multiple that defines the separated bound.

required
z_base float

Unadjusted standard-error multiple that defines the tied bound.

1.96
stable bool | None

Result of a caller-run Monte Carlo stability check, or None when no audit was run (recorded in audited).

None

Returns:

Type Description
ThreeValuedContrast

The reading with both bounds and the unit accounting.

Raises:

Type Description
ValueError

Units or targets disagree, or floor, z_base or z_multiplicity is invalid.

Examples:

>>> from op_infer.posterior import ArtifactReference
>>> target = ArtifactReference.from_bytes(b"units", kind="example-v1")
>>> ids = tuple(str(i) for i in range(8))
>>> left = UnitPredictiveScores(
...     [1.0, 2.0, 1.5, 2.5, 1.0, 2.0, 1.5, 2.5],
...     ids,
...     target,
...     "independent_unit",
... )
>>> right = UnitPredictiveScores([0.0] * 8, ids, target, "independent_unit")
>>> three_valued_contrast(
...     left, right, floor=0.1, z_multiplicity=2.5
... ).reading
'separated'
>>> three_valued_contrast(
...     left, right, floor=5.0, z_multiplicity=2.5
... ).reading
'tied'
>>> three_valued_contrast(
...     left, right, floor=0.1, z_multiplicity=2.5, stable=False
... ).reading
'not_assessable'
Source code in src/op_infer/compare.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def three_valued_contrast(  # noqa: PLR0913 - explicit reading rule
    generator: UnitPredictiveScores,
    alternative: UnitPredictiveScores,
    *,
    floor: float,
    z_multiplicity: float,
    z_base: float = 1.96,
    stable: bool | None = None,
) -> ThreeValuedContrast:
    """Read a paired held-out contrast with a floor and a multiplicity bound.

    The mean paired difference ``d`` and its standard error ``se`` come from
    `paired_predictive_contrast`. The reading rule is fixed before the contrast
    is seen: the contrast is **separated** when ``|d| > max(floor,
    z_multiplicity * se)``, **tied** when ``|d| <= max(floor, z_base * se)``,
    and **borderline** in between. ``z_multiplicity`` is the caller's quantile
    for the number of registered contrasts (for example the two-sided
    ``1 - 0.05 / (2 K)`` normal quantile for ``K`` contrasts), so it must not
    be smaller than ``z_base``. When ``floor`` dominates both products the
    borderline band is empty.

    The normal approximation to a predictive-score difference is poorly
    calibrated for similar predictions, under misspecification with outliers
    and for small numbers of units (Sivula, Magnusson, Matamoros and Vehtari
    2025, arXiv:2008.10296). Two consequences are built in. A contrast whose
    Monte Carlo stability check failed (``stable=False``, for example from
    `op_infer.audit.stability_label`), or whose scores are non-finite, or that
    has fewer than two units, is **not assessable**: it is never reported as
    tied, because a failed check carries no evidence of equivalence. Tied means
    only that the difference is within the fixed bounds, not that the models
    are equivalent.

    Args:
        generator: Held-out unit scores of the generating-model side.
        alternative: Held-out unit scores of the alternative on the same units.
        floor: Smallest absolute mean difference worth reading, in score units
            (nonnegative).
        z_multiplicity: Multiplicity-adjusted standard-error multiple that
            defines the separated bound.
        z_base: Unadjusted standard-error multiple that defines the tied bound.
        stable: Result of a caller-run Monte Carlo stability check, or ``None``
            when no audit was run (recorded in ``audited``).

    Returns:
        The reading with both bounds and the unit accounting.

    Raises:
        ValueError: Units or targets disagree, or ``floor``, ``z_base`` or
            ``z_multiplicity`` is invalid.

    Examples:
        >>> from op_infer.posterior import ArtifactReference
        >>> target = ArtifactReference.from_bytes(b"units", kind="example-v1")
        >>> ids = tuple(str(i) for i in range(8))
        >>> left = UnitPredictiveScores(
        ...     [1.0, 2.0, 1.5, 2.5, 1.0, 2.0, 1.5, 2.5],
        ...     ids,
        ...     target,
        ...     "independent_unit",
        ... )
        >>> right = UnitPredictiveScores([0.0] * 8, ids, target, "independent_unit")
        >>> three_valued_contrast(
        ...     left, right, floor=0.1, z_multiplicity=2.5
        ... ).reading
        'separated'
        >>> three_valued_contrast(
        ...     left, right, floor=5.0, z_multiplicity=2.5
        ... ).reading
        'tied'
        >>> three_valued_contrast(
        ...     left, right, floor=0.1, z_multiplicity=2.5, stable=False
        ... ).reading
        'not_assessable'
    """
    if isinstance(floor, bool) or not math.isfinite(floor) or floor < 0:
        msg = "floor must be a finite nonnegative number"
        raise ValueError(msg)
    if isinstance(z_base, bool) or not math.isfinite(z_base) or z_base <= 0:
        msg = "z_base must be finite and positive"
        raise ValueError(msg)
    if (
        isinstance(z_multiplicity, bool)
        or not math.isfinite(z_multiplicity)
        or z_multiplicity < z_base
    ):
        msg = "z_multiplicity must be finite and at least z_base"
        raise ValueError(msg)
    if stable is not None and not isinstance(stable, bool):
        msg = "stable must be a bool or None"
        raise ValueError(msg)
    base = paired_predictive_contrast(generator, alternative)
    audited = stable is not None
    if base.outcome == "failed" or base.mean_delta is None or base.se_delta is None:
        return ThreeValuedContrast(
            "not_assessable",
            None,
            None,
            None,
            base.n_units,
            base.nonfinite_units,
            None,
            None,
            audited,
            base.reason,
        )
    if stable is False:
        return ThreeValuedContrast(
            "not_assessable",
            None,
            base.mean_delta,
            base.se_delta,
            base.n_units,
            0,
            None,
            None,
            audited,
            "Monte Carlo stability check failed",
        )
    tied_bound = max(floor, z_base * base.se_delta)
    separated_bound = max(floor, z_multiplicity * base.se_delta)
    size = abs(base.mean_delta)
    reading: Literal["separated", "borderline", "tied"] = (
        "separated"
        if size > separated_bound
        else "tied"
        if size <= tied_bound
        else "borderline"
    )
    favours: Literal["generator", "alternative"] | None = (
        None
        if reading == "tied"
        else "generator"
        if base.mean_delta > 0
        else "alternative"
    )
    return ThreeValuedContrast(
        reading,
        favours,
        base.mean_delta,
        base.se_delta,
        base.n_units,
        0,
        tied_bound,
        separated_bound,
        audited,
    )

audit

Blind stratified Monte Carlo stability audit for sampled per-unit scores.

A contrast between two models is a sum over units of per-unit predictive score differences, each estimated by Monte Carlo (often importance sampling with heavy-tailed weights). Before the contrast is read, its reproducibility can be checked on a sample of units: choose the sample from tail diagnostics only, re-score it with independent random keys and larger Monte Carlo settings, and estimate the shift and the Monte Carlo error of the total over all units (see Vehtari, Gelman and Gabry 2017, Statistics and Computing 27:1413, and Sivula, Magnusson, Matamoros and Vehtari 2025, Bayesian Analysis, on the uncertainty of elpd differences).

The sampler takes diagnostics only; it has no argument through which a score could enter (enforced by its signature). Thresholds of the stability rule are the caller's reading-rule choices and have no defaults.

The estimates assume finite-variance, independent per-unit Monte Carlo errors and independent random keys in the two scorings. Correlated errors, shared keys (the noise cancels in the difference) and heavy-tailed importance-sampling errors (Pareto shape above 0.5, where sample variances are unstable and usually too small) can make mc_sd understate the noise. A stable label means the total is reproducible against an independent rerun, not that it is accurate: a bias that both scorings share is invisible to the audit.

AuditSample dataclass

The audited units, the stratum of each, and the stratum population sizes.

Examples:

>>> s = audit_sample(
...     [0.1, 0.2, 0.6, 0.9, 1.1, 1.3], edges=(0.5,), per_stratum=1, seed=3
... )
>>> s.sizes, s.taken
((2, 4), (1, 1))
Source code in src/op_infer/audit.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
@dataclass(frozen=True)
class AuditSample:
    """The audited units, the stratum of each, and the stratum population sizes.

    Examples:
        >>> s = audit_sample(
        ...     [0.1, 0.2, 0.6, 0.9, 1.1, 1.3], edges=(0.5,), per_stratum=1, seed=3
        ... )
        >>> s.sizes, s.taken
        ((2, 4), (1, 1))
    """

    units: tuple[int, ...]
    strata: tuple[int, ...]
    sizes: tuple[int, ...]
    taken: tuple[int, ...]
    seed: int
    edges: tuple[float, ...]

StabilityEstimate dataclass

Monte Carlo noise of a total and the shift between the two scorings.

mc_sd is the conservative standard deviation of the Monte Carlo noise of the total over all units; shift is the estimated difference between the audit total and the original total, with its sampling standard error shift_se (finite population correction included). If a nonempty stratum has fewer than two usable audited units its noise cannot be estimated: insufficient is true and mc_sd and shift_se are NaN.

Source code in src/op_infer/audit.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@dataclass(frozen=True)
class StabilityEstimate:
    """Monte Carlo noise of a total and the shift between the two scorings.

    ``mc_sd`` is the conservative standard deviation of the Monte Carlo noise of
    the total over all units; ``shift`` is the estimated difference between the
    audit total and the original total, with its sampling standard error
    ``shift_se`` (finite population correction included). If a nonempty stratum
    has fewer than two usable audited units its noise cannot be estimated:
    ``insufficient`` is true and ``mc_sd`` and ``shift_se`` are NaN.
    """

    shift: float
    shift_se: float
    mc_sd: float
    n_failed: int
    n_sampled: int
    insufficient: bool = False

audit_sample(diagnostic, *, edges, per_stratum, seed)

Draw a stratified sample of units from a tail diagnostic only.

Each stratum contributes min(per_stratum, size) units, chosen uniformly without replacement; a stratum smaller than per_stratum is taken in full.

Raises:

Type Description
ValueError

per_stratum is not a positive integer or the diagnostic is empty.

Examples:

>>> s = audit_sample(
...     np.linspace(0, 2, 50), edges=(0.5, 1.0), per_stratum=5, seed=1
... )
>>> s.taken, len(s.units) == len(set(s.units))
((5, 5, 5), True)
Source code in src/op_infer/audit.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def audit_sample(
    diagnostic: ArrayLike,
    *,
    edges: Sequence[float],
    per_stratum: int | np.integer[Any],
    seed: int,
) -> AuditSample:
    """Draw a stratified sample of units from a tail diagnostic only.

    Each stratum contributes ``min(per_stratum, size)`` units, chosen uniformly
    without replacement; a stratum smaller than ``per_stratum`` is taken in full.

    Raises:
        ValueError: ``per_stratum`` is not a positive integer or the diagnostic
            is empty.

    Examples:
        >>> s = audit_sample(
        ...     np.linspace(0, 2, 50), edges=(0.5, 1.0), per_stratum=5, seed=1
        ... )
        >>> s.taken, len(s.units) == len(set(s.units))
        ((5, 5, 5), True)
    """
    if isinstance(per_stratum, bool) or not isinstance(per_stratum, Integral):
        msg = "per_stratum must be a positive integer"
        raise ValueError(msg)  # noqa: TRY004 - value contract
    if per_stratum < 1:
        msg = "per_stratum must be a positive integer"
        raise ValueError(msg)
    values = np.asarray(diagnostic, dtype=float)
    if values.ndim != 1 or values.size == 0:
        msg = "the diagnostic must be a nonempty one-dimensional array"
        raise ValueError(msg)
    per_stratum = int(per_stratum)
    labels = stratify(values, edges)
    rng = np.random.default_rng(seed)
    units: list[int] = []
    strata: list[int] = []
    sizes: list[int] = []
    taken: list[int] = []
    for k in range(len(tuple(edges)) + 1):
        members = np.flatnonzero(labels == k)
        n = min(per_stratum, members.size)
        pick = np.sort(rng.permutation(members)[:n])
        units += [int(i) for i in pick]
        strata += [k] * n
        sizes.append(int(members.size))
        taken.append(int(n))
    return AuditSample(
        tuple(units),
        tuple(strata),
        tuple(sizes),
        tuple(taken),
        seed,
        tuple(float(e) for e in edges),
    )

stability_estimate(original, audit, sample)

Estimate the Monte Carlo noise and the shift of a contrast total.

original and audit are per-unit contrast values (for example paired elpd differences) for the sampled units, aligned with sample.units. With e_i = audit_i - original_i, strata s of N_s units, n_s audited, ebar_s and v_s the stratum mean and sample variance:

  • shift = sum_s N_s ebar_s, the estimated difference of the totals (audit minus original), with shift_se = sqrt(sum_s N_s^2 (1 - n_s/N_s) v_s / n_s) the sampling error of that extrapolation from a sample (zero for a census stratum);
  • mc_sd = sqrt(sum_s N_s v_s), the noise of a total over all N_s units if the per-unit errors are independent with variance v_s. var(e) holds the noise of both runs and any between-unit spread of the shift, so under independent errors and keys this overstates the noise of the original run.

A sampled unit with a non-finite value in either run is counted in n_failed and left out of the moments; the shift assumes failures are missing at random within a stratum, and stability_label treats any failure as unassessable. A nonempty stratum with fewer than two usable audited units makes the estimate insufficient instead of raising.

Raises:

Type Description
ValueError

Lengths do not match the sample, or the sample is inconsistent.

Examples:

>>> s = AuditSample((0, 1, 2, 3), (0, 0, 1, 1), (10, 10), (2, 2), 0, (0.5,))
>>> est = stability_estimate([0.0, 0.0, 0.0, 0.0], [1.0, 3.0, 1.0, 3.0], s)
>>> est.shift, round(est.mc_sd, 3), round(est.shift_se, 3), est.n_failed
(40.0, 6.325, 12.649, 0)
Source code in src/op_infer/audit.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def stability_estimate(
    original: ArrayLike, audit: ArrayLike, sample: AuditSample
) -> StabilityEstimate:
    """Estimate the Monte Carlo noise and the shift of a contrast total.

    ``original`` and ``audit`` are per-unit contrast values (for example paired
    elpd differences) for the sampled units, aligned with ``sample.units``. With
    ``e_i = audit_i - original_i``, strata ``s`` of ``N_s`` units, ``n_s``
    audited, ``ebar_s`` and ``v_s`` the stratum mean and sample variance:

    - ``shift = sum_s N_s ebar_s``, the estimated difference of the totals (audit
      minus original), with ``shift_se = sqrt(sum_s N_s^2 (1 - n_s/N_s) v_s /
      n_s)`` the sampling error of that extrapolation from a sample (zero for a
      census stratum);
    - ``mc_sd = sqrt(sum_s N_s v_s)``, the noise of a total over all ``N_s``
      units if the per-unit errors are independent with variance ``v_s``.
      ``var(e)`` holds the noise of **both** runs and any between-unit spread of
      the shift, so under independent errors and keys this overstates the noise
      of the original run.

    A sampled unit with a non-finite value in either run is counted in
    ``n_failed`` and left out of the moments; the shift assumes failures are
    missing at random within a stratum, and ``stability_label`` treats any
    failure as unassessable. A nonempty stratum with fewer than two usable
    audited units makes the estimate ``insufficient`` instead of raising.

    Raises:
        ValueError: Lengths do not match the sample, or the sample is inconsistent.

    Examples:
        >>> s = AuditSample((0, 1, 2, 3), (0, 0, 1, 1), (10, 10), (2, 2), 0, (0.5,))
        >>> est = stability_estimate([0.0, 0.0, 0.0, 0.0], [1.0, 3.0, 1.0, 3.0], s)
        >>> est.shift, round(est.mc_sd, 3), round(est.shift_se, 3), est.n_failed
        (40.0, 6.325, 12.649, 0)
    """
    _check_sample(sample)
    a = np.asarray(original, dtype=float)
    b = np.asarray(audit, dtype=float)
    if a.shape != b.shape or a.shape != (len(sample.units),):
        msg = "original and audit must align with the sampled units"
        raise ValueError(msg)
    e = b - a
    usable = np.isfinite(e)
    strata = np.asarray(sample.strata)
    shift = 0.0
    var_shift = 0.0
    var_noise = 0.0
    insufficient = False
    for k, size in enumerate(sample.sizes):
        x = e[usable & (strata == k)]
        if size == 0:
            continue
        if x.size < 2:  # a variance needs two values
            insufficient = True
            continue
        v = float(x.var(ddof=1))
        shift += size * float(x.mean())
        var_shift += size**2 * (1.0 - x.size / size) * v / x.size
        var_noise += size * v
    n_failed, n_sampled = int(np.sum(~usable)), int(e.size)
    if insufficient:
        nan = float("nan")
        return StabilityEstimate(nan, nan, nan, n_failed, n_sampled, insufficient=True)
    return StabilityEstimate(
        shift,
        float(np.sqrt(max(var_shift, 0.0))),
        float(np.sqrt(var_noise)),
        n_failed,
        n_sampled,
    )

stability_label(estimate, se, *, max_mc_ratio, max_shift_ratio, z=1.645)

Label a contrast stable or not_assessable (never tied).

Stable requires all of: no failed audited unit and no insufficient stratum; mc_sd <= max_mc_ratio * se with se the standard error of the original total; and the shift small including its sampling uncertainty, |shift| + z * shift_se <= max_shift_ratio * se (one-sided, z = 1.645). An audit too small to bound the shift is therefore not assessable. The ratios are the caller's reading-rule choices, fixed before the audit is read, and have no defaults; only z has a default. Stable means reproducible against an independent rerun, not accurate.

Raises:

Type Description
ValueError

se, a ratio or z is not a positive finite number.

Examples:

>>> est = StabilityEstimate(1.0, 0.5, 0.5, n_failed=0, n_sampled=90)
>>> stability_label(est, 4.0, max_mc_ratio=0.25, max_shift_ratio=0.5)[
...     "label"
... ]
'stable'
Source code in src/op_infer/audit.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def stability_label(
    estimate: StabilityEstimate,
    se: float,
    *,
    max_mc_ratio: float,
    max_shift_ratio: float,
    z: float = 1.645,
) -> dict[str, object]:
    """Label a contrast ``stable`` or ``not_assessable`` (never ``tied``).

    Stable requires all of: no failed audited unit and no ``insufficient``
    stratum; ``mc_sd <= max_mc_ratio * se`` with ``se`` the standard error of the
    original total; and the shift small **including its sampling uncertainty**,
    ``|shift| + z * shift_se <= max_shift_ratio * se`` (one-sided, ``z`` =
    1.645). An audit too small to bound the shift is therefore not assessable. The
    ratios are the caller's
    reading-rule choices, fixed before the audit is read, and have no defaults;
    only ``z`` has a default. Stable means reproducible against an independent
    rerun, not accurate.

    Raises:
        ValueError: ``se``, a ratio or ``z`` is not a positive finite number.

    Examples:
        >>> est = StabilityEstimate(1.0, 0.5, 0.5, n_failed=0, n_sampled=90)
        >>> stability_label(est, 4.0, max_mc_ratio=0.25, max_shift_ratio=0.5)[
        ...     "label"
        ... ]
        'stable'
    """
    for name, value in (
        ("se", se),
        ("max_mc_ratio", max_mc_ratio),
        ("max_shift_ratio", max_shift_ratio),
        ("z", z),
    ):
        if isinstance(value, bool) or not np.isfinite(value) or value <= 0:
            msg = f"{name} must be a positive finite number"
            raise ValueError(msg)
    mc_ratio = estimate.mc_sd / se
    shift_bound = (abs(estimate.shift) + z * estimate.shift_se) / se
    stable = (
        not estimate.insufficient
        and estimate.n_failed == 0
        and mc_ratio <= max_mc_ratio
        and shift_bound <= max_shift_ratio
    )
    label: Literal["stable", "not_assessable"] = (
        "stable" if stable else "not_assessable"
    )
    return {
        "label": label,
        "mc_ratio": float(mc_ratio),
        "shift_bound_ratio": float(shift_bound),
        "n_failed": estimate.n_failed,
        "n_sampled": estimate.n_sampled,
        "insufficient": estimate.insufficient,
    }

stratify(diagnostic, edges)

Assign each unit to a stratum by a tail diagnostic.

Stratum k holds values from edges[k-1] (inclusive) up to edges[k] (exclusive); the last stratum is open above. A non-finite diagnostic is assigned to the top stratum, never dropped.

Raises:

Type Description
ValueError

edges is empty, not finite or not strictly increasing.

Examples:

>>> stratify([0.1, 0.5, 0.69, 0.7, 1.2, float("nan")], (0.5, 0.7)).tolist()
[0, 1, 1, 2, 2, 2]
Source code in src/op_infer/audit.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def stratify(diagnostic: ArrayLike, edges: Sequence[float]) -> NDArray[np.intp]:
    """Assign each unit to a stratum by a tail diagnostic.

    Stratum ``k`` holds values from ``edges[k-1]`` (inclusive) up to ``edges[k]``
    (exclusive); the last stratum is open above. A non-finite diagnostic is
    assigned to the **top** stratum, never dropped.

    Raises:
        ValueError: ``edges`` is empty, not finite or not strictly increasing.

    Examples:
        >>> stratify([0.1, 0.5, 0.69, 0.7, 1.2, float("nan")], (0.5, 0.7)).tolist()
        [0, 1, 1, 2, 2, 2]
    """
    cuts = np.asarray(edges, dtype=float)
    if cuts.ndim != 1 or cuts.size == 0 or not np.all(np.isfinite(cuts)):
        msg = "edges must be a nonempty finite sequence"
        raise ValueError(msg)
    if np.any(np.diff(cuts) <= 0):
        msg = "edges must be strictly increasing"
        raise ValueError(msg)
    values = np.asarray(diagnostic, dtype=float)
    labels = np.searchsorted(cuts, values, side="right").astype(np.intp)
    labels[~np.isfinite(values)] = cuts.size
    return labels

ensemble_calibration

Per-member and mixture calibration report for an ensemble of posteriors.

For an equal-weight mixture of independently trained estimators, calibration of the mixture is what is reported (Hermans et al. 2022, arXiv:2110.06581, on ensembling; Talts et al. 2018, arXiv:1804.06788, on SBC). Whether the mixture is wider than its members, how many members individually show rank flags, and how far the members' locations disagree are separate and useful diagnostics: a mixture of members that differ in location can be wider than every member.

This module only summarises records that the caller has produced (or builds them from posterior draws with MemberRecords.from_draws); it reports and gates nothing. Rank flags are counted (n_flagged per member and for the mixture, Benjamini-Hochberg across estimands), never turned into a pass or fail, and member agreement and validation-loss spread are reported only.

The SBC runner stores PITs only, not truths, means or member structure, so the records come from the caller's own loop over replicates (see the docs page).

MemberRecords dataclass

Per-replicate summaries of every member and the mixture for one estimand.

Shapes: truth and mixture_* are (R,); member_* are (M, R). *_pit are PITs in [0, 1], randomised when the estimand has atoms; *_mean and *_sd the posterior mean and SD of each replicate. For an estimand with atoms=True the standardised-error quantities are not defined and are reported as None; SDs may then be zero.

Source code in src/op_infer/ensemble_calibration.py
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@dataclass(frozen=True)
class MemberRecords:
    """Per-replicate summaries of every member and the mixture for one estimand.

    Shapes: ``truth`` and ``mixture_*`` are ``(R,)``; ``member_*`` are ``(M, R)``.
    ``*_pit`` are PITs in [0, 1], randomised when the estimand has atoms;
    ``*_mean`` and ``*_sd`` the posterior mean and SD of each replicate. For an
    estimand with ``atoms=True`` the standardised-error quantities are not
    defined and are reported as ``None``; SDs may then be zero.
    """

    truth: ArrayLike
    member_mean: ArrayLike
    member_sd: ArrayLike
    member_pit: ArrayLike
    mixture_mean: ArrayLike
    mixture_sd: ArrayLike
    mixture_pit: ArrayLike
    atoms: bool = False

    @classmethod
    def from_draws(
        cls,
        truth: ArrayLike,
        draws: ArrayLike,
        *,
        atoms: bool = False,
        rng: np.random.Generator | None = None,
    ) -> MemberRecords:
        """Build records from per-replicate posterior draws.

        ``truth`` is ``(R,)`` and ``draws`` is ``(R, M, S)``: ``S`` draws of the
        estimand from each of ``M`` members for every replicate. The mixture is
        the equal-weight pool of the members' draws. PITs use ``calibrate.pit``
        (randomised with ``rng`` when ``atoms`` is true).

        Raises:
            ValueError: Shapes are inconsistent, or ``atoms`` is set without ``rng``.

        Examples:
            >>> g = np.random.default_rng(0)
            >>> rec = MemberRecords.from_draws(
            ...     g.normal(size=20), g.normal(size=(20, 2, 50))
            ... )
            >>> np.asarray(rec.member_mean).shape, np.asarray(rec.mixture_pit).shape
            ((2, 20), (20,))
        """
        t = np.asarray(truth, dtype=float)
        d = np.asarray(draws, dtype=float)
        if t.ndim != 1 or d.ndim != 3 or d.shape[0] != t.shape[0]:
            msg = "truth must be (R,) and draws (R, M, S)"
            raise ValueError(msg)
        if d.shape[2] < 2:
            msg = "at least two draws per member are needed for a posterior SD"
            raise ValueError(msg)
        n, m, _ = d.shape
        pooled = d.reshape(n, -1)
        return cls(
            truth=t,
            member_mean=d.mean(axis=2).T,
            member_sd=d.std(axis=2).T,
            member_pit=np.array(
                [
                    [pit(d[r, i], t[r], atoms=atoms, rng=rng) for r in range(n)]
                    for i in range(m)
                ]
            ),
            mixture_mean=pooled.mean(axis=1),
            mixture_sd=pooled.std(axis=1),
            mixture_pit=np.array(
                [pit(pooled[r], t[r], atoms=atoms, rng=rng) for r in range(n)]
            ),
            atoms=atoms,
        )

from_draws(truth, draws, *, atoms=False, rng=None) classmethod

Build records from per-replicate posterior draws.

truth is (R,) and draws is (R, M, S): S draws of the estimand from each of M members for every replicate. The mixture is the equal-weight pool of the members' draws. PITs use calibrate.pit (randomised with rng when atoms is true).

Raises:

Type Description
ValueError

Shapes are inconsistent, or atoms is set without rng.

Examples:

>>> g = np.random.default_rng(0)
>>> rec = MemberRecords.from_draws(
...     g.normal(size=20), g.normal(size=(20, 2, 50))
... )
>>> np.asarray(rec.member_mean).shape, np.asarray(rec.mixture_pit).shape
((2, 20), (20,))
Source code in src/op_infer/ensemble_calibration.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@classmethod
def from_draws(
    cls,
    truth: ArrayLike,
    draws: ArrayLike,
    *,
    atoms: bool = False,
    rng: np.random.Generator | None = None,
) -> MemberRecords:
    """Build records from per-replicate posterior draws.

    ``truth`` is ``(R,)`` and ``draws`` is ``(R, M, S)``: ``S`` draws of the
    estimand from each of ``M`` members for every replicate. The mixture is
    the equal-weight pool of the members' draws. PITs use ``calibrate.pit``
    (randomised with ``rng`` when ``atoms`` is true).

    Raises:
        ValueError: Shapes are inconsistent, or ``atoms`` is set without ``rng``.

    Examples:
        >>> g = np.random.default_rng(0)
        >>> rec = MemberRecords.from_draws(
        ...     g.normal(size=20), g.normal(size=(20, 2, 50))
        ... )
        >>> np.asarray(rec.member_mean).shape, np.asarray(rec.mixture_pit).shape
        ((2, 20), (20,))
    """
    t = np.asarray(truth, dtype=float)
    d = np.asarray(draws, dtype=float)
    if t.ndim != 1 or d.ndim != 3 or d.shape[0] != t.shape[0]:
        msg = "truth must be (R,) and draws (R, M, S)"
        raise ValueError(msg)
    if d.shape[2] < 2:
        msg = "at least two draws per member are needed for a posterior SD"
        raise ValueError(msg)
    n, m, _ = d.shape
    pooled = d.reshape(n, -1)
    return cls(
        truth=t,
        member_mean=d.mean(axis=2).T,
        member_sd=d.std(axis=2).T,
        member_pit=np.array(
            [
                [pit(d[r, i], t[r], atoms=atoms, rng=rng) for r in range(n)]
                for i in range(m)
            ]
        ),
        mixture_mean=pooled.mean(axis=1),
        mixture_sd=pooled.std(axis=1),
        mixture_pit=np.array(
            [pit(pooled[r], t[r], atoms=atoms, rng=rng) for r in range(n)]
        ),
        atoms=atoms,
    )

member_calibration(records, *, alpha=0.05, bins=20, validation_losses=None, n_failed=0)

Summarise per-member and mixture calibration over named estimands.

For each estimand: the centred SD (z_sd), mean (z_mean) and root mean square (z_rms) of the standardised error (truth - mean) / sd, and the coverage of the central 50% and 90% intervals taken from the PITs, for every member and for the mixture. z_sd is centred, so a member with the right width but a bias shows z_sd near 1 and a non-zero z_mean; read the two together, or use z_rms. The mixture's z_sd uses its Gaussian summary SD, while its coverage uses the mixture PIT; for non-Gaussian mixtures these are different notions.

With two or more members, z_sd_gap is the smallest member z_sd minus the mixture z_sd: positive when the mixture's standardised errors are smaller than every member's, which is the mixture being wider than its own error scale (it does not by itself show that the mixture is wide enough). agreement is the median over replicates of the range of member means in units of the mixture SD; it grows with the number of members and is not comparable across ensemble sizes. With one member both are None. For atom estimands the standardised-error fields are None.

Rank flags are counted per member and for the mixture across the estimands (Benjamini-Hochberg through calibrate.aggregate); the per-bank underpowered flag, replicate count and failed count are passed through. members_with_flags has no multiplicity control across members: with M calibrated members that share the same truths the chance that at least one is flagged is about 1 - (1 - alpha)**M per estimand, so it is not evidence of member miscalibration by itself. Nothing is gated.

Raises:

Type Description
ValueError

Records are empty, inconsistent or non-finite, the member counts differ between estimands, or validation_losses is not one finite value per member.

Examples:

>>> rng = np.random.default_rng(0)
>>> rec = MemberRecords.from_draws(
...     rng.normal(size=60), rng.normal(size=(60, 3, 200))
... )
>>> out = member_calibration({"theta": rec})
>>> out["n_members"], sorted(out["estimands"]["theta"])
(3, ['agreement', 'members', 'mixture', 'z_sd_gap'])
Source code in src/op_infer/ensemble_calibration.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def member_calibration(
    records: Mapping[str, MemberRecords],
    *,
    alpha: float = 0.05,
    bins: int = 20,
    validation_losses: Sequence[float] | None = None,
    n_failed: int = 0,
) -> dict[str, Any]:
    """Summarise per-member and mixture calibration over named estimands.

    For each estimand: the centred SD (``z_sd``), mean (``z_mean``) and root mean
    square (``z_rms``) of the standardised error ``(truth - mean) / sd``, and the
    coverage of the central 50% and 90% intervals taken from the PITs, for every
    member and for the mixture. ``z_sd`` is centred, so a member with the right
    width but a bias shows ``z_sd`` near 1 and a non-zero ``z_mean``; read the two
    together, or use ``z_rms``. The mixture's ``z_sd`` uses its Gaussian summary
    SD, while its coverage uses the mixture PIT; for non-Gaussian mixtures these
    are different notions.

    With two or more members, ``z_sd_gap`` is the smallest member ``z_sd`` minus
    the mixture ``z_sd``: positive when the mixture's standardised errors are
    smaller than every member's, which is the mixture being wider than its own
    error scale (it does not by itself show that the mixture is wide enough).
    ``agreement`` is the median over replicates of the
    range of member means in units of the mixture SD; it grows with the number of
    members and is not comparable across ensemble sizes. With one member both are
    ``None``. For atom estimands the standardised-error fields are ``None``.

    Rank flags are counted per member and for the mixture across the estimands
    (Benjamini-Hochberg through ``calibrate.aggregate``); the per-bank
    ``underpowered`` flag, replicate count and failed count are passed through.
    ``members_with_flags`` has no multiplicity control across members: with ``M``
    calibrated members that share the same truths the chance that at least one is
    flagged is about ``1 - (1 - alpha)**M`` per estimand, so it is not evidence of
    member miscalibration by itself. Nothing is gated.

    Raises:
        ValueError: Records are empty, inconsistent or non-finite, the member
            counts differ between estimands, or ``validation_losses`` is not one
            finite value per member.

    Examples:
        >>> rng = np.random.default_rng(0)
        >>> rec = MemberRecords.from_draws(
        ...     rng.normal(size=60), rng.normal(size=(60, 3, 200))
        ... )
        >>> out = member_calibration({"theta": rec})
        >>> out["n_members"], sorted(out["estimands"]["theta"])
        (3, ['agreement', 'members', 'mixture', 'z_sd_gap'])
    """
    if not records:
        msg = "provide at least one estimand"
        raise ValueError(msg)
    arrays = {name: _arrays(name, r) for name, r in records.items()}
    sizes = {a["member_mean"].shape[0] for a in arrays.values()}
    if len(sizes) != 1:
        msg = "every estimand must carry the same number of members"
        raise ValueError(msg)
    n_members = sizes.pop()
    losses = (
        None if validation_losses is None else [float(x) for x in validation_losses]
    )
    if losses is not None and (
        len(losses) != n_members or not np.all(np.isfinite(losses))
    ):
        msg = "validation_losses must be finite, one per member"
        raise ValueError(msg)
    table: dict[str, Any] = {}
    for name, a in arrays.items():
        atoms = records[name].atoms
        members = [
            _row(
                a["truth"],
                a["member_mean"][i],
                a["member_sd"][i],
                a["member_pit"][i],
                atoms=atoms,
            )
            for i in range(n_members)
        ]
        mixture = _row(
            a["truth"],
            a["mixture_mean"],
            a["mixture_sd"],
            a["mixture_pit"],
            atoms=atoms,
        )
        gap = agreement = None
        if n_members >= 2 and not atoms:
            gap = float(
                min(cast("float", m["z_sd"]) for m in members)
                - cast("float", mixture["z_sd"])
            )
            spread = a["member_mean"].max(axis=0) - a["member_mean"].min(axis=0)
            agreement = float(np.median(spread / a["mixture_sd"]))
        table[name] = {
            "members": members,
            "mixture": mixture,
            "z_sd_gap": gap,
            "agreement": agreement,
        }
    flags = [
        aggregate(
            {n: a["member_pit"][i] for n, a in arrays.items()},
            bins=bins,
            alpha=alpha,
            n_failed=n_failed,
        )
        for i in range(n_members)
    ]
    mix = aggregate(
        {n: a["mixture_pit"] for n, a in arrays.items()},
        bins=bins,
        alpha=alpha,
        n_failed=n_failed,
    )
    return {
        "reading": "descriptive; no gate is applied",
        "n_members": n_members,
        "estimands": table,
        "member_n_flagged": [f["n_flagged"] for f in flags],
        "member_flagged": [f["flagged"] for f in flags],
        "mixture_n_flagged": mix["n_flagged"],
        "mixture_flagged": mix["flagged"],
        "members_with_flags": int(sum(f["n_flagged"] > 0 for f in flags)),
        "n_replicates": mix["n_replicates"],
        "n_failed": mix["n_failed"],
        "underpowered": mix["underpowered"],
        "underpowered_banner": mix["underpowered_banner"],
        "validation_loss_spread": None
        if losses is None
        else float(max(losses) - min(losses)),
        "settings": {"alpha": alpha, "bins": bins, "levels": list(LEVELS)},
    }

identify

Scoped structural reports and finite-design local Gaussian information.

Optional compiler/engine consumers live in adapters.op_identify. General coordinate transformations, nuisance profiling, observed posterior curvature, profile likelihood and external structural tools retain their separate scopes.

GaussianInformation dataclass

Borrow native information arrays without detaching their graphs.

Matrix entries sum over selected independent measurement cells. Validity and observed count are native scalars. Invalid selected inputs or an empty set return valid=False and a NaN matrix, never a fake rank.

Source code in src/op_infer/geometry.py
160
161
162
163
164
165
166
167
168
169
170
171
172
@dataclass(frozen=True, slots=True)
class GaussianInformation:
    """Borrow native information arrays without detaching their graphs.

    Matrix entries sum over selected independent measurement cells. Validity and
    observed count are native scalars. Invalid selected inputs or an empty set
    return valid=False and a NaN matrix, never a fake rank.
    """

    context: InformationContext
    matrix: object
    valid: object
    n_observed: object

InformationContext

Bases: _Record

Declare a physical-coordinate, data-only, finite-design target.

References retain design, parameter point, observation target, numerical method and independently supplied qualification evidence. They do not authenticate those claims. Units expose the spectrum's coordinate dependence.

Source code in src/op_infer/geometry.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
class InformationContext(_Record):
    """Declare a physical-coordinate, data-only, finite-design target.

    References retain design, parameter point, observation target, numerical
    method and independently supplied qualification evidence. They do not
    authenticate those claims. Units expose the spectrum's coordinate dependence.
    """

    source_model: ArtifactReference
    design: ArtifactReference
    parameter_point: ArtifactReference
    initialization: ArtifactReference
    observation: ArtifactReference
    numerical: ArtifactReference
    qualification: ArtifactReference
    parameter_names: tuple[_Text, ...]
    parameter_units: tuple[_Text, ...]
    observable_names: tuple[_Text, ...]
    coordinates: Literal["physical"] = "physical"
    nuisance_treatment: Literal["none"] = "none"

    @model_validator(mode="after")
    def _layout(self) -> Self:
        if (
            not self.parameter_names
            or not self.observable_names
            or len(self.parameter_names) != len(self.parameter_units)
            or len(set(self.parameter_names)) != len(self.parameter_names)
            or len(set(self.observable_names)) != len(self.observable_names)
        ):
            msg = "Information context requires ordered unique names and complete units"
            raise ValueError(msg)
        return self

InformationLimits dataclass

Bound dense numerical work; borrowed input storage is owned by the caller.

Source code in src/op_infer/geometry.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
@dataclass(frozen=True, slots=True)
class InformationLimits:
    """Bound dense numerical work; borrowed input storage is owned by the caller."""

    max_parameters: int = 128
    max_elements: int = 16_777_216

    def __post_init__(self) -> None:
        """Reject invalid bounds, keeping native selected counts within int32.

        Raises:
            ValueError: Limits are not positive integers or exceed count storage.
        """
        if (
            any(
                type(value) is not int or value < 1
                for value in (self.max_parameters, self.max_elements)
            )
            or self.max_elements >= 2**31
        ):
            msg = "Information limits require positive integers within count capacity"
            raise ValueError(msg)

__post_init__()

Reject invalid bounds, keeping native selected counts within int32.

Raises:

Type Description
ValueError

Limits are not positive integers or exceed count storage.

Source code in src/op_infer/geometry.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def __post_init__(self) -> None:
    """Reject invalid bounds, keeping native selected counts within int32.

    Raises:
        ValueError: Limits are not positive integers or exceed count storage.
    """
    if (
        any(
            type(value) is not int or value < 1
            for value in (self.max_parameters, self.max_elements)
        )
        or self.max_elements >= 2**31
    ):
        msg = "Information limits require positive integers within count capacity"
        raise ValueError(msg)

LocalSpectrum

Bases: _Record

Host report of local eigenvalues with an explicit rank tolerance.

This rank at one point/design is not an identifiable dimension, structural result, quotient dimension or model penalty.

Source code in src/op_infer/geometry.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
class LocalSpectrum(_Record):
    """Host report of local eigenvalues with an explicit rank tolerance.

    This rank at one point/design is not an identifiable dimension, structural
    result, quotient dimension or model penalty.
    """

    context: InformationContext
    eigenvalues: tuple[_Finite, ...]
    eigenvectors: tuple[tuple[_Finite, ...], ...]
    rtol: Annotated[float, Field(ge=0, allow_inf_nan=False)]
    atol: Annotated[float, Field(ge=0, allow_inf_nan=False)]
    threshold: Annotated[float, Field(ge=0, allow_inf_nan=False)]
    local_rank: _Count
    n_observed: Annotated[int, Field(ge=1)]

    @model_validator(mode="after")
    def _spectrum(self) -> Self:
        count = len(self.context.parameter_names)
        threshold = self.atol + self.rtol * max(map(abs, self.eigenvalues), default=0.0)
        if (
            len(self.eigenvalues) != count
            or len(self.eigenvectors) != count
            or any(len(row) != count for row in self.eigenvectors)
            or self.rtol + self.atol <= 0
            or tuple(sorted(self.eigenvalues)) != self.eigenvalues
            or not math.isclose(self.threshold, threshold, rel_tol=1e-12, abs_tol=0.0)
            or self.local_rank
            != sum(value > self.threshold for value in self.eigenvalues)
        ):
            msg = "Saved local spectrum layout, threshold or rank is inconsistent"
            raise ValueError(msg)
        return self

ScalingAssessment

Bases: _Record

Version an existing compiler report, with distinct unavailable statuses.

Ranks describe the reported shared state/parameter-base action. Initial conditions, priors and statistical identifiability are not assessed here.

Source code in src/op_infer/geometry.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class ScalingAssessment(_Record):
    """Version an existing compiler report, with distinct unavailable statuses.

    Ranks describe the reported shared state/parameter-base action. Initial
    conditions, priors and statistical identifiability are not assessed here.
    """

    source_model: ArtifactReference
    status: Literal["unassessed", "unsupported", "reported"]
    reason: _Text
    parameter_bases: tuple[str, ...] = ()
    generators: tuple[ScalingGenerator, ...] = ()
    action_rank: _Count | None = None
    parameter_action_rank: _Count | None = None
    invariant_monomials: tuple[tuple[tuple[str, int], ...], ...] = ()
    detection_requested: bool = False
    verification: ScalingVerification | None = None

    @model_validator(mode="after")
    def _status(self) -> Self:
        if self.status != "reported":
            if (
                self.action_rank is not None
                or self.parameter_action_rank is not None
                or self.generators
                or self.invariant_monomials
                or self.verification is not None
            ):
                msg = "Unavailable scaling reports cannot claim ranks or actions"
                raise ValueError(msg)
        elif (
            self.action_rank is None
            or self.parameter_action_rank is None
            or self.action_rank != len(self.generators)
            or self.parameter_action_rank
            > min(self.action_rank, len(self.parameter_bases))
        ):
            msg = "Scaling ranks must match the producer's independent basis"
            raise ValueError(msg)
        return self

ScalingGenerator

Bases: _Record

Copy a shared-template scaling action without changing coordinates.

Source code in src/op_infer/geometry.py
62
63
64
65
66
67
class ScalingGenerator(_Record):
    """Copy a shared-template scaling action without changing coordinates."""

    name: _Text
    states: tuple[tuple[_Text, _Finite], ...]
    parameters: tuple[tuple[_Text, _Finite], ...]

ScalingVerification

Bases: _Record

Retain producer probes; finite witnesses are not global proofs.

Source code in src/op_infer/geometry.py
70
71
72
73
74
75
76
77
78
79
80
class ScalingVerification(_Record):
    """Retain producer probes; finite witnesses are not global proofs."""

    seed: _Count
    n_probes: Annotated[int, Field(ge=1)]
    scales: tuple[Annotated[float, Field(gt=0, allow_inf_nan=False)], ...]
    rtol: Annotated[float, Field(ge=0, allow_inf_nan=False)]
    atol: Annotated[float, Field(ge=0, allow_inf_nan=False)]
    max_absolute_error: Annotated[float, Field(ge=0, allow_inf_nan=False)]
    observables: tuple[str, ...]
    structural_homogeneity_checked: bool

gaussian_mean_information(sensitivities, standard_deviation, *, context, mask=None, limits=None)

Compute native J.T @ diag(1/sigma**2) @ J for measured-mean derivatives.

Shape is (..., observables, parameters). All leading cells are independent measurements. Sigma is scalar or matches the measurement shape; masks are native booleans of that exact shape. Missing NaNs are replaced before arithmetic. Fixed known variances give conditional Gaussian information; parameter-dependent variance needs terms beyond this mean contribution.

Returns:

Type Description
GaussianInformation

Bounded native dense information and validity, without adding a prior.

Raises:

Type Description
ValueError

Static layout, bounds or precision differs.

TypeError

Inputs are not native real floating arrays.

Source code in src/op_infer/geometry.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def gaussian_mean_information(
    sensitivities: object,
    standard_deviation: object,
    *,
    context: InformationContext,
    mask: object | None = None,
    limits: InformationLimits | None = None,
) -> GaussianInformation:
    """Compute native ``J.T @ diag(1/sigma**2) @ J`` for measured-mean derivatives.

    Shape is (..., observables, parameters). All leading cells are independent
    measurements. Sigma is scalar or matches the measurement shape; masks are
    native booleans of that exact shape. Missing NaNs are replaced before
    arithmetic. Fixed known variances give conditional Gaussian information;
    parameter-dependent variance needs terms beyond this mean contribution.

    Returns:
        Bounded native dense information and validity, without adding a prior.

    Raises:
        ValueError: Static layout, bounds or precision differs.
        TypeError: Inputs are not native real floating arrays.
    """
    context = InformationContext.model_validate(context)
    if limits is not None and not isinstance(limits, InformationLimits):
        msg = "Information bounds require InformationLimits"
        raise TypeError(msg)
    bounds = limits or InformationLimits()
    values: Any = sensitivities
    sigma: Any = standard_deviation
    if any(
        getattr(value, "dtype", None) is None or getattr(value, "shape", None) is None
        for value in (values, sigma)
    ):
        msg = "Gaussian information inputs must be native arrays"
        raise TypeError(msg)
    xp = array_namespace(values, sigma)
    shape = tuple(values.shape)
    if not xp.isdtype(values.dtype, "real floating") or not xp.isdtype(
        sigma.dtype, "real floating"
    ):
        msg = "Gaussian information requires real floating native inputs"
        raise TypeError(msg)
    if (
        len(shape) < 2
        or shape[-2:] != (len(context.observable_names), len(context.parameter_names))
        or tuple(sigma.shape) not in {(), shape[:-1]}
        or sigma.dtype != values.dtype
    ):
        msg = "Sensitivity/noise layout or precision differs from information context"
        raise ValueError(msg)
    if shape[-1] > bounds.max_parameters or math.prod(shape) > bounds.max_elements:
        msg = "Information exceeds its dense parameter/element bound"
        raise ValueError(msg)
    sigma = xp.broadcast_to(sigma, shape[:-1])
    selected: Any = xp.ones_like(sigma, dtype=xp.bool) if mask is None else mask
    if (
        array_namespace(selected) is not xp
        or selected.dtype != xp.bool
        or tuple(selected.shape) != shape[:-1]
    ):
        msg = "Information mask must be native boolean with the measurement shape"
        raise ValueError(msg)
    sigma_ok = xp.isfinite(sigma) & (sigma > 0)
    valid = xp.all(
        ~selected | (sigma_ok & xp.all(xp.isfinite(values), axis=-1))
    ) & xp.any(selected)
    safe_sigma = xp.where(selected & sigma_ok, sigma, xp.ones_like(sigma))
    safe_values = xp.where(
        xp.expand_dims(selected, axis=-1), values, xp.zeros_like(values)
    )
    weighted = xp.reshape(
        safe_values / xp.expand_dims(safe_sigma, axis=-1), (-1, shape[-1])
    )
    matrix = xp.matrix_transpose(weighted) @ weighted
    valid = valid & xp.all(xp.isfinite(matrix))
    matrix = xp.where(valid, matrix, xp.full_like(matrix, xp.nan))
    return GaussianInformation(
        context, matrix, valid, xp.sum(xp.astype(selected, xp.int32))
    )

local_spectrum(information, *, rtol, atol)

Snapshot a valid small matrix and report its local eigenspectrum.

This explicit host boundary synchronizes/copies native data. Keep the original matrix for AD/JIT; no prior or posterior coordinates change.

Returns:

Type Description
LocalSpectrum

Ascending eigenvalues, column eigenvectors, context and threshold.

Raises:

Type Description
ValueError

Tolerances, validity or matrix are inconsistent/nonfinite.

Source code in src/op_infer/geometry.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def local_spectrum(
    information: GaussianInformation, *, rtol: float, atol: float
) -> LocalSpectrum:
    """Snapshot a valid small matrix and report its local eigenspectrum.

    This explicit host boundary synchronizes/copies native data. Keep the
    original matrix for AD/JIT; no prior or posterior coordinates change.

    Returns:
        Ascending eigenvalues, column eigenvectors, context and threshold.

    Raises:
        ValueError: Tolerances, validity or matrix are inconsistent/nonfinite.
    """
    if (
        any(
            isinstance(v, (bool, np.bool_))
            or not isinstance(v, Real)
            or not math.isfinite(v)
            or v < 0
            for v in (rtol, atol)
        )
        or rtol + atol <= 0
    ):
        msg = "Local spectrum requires finite nonnegative, nonzero tolerances"
        raise ValueError(msg)
    valid = _host(information.valid)
    if valid.shape != () or valid.item() != 1:
        msg = "Invalid/empty selected data cannot have an information spectrum"
        raise ValueError(msg)
    matrix = _host(information.matrix)
    count = len(information.context.parameter_names)
    if (
        matrix.shape != (count, count)
        or not np.all(np.isfinite(matrix))
        or not np.allclose(matrix, matrix.T, rtol=rtol, atol=atol)
    ):
        msg = "Local information must be finite, ordered and symmetric"
        raise ValueError(msg)
    eigenvalues, eigenvectors = np.linalg.eigh((matrix + matrix.T) / 2)
    threshold = float(atol + rtol * np.max(np.abs(eigenvalues), initial=0.0))
    if float(eigenvalues.min(initial=0.0)) < -threshold:
        msg = "Gaussian information has a materially negative eigenvalue"
        raise ValueError(msg)
    return LocalSpectrum(
        context=information.context,
        eigenvalues=tuple(float(value) for value in eigenvalues),
        eigenvectors=tuple(tuple(float(v) for v in row) for row in eigenvectors),
        rtol=float(rtol),
        atol=float(atol),
        threshold=threshold,
        local_rank=int(np.count_nonzero(eigenvalues > threshold)),
        n_observed=int(_host(information.n_observed).item()),
    )

op_identify

Optional read-only compiler reports and measured sensitivity interoperability.

No second gauge detector or ODE solver is implemented. Structural action ranks, finite-design Gaussian spectra and posterior geometry retain separate meanings.

information_from_sensitivities(solution, observation, *, context, mask=None)

Apply one fixed iid Normal law to the engine's measured sensitivities.

The affine measurement slope is included; its fixed offset has zero derivative. The known fixed scale supplies the conditional observation variance. Censoring/count/dependent laws need separate information formulas.

Returns:

Type Description
GaussianInformation

Physical-coordinate mean information with exact source/layout guards.

Raises:

Type Description
ValueError

Model, numerical, observation or coordinate layouts differ.

NotImplementedError

The observation model needs a different formula.

Source code in src/op_infer/adapters/op_identify.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def information_from_sensitivities(
    solution: object,
    observation: IIDObservation,
    *,
    context: InformationContext,
    mask: object | None = None,
) -> GaussianInformation:
    """Apply one fixed iid Normal law to the engine's measured sensitivities.

    The affine measurement slope is included; its fixed offset has zero
    derivative. The known fixed scale supplies the conditional observation
    variance. Censoring/count/dependent laws need separate information formulas.

    Returns:
        Physical-coordinate mean information with exact source/layout guards.

    Raises:
        ValueError: Model, numerical, observation or coordinate layouts differ.
        NotImplementedError: The observation model needs a different formula.
    """
    result = _solution(solution)
    context = InformationContext.model_validate(context)
    observation = IIDObservation.model_validate(observation)
    if (
        observation.family != "normal"
        or observation.lower_limit is not None
        or observation.upper_limit is not None
    ):
        msg = "Engine information adapter requires uncensored iid Normal observations"
        raise NotImplementedError(msg)
    if (
        context.source_model.kind != "op-system-structural-model-v1"
        or context.source_model.digest != result.source_model
        or context.parameter_names != result.parameter_names
        or context.observable_names != result.observable_names
        or context.observation != observation.reference
        or context.numerical != sensitivity_execution_reference(result)
    ):
        msg = "Information model/observation/numerical/layout context mismatch"
        raise ValueError(msg)
    values = result.observable_derivatives * observation.slope
    xp = array_namespace(values)
    sigma = xp.full_like(xp.sum(values, axis=-1), observation.scale)
    return gaussian_mean_information(values, sigma, context=context, mask=mask)

scaling_assessment(compiled, *, expected=None)

Copy an existing compiler report; never rerun or invent a detector.

The producer's parameter-base layout differs from an expanded physical parameter sensitivity layout. Finite probes retain their seed/tolerances; a reported action does not assess initial conditions or priors.

Returns:

Type Description
ScalingAssessment

Versioned unassessed, unsupported or reported scaling evidence.

Raises:

Type Description
ValueError

The independently expected source identity differs.

Source code in src/op_infer/adapters/op_identify.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def scaling_assessment(
    compiled: object, *, expected: ArtifactReference | None = None
) -> ScalingAssessment:
    """Copy an existing compiler report; never rerun or invent a detector.

    The producer's parameter-base layout differs from an expanded physical
    parameter sensitivity layout. Finite probes retain their seed/tolerances;
    a reported action does not assess initial conditions or priors.

    Returns:
        Versioned unassessed, unsupported or reported scaling evidence.

    Raises:
        ValueError: The independently expected source identity differs.
    """
    artifact: Any = compiled
    source = structural_model_reference(compiled)
    if expected is not None and expected != source:
        msg = "Structural assessment source model identity mismatch"
        raise ValueError(msg)
    if (
        artifact.operators
        or artifact.history_requirements
        or artifact.meta.get("time_varying_params")
        or artifact.gauge_fix is not None
    ):
        return ScalingAssessment(
            source_model=source,
            status="unsupported",
            reason=(
                "Operator/history/table or gauge-fixed execution needs "
                "a separate structural/statistical contract"
            ),
        )
    info = artifact.gauges
    if info is None:
        return ScalingAssessment(
            source_model=source,
            status="unassessed",
            reason="No compiler scaling assessment was requested; no zero-rank claim",
        )
    verification = None
    if info.verification is not None:
        probe = info.verification
        verification = ScalingVerification(
            seed=probe.seed,
            n_probes=probe.n_probes,
            scales=probe.scales,
            rtol=probe.rtol,
            atol=probe.atol,
            max_absolute_error=probe.max_absolute_error,
            observables=probe.observables,
            structural_homogeneity_checked=probe.structural,
        )
    return ScalingAssessment(
        source_model=source,
        status="reported",
        reason=(
            "Existing shared positive-scaling analysis; initial conditions "
            "and prior effects unassessed"
        ),
        parameter_bases=info.parameter_names,
        generators=tuple(
            ScalingGenerator(name=g.name, states=g.states, parameters=g.parameters)
            for g in info.generators
        ),
        action_rank=info.rank,
        parameter_action_rank=info.parameter_rank,
        invariant_monomials=tuple(
            value.exponents for value in info.invariant_coordinates
        ),
        detection_requested=info.detection_requested,
        verification=verification,
    )

sensitivity_execution_reference(solution)

Identify relevant fixed-sensitivity execution/layout without copying arrays.

Initial functions and parameter values remain separately identified caller inputs. This reference does not authenticate the implementation or replace independent qualification evidence and runtime/source records.

Returns:

Type Description
ArtifactReference

Versioned numerical execution reference expected by InformationContext.

Source code in src/op_infer/adapters/op_identify.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def sensitivity_execution_reference(solution: object) -> ArtifactReference:
    """Identify relevant fixed-sensitivity execution/layout without copying arrays.

    Initial functions and parameter values remain separately identified caller
    inputs. This reference does not authenticate the implementation or replace
    independent qualification evidence and runtime/source records.

    Returns:
        Versioned numerical execution reference expected by InformationContext.
    """
    result = _solution(solution)
    options = result.options
    settings = options.solver
    data = {
        "format": "op-engine-forward-sensitivities",
        "schema_version": 1,
        "source_model": result.source_model,
        "states": result.state_names,
        "parameters": result.parameter_names,
        "observables": result.observable_names,
        "mesh": result.mesh,
        "retained_times": result.times,
        "dtype": str(result.states.dtype),
        "method": settings.method,
        "fixed_max_step": settings.fixed_max_step,
        "fixed_loop": settings.fixed_loop,
        "fixed_checkpoint": settings.fixed_checkpoint,
        "store_history": options.store_history,
        "max_augmented_states": options.max_augmented_states,
        "max_output_bytes": options.max_output_bytes,
    }
    return ArtifactReference.from_bytes(
        json.dumps(
            data, sort_keys=True, separators=(",", ":"), allow_nan=False
        ).encode(),
        kind="op-engine-forward-sensitivities-v1",
    )

design

Design recovery, design power and value of information.

Implemented: bounded fixed-bank held-out simulate/refit comparison. General gate orchestration, Fisher screens and EVSI remain planned.

Scope: DesignStudy on trade_study: simulate under each generating model with the training acceptance rule, refit with design-aware estimators, score with op_infer.compare, report recovery with Wilson intervals, three-way outcomes and counted failures; replicate sizing from target precision; nested designs with common random numbers; Fisher screens (explicitly screens) feeding simulate-and-refit or EVSI.

DesignConfusion dataclass

Counts and Wilson intervals of verdicts by generating model for one design.

rows are the generating models and columns the verdicts: favor:<model> for each model, then indistinguishable and failed. counts[i][j] is the number of planned cohorts generated by rows[i] with verdict columns[j]; missing records are counted as failed, so every row sums to planned. intervals[i][j] is the trade-study ProportionInterval at confidence; with adjustment="bonferroni" that level is 1 - (1 - family_confidence) / len(columns).

Source code in src/op_infer/design.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@dataclass(frozen=True)
class DesignConfusion:
    """Counts and Wilson intervals of verdicts by generating model for one design.

    ``rows`` are the generating models and ``columns`` the verdicts: ``favor:<model>``
    for each model, then ``indistinguishable`` and ``failed``. ``counts[i][j]`` is
    the number of planned cohorts generated by ``rows[i]`` with verdict
    ``columns[j]``; missing records are counted as failed, so every row sums to
    ``planned``. ``intervals[i][j]`` is the trade-study ``ProportionInterval``
    at ``confidence``; with ``adjustment="bonferroni"`` that
    level is ``1 - (1 - family_confidence) / len(columns)``.
    """

    design: str
    rows: tuple[str, ...]
    columns: tuple[str, ...]
    counts: tuple[tuple[int, ...], ...]
    intervals: tuple[tuple[ProportionInterval, ...], ...]
    planned: int
    confidence: float
    family_confidence: float
    adjustment: str | None

DesignDefinition dataclass

Project a shared full cohort onto a design and record its cost/burden.

Source code in src/op_infer/design.py
57
58
59
60
61
62
@dataclass(frozen=True)
class DesignDefinition:
    """Project a shared full cohort onto a design and record its cost/burden."""

    observe: Callable[[object], DesignObservation]
    cost: float

DesignFit dataclass

Reporting fit, including joint latent draws, with explicit adequacy.

Source code in src/op_infer/design.py
81
82
83
84
85
86
87
88
@dataclass(frozen=True)
class DesignFit:
    """Reporting fit, including joint latent draws, with explicit adequacy."""

    posterior: object
    estimator: ArtifactReference
    adequate: bool
    diagnostics: Mapping[str, Any]

DesignGate dataclass

Caller-supplied calibration evidence for one design/model estimator.

This is an execution prerequisite for replicated design studies, not the general Gate/GateRecord API. Underpowered passes never count as calibrated estimators here.

Source code in src/op_infer/design.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@dataclass(frozen=True)
class DesignGate:
    """Caller-supplied calibration evidence for one design/model estimator.

    This is an execution prerequisite for replicated design studies, not the general
    Gate/GateRecord
    API. Underpowered passes never count as calibrated estimators here.
    """

    design: str
    model: str
    estimator: ArtifactReference
    calibration: ArtifactReference
    label: Literal["pass", "fail", "underpowered pass"]

DesignObservation dataclass

Separated fitting/held-out data with one declared predictive target.

Source code in src/op_infer/design.py
48
49
50
51
52
53
54
@dataclass(frozen=True)
class DesignObservation:
    """Separated fitting/held-out data with one declared predictive target."""

    training: object
    held_out: object
    target: ArtifactReference

DesignStudy dataclass

Bounded prespecified simulate/refit/predict workflow on trade-study.

Generators receive separate parameter/simulation keys. Each generated cohort is shared across designs, preserving common random numbers. Callbacks own model-specific inference and proper predictive scoring; every alternative is fitted on training data before scoring the same held-out target.

Source code in src/op_infer/design.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
@dataclass(frozen=True)
class DesignStudy:
    """Bounded prespecified simulate/refit/predict workflow on trade-study.

    Generators receive separate parameter/simulation keys. Each generated
    cohort is shared across designs, preserving common random numbers. Callbacks
    own model-specific inference and proper predictive scoring; every alternative
    is fitted on training data before scoring the same held-out target.
    """

    models: tuple[str, ...]
    designs: Mapping[str, DesignDefinition]
    generate: Callable[[str, RandomKey, RandomKey], object]
    fit: Callable[[str, str, object, RandomKey], DesignFit]
    score: Callable[[str, DesignFit, object, RandomKey], UnitPredictiveScores]
    gates: Mapping[tuple[str, str], DesignGate]
    provenance: Provenance
    threshold_se: float = 2.0

    def __post_init__(self) -> None:
        """Validate the complete model/design/gate bank before simulation.

        Raises:
            ValueError: The prespecified design contract is incomplete or invalid.
        """
        names = (*self.models, *self.designs)
        if (
            len(self.models) < 2
            or len(set(self.models)) != len(self.models)
            or not self.designs
        ):
            msg = (
                "A DesignStudy requires distinct candidate models and nonempty designs"
            )
            raise ValueError(msg)
        if any(not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", name) for name in names):
            msg = "Model/design names must be portable identifiers"
            raise ValueError(msg)
        if (
            any(not np.isfinite(d.cost) or d.cost < 0 for d in self.designs.values())
            or not np.isfinite(self.threshold_se)
            or self.threshold_se <= 0
        ):
            msg = "Costs must be finite/non-negative and threshold_se positive"
            raise ValueError(msg)
        for design in self.designs:
            for model in self.models:
                gate = self.gates.get((design, model))
                if (
                    gate is None
                    or (gate.design, gate.model) != (design, model)
                    or gate.label not in {"pass", "fail", "underpowered pass"}
                ):
                    msg = f"Invalid calibration evidence for {design}/{model}"
                    raise ValueError(msg)
        Provenance.model_validate(self.provenance)

    def _identity(self, directory: Path, seed: int) -> str:
        """Return an immutable artifact contract independent of shard layout."""
        contract = {
            "schema_version": 1,
            "provenance": self.provenance.model_dump(mode="json"),
            "models": self.models,
            "designs": {name: d.cost for name, d in self.designs.items()},
            "seed": seed,
            "threshold_se": self.threshold_se,
            "gates": {
                f"{d}/{m}": {
                    "estimator": g.estimator.model_dump(mode="json"),
                    "calibration": g.calibration.model_dump(mode="json"),
                    "label": g.label,
                }
                for (d, m), g in self.gates.items()
            },
        }
        return _require_manifest(directory, contract, filename="design-manifest.meta")

    def run(
        self,
        directory: str | Path,
        *,
        replicate_ids: Sequence[int],
        seed: int,
        n_jobs: int = 1,
    ) -> None:
        """Run a prespecified bank, resuming complete successes and failures.

        Disjoint ID shards share a contract. No retry or result-dependent stop
        changes the population. Generators implement the training acceptance rule
        and likelihood support; this workflow applies no extra filter.

        Raises:
            ImportError: The optional study extra is absent.
            ValueError: Task addresses or existing provenance are invalid.
        """
        try:
            from trade_study import (  # noqa: PLC0415 - optional dependency
                Direction,
                Observable,
                run_grid,
            )
        except ImportError as error:
            msg = "DesignStudy requires pip install 'op_infer[study]'"
            raise ImportError(msg) from error
        ids = tuple(replicate_ids)
        if not ids or len(set(ids)) != len(ids):
            msg = "Provide distinct nonempty independent cohort IDs"
            raise ValueError(msg)
        for index in ids:
            RandomKey(seed=seed, stream="design.validation", index=index)
        directory = Path(directory)
        identity = self._identity(directory, seed)
        banks = {}
        for model in self.models:
            for index in ids:
                if all(
                    _record_path(directory, d, model, index).exists()
                    for d in self.designs
                ):
                    continue
                parameter_key = RandomKey(
                    seed=seed, stream=f"design.parameters.{model}", index=index
                )
                simulation_key = RandomKey(
                    seed=seed, stream=f"design.simulation.{model}", index=index
                )
                try:
                    banks[(model, index)] = _Cohort(
                        self.generate(model, parameter_key, simulation_key)
                    )
                except Exception as error:  # noqa: BLE001 - retain shared generator failures
                    banks[(model, index)] = _Cohort(
                        None, f"{type(error).__name__}: {error}"
                    )
        configs = [
            {"design": design, "generator": model, "cohort": i}
            for design in self.designs
            for model in self.models
            for i in ids
        ]
        run_grid(
            _DesignWorld(self, banks, directory, identity, seed),
            _FailureScorer(),
            configs,
            [Observable("failed", Direction.MINIMIZE)],
            n_reps=1,
            n_jobs=n_jobs,
        )

    def confusion(
        self,
        directory: str | Path,
        *,
        replicate_ids: Sequence[int],
        seed: int,
        confidence: float = 0.95,
        adjustment: Literal["bonferroni"] | None = None,
    ) -> dict[str, DesignConfusion]:
        """Tabulate verdicts by generating model for every design over all planned IDs.

        Uses the stored records and the provenance validation of ``summarize``.
        Failed and missing trials stay in the denominator as the ``failed``
        column. Each independent generated cohort is one replicate; the intervals
        are fixed-sample Wilson intervals, marginal unless ``adjustment`` is
        ``"bonferroni"``, which holds the intervals of one row over its columns
        simultaneously at ``confidence``.

        Returns:
            One ``DesignConfusion`` per design, in declared design order.

        Raises:
            ValueError: No planned IDs exist, an adjustment is unsupported, or
                artifact provenance differs.
        """
        from trade_study import proportion_interval  # noqa: PLC0415 - optional dependency

        if adjustment not in (None, "bonferroni"):
            msg = "adjustment must be None or 'bonferroni'"
            raise ValueError(msg)
        ids = tuple(replicate_ids)
        if not ids or len(set(ids)) != len(ids):
            msg = "Summaries require distinct nonempty planned cohort IDs"
            raise ValueError(msg)
        for index in ids:
            RandomKey(seed=seed, stream="design.validation", index=index)
        directory = Path(directory)
        identity = self._identity(directory, seed)
        columns = (*(f"favor:{m}" for m in self.models), "indistinguishable", "failed")
        level = (
            1 - (1 - confidence) / len(columns)
            if adjustment == "bonferroni"
            else confidence
        )
        tables: dict[str, DesignConfusion] = {}
        for design in self.designs:
            counts = []
            for model in self.models:
                row = dict.fromkeys(columns, 0)
                for index in ids:
                    record = _read_record(
                        _record_path(directory, design, model, index),
                        {
                            "contract": identity,
                            "design": design,
                            "generator": model,
                            "cohort": index,
                        },
                    )
                    row[_verdict(record, model, self.models)] += 1
                counts.append(tuple(row[c] for c in columns))
            tables[design] = DesignConfusion(
                design=design,
                rows=tuple(self.models),
                columns=columns,
                counts=tuple(counts),
                intervals=tuple(
                    tuple(
                        proportion_interval(k, len(ids), confidence=level) for k in row
                    )
                    for row in counts
                ),
                planned=len(ids),
                confidence=float(level),
                family_confidence=float(confidence),
                adjustment=adjustment,
            )
        return tables

    def summarize(
        self,
        directory: str | Path,
        *,
        replicate_ids: Sequence[int],
        seed: int,
        confidence: float = 0.95,
    ) -> ResultsTable:
        """Report three-way pipeline outcomes plus failures over all planned IDs.

        Returns:
            A trade-study table with cost and marginal Wilson intervals. Each
            independent generated cohort is one replicate; bootstrap resamples
            are not new replicates. Failed/missing trials stay in the denominator.

        Raises:
            ValueError: No planned IDs exist or artifact provenance differs.
        """
        from trade_study import (  # noqa: PLC0415 - optional dependency
            ResultsTable,
            proportion_interval,
        )

        ids = tuple(replicate_ids)
        if not ids or len(set(ids)) != len(ids):
            msg = "Summaries require distinct nonempty planned cohort IDs"
            raise ValueError(msg)
        for index in ids:
            RandomKey(seed=seed, stream="design.validation", index=index)
        directory = Path(directory)
        identity = self._identity(directory, seed)
        configs, values, metadata = [], [], []
        for design, definition in self.designs.items():
            for model in self.models:
                counts = dict.fromkeys(
                    ("generator", "alternative", "indistinguishable", "failed"), 0
                )
                missing = 0
                for index in ids:
                    record = _read_record(
                        _record_path(directory, design, model, index),
                        {
                            "contract": identity,
                            "design": design,
                            "generator": model,
                            "cohort": index,
                        },
                    )
                    if record is None:
                        counts["failed"] += 1
                        missing += 1
                        continue
                    if record.get("outcome") not in counts:
                        msg = "Design artifact provenance/outcome mismatch"
                        raise ValueError(msg)
                    counts[record["outcome"]] += 1
                intervals = {
                    name: asdict(
                        proportion_interval(k, len(ids), confidence=confidence)
                    )
                    for name, k in counts.items()
                }
                configs.append({"design": design, "generator": model})
                values.append(
                    [*(counts[name] / len(ids) for name in counts), definition.cost]
                )
                metadata.append(
                    {
                        "planned": len(ids),
                        "failed": counts["failed"],
                        "missing": missing,
                        "replicate_unit": "independent_generated_cohort",
                        "wilson": intervals,
                        "probability_scope": "all_prespecified_pipeline_trials",
                        "multiplicity": "marginal Wilson; prespecified joint decision",
                        "gate_power_assessed": False,
                    }
                )
        return ResultsTable(
            configs,
            np.asarray(values, dtype=float),
            [
                "favor_generator",
                "favor_alternative",
                "indistinguishable",
                "failed",
                "cost",
            ],
            metadata=metadata,
        )

__post_init__()

Validate the complete model/design/gate bank before simulation.

Raises:

Type Description
ValueError

The prespecified design contract is incomplete or invalid.

Source code in src/op_infer/design.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
def __post_init__(self) -> None:
    """Validate the complete model/design/gate bank before simulation.

    Raises:
        ValueError: The prespecified design contract is incomplete or invalid.
    """
    names = (*self.models, *self.designs)
    if (
        len(self.models) < 2
        or len(set(self.models)) != len(self.models)
        or not self.designs
    ):
        msg = (
            "A DesignStudy requires distinct candidate models and nonempty designs"
        )
        raise ValueError(msg)
    if any(not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", name) for name in names):
        msg = "Model/design names must be portable identifiers"
        raise ValueError(msg)
    if (
        any(not np.isfinite(d.cost) or d.cost < 0 for d in self.designs.values())
        or not np.isfinite(self.threshold_se)
        or self.threshold_se <= 0
    ):
        msg = "Costs must be finite/non-negative and threshold_se positive"
        raise ValueError(msg)
    for design in self.designs:
        for model in self.models:
            gate = self.gates.get((design, model))
            if (
                gate is None
                or (gate.design, gate.model) != (design, model)
                or gate.label not in {"pass", "fail", "underpowered pass"}
            ):
                msg = f"Invalid calibration evidence for {design}/{model}"
                raise ValueError(msg)
    Provenance.model_validate(self.provenance)

confusion(directory, *, replicate_ids, seed, confidence=0.95, adjustment=None)

Tabulate verdicts by generating model for every design over all planned IDs.

Uses the stored records and the provenance validation of summarize. Failed and missing trials stay in the denominator as the failed column. Each independent generated cohort is one replicate; the intervals are fixed-sample Wilson intervals, marginal unless adjustment is "bonferroni", which holds the intervals of one row over its columns simultaneously at confidence.

Returns:

Type Description
dict[str, DesignConfusion]

One DesignConfusion per design, in declared design order.

Raises:

Type Description
ValueError

No planned IDs exist, an adjustment is unsupported, or artifact provenance differs.

Source code in src/op_infer/design.py
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def confusion(
    self,
    directory: str | Path,
    *,
    replicate_ids: Sequence[int],
    seed: int,
    confidence: float = 0.95,
    adjustment: Literal["bonferroni"] | None = None,
) -> dict[str, DesignConfusion]:
    """Tabulate verdicts by generating model for every design over all planned IDs.

    Uses the stored records and the provenance validation of ``summarize``.
    Failed and missing trials stay in the denominator as the ``failed``
    column. Each independent generated cohort is one replicate; the intervals
    are fixed-sample Wilson intervals, marginal unless ``adjustment`` is
    ``"bonferroni"``, which holds the intervals of one row over its columns
    simultaneously at ``confidence``.

    Returns:
        One ``DesignConfusion`` per design, in declared design order.

    Raises:
        ValueError: No planned IDs exist, an adjustment is unsupported, or
            artifact provenance differs.
    """
    from trade_study import proportion_interval  # noqa: PLC0415 - optional dependency

    if adjustment not in (None, "bonferroni"):
        msg = "adjustment must be None or 'bonferroni'"
        raise ValueError(msg)
    ids = tuple(replicate_ids)
    if not ids or len(set(ids)) != len(ids):
        msg = "Summaries require distinct nonempty planned cohort IDs"
        raise ValueError(msg)
    for index in ids:
        RandomKey(seed=seed, stream="design.validation", index=index)
    directory = Path(directory)
    identity = self._identity(directory, seed)
    columns = (*(f"favor:{m}" for m in self.models), "indistinguishable", "failed")
    level = (
        1 - (1 - confidence) / len(columns)
        if adjustment == "bonferroni"
        else confidence
    )
    tables: dict[str, DesignConfusion] = {}
    for design in self.designs:
        counts = []
        for model in self.models:
            row = dict.fromkeys(columns, 0)
            for index in ids:
                record = _read_record(
                    _record_path(directory, design, model, index),
                    {
                        "contract": identity,
                        "design": design,
                        "generator": model,
                        "cohort": index,
                    },
                )
                row[_verdict(record, model, self.models)] += 1
            counts.append(tuple(row[c] for c in columns))
        tables[design] = DesignConfusion(
            design=design,
            rows=tuple(self.models),
            columns=columns,
            counts=tuple(counts),
            intervals=tuple(
                tuple(
                    proportion_interval(k, len(ids), confidence=level) for k in row
                )
                for row in counts
            ),
            planned=len(ids),
            confidence=float(level),
            family_confidence=float(confidence),
            adjustment=adjustment,
        )
    return tables

run(directory, *, replicate_ids, seed, n_jobs=1)

Run a prespecified bank, resuming complete successes and failures.

Disjoint ID shards share a contract. No retry or result-dependent stop changes the population. Generators implement the training acceptance rule and likelihood support; this workflow applies no extra filter.

Raises:

Type Description
ImportError

The optional study extra is absent.

ValueError

Task addresses or existing provenance are invalid.

Source code in src/op_infer/design.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def run(
    self,
    directory: str | Path,
    *,
    replicate_ids: Sequence[int],
    seed: int,
    n_jobs: int = 1,
) -> None:
    """Run a prespecified bank, resuming complete successes and failures.

    Disjoint ID shards share a contract. No retry or result-dependent stop
    changes the population. Generators implement the training acceptance rule
    and likelihood support; this workflow applies no extra filter.

    Raises:
        ImportError: The optional study extra is absent.
        ValueError: Task addresses or existing provenance are invalid.
    """
    try:
        from trade_study import (  # noqa: PLC0415 - optional dependency
            Direction,
            Observable,
            run_grid,
        )
    except ImportError as error:
        msg = "DesignStudy requires pip install 'op_infer[study]'"
        raise ImportError(msg) from error
    ids = tuple(replicate_ids)
    if not ids or len(set(ids)) != len(ids):
        msg = "Provide distinct nonempty independent cohort IDs"
        raise ValueError(msg)
    for index in ids:
        RandomKey(seed=seed, stream="design.validation", index=index)
    directory = Path(directory)
    identity = self._identity(directory, seed)
    banks = {}
    for model in self.models:
        for index in ids:
            if all(
                _record_path(directory, d, model, index).exists()
                for d in self.designs
            ):
                continue
            parameter_key = RandomKey(
                seed=seed, stream=f"design.parameters.{model}", index=index
            )
            simulation_key = RandomKey(
                seed=seed, stream=f"design.simulation.{model}", index=index
            )
            try:
                banks[(model, index)] = _Cohort(
                    self.generate(model, parameter_key, simulation_key)
                )
            except Exception as error:  # noqa: BLE001 - retain shared generator failures
                banks[(model, index)] = _Cohort(
                    None, f"{type(error).__name__}: {error}"
                )
    configs = [
        {"design": design, "generator": model, "cohort": i}
        for design in self.designs
        for model in self.models
        for i in ids
    ]
    run_grid(
        _DesignWorld(self, banks, directory, identity, seed),
        _FailureScorer(),
        configs,
        [Observable("failed", Direction.MINIMIZE)],
        n_reps=1,
        n_jobs=n_jobs,
    )

summarize(directory, *, replicate_ids, seed, confidence=0.95)

Report three-way pipeline outcomes plus failures over all planned IDs.

Returns:

Type Description
ResultsTable

A trade-study table with cost and marginal Wilson intervals. Each

ResultsTable

independent generated cohort is one replicate; bootstrap resamples

ResultsTable

are not new replicates. Failed/missing trials stay in the denominator.

Raises:

Type Description
ValueError

No planned IDs exist or artifact provenance differs.

Source code in src/op_infer/design.py
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
def summarize(
    self,
    directory: str | Path,
    *,
    replicate_ids: Sequence[int],
    seed: int,
    confidence: float = 0.95,
) -> ResultsTable:
    """Report three-way pipeline outcomes plus failures over all planned IDs.

    Returns:
        A trade-study table with cost and marginal Wilson intervals. Each
        independent generated cohort is one replicate; bootstrap resamples
        are not new replicates. Failed/missing trials stay in the denominator.

    Raises:
        ValueError: No planned IDs exist or artifact provenance differs.
    """
    from trade_study import (  # noqa: PLC0415 - optional dependency
        ResultsTable,
        proportion_interval,
    )

    ids = tuple(replicate_ids)
    if not ids or len(set(ids)) != len(ids):
        msg = "Summaries require distinct nonempty planned cohort IDs"
        raise ValueError(msg)
    for index in ids:
        RandomKey(seed=seed, stream="design.validation", index=index)
    directory = Path(directory)
    identity = self._identity(directory, seed)
    configs, values, metadata = [], [], []
    for design, definition in self.designs.items():
        for model in self.models:
            counts = dict.fromkeys(
                ("generator", "alternative", "indistinguishable", "failed"), 0
            )
            missing = 0
            for index in ids:
                record = _read_record(
                    _record_path(directory, design, model, index),
                    {
                        "contract": identity,
                        "design": design,
                        "generator": model,
                        "cohort": index,
                    },
                )
                if record is None:
                    counts["failed"] += 1
                    missing += 1
                    continue
                if record.get("outcome") not in counts:
                    msg = "Design artifact provenance/outcome mismatch"
                    raise ValueError(msg)
                counts[record["outcome"]] += 1
            intervals = {
                name: asdict(
                    proportion_interval(k, len(ids), confidence=confidence)
                )
                for name, k in counts.items()
            }
            configs.append({"design": design, "generator": model})
            values.append(
                [*(counts[name] / len(ids) for name in counts), definition.cost]
            )
            metadata.append(
                {
                    "planned": len(ids),
                    "failed": counts["failed"],
                    "missing": missing,
                    "replicate_unit": "independent_generated_cohort",
                    "wilson": intervals,
                    "probability_scope": "all_prespecified_pipeline_trials",
                    "multiplicity": "marginal Wilson; prespecified joint decision",
                    "gate_power_assessed": False,
                }
            )
    return ResultsTable(
        configs,
        np.asarray(values, dtype=float),
        [
            "favor_generator",
            "favor_alternative",
            "indistinguishable",
            "failed",
            "cost",
        ],
        metadata=metadata,
    )

rng

Explicit, backend-lowered random streams.

Scope: immutable seed/stream/index addresses, separate parameter and simulation streams, and fresh NumPy generators. Optional JAX/Torch lowerings live in op_infer.adapters.rng. Addresses are host metadata, not traced array inputs.

Estimator adapters and simulation-based calibration consume these task addresses. This module wraps native RNGs; it does not implement a sampler or promise bitwise-equivalent samples across backends, devices or dependency versions.

RandomKey

Bases: _Address

Address one replayable task stream.

Attributes:

Name Type Description
schema_version Literal[1]

Derivation scheme; unknown versions are refused.

seed _Seed

Explicit unsigned 128-bit root entropy, recorded by the caller.

stream _Stream

Case-sensitive ASCII namespace, e.g. parameters or simulation.

index _Index

Unsigned 64-bit task/attempt counter, independent of worker order.

Examples:

>>> key = RandomKey(seed=2026, stream="simulation", index=8)
>>> a = key.numpy_generator().normal(size=3)
>>> np.array_equal(a, key.numpy_generator().normal(size=3))
True
>>> RandomKey.model_validate_json(key.model_dump_json()) == key
True
Source code in src/op_infer/rng.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
class RandomKey(_Address):
    """Address one replayable task stream.

    Attributes:
        schema_version: Derivation scheme; unknown versions are refused.
        seed: Explicit unsigned 128-bit root entropy, recorded by the caller.
        stream: Case-sensitive ASCII namespace, e.g. ``parameters`` or ``simulation``.
        index: Unsigned 64-bit task/attempt counter, independent of worker order.

    Examples:
        >>> key = RandomKey(seed=2026, stream="simulation", index=8)
        >>> a = key.numpy_generator().normal(size=3)
        >>> np.array_equal(a, key.numpy_generator().normal(size=3))
        True
        >>> RandomKey.model_validate_json(key.model_dump_json()) == key
        True
    """

    stream: _Stream

    def seed_sequence(self) -> np.random.SeedSequence:
        """Create a fresh SeedSequence for native adapters.

        Version 1 hashes ASCII stream bytes with SHA-256, interprets the digest
        as eight little-endian uint32 words and uses the spawn path
        ``(0x4F504931, *stream_words, index_low32, index_high32)``. The root
        entropy is the complete seed; the pool has four words. No Python hash,
        worker number, batch length or mutable spawn counter enters the identity.

        Returns:
            A fresh native SeedSequence with the recorded entropy/path.

        Raises:
            ValueError: The address was constructed with invalid metadata.
        """
        key = RandomKey.model_validate(self)
        digest = hashlib.sha256(key.stream.encode("ascii")).digest()
        words = tuple(
            int.from_bytes(digest[offset : offset + 4], "little")
            for offset in range(0, len(digest), 4)
        )
        return np.random.SeedSequence(
            key.seed,
            spawn_key=(
                _SCHEME_WORD,
                *words,
                key.index & _WORD_MASK,
                key.index >> 32,
            ),
            pool_size=4,
        )

    def numpy_generator(self) -> np.random.Generator:
        """Start a fresh PCG64DXSM generator for prior/simulation consumers.

        Repeated lowering deliberately replays the start; retain the mutable
        generator to continue a stream, or change the address for a fresh task.
        NumPy's global random state is never read or seeded.

        Returns:
            A local generator using the explicitly named PCG64DXSM algorithm.
        """
        return np.random.Generator(np.random.PCG64DXSM(self.seed_sequence()))

numpy_generator()

Start a fresh PCG64DXSM generator for prior/simulation consumers.

Repeated lowering deliberately replays the start; retain the mutable generator to continue a stream, or change the address for a fresh task. NumPy's global random state is never read or seeded.

Returns:

Type Description
Generator

A local generator using the explicitly named PCG64DXSM algorithm.

Source code in src/op_infer/rng.py
102
103
104
105
106
107
108
109
110
111
112
def numpy_generator(self) -> np.random.Generator:
    """Start a fresh PCG64DXSM generator for prior/simulation consumers.

    Repeated lowering deliberately replays the start; retain the mutable
    generator to continue a stream, or change the address for a fresh task.
    NumPy's global random state is never read or seeded.

    Returns:
        A local generator using the explicitly named PCG64DXSM algorithm.
    """
    return np.random.Generator(np.random.PCG64DXSM(self.seed_sequence()))

seed_sequence()

Create a fresh SeedSequence for native adapters.

Version 1 hashes ASCII stream bytes with SHA-256, interprets the digest as eight little-endian uint32 words and uses the spawn path (0x4F504931, *stream_words, index_low32, index_high32). The root entropy is the complete seed; the pool has four words. No Python hash, worker number, batch length or mutable spawn counter enters the identity.

Returns:

Type Description
SeedSequence

A fresh native SeedSequence with the recorded entropy/path.

Raises:

Type Description
ValueError

The address was constructed with invalid metadata.

Source code in src/op_infer/rng.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def seed_sequence(self) -> np.random.SeedSequence:
    """Create a fresh SeedSequence for native adapters.

    Version 1 hashes ASCII stream bytes with SHA-256, interprets the digest
    as eight little-endian uint32 words and uses the spawn path
    ``(0x4F504931, *stream_words, index_low32, index_high32)``. The root
    entropy is the complete seed; the pool has four words. No Python hash,
    worker number, batch length or mutable spawn counter enters the identity.

    Returns:
        A fresh native SeedSequence with the recorded entropy/path.

    Raises:
        ValueError: The address was constructed with invalid metadata.
    """
    key = RandomKey.model_validate(self)
    digest = hashlib.sha256(key.stream.encode("ascii")).digest()
    words = tuple(
        int.from_bytes(digest[offset : offset + 4], "little")
        for offset in range(0, len(digest), 4)
    )
    return np.random.SeedSequence(
        key.seed,
        spawn_key=(
            _SCHEME_WORD,
            *words,
            key.index & _WORD_MASK,
            key.index >> 32,
        ),
        pool_size=4,
    )

SimulationStreams

Bases: _Address

Supply distinct default stream addresses to prior and forward consumers.

Rejections/retries need a new explicit index or namespace; the object does not silently advance or retry anything.

Attributes:

Name Type Description
schema_version Literal[1]

Derivation scheme shared by both keys.

seed _Seed

Explicit unsigned 128-bit root entropy.

index _Index

Unsigned 64-bit task/attempt identity shared by both roles.

Examples:

>>> streams = SimulationStreams(seed=2026, index=12)
>>> streams.parameters.stream, streams.simulation.stream
('parameters', 'simulation')
>>> streams.parameters.index == streams.simulation.index
True
Source code in src/op_infer/rng.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class SimulationStreams(_Address):
    """Supply distinct default stream addresses to prior and forward consumers.

    Rejections/retries need a new explicit
    index or namespace; the object does not silently advance or retry anything.

    Attributes:
        schema_version: Derivation scheme shared by both keys.
        seed: Explicit unsigned 128-bit root entropy.
        index: Unsigned 64-bit task/attempt identity shared by both roles.

    Examples:
        >>> streams = SimulationStreams(seed=2026, index=12)
        >>> streams.parameters.stream, streams.simulation.stream
        ('parameters', 'simulation')
        >>> streams.parameters.index == streams.simulation.index
        True
    """

    @property
    def parameters(self) -> RandomKey:
        """Return the parameter key  without mutable shared state."""
        validated = SimulationStreams.model_validate(self)
        return RandomKey(
            seed=validated.seed, stream="parameters", index=validated.index
        )

    @property
    def simulation(self) -> RandomKey:
        """Return the separate simulation key for forward-model calls."""
        validated = SimulationStreams.model_validate(self)
        return RandomKey(
            seed=validated.seed, stream="simulation", index=validated.index
        )

parameters property

Return the parameter key without mutable shared state.

simulation property

Return the separate simulation key for forward-model calls.

registry

Plugin registry and configuration models.

Status: planned (no public API yet). See docs/design/proposal.md and the issue tracker.

Scope: Namespaces prior, observation, estimator and gate; entry-point discovery; Pydantic/YAML configuration models shaped like flepimop2's, without importing flepimop2 (the provider package does that).

Reference implementations to port (rule of two): flepimop2 module.py (pattern only).

SBC execution

sbc

Replayable SBC execution on trade-study, writing the existing rank schema.

Scheduling belongs to trade-study; fitting belongs to the caller's reporting estimator. This host artifact boundary accepts NumPy-compatible observations and scalar estimand draws, not traced model arrays.

SBCEstimand dataclass

A scalar truth/draw transformation with an explicitly declared atom rule.

value accepts either parameter scalars or posterior arrays. The caller supplies a prior standard deviation for contraction on the same scale.

Examples:

>>> estimand = SBCEstimand(lambda values: values["theta"], prior_sd=1.0)
>>> estimand.value({"theta": np.array([1.0, 2.0])}).tolist()
[1.0, 2.0]
>>> estimand.atoms
False
Source code in src/op_infer/sbc.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@dataclass(frozen=True)
class SBCEstimand:
    """A scalar truth/draw transformation with an explicitly declared atom rule.

    ``value`` accepts either parameter scalars or posterior arrays. The caller
    supplies a prior standard deviation for contraction on the same scale.

    Examples:
        >>> estimand = SBCEstimand(lambda values: values["theta"], prior_sd=1.0)
        >>> estimand.value({"theta": np.array([1.0, 2.0])}).tolist()
        [1.0, 2.0]
        >>> estimand.atoms
        False
    """

    value: Callable[[Mapping[str, ArrayLike]], ArrayLike]
    prior_sd: float
    atoms: bool = False

SBCExecution dataclass

Requested, written, resumed and failed replicate counts; no gate verdict.

Source code in src/op_infer/sbc.py
76
77
78
79
80
81
82
83
@dataclass(frozen=True)
class SBCExecution:
    """Requested, written, resumed and failed replicate counts; no gate verdict."""

    requested: int
    written: int
    resumed: int
    failed: int

SBCFit dataclass

Reporting-estimator draws and retained per-fit adequacy evidence.

Scalar variable arrays share one draw dimension. MCMC fits require an explicit adequate verdict and finite ESS; the runner selects evenly spaced draws up to floor(ESS). This thinning is bookkeeping, not an adequacy diagnostic or proof of independent MCMC draws. Adapters own diagnostics and their qualification.

Source code in src/op_infer/sbc.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@dataclass(frozen=True)
class SBCFit:
    """Reporting-estimator draws and retained per-fit adequacy evidence.

    Scalar variable arrays share one draw dimension. MCMC fits require an explicit
    adequate verdict and finite ESS; the runner selects evenly spaced draws up to
    floor(ESS). This thinning is bookkeeping, not an adequacy diagnostic or proof
    of independent MCMC draws. Adapters own diagnostics and their qualification.
    """

    draws: Mapping[str, ArrayLike]
    diagnostics: Mapping[str, Any]
    kind: Literal["independent", "mcmc"] = "independent"
    effective_sample_size: float | None = None
    adequate: bool | None = None

run_sbc(prior_sampler, simulator, estimator, *, estimands, observed, directory, replicate_ids, seed, provenance, mask=None, n_jobs=1, stress=None)

Schedule a prespecified SBC bank with guarded resume and counted failures.

Use the reporting estimator and the same prior/acceptance rule as training. Disjoint ID shards share one directory; failures are complete artifacts too. stress declares a perturbed generator implemented by the supplied callbacks; it enters the immutable contract so a stress bank and its control cannot share a directory (compare them with op_infer.stress.stress_verdict). Existing failure records are retained on resume. No retry, plausibility filter or result-dependent stopping changes the planned denominator. Call aggregate and gate after all shards complete; replicate sizing uses trade-study helpers.

Returns:

Type Description
SBCExecution

Completion accounting for exactly the requested replicate IDs.

Raises:

Type Description
ImportError

The optional study extra is not installed.

ValueError

The contract is invalid or existing artifacts disagree.

Source code in src/op_infer/sbc.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def run_sbc(  # noqa: PLR0913 - explicit scientific callbacks and artifact contract
    prior_sampler: Callable[[RandomKey], Mapping[str, ArrayLike]],
    simulator: Callable[[Mapping[str, ArrayLike], RandomKey], ArrayLike],
    estimator: Callable[[ArrayLike, RandomKey], SBCFit],
    *,
    estimands: Mapping[str, SBCEstimand],
    observed: ArrayLike,
    directory: str | Path,
    replicate_ids: Sequence[int],
    seed: int,
    provenance: Provenance,
    mask: ArrayLike | None = None,
    n_jobs: int = 1,
    stress: StressSpec | None = None,
) -> SBCExecution:
    """Schedule a prespecified SBC bank with guarded resume and counted failures.

    Use the reporting estimator and the same prior/acceptance rule as training.
    Disjoint ID shards share one directory; failures are complete artifacts too.
    ``stress`` declares a perturbed generator implemented by the supplied
    callbacks; it enters the immutable contract so a stress bank and its control
    cannot share a directory (compare them with ``op_infer.stress.stress_verdict``).
    Existing failure records are retained on resume. No retry, plausibility filter
    or result-dependent stopping changes the planned denominator. Call aggregate
    and gate after all shards complete; replicate sizing uses trade-study helpers.

    Returns:
        Completion accounting for exactly the requested replicate IDs.

    Raises:
        ImportError: The optional study extra is not installed.
        ValueError: The contract is invalid or existing artifacts disagree.
    """
    try:
        from trade_study import (  # noqa: PLC0415 - optional extra
            Direction,
            Observable,
            run_grid,
        )
    except ImportError as error:
        msg = "SBC execution requires pip install 'op_infer[study]'"
        raise ImportError(msg) from error
    ids = tuple(replicate_ids)
    if not ids or len(set(ids)) != len(ids):
        msg = "Provide nonempty, distinct stable replicate IDs"
        raise ValueError(msg)
    for identity in ids:
        SimulationStreams(seed=seed, index=identity)
    if not estimands or any(
        not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", name) for name in estimands
    ):
        msg = "Estimands require nonempty portable names"
        raise ValueError(msg)
    if any(not np.isfinite(e.prior_sd) or e.prior_sd <= 0 for e in estimands.values()):
        msg = "Each estimand requires a finite positive prior_sd"
        raise ValueError(msg)
    observed_array = np.asarray(observed)
    mask = np.isfinite(observed_array) if mask is None else np.asarray(mask, dtype=bool)
    if (
        mask.shape != observed_array.shape
        or not np.any(mask)
        or not np.all(np.isfinite(observed_array[mask]))
    ):
        msg = "SBC observed data require an aligned nonempty finite-cell mask"
        raise ValueError(msg)
    provenance = Provenance.model_validate(provenance)
    contract = {
        "schema_version": 1,
        "provenance": provenance.model_dump(mode="json"),
        "seed": seed,
        "estimands": {
            name: {"atoms": e.atoms, "prior_sd": e.prior_sd}
            for name, e in sorted(estimands.items())
        },
        "observed": _digest_array(observed),
        "mask": None if mask is None else _digest_array(mask),
    }
    if stress is not None:
        contract["stress"] = stress.record()
    directory = Path(directory)
    contract_identity = _require_manifest(directory, contract)
    world = _SBCWorld(
        prior_sampler,
        simulator,
        estimator,
        dict(estimands),
        observed,
        mask,
        directory,
        seed,
        contract_identity,
    )
    result = run_grid(
        world,
        _StatusScorer(),
        [{"replicate": i} for i in ids],
        [
            Observable("failed", Direction.MINIMIZE),
            Observable("resumed", Direction.MINIMIZE),
        ],
        n_reps=1,
        n_jobs=n_jobs,
    )
    failures, resumed = np.sum(result.scores, axis=0).astype(int)
    return SBCExecution(len(ids), len(ids) - int(resumed), int(resumed), int(failures))

masked_sbc

Masked-unit calibration on the existing fixed-bank SBC runner.

Full cohorts are simulated before masking. Projects supply the reporting and optional comparison estimators; scheduling and fitting are not reimplemented.

MaskedSBCExecution dataclass

Shard completion counts and the independently retainable full-bank contract.

Source code in src/op_infer/masked_sbc.py
111
112
113
114
115
116
117
118
119
@dataclass(frozen=True)
class MaskedSBCExecution:
    """Shard completion counts and the independently retainable full-bank contract."""

    contract: ArtifactReference
    requested: int
    written: int
    resumed: int
    failed: int

MaskedSBCPlan

Bases: _Record

Prespecify the complete bank and ordered units before running shards.

Only units with observed cells are eligible. An optional stratum restricts the pool. Replicate ID modulo pool length selects the removed unit, so selection is independent of shard/worker order and outcomes. Arbitrary ID subsets need not balance the units; the summary retains actual allocations.

Examples:

>>> plan = MaskedSBCPlan(
...     units=(
...         MaskedUnit(name="a", stratum="A"),
...         MaskedUnit(name="b", stratum="B"),
...     ),
...     replicate_ids=(0, 1, 2, 3),
...     seed=7,
... )
>>> plan.replicate_ids
(0, 1, 2, 3)
Source code in src/op_infer/masked_sbc.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
class MaskedSBCPlan(_Record):
    """Prespecify the complete bank and ordered units before running shards.

    Only units with observed cells are eligible. An optional stratum restricts
    the pool. Replicate ID modulo pool length selects the removed unit, so
    selection is independent of shard/worker order and outcomes. Arbitrary ID
    subsets need not balance the units; the summary retains actual allocations.

    Examples:
        >>> plan = MaskedSBCPlan(
        ...     units=(
        ...         MaskedUnit(name="a", stratum="A"),
        ...         MaskedUnit(name="b", stratum="B"),
        ...     ),
        ...     replicate_ids=(0, 1, 2, 3),
        ...     seed=7,
        ... )
        >>> plan.replicate_ids
        (0, 1, 2, 3)
    """

    units: tuple[MaskedUnit, ...]
    replicate_ids: tuple[_ID, ...]
    seed: Annotated[int, Field(ge=0, lt=2**128)]
    stratum: _Text | None = None

    @model_validator(mode="after")
    def _layout(self) -> Self:
        if (
            len(self.units) < 2
            or len({unit.name for unit in self.units}) != len(self.units)
            or not self.replicate_ids
            or len(set(self.replicate_ids)) != len(self.replicate_ids)
            or (
                self.stratum is not None
                and self.stratum not in {u.stratum for u in self.units}
            )
        ):
            msg = (
                "Masked SBC requires distinct units/IDs and a declared eligible stratum"
            )
            raise ValueError(msg)
        return self

MaskedUnit

Bases: _Record

One unit on the observation array's first axis, with a declared stratum.

Source code in src/op_infer/masked_sbc.py
59
60
61
62
63
class MaskedUnit(_Record):
    """One unit on the observation array's first axis, with a declared stratum."""

    name: _Text
    stratum: _Text

run_masked_sbc(prior_sampler, simulator, estimator, *, plan, estimands, observed, directory, provenance, replicate_ids=None, observed_mask=None, baseline=None, baseline_provenance=None, n_jobs=1)

Run a fixed masked-unit bank or disjoint shard through run_sbc.

Simulate the full cohort using the reporting prior/acceptance rule. The estimator receives the full original-shaped data, an explicit observed-cell mask and its own RandomKey. It must honor that mask; no missing-value encoding or row deletion is inferred.

The baseline has a separate provenance and independent estimator stream. Baseline failures remain unavailable comparisons without deleting the primary fit's calibration result. MCMC validation/thinning follows the existing runner.

Returns:

Type Description
MaskedSBCExecution

Requested shard counts plus the complete prespecified bank's contract.

MaskedSBCExecution

Retain that reference independently for :func:summarize_masked_sbc.

Raises:

Type Description
ValueError

Plan, masks, baseline context or existing artifacts disagree.

ImportError

The optional study extra is unavailable.

Source code in src/op_infer/masked_sbc.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def run_masked_sbc(  # noqa: PLR0913 - explicit estimators, fixed bank and provenance
    prior_sampler: Callable[[RandomKey], Mapping[str, ArrayLike]],
    simulator: Callable[[Mapping[str, ArrayLike], RandomKey], ArrayLike],
    estimator: Callable[[ArrayLike, NDArray[np.bool_], RandomKey], SBCFit],
    *,
    plan: MaskedSBCPlan,
    estimands: Mapping[str, SBCEstimand],
    observed: ArrayLike,
    directory: str | Path,
    provenance: Provenance,
    replicate_ids: Sequence[int] | None = None,
    observed_mask: ArrayLike | None = None,
    baseline: Callable[[ArrayLike, NDArray[np.bool_], RandomKey], SBCFit] | None = None,
    baseline_provenance: Provenance | None = None,
    n_jobs: int = 1,
) -> MaskedSBCExecution:
    """Run a fixed masked-unit bank or disjoint shard through ``run_sbc``.

    Simulate the full cohort
    using the reporting prior/acceptance rule. The estimator receives the full
    original-shaped data, an explicit observed-cell mask and its own RandomKey.
    It must honor that mask; no missing-value encoding or row deletion is inferred.

    The baseline has a separate provenance and independent estimator stream.
    Baseline failures remain unavailable comparisons without deleting the primary
    fit's calibration result. MCMC validation/thinning follows the existing runner.

    Returns:
        Requested shard counts plus the complete prespecified bank's contract.
        Retain that reference independently for :func:`summarize_masked_sbc`.

    Raises:
        ValueError: Plan, masks, baseline context or existing artifacts disagree.
        ImportError: The optional study extra is unavailable.
    """
    plan = MaskedSBCPlan.model_validate(plan)
    provenance = Provenance.model_validate(provenance)
    if (baseline is None) != (baseline_provenance is None):
        msg = "A baseline requires both its callback and complete provenance"
        raise ValueError(msg)
    if baseline_provenance is not None:
        baseline_provenance = Provenance.model_validate(baseline_provenance)
        _compatible_baseline(provenance, baseline_provenance)
    values = np.asarray(observed)
    mask = (
        np.isfinite(values)
        if observed_mask is None
        else np.asarray(observed_mask, dtype=bool)
    )
    if (
        values.ndim < 1
        or values.shape[0] != len(plan.units)
        or mask.shape != values.shape
        or not np.all(np.isfinite(values[mask]))
        or np.count_nonzero(mask.reshape(len(plan.units), -1).any(axis=1)) < 2
    ):
        msg = "Masked SBC requires aligned first-axis units and two observed units"
        raise ValueError(msg)
    eligible = tuple(
        i
        for i, unit in enumerate(plan.units)
        if np.any(mask[i]) and (plan.stratum is None or unit.stratum == plan.stratum)
    )
    if not eligible:
        msg = "The declared stratum has no observed eligible units"
        raise ValueError(msg)
    requested = plan.replicate_ids if replicate_ids is None else tuple(replicate_ids)
    if (
        not requested
        or len(set(requested)) != len(requested)
        or any(type(i) is not int or i not in plan.replicate_ids for i in requested)
    ):
        msg = "A shard must contain distinct IDs from the prespecified bank"
        raise ValueError(msg)
    if not estimands or any(
        not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", name)
        or isinstance(e.prior_sd, (bool, np.bool_))
        or not np.isfinite(e.prior_sd)
        or e.prior_sd <= 0
        for name, e in estimands.items()
    ):
        msg = "Masked SBC requires estimands with finite positive prior SDs"
        raise ValueError(msg)
    try:
        versions = {
            name: importlib.metadata.version(name)
            for name in ("trade-study", "numpy", "scipy", "op_infer")
        }
    except importlib.metadata.PackageNotFoundError as error:
        msg = "Masked SBC requires op_infer[study] in an installed environment"
        raise ImportError(msg) from error
    versions["python"] = platform.python_version()
    payload = {
        "schema_version": 1,
        "plan": plan.model_dump(mode="json"),
        "provenance": provenance.model_dump(mode="json"),
        "baseline_provenance": None
        if baseline_provenance is None
        else baseline_provenance.model_dump(mode="json"),
        "estimands": {
            name: {"atoms": e.atoms, "prior_sd": e.prior_sd}
            for name, e in sorted(estimands.items())
        },
        "observed": _digest_array(values),
        "mask": _digest_array(mask),
        "eligible": eligible,
        "unit_masks": {str(i): _digest_array(_unit_mask(mask, i)) for i in eligible},
        "implementation": {
            name: ArtifactReference.from_bytes(
                Path(__file__).with_name(name).read_bytes(), kind="python-source-v1"
            ).model_dump(mode="json")
            for name in ("masked_sbc.py", "sbc.py", "calibrate.py")
        },
        "backend_versions": versions,
    }
    root = Path(directory)
    contract = ArtifactReference(
        kind="masked-sbc-contract-v1",
        digest=_require_manifest(root, payload, filename="masked-sbc-manifest.meta"),
    )
    written = resumed = failed = 0
    for index in eligible:
        ids = tuple(i for i in requested if eligible[i % len(eligible)] == index)
        if not ids:
            continue
        unit_mask = _unit_mask(mask, index)
        result = run_sbc(
            prior_sampler,
            simulator,
            _MaskedEstimator(estimator, baseline, estimands, unit_mask, index),
            estimands=estimands,
            observed=values,
            mask=unit_mask,
            directory=root / f"unit_{index:06d}",
            replicate_ids=ids,
            seed=plan.seed,
            provenance=_unit_provenance(provenance, contract, index),
            n_jobs=n_jobs,
        )
        written += result.written
        resumed += result.resumed
        failed += result.failed
    return MaskedSBCExecution(contract, len(requested), written, resumed, failed)

summarize_masked_sbc(directory, *, expected, bins=20, power_floor=POWER_FLOOR, alpha=0.05)

Read the complete planned bank, retaining missing and failed comparisons.

Each complete group reuses existing rank aggregation. BH adjustment is within each group; overlapping overall/stratum summaries are not a qualified joint gate. Raw width ratios/differences have no implicit informativeness threshold.

Returns:

Type Description
dict[str, Any]

Overall/stratum planned denominators, guarded records and width summaries.

dict[str, Any]

Incomplete groups have no rank reading; zero-plan strata remain visible.

dict[str, Any]

Baseline-zero SDs retain differences and unavailable ratio denominators.

Raises:

Type Description
ValueError

Expected contract, group manifest, record or metadata differs.

OSError

Required contract metadata cannot be read.

Source code in src/op_infer/masked_sbc.py
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def summarize_masked_sbc(
    directory: str | Path,
    *,
    expected: ArtifactReference,
    bins: int = 20,
    power_floor: int = POWER_FLOOR,
    alpha: float = 0.05,
) -> dict[str, Any]:
    """Read the complete planned bank, retaining missing and failed comparisons.

    Each complete group reuses existing rank aggregation. BH adjustment is within each
    group; overlapping overall/stratum summaries are not a qualified joint gate.
    Raw width ratios/differences have no implicit informativeness threshold.

    Returns:
        Overall/stratum planned denominators, guarded records and width summaries.
        Incomplete groups have no rank reading; zero-plan strata remain visible.
        Baseline-zero SDs retain differences and unavailable ratio denominators.

    Raises:
        ValueError: Expected contract, group manifest, record or metadata differs.
        OSError: Required contract metadata cannot be read.
    """
    bins, power_floor, alpha = _rank_settings(bins, power_floor, alpha)
    root = Path(directory)
    encoded = (root / "masked-sbc-manifest.meta").read_bytes()
    actual = ArtifactReference.from_bytes(encoded, kind="masked-sbc-contract-v1")
    if actual != expected:
        msg = "Masked SBC contract differs from the independent expected reference"
        raise ValueError(msg)
    payload = json.loads(encoded)
    if type(payload.get("schema_version")) is not int or payload["schema_version"] != 1:
        msg = "Unsupported masked SBC schema"
        raise ValueError(msg)
    plan = MaskedSBCPlan.model_validate_json(json.dumps(payload["plan"]))
    provenance = Provenance.model_validate_json(json.dumps(payload["provenance"]))
    eligible = tuple(payload["eligible"])
    names = tuple(payload["estimands"])
    rows = []
    checked = {}
    for identity in plan.replicate_ids:
        index = eligible[identity % len(eligible)]
        unit = plan.units[index]
        folder = root / f"unit_{index:06d}"
        path = folder / f"rep_{identity:020d}.json"
        record = None
        evidence = None
        if not path.exists():
            status, reason = "missing", "replicate_not_written"
        else:
            if index not in checked:
                manifest = (folder / "sbc-manifest.meta").read_bytes()
                required = {
                    "schema_version": 1,
                    "provenance": _unit_provenance(
                        provenance, expected, index
                    ).model_dump(mode="json"),
                    "seed": plan.seed,
                    "estimands": payload["estimands"],
                    "observed": payload["observed"],
                    "mask": payload["unit_masks"][str(index)],
                }
                if json.loads(manifest) != required:
                    msg = "Masked unit manifest differs from the planned contract"
                    raise ValueError(msg)
                checked[index] = "sha256:" + hashlib.sha256(manifest).hexdigest()
            record = json.loads(path.read_text())
            if record.get("_meta") != {
                "runner_schema": 1,
                "contract": checked[index],
                "replicate": identity,
            }:
                msg = "Masked replicate identity or contract differs"
                raise ValueError(msg)
            if record.get("_failed") is True:
                status, reason = "failed", record["_reason"]
            else:
                evidence = _read_evidence(record, index, payload)
                status, reason = "successful", None
        rows.append(
            {
                "replicate_id": identity,
                "unit": unit.name,
                "stratum": unit.stratum,
                "status": status,
                "reason": reason,
                "informativeness": None
                if evidence is None
                else evidence.model_dump(mode="json"),
                "record": record,
            }
        )

    def summarize(selected: Sequence[dict[str, Any]]) -> dict[str, Any]:
        return _group(selected, names, bins=bins, power_floor=power_floor, alpha=alpha)

    return {
        "schema_version": 1,
        "contract": expected.model_dump(mode="json"),
        "provenance": provenance.model_dump(mode="json"),
        "plan": plan.model_dump(mode="json"),
        "overall": summarize(rows),
        "baseline_provenance": payload["baseline_provenance"],
        "implementation": payload["implementation"],
        "backend_versions": payload["backend_versions"],
        "rank_settings": {"bins": bins, "power_floor": power_floor, "alpha": alpha},
        "report_implementation": {
            name: ArtifactReference.from_bytes(
                Path(__file__).with_name(name).read_bytes(), kind="python-source-v1"
            ).model_dump(mode="json")
            for name in ("masked_sbc.py", "calibrate.py")
        },
        "report_backend_versions": {
            name: importlib.metadata.version(name)
            for name in ("numpy", "scipy", "op_infer")
        }
        | {"python": platform.python_version()},
        "by_stratum": {
            stratum: summarize([r for r in rows if r["stratum"] == stratum])
            for stratum in dict.fromkeys(u.stratum for u in plan.units)
        },
        "replicates": [{k: v for k, v in row.items() if k != "record"} for row in rows],
        "multiplicity": "within-group BH; overlapping groups need joint qualification",
        "adequacy_status": "not_assessed",
    }

stress

Robustness of an unchanged estimator under a declared perturbed generator.

SBC under the training generator checks the computation, not what happens when the data come from a different generator (Cannon, Ward and Schmon 2022, arXiv:2209.01845; Ward et al. 2022, arXiv:2210.06564). A stress run draws a replicate bank from a declared perturbation while the estimator is unchanged; a paired control run uses the same seed, replicate IDs, estimator and estimands without it. The comparison is a robustness reading, not a calibration reading.

StressSpec dataclass

A named, declared perturbation of the generator.

The record enters the immutable SBC run contract, so a stress bank cannot share a directory with its control or with a different stress. settings must be JSON-serialisable (plain Python numbers, strings, lists and dicts; no NumPy scalars) and every field, including description, is part of the contract identity.

Examples:

>>> spec = StressSpec("noise_x2", "observation noise doubled", {"s": 2.0})
>>> spec.record()["settings"]
{'s': 2.0}
Source code in src/op_infer/stress.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
@dataclass(frozen=True)
class StressSpec:
    """A named, declared perturbation of the generator.

    The record enters the immutable SBC run contract, so a stress bank cannot
    share a directory with its control or with a different stress. ``settings``
    must be JSON-serialisable (plain Python numbers, strings, lists and dicts; no
    NumPy scalars) and every field, including ``description``, is part of the
    contract identity.

    Examples:
        >>> spec = StressSpec("noise_x2", "observation noise doubled", {"s": 2.0})
        >>> spec.record()["settings"]
        {'s': 2.0}
    """

    name: str
    description: str
    settings: Mapping[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Reject names that are not portable identifiers.

        Raises:
            ValueError: The name is not a portable identifier.
        """
        if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", self.name):
            msg = "StressSpec names must be portable identifiers"
            raise ValueError(msg)

    def record(self) -> dict[str, Any]:
        """Return the JSON-compatible record stored in the run contract."""
        return {
            "name": self.name,
            "description": self.description,
            "settings": dict(self.settings),
        }

__post_init__()

Reject names that are not portable identifiers.

Raises:

Type Description
ValueError

The name is not a portable identifier.

Source code in src/op_infer/stress.py
47
48
49
50
51
52
53
54
55
def __post_init__(self) -> None:
    """Reject names that are not portable identifiers.

    Raises:
        ValueError: The name is not a portable identifier.
    """
    if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", self.name):
        msg = "StressSpec names must be portable identifiers"
        raise ValueError(msg)

record()

Return the JSON-compatible record stored in the run contract.

Source code in src/op_infer/stress.py
57
58
59
60
61
62
63
def record(self) -> dict[str, Any]:
    """Return the JSON-compatible record stored in the run contract."""
    return {
        "name": self.name,
        "description": self.description,
        "settings": dict(self.settings),
    }

stress_verdict(stress_directory, control_directory, estimands, *, level, floor, drop, confidence=0.95)

Compare central coverage under stress with the paired control.

The two banks must come from run_sbc: the stress bank's manifest must carry a stress record and otherwise equal the control's manifest (same seed, provenance, estimands and observations). Replicates are paired by file name (replicate ID) and used only if both succeeded; failures and unpaired replicates are counted, never dropped silently. An estimand passes when its stress coverage point estimate is at least max(floor, control_coverage - drop); the Wilson intervals are reported but play no part in the verdict, so small banks give noisy readings. The caller supplies floor and drop (no defaults): they are reading-rule choices, to be fixed before the banks are read. This is a robustness reading; it does not certify calibration and the intervals are marginal, without adjustment across estimands.

Parameters:

Name Type Description Default
stress_directory str | Path

SBC bank from the perturbed generator.

required
control_directory str | Path

SBC bank from the same seed and IDs without the stress.

required
estimands Sequence[str]

Distinct estimand names to read (a list, not a string).

required
level float

Central interval level in (0, 1).

required
floor float

Absolute coverage floor in [0, 1].

required
drop float

Allowed drop from the control coverage, in [0, 1].

required
confidence float

Wilson interval confidence in (0, 1).

0.95

Returns:

Type Description
dict[str, Any]

JSON-compatible result. n_stress and n_control count all

dict[str, Any]

replicate files of each bank, n_failed_* the failed ones,

dict[str, Any]

n_unpaired the replicate IDs present in only one bank and

dict[str, Any]

n_paired the pairs successful in both banks, on which every

dict[str, Any]

coverage is computed. One row per estimand holds both coverages with

dict[str, Any]

Wilson intervals, the requirement and the verdict; passes is true

dict[str, Any]

only if every estimand passes.

Raises:

Type Description
ValueError

Settings are invalid, the banks are not a stress and control pair, a record lacks a requested estimand, or no replicate is paired and successful.

Examples:

Requires the study extra; the doctest is skipped, and tests/test_stress_sbc.py runs the full workflow.

>>> v = stress_verdict(
...     "stress-bank",
...     "control-bank",
...     ["theta"],
...     level=0.9,
...     floor=0.8,
...     drop=0.1,
... )
>>> v["passes"]
True
Source code in src/op_infer/stress.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def stress_verdict(  # noqa: PLR0913 - explicit reading rule, no defaults
    stress_directory: str | Path,
    control_directory: str | Path,
    estimands: Sequence[str],
    *,
    level: float,
    floor: float,
    drop: float,
    confidence: float = 0.95,
) -> dict[str, Any]:
    """Compare central coverage under stress with the paired control.

    The two banks must come from ``run_sbc``: the stress bank's manifest must
    carry a ``stress`` record and otherwise equal the control's manifest (same
    seed, provenance, estimands and observations). Replicates are paired by file
    name (replicate ID) and used only if both succeeded; failures and unpaired
    replicates are counted, never dropped silently. An estimand passes when its
    stress coverage **point estimate** is at least ``max(floor, control_coverage -
    drop)``; the Wilson intervals are reported but play no part in the verdict,
    so small banks give noisy readings. The caller supplies ``floor`` and
    ``drop`` (no defaults): they are reading-rule choices, to be fixed before the
    banks are read. This is a robustness reading; it does not certify calibration
    and the intervals are marginal, without adjustment across estimands.

    Args:
        stress_directory: SBC bank from the perturbed generator.
        control_directory: SBC bank from the same seed and IDs without the stress.
        estimands: Distinct estimand names to read (a list, not a string).
        level: Central interval level in (0, 1).
        floor: Absolute coverage floor in [0, 1].
        drop: Allowed drop from the control coverage, in [0, 1].
        confidence: Wilson interval confidence in (0, 1).

    Returns:
        JSON-compatible result. ``n_stress`` and ``n_control`` count all
        replicate files of each bank, ``n_failed_*`` the failed ones,
        ``n_unpaired`` the replicate IDs present in only one bank and
        ``n_paired`` the pairs successful in both banks, on which every
        coverage is computed. One row per estimand holds both coverages with
        Wilson intervals, the requirement and the verdict; ``passes`` is true
        only if every estimand passes.

    Raises:
        ValueError: Settings are invalid, the banks are not a stress and control
            pair, a record lacks a requested estimand, or no replicate is paired
            and successful.

    Examples:
        Requires the study extra; the doctest is skipped, and
        ``tests/test_stress_sbc.py`` runs the full workflow.

        >>> v = stress_verdict(
        ...     "stress-bank",
        ...     "control-bank",
        ...     ["theta"],
        ...     level=0.9,
        ...     floor=0.8,
        ...     drop=0.1,
        ... )  # doctest: +SKIP
        >>> v["passes"]  # doctest: +SKIP
        True
    """
    _number("level", level, 0.0, 1.0, open_=True)
    _number("confidence", confidence, 0.0, 1.0, open_=True)
    _number("floor", floor, 0.0, 1.0, open_=False)
    _number("drop", drop, 0.0, 1.0, open_=False)
    if isinstance(estimands, str):
        msg = "estimands must be a sequence of names, not a string"
        raise TypeError(msg)
    names = list(estimands)
    if not names or len(set(names)) != len(names):
        msg = "provide distinct estimand names"
        raise ValueError(msg)
    s_dir, c_dir = Path(stress_directory), Path(control_directory)
    _check_pair(s_dir, c_dir)
    stress, control = _replicates(s_dir), _replicates(c_dir)
    both = [
        n
        for n in sorted(set(stress) & set(control))
        if _ok(stress[n]) and _ok(control[n])
    ]
    if not both:
        msg = "no replicate is paired and successful in both banks"
        raise ValueError(msg)
    covs = {
        which: coverage_summary(
            {e: [_pit(n, records[n], e) for n in both] for e in names},
            levels=(level,),
            confidence=confidence,
        )
        for which, records in (("stress", stress), ("control", control))
    }
    rows: dict[str, Any] = {}
    for e in names:
        s_row = covs["stress"]["estimands"][e][0]
        c_row = covs["control"]["estimands"][e][0]
        need = max(floor, c_row["estimate"] - drop)
        rows[e] = {
            "stress": {k: s_row[k] for k in ("estimate", "low", "high")},
            "control": {k: c_row[k] for k in ("estimate", "low", "high")},
            "required": float(need),
            "passes": bool(s_row["estimate"] >= need),
        }
    return {
        "reading": "robustness under a declared perturbation, not calibration",
        "settings": {
            "level": level,
            "floor": floor,
            "drop": drop,
            "confidence": confidence,
            "method": "wilson",
            "decision": "point estimate",
        },
        "n_paired": len(both),
        "n_stress": len(stress),
        "n_control": len(control),
        "n_failed_stress": sum(not _ok(r) for r in stress.values()),
        "n_failed_control": sum(not _ok(r) for r in control.values()),
        "n_unpaired": len(set(stress) ^ set(control)),
        "estimands": rows,
        "passes": bool(all(r["passes"] for r in rows.values())),
        "multiplicity": "marginal; no adjustment across estimands",
    }

Native masked NPE

sbi

Bounded native sbi NPE adapter for masked cohorts and seed ensembles.

This adapter wraps native sbi density estimation; it implements neither flows nor posterior calibration. CPU or one explicitly selected CUDA device, float32, single-round training and full-real parameter support are the qualified scope.

NpeEnsemble dataclass

Equal-weight native seed members, distinct from MCMC chains.

Members must agree on prior, model, design, code, target and all settings except the training key. Gate-driven retraining creates a new ensemble and provenance; it never turns a failed calibration result into a pass by itself.

Source code in src/op_infer/adapters/sbi.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
@dataclass(frozen=True)
class NpeEnsemble:
    """Equal-weight native seed members, distinct from MCMC chains.

    Members must agree on prior, model, design, code, target and all settings
    except the training key. Gate-driven retraining creates a new ensemble and
    provenance; it never turns a failed calibration result into a pass by itself.
    """

    members: tuple[NpeFit, ...]

    def __post_init__(self) -> None:
        """Validate the complete common scientific and training contract.

        Raises:
            ValueError: Members are absent, mismatched or share effective seeds.
        """
        if not isinstance(self.members, tuple) or not self.members:
            msg = "NPE ensembles require a nonempty immutable tuple of members"
            raise ValueError(msg)
        first = self.members[0]
        controls = first.settings.model_dump(exclude={"key"})
        for member in self.members:
            _require_provenance(member.settings, member.provenance)
            if member.settings.model_dump(exclude={"key"}) != controls:
                msg = "NPE ensemble settings mismatch"
                raise ValueError(msg)
            member.provenance.require_match(
                first.provenance.model_copy(
                    update={
                        "estimator_settings": member.provenance.estimator_settings,
                    }
                )
            )
        torch_generators(tuple(m.settings.key for m in self.members))

    def sample(
        self,
        observation: Tensor,
        *,
        per_seed: int,
        key: RandomKey,
    ) -> Posterior[Tensor]:
        """Draw exactly per_seed samples from every native estimator.

        Returns:
            Native named posterior with separate seed/draw coordinates and
            conditioning/member/sampling provenance. Latent-state variables can
            be named parameters and are retained for subsequent forecasting.

        Raises:
            ValueError: Observation layout or draw count is invalid.
        """
        torch, _inference, _nets = _native()
        settings = self.members[0].settings
        if isinstance(per_seed, bool) or not isinstance(per_seed, int) or per_seed < 2:
            msg = "per_seed must be an integer >= 2"
            raise ValueError(msg)
        target = _npe_device(settings.device)
        condition = torch.as_tensor(observation, dtype=torch.float32, device=target)
        if condition.ndim != 2:
            msg = "Sample one cohort (design units, features) at a time"
            raise ValueError(msg)
        torch_generators((*tuple(m.settings.key for m in self.members), key))
        condition = condition.unsqueeze(0)
        _presence(condition, settings)
        parts = []
        with _torch_scope(key, device=settings.device), torch.no_grad():
            for member in self.members:
                estimator = cast("Any", member.estimator).eval()
                parts.append(
                    estimator.sample((per_seed,), condition=condition).reshape(
                        per_seed, len(settings.parameter_names)
                    )
                )
        values = torch.stack(parts)
        if not bool(torch.isfinite(values).all()):
            msg = "NPE produced non-finite draws; retain a failed fit/sample record"
            raise ValueError(msg)
        references = {
            "ensemble": _ensemble_reference(self.members).model_dump(mode="json"),
            "sample_key": key.model_dump(mode="json"),
            "per_seed": per_seed,
            "condition": hashlib.sha256(
                condition.detach().cpu().numpy().tobytes()
            ).hexdigest(),
        }
        provenance = self.members[0].provenance.model_copy(
            update={
                "estimator_stage": "reporting",
                "estimator_settings": ArtifactReference.from_bytes(
                    json.dumps(references, sort_keys=True).encode(),
                    kind="sbi-reporting-samples-v1",
                ),
            }
        )
        return Posterior(
            tuple(
                SampledVariable(name, values[:, :, i], ())
                for i, name in enumerate(settings.parameter_names)
            ),
            (
                Coordinate(
                    name="seed",
                    labels=tuple(
                        m.settings.key.model_dump_json() for m in self.members
                    ),
                ),
                Coordinate(name="draw", labels=tuple(range(per_seed))),
            ),
            provenance,
            sample_axis="seed",
        )

__post_init__()

Validate the complete common scientific and training contract.

Raises:

Type Description
ValueError

Members are absent, mismatched or share effective seeds.

Source code in src/op_infer/adapters/sbi.py
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def __post_init__(self) -> None:
    """Validate the complete common scientific and training contract.

    Raises:
        ValueError: Members are absent, mismatched or share effective seeds.
    """
    if not isinstance(self.members, tuple) or not self.members:
        msg = "NPE ensembles require a nonempty immutable tuple of members"
        raise ValueError(msg)
    first = self.members[0]
    controls = first.settings.model_dump(exclude={"key"})
    for member in self.members:
        _require_provenance(member.settings, member.provenance)
        if member.settings.model_dump(exclude={"key"}) != controls:
            msg = "NPE ensemble settings mismatch"
            raise ValueError(msg)
        member.provenance.require_match(
            first.provenance.model_copy(
                update={
                    "estimator_settings": member.provenance.estimator_settings,
                }
            )
        )
    torch_generators(tuple(m.settings.key for m in self.members))

sample(observation, *, per_seed, key)

Draw exactly per_seed samples from every native estimator.

Returns:

Type Description
Posterior[Tensor]

Native named posterior with separate seed/draw coordinates and

Posterior[Tensor]

conditioning/member/sampling provenance. Latent-state variables can

Posterior[Tensor]

be named parameters and are retained for subsequent forecasting.

Raises:

Type Description
ValueError

Observation layout or draw count is invalid.

Source code in src/op_infer/adapters/sbi.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
def sample(
    self,
    observation: Tensor,
    *,
    per_seed: int,
    key: RandomKey,
) -> Posterior[Tensor]:
    """Draw exactly per_seed samples from every native estimator.

    Returns:
        Native named posterior with separate seed/draw coordinates and
        conditioning/member/sampling provenance. Latent-state variables can
        be named parameters and are retained for subsequent forecasting.

    Raises:
        ValueError: Observation layout or draw count is invalid.
    """
    torch, _inference, _nets = _native()
    settings = self.members[0].settings
    if isinstance(per_seed, bool) or not isinstance(per_seed, int) or per_seed < 2:
        msg = "per_seed must be an integer >= 2"
        raise ValueError(msg)
    target = _npe_device(settings.device)
    condition = torch.as_tensor(observation, dtype=torch.float32, device=target)
    if condition.ndim != 2:
        msg = "Sample one cohort (design units, features) at a time"
        raise ValueError(msg)
    torch_generators((*tuple(m.settings.key for m in self.members), key))
    condition = condition.unsqueeze(0)
    _presence(condition, settings)
    parts = []
    with _torch_scope(key, device=settings.device), torch.no_grad():
        for member in self.members:
            estimator = cast("Any", member.estimator).eval()
            parts.append(
                estimator.sample((per_seed,), condition=condition).reshape(
                    per_seed, len(settings.parameter_names)
                )
            )
    values = torch.stack(parts)
    if not bool(torch.isfinite(values).all()):
        msg = "NPE produced non-finite draws; retain a failed fit/sample record"
        raise ValueError(msg)
    references = {
        "ensemble": _ensemble_reference(self.members).model_dump(mode="json"),
        "sample_key": key.model_dump(mode="json"),
        "per_seed": per_seed,
        "condition": hashlib.sha256(
            condition.detach().cpu().numpy().tobytes()
        ).hexdigest(),
    }
    provenance = self.members[0].provenance.model_copy(
        update={
            "estimator_stage": "reporting",
            "estimator_settings": ArtifactReference.from_bytes(
                json.dumps(references, sort_keys=True).encode(),
                kind="sbi-reporting-samples-v1",
            ),
        }
    )
    return Posterior(
        tuple(
            SampledVariable(name, values[:, :, i], ())
            for i, name in enumerate(settings.parameter_names)
        ),
        (
            Coordinate(
                name="seed",
                labels=tuple(
                    m.settings.key.model_dump_json() for m in self.members
                ),
            ),
            Coordinate(name="draw", labels=tuple(range(per_seed))),
        ),
        provenance,
        sample_axis="seed",
    )

NpeFit dataclass

Native density estimator with its exact fit identity; no gate verdict.

Source code in src/op_infer/adapters/sbi.py
305
306
307
308
309
310
311
312
313
@dataclass(frozen=True)
class NpeFit:
    """Native density estimator with its exact fit identity; no gate verdict."""

    estimator: object = field(repr=False)
    settings: NpeSettings
    provenance: Provenance
    n_simulations: int
    epochs: int

NpeSettings

Bases: BaseModel

Immutable architecture, training controls, named parameters and task key.

Examples:

>>> settings = NpeSettings(
...     key=RandomKey(seed=2026, stream="training"),
...     parameter_names=("theta", "latent"),
...     n_max=3,
...     feature_dim=2,
... )
>>> settings.parameter_names, settings.n_max
(('theta', 'latent'), 3)
>>> npe_settings_reference(settings).kind
'sbi-npe-settings-v1'
Source code in src/op_infer/adapters/sbi.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
class NpeSettings(BaseModel):
    """Immutable architecture, training controls, named parameters and task key.

    Examples:
        >>> settings = NpeSettings(
        ...     key=RandomKey(seed=2026, stream="training"),
        ...     parameter_names=("theta", "latent"),
        ...     n_max=3,
        ...     feature_dim=2,
        ... )
        >>> settings.parameter_names, settings.n_max
        (('theta', 'latent'), 3)
        >>> npe_settings_reference(settings).kind
        'sbi-npe-settings-v1'
    """

    model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
    key: RandomKey
    parameter_names: tuple[str, ...]
    n_max: int = Field(ge=1)
    feature_dim: int = Field(ge=1)
    latent_dim: int = Field(default=16, ge=1)
    embedding_dim: int = Field(default=16, ge=1)
    hidden_features: int = Field(default=32, ge=1)
    num_transforms: int = Field(default=3, ge=1)
    mask_probability: float = Field(default=0.0, ge=0.0, le=1.0, allow_inf_nan=False)
    batch_size: int = Field(default=128, ge=2)
    validation_fraction: float = Field(default=0.1, gt=0.0, lt=1.0, allow_inf_nan=False)
    max_epochs: int = Field(default=200, ge=1)
    stop_after_epochs: int = Field(default=20, ge=1)
    learning_rate: float = Field(default=5e-4, gt=0.0, allow_inf_nan=False)
    model: Literal["maf"] = "maf"
    device: str = Field(
        default="cpu",
        pattern=r"^(cpu|cuda:(0|[1-9][0-9]*))$",
        exclude_if=lambda value: value == "cpu",
    )

    @model_validator(mode="after")
    def _names(self) -> NpeSettings:
        """Return settings with a complete distinct scalar parameter layout.

        Raises:
            ValueError: Parameter names are missing or repeated.
        """
        if not self.parameter_names or len(set(self.parameter_names)) != len(
            self.parameter_names
        ):
            msg = "NPE requires distinct nonempty parameter names"
            raise ValueError(msg)
        for name in self.parameter_names:
            Coordinate(name=name, labels=(0,))
        return self

build_masked_set_embedding(settings)

Build per-cohort mean/count pooling with training-only unit removal.

Returns:

Type Description
Module

A native Torch module mapping (batch, units, features) to embeddings.

Module

State dictionaries are portable through this factory; no local class

Module

object is serialized.

Source code in src/op_infer/adapters/sbi.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def build_masked_set_embedding(settings: NpeSettings) -> Module:
    """Build per-cohort mean/count pooling with training-only unit removal.

    Returns:
        A native Torch module mapping (batch, units, features) to embeddings.
        State dictionaries are portable through this factory; no local class
        object is serialized.
    """
    torch, _inference, _nets = _native()

    class MaskedSetEmbedding(torch.nn.Module):  # type: ignore[misc, name-defined]
        def __init__(self) -> None:
            super().__init__()
            options = {"dtype": torch.float32, "device": "cpu"}
            self.unit = torch.nn.Sequential(
                torch.nn.Linear(
                    settings.feature_dim, settings.hidden_features, **options
                ),
                torch.nn.ReLU(),
                torch.nn.Linear(
                    settings.hidden_features, settings.latent_dim, **options
                ),
                torch.nn.ReLU(),
            )
            self.head = torch.nn.Sequential(
                torch.nn.Linear(
                    settings.latent_dim + 1, settings.embedding_dim, **options
                ),
                torch.nn.ReLU(),
            )

        def forward(self, features: Tensor) -> Tensor:
            """Embed each cohort using its own presence count."""
            present = _presence(features, settings)
            if self.training and settings.mask_probability > 0:
                remove = (
                    torch.rand(
                        len(features), device=features.device, dtype=torch.float32
                    )
                    < settings.mask_probability
                ) & (present.sum(-1) > 1)
                scores = torch.rand(
                    present.shape, device=features.device, dtype=torch.float32
                ).masked_fill(~present, -1.0)
                victim = scores.argmax(-1)
                present = present.clone()
                present[
                    torch.arange(len(features), device=features.device)[remove],
                    victim[remove],
                ] = False
            weights = present.unsqueeze(-1).to(features.dtype)
            encoded = self.unit(torch.nan_to_num(features, nan=0.0)) * weights
            count = weights.sum(1)
            pooled = encoded.sum(1) / count.clamp_min(1.0)
            return cast(
                "Tensor", self.head(torch.cat((pooled, count / settings.n_max), dim=-1))
            )

    return cast("Module", MaskedSetEmbedding())

fit_npe(theta, observations, *, prior, settings, provenance, checkpoint_path=None, resume_from=None, until_epoch=None, checkpoint_interval=1, borrow_bank=False)

Train one native sbi NPE on a prespecified, prior-coherent simulation bank.

Used by masked-cohort design workflows. The caller owns the prior/observation/acceptance provenance. Full-real parameter support is required because masked inference samples the estimator directly, bypassing DirectPosterior's prior-support rejection. Transform bounded parameters before fitting and record that transformation in prior/parameter provenance.

checkpoint_path saves resumable native training boundaries, distinct from save_npe inference snapshots. resume_from requires the same ordered effective training bank, complete provenance, settings and runtime. The optional until_epoch is a cumulative completed-epoch limit for this call; the original native budget permits settings.max_epochs + 1 epochs. Chunk boundaries do not change the declared full budget or early-stop rule. Checkpoints require sbi 0.27.0 and serialized CPU calls, like native fitting. borrow_bank=True retains contiguous CPU float32 tensors (including native tensors backed by copy-on-write NumPy memory maps) without full observation copies. Keep their storage immutable for the duration of fitting. Native parameter standardization still materializes the training theta subset.

Parameters:

Name Type Description Default
theta Tensor

Aligned simulation-by-parameter training targets.

required
observations Tensor

Simulation-by-unit-by-feature data, with all-NaN absent units.

required
prior Distribution

Native full-real-support prior used to generate the training bank, with distribution tensors on the declared execution device.

required
settings NpeSettings

Fixed architecture, full native epoch budget and training key.

required
provenance Provenance

Independently supplied scientific/settings/runtime contract.

required
checkpoint_path str | Path | None

Optional atomic output for resumable training boundaries.

None
resume_from str | Path | None

Previous training checkpoint, requiring the same effective bank.

None
until_epoch int | None

Optional cumulative completed-epoch limit, at least two.

None
checkpoint_interval int

Positive interval between checkpointed complete epochs; the first epoch and requested chunk limit are also saved.

1
borrow_bank bool

Retain original CPU float32 observation storage without full bank copies; requires contiguous tensors and qualified sbi 0.27.0.

False

Returns:

Type Description
NpeFit

Native float32 fit on the declared device, retaining named variables and

NpeFit

exact provenance.

Raises:

Type Description
ValueError

Data, prior support or provenance do not meet this contract.

Source code in src/op_infer/adapters/sbi.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
def fit_npe(  # noqa: PLR0913
    theta: Tensor,
    observations: Tensor,
    *,
    prior: Distribution,
    settings: NpeSettings,
    provenance: Provenance,
    checkpoint_path: str | Path | None = None,
    resume_from: str | Path | None = None,
    until_epoch: int | None = None,
    checkpoint_interval: int = 1,
    borrow_bank: bool = False,
) -> NpeFit:
    """Train one native sbi NPE on a prespecified, prior-coherent simulation bank.

    Used by masked-cohort design workflows. The caller
    owns the prior/observation/acceptance provenance. Full-real parameter support
    is required because masked inference samples the estimator directly, bypassing
    DirectPosterior's prior-support rejection. Transform bounded parameters before
    fitting and record that transformation in prior/parameter provenance.

    ``checkpoint_path`` saves resumable native training boundaries, distinct from
    ``save_npe`` inference snapshots. ``resume_from`` requires the same ordered
    effective training bank, complete provenance, settings and runtime. The
    optional ``until_epoch`` is a cumulative completed-epoch limit for this call;
    the original native budget permits ``settings.max_epochs + 1`` epochs.
    Chunk boundaries do not change the declared full budget or early-stop rule.
    Checkpoints require sbi 0.27.0 and serialized CPU calls, like native fitting.
    ``borrow_bank=True`` retains contiguous CPU float32 tensors (including native
    tensors backed by copy-on-write NumPy memory maps) without full observation
    copies. Keep their storage immutable for the duration of fitting. Native
    parameter standardization still materializes the training theta subset.

    Args:
        theta: Aligned simulation-by-parameter training targets.
        observations: Simulation-by-unit-by-feature data, with all-NaN absent units.
        prior: Native full-real-support prior used to generate the training bank,
            with distribution tensors on the declared execution device.
        settings: Fixed architecture, full native epoch budget and training key.
        provenance: Independently supplied scientific/settings/runtime contract.
        checkpoint_path: Optional atomic output for resumable training boundaries.
        resume_from: Previous training checkpoint, requiring the same effective bank.
        until_epoch: Optional cumulative completed-epoch limit, at least two.
        checkpoint_interval: Positive interval between checkpointed complete epochs;
            the first epoch and requested chunk limit are also saved.
        borrow_bank: Retain original CPU float32 observation storage without full
            bank copies; requires contiguous tensors and qualified sbi 0.27.0.

    Returns:
        Native float32 fit on the declared device, retaining named variables and
        exact provenance.

    Raises:
        ValueError: Data, prior support or provenance do not meet this contract.
    """
    _torch, inference, nets = _native()
    _require_provenance(settings, provenance)
    target = _npe_device(settings.device)
    limit = settings.max_epochs + 1 if until_epoch is None else until_epoch
    if (
        type(limit) is not int
        or not 2 <= limit <= settings.max_epochs + 1
        or type(checkpoint_interval) is not int
        or checkpoint_interval < 1
        or (until_epoch is not None and checkpoint_path is None)
    ):
        msg = (
            "Use integer epoch controls within the full budget, until_epoch >= 2 "
            "and a checkpoint path"
        )
        raise ValueError(msg)
    checkpointed = checkpoint_path is not None or resume_from is not None
    if checkpointed and target.type != "cpu":
        msg = "NPE training checkpoints currently require device='cpu'"
        raise ValueError(msg)
    if checkpointed or borrow_bank:
        require_checkpoint_runtime()
    theta, observations = _prepare_bank(
        theta, observations, prior, settings, borrow_bank=borrow_bank
    )
    bank = bank_digest(theta, observations) if checkpointed else ""
    with (
        tempfile.TemporaryDirectory(prefix="op-infer-npe-") as logs,
        _torch_scope(settings.key, device=settings.device),
        closing(
            importlib.import_module("torch.utils.tensorboard").SummaryWriter(logs)
        ) as writer,
    ):
        embedding = build_masked_set_embedding(settings)
        builder = nets.posterior_nn(
            model=settings.model,
            embedding_net=embedding,
            hidden_features=settings.hidden_features,
            num_transforms=settings.num_transforms,
            z_score_theta="independent",
            z_score_x="none",
        )
        native = inference.NPE(
            prior=prior,
            density_estimator=builder,
            device=settings.device,
            show_progress_bars=False,
            summary_writer=writer,
        )
        if borrow_bank:
            borrow_simulations(native, theta, observations)
        else:
            native.append_simulations(
                theta,
                observations,
                exclude_invalid_x=False,
                data_device="cpu",
            )
        if len(native.get_simulations()[0]) != len(theta):
            msg = "Native sbi unexpectedly excluded simulation rows"
            raise RuntimeError(msg)
        if resume_from is not None:
            restore_training(
                native,
                resume_from,
                settings=settings,
                provenance=provenance,
                bank=bank,
                n_simulations=len(theta),
                until_epoch=limit,
            )
        with training_checkpoints(
            native,
            path=checkpoint_path,
            settings=settings,
            provenance=provenance,
            bank=bank,
            until_epoch=limit,
            interval=checkpoint_interval,
        ):
            estimator = native.train(
                training_batch_size=settings.batch_size,
                validation_fraction=settings.validation_fraction,
                max_num_epochs=limit - 1,
                stop_after_epochs=settings.stop_after_epochs,
                learning_rate=settings.learning_rate,
                show_train_summary=False,
                resume_training=resume_from is not None,
            )
        estimator.eval()
    return NpeFit(estimator, settings, provenance, len(theta), int(native.epoch))

load_npe(path, *, expected)

Load tensor-only weights after independently supplied provenance matches.

Returns:

Type Description
NpeFit

Reconstructed native estimator in evaluation mode.

Raises:

Type Description
ValueError

Schema, provenance, runtime, settings or weight integrity differ.

Source code in src/op_infer/adapters/sbi.py
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
def load_npe(path: str | Path, *, expected: Provenance) -> NpeFit:
    """Load tensor-only weights after independently supplied provenance matches.

    Returns:
        Reconstructed native estimator in evaluation mode.

    Raises:
        ValueError: Schema, provenance, runtime, settings or weight integrity differ.
    """
    torch, _inference, nets = _native()
    payload = torch.load(path, map_location="cpu", weights_only=True)
    if payload.get("schema_version") != 1:
        msg = "Unknown NPE artifact schema"
        raise ValueError(msg)
    provenance = Provenance.load_json(payload["provenance"], expected=expected)
    if _weights_digest(payload["state"]) != payload["state_digest"]:
        msg = "NPE state integrity mismatch"
        raise ValueError(msg)
    settings = NpeSettings.model_validate_json(payload["settings"])
    _require_provenance(settings, provenance)
    target = _npe_device(settings.device)
    with _torch_scope(settings.key, device=settings.device):
        embedding = build_masked_set_embedding(settings)
        builder = nets.posterior_nn(
            model=settings.model,
            embedding_net=embedding,
            hidden_features=settings.hidden_features,
            num_transforms=settings.num_transforms,
            z_score_theta="independent",
            z_score_x="none",
        )
        dummy_theta = torch.stack(
            (
                -torch.ones(len(settings.parameter_names)),
                torch.ones(len(settings.parameter_names)),
            )
        )
        dummy_x = torch.zeros(
            (2, settings.n_max, settings.feature_dim), dtype=torch.float32
        )
        estimator = builder(dummy_theta, dummy_x)
        estimator.load_state_dict(payload["state"], strict=True)
        estimator.to(target)
        estimator.eval()
    if _state_digest(estimator) != payload["state_digest"]:
        msg = "NPE state integrity mismatch"
        raise ValueError(msg)
    return NpeFit(
        estimator,
        settings,
        provenance,
        int(payload["n_simulations"]),
        int(payload["epochs"]),
    )

npe_settings_reference(settings)

Return the canonical architecture/control/key identity expected in provenance.

Source code in src/op_infer/adapters/sbi.py
169
170
171
172
173
def npe_settings_reference(settings: NpeSettings) -> ArtifactReference:
    """Return the canonical architecture/control/key identity expected in provenance."""
    return ArtifactReference.from_bytes(
        settings.model_dump_json().encode(), kind="sbi-npe-settings-v1"
    )

save_npe(fit, path)

Save state tensors and primitive metadata, never a native estimator object.

Source code in src/op_infer/adapters/sbi.py
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
def save_npe(fit: NpeFit, path: str | Path) -> None:
    """Save state tensors and primitive metadata, never a native estimator object."""
    torch, _inference, _nets = _native()
    _require_provenance(fit.settings, fit.provenance)
    payload = {
        "schema_version": 1,
        "settings": fit.settings.model_dump_json(),
        "provenance": fit.provenance.model_dump_json(),
        "n_simulations": fit.n_simulations,
        "epochs": fit.epochs,
        "state_digest": _state_digest(fit.estimator),
        "state": cast("Any", fit.estimator).state_dict(),
    }
    destination = Path(path)
    destination.parent.mkdir(parents=True, exist_ok=True)
    descriptor, scratch = tempfile.mkstemp(
        dir=destination.parent, prefix="npe-", suffix=".tmp.pt"
    )
    os.close(descriptor)
    try:
        torch.save(payload, scratch)
        Path(scratch).replace(destination)
    finally:
        Path(scratch).unlink(missing_ok=True)

sbi_backend_versions(*, device='cpu')

Return exact runtime and, for CUDA, device identities.

Source code in src/op_infer/adapters/sbi.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def sbi_backend_versions(*, device: str = "cpu") -> tuple[BackendVersion, ...]:
    """Return exact runtime and, for CUDA, device identities."""
    versions = tuple(
        BackendVersion(
            name=name,
            version=platform.python_version()
            if name == "python"
            else importlib.metadata.version(name),
        )
        for name in ("numpy", "python", "sbi", "torch")
    )
    target = _npe_device(device)
    if target.type == "cpu":
        return versions
    torch, _inference, _nets = _native()
    capability = torch.cuda.get_device_capability(target)
    return (
        BackendVersion(
            name="cuda-device",
            version=(
                f"{torch.cuda.get_device_name(target)}; "
                f"capability={capability[0]}.{capability[1]}"
            ),
        ),
        BackendVersion(name="cuda-runtime", version=str(torch.version.cuda)),
        *versions,
    )

Saved gate records

gates

Prespecified, seeded gate records with sampler adequacy and amendments.

This module records scalar criteria and their application. Consumers supply diagnostics and qualify statistical operating characteristics; neither a saved specification nor a pass certifies calibration.

Gate

Bases: _Record

One inclusive scalar criterion, with a separately named input metric.

adequacy criteria govern whether results are readable, including sampler diagnostics, replicate floors and failure limits. decision criteria govern the substantive reading. At least one finite bound is required. Missing/nonfinite values are unavailable and cannot pass.

Examples:

>>> criterion = Gate(
...     name="bias",
...     metric="mean_pit_error",
...     role="decision",
...     lower=-0.05,
...     upper=0.05,
... )
>>> criterion.lower, criterion.upper
(-0.05, 0.05)
Source code in src/op_infer/gates.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Gate(_Record):
    """One inclusive scalar criterion, with a separately named input metric.

    ``adequacy`` criteria govern whether results are readable, including sampler
    diagnostics, replicate floors and failure limits. ``decision`` criteria
    govern the substantive reading. At least one finite bound is required.
    Missing/nonfinite values are unavailable and cannot pass.

    Examples:
        >>> criterion = Gate(
        ...     name="bias",
        ...     metric="mean_pit_error",
        ...     role="decision",
        ...     lower=-0.05,
        ...     upper=0.05,
        ... )
        >>> criterion.lower, criterion.upper
        (-0.05, 0.05)
    """

    name: _Text
    metric: _Text
    role: Literal["adequacy", "decision"]
    lower: _Finite | None = None
    upper: _Finite | None = None

    @model_validator(mode="after")
    def _bounds(self) -> Self:
        if self.lower is None and self.upper is None:
            msg = "A gate requires at least one bound"
            raise ValueError(msg)
        if (
            self.lower is not None
            and self.upper is not None
            and self.lower > self.upper
        ):
            msg = "Gate lower bound exceeds upper bound"
            raise ValueError(msg)
        return self

GateAmendment

Bases: _Record

Disclose a prospective revision and the evidence already seen.

supersedes identifies the prior saved decision contract. An empty seen_before_amendment explicitly records that no result artifacts were seen. The timestamp and disclosure are supplied by the author; the package cannot authenticate chronology or establish independence of fresh evidence.

Source code in src/op_infer/gates.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class GateAmendment(_Record):
    """Disclose a prospective revision and the evidence already seen.

    ``supersedes`` identifies the prior saved decision contract. An empty
    ``seen_before_amendment`` explicitly records that no result artifacts were
    seen. The timestamp and disclosure are supplied by the author; the package
    cannot authenticate chronology or establish independence of fresh evidence.
    """

    supersedes: ArtifactReference
    recorded_at: datetime
    reason: _Text
    seen_before_amendment: tuple[ArtifactReference, ...]

    @model_validator(mode="after")
    def _timezone(self) -> Self:
        if self.recorded_at.utcoffset() is None:
            msg = "Amendments require a timezone-aware timestamp"
            raise ValueError(msg)
        return self

GateOutcome

Bases: _Record

The scalar read for one criterion; None means unavailable.

Source code in src/op_infer/gates.py
258
259
260
261
262
class GateOutcome(_Record):
    """The scalar read for one criterion; None means unavailable."""

    name: _Text
    value: _Finite | None

GateRecord

Bases: _Record

Immutable criteria and evidence; derive readable/passed on every load.

readable requires all adequacy criteria to pass. passed additionally requires all decision criteria. An unavailable or underpowered reading cannot pass when its requisite evidence/floor is an adequacy criterion. The record retains values for failed and unreadable runs.

Source code in src/op_infer/gates.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
class GateRecord(_Record):
    """Immutable criteria and evidence; derive readable/passed on every load.

    ``readable`` requires all adequacy criteria to pass. ``passed`` additionally
    requires all decision criteria. An unavailable or underpowered reading
    cannot pass when its requisite evidence/floor is an adequacy criterion.
    The record retains values for failed and unreadable runs.
    """

    specification: GateSet
    evidence: ArtifactReference
    outcomes: tuple[GateOutcome, ...]

    @model_validator(mode="after")
    def _names(self) -> Self:
        if tuple(o.name for o in self.outcomes) != tuple(
            g.name for g in self.specification.gates
        ):
            msg = "Outcomes must match every criterion in specification order"
            raise ValueError(msg)
        return self

    def statuses(self) -> tuple[Literal["pass", "fail", "unavailable"], ...]:
        """Return criterion verdicts, preserving unavailable outcomes."""
        statuses: list[Literal["pass", "fail", "unavailable"]] = []
        for gate, outcome in zip(self.specification.gates, self.outcomes, strict=True):
            value = outcome.value
            if value is None:
                statuses.append("unavailable")
            else:
                passed = (gate.lower is None or value >= gate.lower) and (
                    gate.upper is None or value <= gate.upper
                )
                statuses.append("pass" if passed else "fail")
        return tuple(statuses)

    @property
    def readable(self) -> bool:
        """Whether all declared adequacy criteria pass."""
        return all(
            status == "pass"
            for gate, status in zip(
                self.specification.gates, self.statuses(), strict=True
            )
            if gate.role == "adequacy"
        )

    @property
    def passed(self) -> bool:
        """Whether a readable result passes every decision criterion."""
        return self.readable and all(status == "pass" for status in self.statuses())

passed property

Whether a readable result passes every decision criterion.

readable property

Whether all declared adequacy criteria pass.

statuses()

Return criterion verdicts, preserving unavailable outcomes.

Source code in src/op_infer/gates.py
287
288
289
290
291
292
293
294
295
296
297
298
299
def statuses(self) -> tuple[Literal["pass", "fail", "unavailable"], ...]:
    """Return criterion verdicts, preserving unavailable outcomes."""
    statuses: list[Literal["pass", "fail", "unavailable"]] = []
    for gate, outcome in zip(self.specification.gates, self.outcomes, strict=True):
        value = outcome.value
        if value is None:
            statuses.append("unavailable")
        else:
            passed = (gate.lower is None or value >= gate.lower) and (
                gate.upper is None or value <= gate.upper
            )
            statuses.append("pass" if passed else "fail")
    return tuple(statuses)

GateSet

Bases: _Record

Stage-specific criteria saved before invoking a seeded evaluator.

The context reference identifies the estimator/design/prior contract; evidence identifies exact diagnostic inputs. The callback receives a fresh immutable RandomKey on each call. It owns native RNG lowering and must use that key for all stochastic diagnostics. Replaying external mutable state or ignoring the key is outside this bookkeeping contract.

write refuses a different existing specification. evaluate reads and checks that saved specification before calling the evaluator. External version control establishes whether results were unseen at registration.

Examples:

>>> import tempfile
>>> key = RandomKey(seed=7, stream="gates.validation")
>>> context = ArtifactReference.from_bytes(b"toy", kind="design-v1")
>>> criteria = GateSet(
...     name="toy",
...     stage="validation",
...     context=context,
...     key=key,
...     gates=(
...         Gate(
...             name="adequate", metric="ess", role="adequacy", lower=100.0
...         ),
...         Gate(
...             name="error",
...             metric="error",
...             role="decision",
...             lower=-0.05,
...             upper=0.05,
...         ),
...     ),
... )
>>> with tempfile.TemporaryDirectory() as directory:
...     path = Path(directory) / "criteria.json"
...     _ = criteria.write(path)
...     result = criteria.evaluate(
...         path,
...         lambda key: {"ess": 1000.0, "error": 0.01},
...         evidence=context,
...         context=context,
...     )
>>> result.readable, result.passed
(True, True)
>>> restored = GateRecord.model_validate_json(result.model_dump_json())
>>> restored.readable, restored.passed
(True, True)
Source code in src/op_infer/gates.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
class GateSet(_Record):
    """Stage-specific criteria saved before invoking a seeded evaluator.

    The context reference identifies the estimator/design/prior contract;
    evidence identifies exact diagnostic inputs. The callback receives a fresh
    immutable RandomKey on each call. It owns native RNG lowering and must use
    that key for all stochastic diagnostics. Replaying external mutable state
    or ignoring the key is outside this bookkeeping contract.

    ``write`` refuses a different existing specification. ``evaluate`` reads
    and checks that saved specification before calling the evaluator. External
    version control establishes whether results were unseen at registration.

    Examples:
        >>> import tempfile
        >>> key = RandomKey(seed=7, stream="gates.validation")
        >>> context = ArtifactReference.from_bytes(b"toy", kind="design-v1")
        >>> criteria = GateSet(
        ...     name="toy",
        ...     stage="validation",
        ...     context=context,
        ...     key=key,
        ...     gates=(
        ...         Gate(
        ...             name="adequate", metric="ess", role="adequacy", lower=100.0
        ...         ),
        ...         Gate(
        ...             name="error",
        ...             metric="error",
        ...             role="decision",
        ...             lower=-0.05,
        ...             upper=0.05,
        ...         ),
        ...     ),
        ... )
        >>> with tempfile.TemporaryDirectory() as directory:
        ...     path = Path(directory) / "criteria.json"
        ...     _ = criteria.write(path)
        ...     result = criteria.evaluate(
        ...         path,
        ...         lambda key: {"ess": 1000.0, "error": 0.01},
        ...         evidence=context,
        ...         context=context,
        ...     )
        >>> result.readable, result.passed
        (True, True)
        >>> restored = GateRecord.model_validate_json(result.model_dump_json())
        >>> restored.readable, restored.passed
        (True, True)
    """

    schema_version: Literal[1] = 1
    name: _Text
    stage: _Text
    context: ArtifactReference
    key: RandomKey
    gates: tuple[Gate, ...]
    amendment: GateAmendment | None = None

    @field_validator("schema_version", mode="before")
    @classmethod
    def _integer_version(cls, value: object) -> object:
        if type(value) is not int:
            msg = "schema_version must be an integer"
            raise ValueError(msg)
        return value

    @model_validator(mode="after")
    def _criteria(self) -> Self:
        if len({g.name for g in self.gates}) != len(self.gates):
            msg = "Gate names must be unique"
            raise ValueError(msg)
        if {g.role for g in self.gates} != {"adequacy", "decision"}:
            msg = "A GateSet requires adequacy and decision criteria"
            raise ValueError(msg)
        return self

    def reference(self) -> ArtifactReference:
        """Return the content identity of this complete specification."""
        return ArtifactReference.from_bytes(
            self.model_dump_json().encode(), kind="op-infer-gate-set-v1"
        )

    def write(self, path: str | Path) -> ArtifactReference:
        """Atomically save criteria, refusing to replace a different contract.

        Returns:
            The saved specification's content reference.

        Raises:
            ValueError: The destination already contains different bytes.
        """
        write_immutable_json(
            path,
            self.model_dump_json().encode(),
            conflict="Saved gate specification differs; write an amendment separately",
        )
        return self.reference()

    def amend(
        self,
        *,
        gates: tuple[Gate, ...],
        key: RandomKey,
        disclosure: GateAmendment,
    ) -> GateSet:
        """Create revised criteria with an explicit prior-artifact reference.

        Returns:
            A new specification to save separately before fresh evaluation.

        Raises:
            ValueError: The disclosure does not reference this specification.
        """
        if disclosure.supersedes != self.reference():
            msg = "Amendment must reference the specification it supersedes"
            raise ValueError(msg)
        return GateSet(
            name=self.name,
            stage=self.stage,
            context=self.context,
            key=key,
            gates=gates,
            amendment=disclosure,
        )

    def evaluate(
        self,
        path: str | Path,
        evaluator: Callable[[RandomKey], Mapping[str, float | None]],
        *,
        evidence: ArtifactReference,
        context: ArtifactReference,
    ) -> GateRecord:
        """Check saved criteria/context, then evaluate using the declared key.

        Returns:
            A complete record with separate readable and passed decisions.
            Exceptions from the evaluator propagate; they cannot produce a pass.

        Raises:
            ValueError: Saved criteria or evidence context do not match.
            FileNotFoundError: No criteria have been saved at the supplied path.
        """
        saved = GateSet.model_validate_json(Path(path).read_bytes())
        if saved != self or context != self.context:
            msg = "Saved gate specification or evidence context differs"
            raise ValueError(msg)
        values = evaluator(self.key)
        outcomes = []
        for gate in self.gates:
            raw = values.get(gate.metric)
            value = None if raw is None or not math.isfinite(raw) else float(raw)
            outcomes.append(GateOutcome(name=gate.name, value=value))
        return GateRecord(
            specification=self, evidence=evidence, outcomes=tuple(outcomes)
        )

amend(*, gates, key, disclosure)

Create revised criteria with an explicit prior-artifact reference.

Returns:

Type Description
GateSet

A new specification to save separately before fresh evaluation.

Raises:

Type Description
ValueError

The disclosure does not reference this specification.

Source code in src/op_infer/gates.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def amend(
    self,
    *,
    gates: tuple[Gate, ...],
    key: RandomKey,
    disclosure: GateAmendment,
) -> GateSet:
    """Create revised criteria with an explicit prior-artifact reference.

    Returns:
        A new specification to save separately before fresh evaluation.

    Raises:
        ValueError: The disclosure does not reference this specification.
    """
    if disclosure.supersedes != self.reference():
        msg = "Amendment must reference the specification it supersedes"
        raise ValueError(msg)
    return GateSet(
        name=self.name,
        stage=self.stage,
        context=self.context,
        key=key,
        gates=gates,
        amendment=disclosure,
    )

evaluate(path, evaluator, *, evidence, context)

Check saved criteria/context, then evaluate using the declared key.

Returns:

Type Description
GateRecord

A complete record with separate readable and passed decisions.

GateRecord

Exceptions from the evaluator propagate; they cannot produce a pass.

Raises:

Type Description
ValueError

Saved criteria or evidence context do not match.

FileNotFoundError

No criteria have been saved at the supplied path.

Source code in src/op_infer/gates.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def evaluate(
    self,
    path: str | Path,
    evaluator: Callable[[RandomKey], Mapping[str, float | None]],
    *,
    evidence: ArtifactReference,
    context: ArtifactReference,
) -> GateRecord:
    """Check saved criteria/context, then evaluate using the declared key.

    Returns:
        A complete record with separate readable and passed decisions.
        Exceptions from the evaluator propagate; they cannot produce a pass.

    Raises:
        ValueError: Saved criteria or evidence context do not match.
        FileNotFoundError: No criteria have been saved at the supplied path.
    """
    saved = GateSet.model_validate_json(Path(path).read_bytes())
    if saved != self or context != self.context:
        msg = "Saved gate specification or evidence context differs"
        raise ValueError(msg)
    values = evaluator(self.key)
    outcomes = []
    for gate in self.gates:
        raw = values.get(gate.metric)
        value = None if raw is None or not math.isfinite(raw) else float(raw)
        outcomes.append(GateOutcome(name=gate.name, value=value))
    return GateRecord(
        specification=self, evidence=evidence, outcomes=tuple(outcomes)
    )

reference()

Return the content identity of this complete specification.

Source code in src/op_infer/gates.py
176
177
178
179
180
def reference(self) -> ArtifactReference:
    """Return the content identity of this complete specification."""
    return ArtifactReference.from_bytes(
        self.model_dump_json().encode(), kind="op-infer-gate-set-v1"
    )

write(path)

Atomically save criteria, refusing to replace a different contract.

Returns:

Type Description
ArtifactReference

The saved specification's content reference.

Raises:

Type Description
ValueError

The destination already contains different bytes.

Source code in src/op_infer/gates.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def write(self, path: str | Path) -> ArtifactReference:
    """Atomically save criteria, refusing to replace a different contract.

    Returns:
        The saved specification's content reference.

    Raises:
        ValueError: The destination already contains different bytes.
    """
    write_immutable_json(
        path,
        self.model_dump_json().encode(),
        conflict="Saved gate specification differs; write an amendment separately",
    )
    return self.reference()

readings

Saved point and interval readings of a fixed calibration replicate bank.

Consumers supply metric definitions and qualify their statistical assumptions. An interval reading reports compatibility, not equivalence or calibration. Application-specific statistics and thresholds are supplied by the consumer.

CalibrationEvidence

Bases: _Record

Exact usable and failed identities, with no omitted planned replicates.

Each metric must describe the same complete usable cohort. The reader checks identities/counts; the producer owns numerical correctness and independence.

Source code in src/op_infer/readings.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
class CalibrationEvidence(_Record):
    """Exact usable and failed identities, with no omitted planned replicates.

    Each metric must describe the same complete usable cohort. The reader checks
    identities/counts; the producer owns numerical correctness and independence.
    """

    context: ArtifactReference
    source: ArtifactReference
    usable: tuple[_Text, ...]
    failures: tuple[ReplicateFailure, ...]
    metrics: tuple[MetricEstimate, ...]

    @model_validator(mode="after")
    def _cohort(self) -> Self:
        identities = self.usable + tuple(f.replicate for f in self.failures)
        keys = tuple((m.quantity, m.metric) for m in self.metrics)
        if (
            len(set(identities)) != len(identities)
            or len(set(keys)) != len(keys)
            or any(m.n_usable != len(self.usable) for m in self.metrics)
        ):
            msg = "Evidence requires unique replicates/metrics and one usable cohort"
            raise ValueError(msg)
        return self

CalibrationPolicy

Bases: _Record

Prespecify both readings, the governing choice and complete trial bank.

Failure allowance counts distinct quantities, not individual criteria. Every reading must cover the same quantity set. A missing metric, exceeded failure budget or replicate floor prevents a pass. External records establish when results became visible; local registration cannot authenticate chronology.

Source code in src/op_infer/readings.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
class CalibrationPolicy(_Record):
    """Prespecify both readings, the governing choice and complete trial bank.

    Failure allowance counts distinct quantities, not individual criteria. Every
    reading must cover the same quantity set. A missing metric, exceeded failure
    budget or replicate floor prevents a pass. External records establish when
    results became visible; local registration cannot authenticate chronology.
    """

    name: _Text
    context: ArtifactReference
    governing: _ReadingName
    rationale: _Text
    replicate_ids: tuple[_Text, ...]
    minimum_usable: Annotated[int, Field(ge=1)]
    max_failure_fraction: Annotated[float, Field(ge=0, le=1, allow_inf_nan=False)]
    max_failed_quantities: _Count
    must_pass: tuple[_Text, ...]
    rules: tuple[CalibrationRule, ...]
    amendment: GateAmendment | None = None

    @model_validator(mode="after")
    def _design(self) -> Self:
        quantities = {r.quantity for r in self.rules}
        if (
            not self.replicate_ids
            or len(set(self.replicate_ids)) != len(self.replicate_ids)
            or self.minimum_usable > len(self.replicate_ids)
            or not self.rules
            or len({r.name for r in self.rules}) != len(self.rules)
            or len(set(self.must_pass)) != len(self.must_pass)
            or not set(self.must_pass) <= quantities
            or self.max_failed_quantities > len(quantities)
            or any(
                {r.quantity for r in self.rules if reading in r.applies_to}
                != quantities
                for reading in ("point", "interval")
            )
        ):
            msg = (
                "Policy requires a fixed bank, complete readings "
                "and declared quantities"
            )
            raise ValueError(msg)
        methods: dict[tuple[str, str], ArtifactReference] = {}
        for rule in self.rules:
            key = (rule.quantity, rule.metric)
            if key in methods and methods[key] != rule.method:
                msg = "A named metric must have one declared method"
                raise ValueError(msg)
            methods[key] = rule.method
        return self

    def write(self, path: str | Path) -> ArtifactReference:
        """Atomically register this policy; a different policy needs a new file."""
        write_immutable_json(
            path,
            self.model_dump_json().encode(),
            conflict="Saved calibration policy differs; write an amendment separately",
        )
        return self.reference

    def evaluate(
        self, path: str | Path, evidence: CalibrationEvidence
    ) -> CalibrationRecord:
        """Require exact saved criteria, then retain evidence and both readings.

        Returns:
            A record whose decisions are derived again on every read.

        Raises:
            ValueError: Saved policy, context, methods or planned cohort differ.
            FileNotFoundError: No policy is registered at the supplied path.
        """
        saved = CalibrationPolicy.model_validate_json(Path(path).read_bytes())
        if saved != self:
            msg = "Saved calibration policy differs"
            raise ValueError(msg)
        return CalibrationRecord(policy=self, evidence=evidence)

evaluate(path, evidence)

Require exact saved criteria, then retain evidence and both readings.

Returns:

Type Description
CalibrationRecord

A record whose decisions are derived again on every read.

Raises:

Type Description
ValueError

Saved policy, context, methods or planned cohort differ.

FileNotFoundError

No policy is registered at the supplied path.

Source code in src/op_infer/readings.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def evaluate(
    self, path: str | Path, evidence: CalibrationEvidence
) -> CalibrationRecord:
    """Require exact saved criteria, then retain evidence and both readings.

    Returns:
        A record whose decisions are derived again on every read.

    Raises:
        ValueError: Saved policy, context, methods or planned cohort differ.
        FileNotFoundError: No policy is registered at the supplied path.
    """
    saved = CalibrationPolicy.model_validate_json(Path(path).read_bytes())
    if saved != self:
        msg = "Saved calibration policy differs"
        raise ValueError(msg)
    return CalibrationRecord(policy=self, evidence=evidence)

write(path)

Atomically register this policy; a different policy needs a new file.

Source code in src/op_infer/readings.py
217
218
219
220
221
222
223
224
def write(self, path: str | Path) -> ArtifactReference:
    """Atomically register this policy; a different policy needs a new file."""
    write_immutable_json(
        path,
        self.model_dump_json().encode(),
        conflict="Saved calibration policy differs; write an amendment separately",
    )
    return self.reference

CalibrationRecord

Bases: _Record

Retain full policy/evidence; derive both panels without mutable verdicts.

Source code in src/op_infer/readings.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
class CalibrationRecord(_Record):
    """Retain full policy/evidence; derive both panels without mutable verdicts."""

    policy: CalibrationPolicy
    evidence: CalibrationEvidence

    @model_validator(mode="after")
    def _match(self) -> Self:
        spec, data = self.policy, self.evidence
        identities = data.usable + tuple(f.replicate for f in data.failures)
        methods = {(r.quantity, r.metric): r.method for r in spec.rules}
        if data.context != spec.context or set(identities) != set(spec.replicate_ids):
            msg = "Evidence context or complete planned replicate bank differs"
            raise ValueError(msg)
        for metric in data.metrics:
            key = (metric.quantity, metric.metric)
            if key not in methods or metric.method != methods[key]:
                msg = "Evidence metric or declared method differs"
                raise ValueError(msg)
        return self

    def readings(self) -> tuple[Reading, Reading]:
        """Compute both panels, preserving failures even when evidence is inadequate."""
        spec, data = self.policy, self.evidence
        metrics = {(m.quantity, m.metric): m for m in data.metrics}
        common = []
        if len(data.usable) < spec.minimum_usable:
            common.append("below_minimum_usable")
        if len(data.failures) > spec.max_failure_fraction * len(spec.replicate_ids):
            common.append("failure_budget_exceeded")
        panels = []
        for name in ("point", "interval"):
            rules = tuple(r for r in spec.rules if name in r.applies_to)
            outcomes = tuple(
                _outcome(r, metrics.get((r.quantity, r.metric)), name) for r in rules
            )
            failed = tuple(
                sorted(
                    {
                        r.quantity
                        for r, o in zip(rules, outcomes, strict=True)
                        if o.status == "fail"
                    }
                )
            )
            reasons = tuple(common) + tuple(
                f"unavailable:{o.rule}" for o in outcomes if o.status == "unavailable"
            )
            state: Literal["pass", "fail", "insufficient_evidence"] = (
                "insufficient_evidence"
                if reasons
                else (
                    "fail"
                    if len(failed) > spec.max_failed_quantities
                    or set(failed) & set(spec.must_pass)
                    else "pass"
                )
            )
            panels.append(
                Reading(
                    name=name,
                    state=state,
                    reasons=reasons,
                    failed_quantities=failed,
                    outcomes=outcomes,
                )
            )
        return panels[0], panels[1]

    @property
    def governing_reading(self) -> Reading:
        """Return the prospectively selected panel, preserving the alternative."""
        return self.readings()[0 if self.policy.governing == "point" else 1]

governing_reading property

Return the prospectively selected panel, preserving the alternative.

readings()

Compute both panels, preserving failures even when evidence is inadequate.

Source code in src/op_infer/readings.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def readings(self) -> tuple[Reading, Reading]:
    """Compute both panels, preserving failures even when evidence is inadequate."""
    spec, data = self.policy, self.evidence
    metrics = {(m.quantity, m.metric): m for m in data.metrics}
    common = []
    if len(data.usable) < spec.minimum_usable:
        common.append("below_minimum_usable")
    if len(data.failures) > spec.max_failure_fraction * len(spec.replicate_ids):
        common.append("failure_budget_exceeded")
    panels = []
    for name in ("point", "interval"):
        rules = tuple(r for r in spec.rules if name in r.applies_to)
        outcomes = tuple(
            _outcome(r, metrics.get((r.quantity, r.metric)), name) for r in rules
        )
        failed = tuple(
            sorted(
                {
                    r.quantity
                    for r, o in zip(rules, outcomes, strict=True)
                    if o.status == "fail"
                }
            )
        )
        reasons = tuple(common) + tuple(
            f"unavailable:{o.rule}" for o in outcomes if o.status == "unavailable"
        )
        state: Literal["pass", "fail", "insufficient_evidence"] = (
            "insufficient_evidence"
            if reasons
            else (
                "fail"
                if len(failed) > spec.max_failed_quantities
                or set(failed) & set(spec.must_pass)
                else "pass"
            )
        )
        panels.append(
            Reading(
                name=name,
                state=state,
                reasons=reasons,
                failed_quantities=failed,
                outcomes=outcomes,
            )
        )
    return panels[0], panels[1]

CalibrationRule

Bases: _Record

Inclusive bounds with an explicit view of a named metric.

band uses the point in the point reading and interval overlap in the interval reading. point, lower and upper always use that fixed metric view, for example a practical cap on a supplied lower endpoint. An interval's length is never substituted for a consumer's width statistic.

Source code in src/op_infer/readings.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
class CalibrationRule(_Record):
    """Inclusive bounds with an explicit view of a named metric.

    ``band`` uses the point in the point reading and interval overlap in the
    interval reading. ``point``, ``lower`` and ``upper`` always use that fixed
    metric view, for example a practical cap on a supplied lower endpoint.
    An interval's length is never substituted for a consumer's width statistic.
    """

    name: _Text
    quantity: _Text
    metric: _Text
    method: ArtifactReference
    lower: _Finite | None = None
    upper: _Finite | None = None
    view: Literal["band", "point", "lower", "upper"] = "band"
    applies_to: tuple[_ReadingName, ...] = ("point", "interval")

    @model_validator(mode="after")
    def _bounds(self) -> Self:
        if (
            (self.lower is None and self.upper is None)
            or (
                self.lower is not None
                and self.upper is not None
                and self.lower > self.upper
            )
            or not self.applies_to
            or len(set(self.applies_to)) != len(self.applies_to)
        ):
            msg = "Rules require ordered bounds and unique nonempty readings"
            raise ValueError(msg)
        return self

MetricEstimate

Bases: _Record

A consumer-defined scalar and optional interval on the usable cohort.

method identifies the formula, assumptions, interval family/level and any clipping or other options. None explicitly denotes unavailable evidence.

Source code in src/op_infer/readings.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class MetricEstimate(_Record):
    """A consumer-defined scalar and optional interval on the usable cohort.

    ``method`` identifies the formula, assumptions, interval family/level and
    any clipping or other options. None explicitly denotes unavailable evidence.
    """

    quantity: _Text
    metric: _Text
    method: ArtifactReference
    n_usable: _Count
    point: _Finite | None
    lower: _Finite | None = None
    upper: _Finite | None = None

    @model_validator(mode="after")
    def _interval(self) -> Self:
        if (self.lower is None) != (self.upper is None) or (
            self.lower is not None
            and self.upper is not None
            and self.lower > self.upper
        ):
            msg = "Metric intervals require both ordered finite endpoints"
            raise ValueError(msg)
        if self.n_usable == 0 and any(
            value is not None for value in (self.point, self.lower, self.upper)
        ):
            msg = "An empty cohort cannot supply a metric estimate"
            raise ValueError(msg)
        return self

Reading

Bases: _Record

One alternative panel, including adequacy reasons and failed quantities.

Source code in src/op_infer/readings.py
254
255
256
257
258
259
260
261
class Reading(_Record):
    """One alternative panel, including adequacy reasons and failed quantities."""

    name: _ReadingName
    state: Literal["pass", "fail", "insufficient_evidence"]
    reasons: tuple[str, ...]
    failed_quantities: tuple[str, ...]
    outcomes: tuple[RuleOutcome, ...]

ReplicateFailure

Bases: _Record

Retain a planned replicate's failure and its diagnostic reference.

Source code in src/op_infer/readings.py
129
130
131
132
133
134
class ReplicateFailure(_Record):
    """Retain a planned replicate's failure and its diagnostic reference."""

    replicate: _Text
    reason: _Text
    evidence: ArtifactReference

RuleOutcome

Bases: _Record

One criterion's complete scalar or interval input and verdict.

Source code in src/op_infer/readings.py
245
246
247
248
249
250
251
class RuleOutcome(_Record):
    """One criterion's complete scalar or interval input and verdict."""

    rule: str
    lower: _Finite | None
    upper: _Finite | None
    status: Literal["pass", "fail", "unavailable"]

wilson_coverage(*, quantity, metric, successes, trials, confidence)

Wrap SciPy's Wilson interval without substituting a new statistical kernel.

Returns:

Type Description
MetricEstimate

Explicitly unavailable evidence at zero trials, otherwise a point and CI.

Raises:

Type Description
ValueError

Counts are nonintegers or outside their binomial support.

Source code in src/op_infer/readings.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
def wilson_coverage(
    *, quantity: str, metric: str, successes: int, trials: int, confidence: float
) -> MetricEstimate:
    """Wrap SciPy's Wilson interval without substituting a new statistical kernel.

    Returns:
        Explicitly unavailable evidence at zero trials, otherwise a point and CI.

    Raises:
        ValueError: Counts are nonintegers or outside their binomial support.
    """
    method = wilson_method(confidence=confidence)
    if (
        type(successes) is not int
        or type(trials) is not int
        or not 0 <= successes <= trials
    ):
        msg = "Coverage requires integer counts with 0 <= successes <= trials"
        raise ValueError(msg)
    if trials == 0:
        return MetricEstimate(
            quantity=quantity, metric=metric, method=method, n_usable=0, point=None
        )
    interval = binomtest(successes, trials).proportion_ci(
        confidence_level=confidence, method="wilson"
    )
    return MetricEstimate(
        quantity=quantity,
        metric=metric,
        method=method,
        n_usable=trials,
        point=successes / trials,
        lower=float(interval.low),
        upper=float(interval.high),
    )

wilson_method(*, confidence)

Identify the ordinary independent-binomial Wilson coverage procedure.

Returns:

Type Description
ArtifactReference

A method reference including confidence level and cohort assumptions.

Raises:

Type Description
ValueError

Confidence is not a finite float strictly between zero and one.

Source code in src/op_infer/readings.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def wilson_method(*, confidence: float) -> ArtifactReference:
    """Identify the ordinary independent-binomial Wilson coverage procedure.

    Returns:
        A method reference including confidence level and cohort assumptions.

    Raises:
        ValueError: Confidence is not a finite float strictly between zero and one.
    """
    if type(confidence) is not float or not 0 < confidence < 1:
        msg = "Wilson confidence must be a float strictly between zero and one"
        raise ValueError(msg)
    return ArtifactReference.from_bytes(
        json.dumps(
            {
                "family": "binomial-proportion",
                "interval": "wilson",
                "confidence": confidence,
                "cohort": "fixed-independent-usable-trials",
            },
            sort_keys=True,
        ).encode(),
        kind="op-infer-coverage-method-v1",
    )

Shared statistical models

simulation

Identified forward-to-observation composition without implicit array transfers.

ObservationChannel dataclass

Bind one named measurement stream to a selected latent output.

Source code in src/op_infer/simulation.py
24
25
26
27
28
29
30
@dataclass(frozen=True, slots=True)
class ObservationChannel:
    """Bind one named measurement stream to a selected latent output."""

    name: str
    latent_output: str
    model: ObservationModel

SimulationResult dataclass

Keep parameters, latent values and random measurements distinguishable.

Arrays are borrowed native values, not immutable snapshots. The pipeline reference identifies declarations/execution provenance, not the result bytes. Retain streams and serialize/harden arrays at an explicit artifact boundary.

Source code in src/op_infer/simulation.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@dataclass(frozen=True, slots=True)
class SimulationResult:
    """Keep parameters, latent values and random measurements distinguishable.

    Arrays are borrowed native values, not immutable snapshots. The pipeline
    reference identifies declarations/execution provenance, not the result bytes.
    Retain streams and serialize/harden arrays at an explicit artifact boundary.
    """

    parameters: Mapping[str, object]
    latent: Mapping[str, object]
    measurements: Mapping[str, object]
    streams: SimulationStreams
    pipeline: ArtifactReference

StatisticalModel dataclass

Reuse an identified forward, ordered prior and statistical observations.

Calling simulate uses explicitly supplied native parameters. The separate sample_numpy convenience draws the declared prior on its parameter stream; it does not move NumPy draws into JAX/Torch implicitly. log_prob returns per-channel per-cell terms; consumers choose their own unit/event reduction.

Source code in src/op_infer/simulation.py
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@dataclass(frozen=True, slots=True)
class StatisticalModel:
    """Reuse an identified forward, ordered prior and statistical observations.

    Calling ``simulate`` uses explicitly supplied native parameters. The separate
    ``sample_numpy`` convenience draws the declared prior on its parameter stream;
    it does not move NumPy draws into JAX/Torch implicitly. ``log_prob`` returns
    per-channel per-cell terms; consumers choose their own unit/event reduction.
    """

    forward: ForwardModel
    prior: JointPrior
    channels: tuple[ObservationChannel, ...]

    def __post_init__(self) -> None:
        """Refuse prior/layout or latent-channel mismatches before simulation."""
        JointPrior.model_validate(self.prior)
        if self.prior.reference != self.forward.provenance.prior:
            msg = "Statistical model prior identity differs from forward provenance"
            raise ValueError(msg)
        if self.prior.parameter_names != self.forward.parameter_names:
            msg = "Statistical model parameter order differs from forward layout"
            raise ValueError(msg)
        names = [channel.name for channel in self.channels]
        if (
            not isinstance(self.channels, tuple)
            or not names
            or len(set(names)) != len(names)
        ):
            msg = "Declare nonempty unique observation channel names"
            raise ValueError(msg)
        for channel in self.channels:
            if (
                not isinstance(channel.name, str)
                or not channel.name.strip()
                or channel.latent_output not in self.forward.output_names
            ):
                msg = "Observation channels require names and declared latent outputs"
                raise ValueError(msg)
            ArtifactReference.model_validate(channel.model.reference)

    @property
    def reference(self) -> ArtifactReference:
        """Identify the complete ordered pipeline, including statistical outputs.

        This supplements existing provenance; it never silently relabels an old
        bank, replaces its likelihood target or certifies supplied identities.
        """
        data = {
            "schema_version": 1,
            "forward_provenance": self.forward.provenance.identity,
            "prior": self.prior.reference.model_dump(mode="json"),
            "channels": [
                {
                    "name": channel.name,
                    "latent_output": channel.latent_output,
                    "model": channel.model.reference.model_dump(mode="json"),
                }
                for channel in self.channels
            ],
        }
        payload = json.dumps(
            data, sort_keys=True, separators=(",", ":"), allow_nan=False
        )
        return ArtifactReference.from_bytes(
            payload.encode(), kind="statistical-pipeline-v1"
        )

    def simulate(
        self,
        parameters: Mapping[str, object],
        design: ForwardDesign,
        streams: SimulationStreams,
    ) -> SimulationResult:
        """Evaluate latent outputs and independently address each noise channel."""
        SimulationStreams.model_validate(streams)
        latent = self.forward(parameters, design, streams.simulation)
        measurements = {}
        for channel in self.channels:
            key = RandomKey(
                seed=streams.seed,
                index=streams.index,
                stream=f"simulation/observation/{channel.name.encode('utf-8').hex()}",
            )
            measurements[channel.name] = channel.model.sample(
                latent[channel.latent_output], key
            )
        return SimulationResult(
            parameters, latent, measurements, streams, self.reference
        )

    def sample_numpy(
        self, design: ForwardDesign, streams: SimulationStreams
    ) -> SimulationResult:
        """Draw the prior then execute a NumPy-compatible forward; never retry."""
        parameters: dict[str, np.ndarray[Any, Any]] = self.prior.sample(
            streams.parameters
        )
        return self.simulate(parameters, design, streams)

    def log_prob(
        self,
        parameters: Mapping[str, object],
        design: ForwardDesign,
        key: RandomKey,
        observed: Mapping[str, object],
        *,
        masks: Mapping[str, object] | None = None,
    ) -> dict[str, object]:
        """Evaluate the same observation target used by simulation, without draws."""
        names = {channel.name for channel in self.channels}
        if set(observed) != names or (masks is not None and set(masks) != names):
            msg = "Observed and mask channel names must match the declared layout"
            raise ValueError(msg)
        latent = self.forward(parameters, design, key)
        return {
            channel.name: channel.model.log_prob(
                latent[channel.latent_output],
                observed[channel.name],
                mask=None if masks is None else masks[channel.name],
            )
            for channel in self.channels
        }

reference property

Identify the complete ordered pipeline, including statistical outputs.

This supplements existing provenance; it never silently relabels an old bank, replaces its likelihood target or certifies supplied identities.

__post_init__()

Refuse prior/layout or latent-channel mismatches before simulation.

Source code in src/op_infer/simulation.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def __post_init__(self) -> None:
    """Refuse prior/layout or latent-channel mismatches before simulation."""
    JointPrior.model_validate(self.prior)
    if self.prior.reference != self.forward.provenance.prior:
        msg = "Statistical model prior identity differs from forward provenance"
        raise ValueError(msg)
    if self.prior.parameter_names != self.forward.parameter_names:
        msg = "Statistical model parameter order differs from forward layout"
        raise ValueError(msg)
    names = [channel.name for channel in self.channels]
    if (
        not isinstance(self.channels, tuple)
        or not names
        or len(set(names)) != len(names)
    ):
        msg = "Declare nonempty unique observation channel names"
        raise ValueError(msg)
    for channel in self.channels:
        if (
            not isinstance(channel.name, str)
            or not channel.name.strip()
            or channel.latent_output not in self.forward.output_names
        ):
            msg = "Observation channels require names and declared latent outputs"
            raise ValueError(msg)
        ArtifactReference.model_validate(channel.model.reference)

log_prob(parameters, design, key, observed, *, masks=None)

Evaluate the same observation target used by simulation, without draws.

Source code in src/op_infer/simulation.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def log_prob(
    self,
    parameters: Mapping[str, object],
    design: ForwardDesign,
    key: RandomKey,
    observed: Mapping[str, object],
    *,
    masks: Mapping[str, object] | None = None,
) -> dict[str, object]:
    """Evaluate the same observation target used by simulation, without draws."""
    names = {channel.name for channel in self.channels}
    if set(observed) != names or (masks is not None and set(masks) != names):
        msg = "Observed and mask channel names must match the declared layout"
        raise ValueError(msg)
    latent = self.forward(parameters, design, key)
    return {
        channel.name: channel.model.log_prob(
            latent[channel.latent_output],
            observed[channel.name],
            mask=None if masks is None else masks[channel.name],
        )
        for channel in self.channels
    }

sample_numpy(design, streams)

Draw the prior then execute a NumPy-compatible forward; never retry.

Source code in src/op_infer/simulation.py
140
141
142
143
144
145
146
147
def sample_numpy(
    self, design: ForwardDesign, streams: SimulationStreams
) -> SimulationResult:
    """Draw the prior then execute a NumPy-compatible forward; never retry."""
    parameters: dict[str, np.ndarray[Any, Any]] = self.prior.sample(
        streams.parameters
    )
    return self.simulate(parameters, design, streams)

simulate(parameters, design, streams)

Evaluate latent outputs and independently address each noise channel.

Source code in src/op_infer/simulation.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def simulate(
    self,
    parameters: Mapping[str, object],
    design: ForwardDesign,
    streams: SimulationStreams,
) -> SimulationResult:
    """Evaluate latent outputs and independently address each noise channel."""
    SimulationStreams.model_validate(streams)
    latent = self.forward(parameters, design, streams.simulation)
    measurements = {}
    for channel in self.channels:
        key = RandomKey(
            seed=streams.seed,
            index=streams.index,
            stream=f"simulation/observation/{channel.name.encode('utf-8').hex()}",
        )
        measurements[channel.name] = channel.model.sample(
            latent[channel.latent_output], key
        )
    return SimulationResult(
        parameters, latent, measurements, streams, self.reference
    )