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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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]]
|
|
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 | |
__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 | |
__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 | |
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 | |
__post_init__()
Validate immutable metadata without examining native inputs.
Source code in src/op_infer/forward.py
51 52 53 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
BackendVersion
Bases: _Record
Record one numerical/backend dependency.
Source code in src/op_infer/posterior.py
277 278 279 280 281 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
__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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
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 | |
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: |
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 | |
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: |
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 |
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 | |
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 |
Raises:
| Type | Description |
|---|---|
ImportError
|
Install |
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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_floorreplicates 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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
reference()
Return the content identity of this complete specification.
Source code in src/op_infer/gates.py
176 177 178 179 180 | |
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 | |
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
|
0
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The per-estimand table under |
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 | |
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 | |
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 | |
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 | |
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 | |
format_table(result)
Return the per-estimand table as text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Mapping[str, Any]
|
Output of |
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 | |
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 |
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]
|
|
dict[str, Any]
|
pass"), |
dict[str, Any]
|
|
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 | |
load_replicates(directory)
Read the replicate JSON files of a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Directory with one |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[float]]
|
|
dict[str, list[float]]
|
the successful replicates, and |
dict[str, Any]
|
|
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 |
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 | |
main(argv=None)
Run the aggregate command line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
Sequence[str] | None
|
Arguments (default |
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 | |
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 |
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
|
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 | |
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]
|
|
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 | |
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
|
|
float
|
prior. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there are no finite draws or |
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 | |
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 |
required |
reason
|
str | None
|
Optional short cause (timeout, non-convergence), stored as
|
None
|
metadata
|
Mapping[str, Any] | None
|
Optional runner/provenance metadata, stored as |
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 | |
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 ( |
required |
meta
|
Mapping[str, Any]
|
Provenance such as the script name and settings; |
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 | |
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 |
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 |
None
|
metadata
|
Mapping[str, Any] | None
|
Optional runner/provenance metadata, stored as |
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 | |
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 | |
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 | |
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]
|
|
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 | |
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, |
required |
truth
|
NDArray[generic]
|
True reported quantities, |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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
|
Returns:
| Type | Description |
|---|---|
ThreeValuedContrast
|
The reading with both bounds and the unit accounting. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Units or targets disagree, or |
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 | |
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 | |
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 | |
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
|
|
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 | |
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), withshift_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 allN_sunits if the per-unit errors are independent with variancev_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 | |
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
|
|
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 | |
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
|
|
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 | |
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 | |
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 |
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
__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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
__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 | |
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 |
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 | |
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 | |
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 | |
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. |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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: |
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 | |
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 | |
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 | |
__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 | |
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 | |
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. |
dict[str, Any]
|
replicate files of each bank, |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
coverage is computed. One row per estimand holds both coverages with |
dict[str, Any]
|
Wilson intervals, the requirement and the verdict; |
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 | |
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 | |
__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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
reference()
Return the content identity of this complete specification.
Source code in src/op_infer/gates.py
176 177 178 179 180 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |