Skip to content

AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.

Validation

This page documents the predictive checks, the scores of an approximate posterior against a reference posterior, and simulation-based calibration. The diagnostics recorded on a posterior, such as R-hat and leave-one-out cross-validation, are on Diagnostics.

Predictive checks

predictive_check(kernel, law, test_fns, observed_data=None, *, num_replications=500)

Compare replicated data with the observed data through test statistics.

A replication is a draw of the kernel's event from the merge kernel & law, which draws the inputs from law and then the kernel's event at those values. With the posterior as law the check is a posterior predictive check, and with the prior it is a prior predictive check. Each statistic is computed on the same replications and, when observed_data is given, on the observed data; its p-value is the fraction of replications whose statistic is at least the observed one.

A statistic receives a replication in the form the kernel declares for its event: a whole term is its value, such as an array, and a record whose fields are the kernel's outputs is the mapping of its fields. A statistic that JAX can trace is computed on every replication in one jax.vmap call, and any other in a loop.

The replications are one workflow-owned random event of the enclosing workflow scope. A call inside workflow_run(seed=...) therefore reproduces them, and a call outside every scope draws fresh replications.

Parameters:

Name Type Description Default
kernel ConditionalDistribution

The law of the observations given the parameters, such as the likelihood of a model likelihood & prior.

required
law Distribution

A law over the kernel's inputs: the posterior for a posterior predictive check, or the prior for a prior predictive check. A NumericRecord of stacked draws is read as the empirical law of its rows.

required
test_fns callable or sequence of callables

One or more test statistics, each mapping a dataset to a scalar. A statistic is named by its __name__, and the names in a sequence are distinct.

required
observed_data optional

The observed data, in the form of a replication, or as a mapping from the kernel's outputs to their values, the form condition_on takes.

None
num_replications int

The number of replications.

500

Returns:

Type Description
Record

For a single statistic, the record has the fields:

  • replicated_statistics: an EmpiricalDistribution over the statistic's values at the replications, labeled by the statistic's name and declared under the output replicated_statistics.
  • test_fn_name: the statistic's name.
  • observed_statistic: the statistic of observed_data, when observed_data is given.
  • p_value: the fraction of replications whose statistic is at least observed_statistic, when observed_data is given.

For a sequence of statistics, each statistic's fields are nested under its name, so check["mean/p_value"] is the p-value of a statistic named mean.

Raises:

Type Description
TypeError

If kernel is not a ConditionalDistribution, law does not sample, test_fns is neither a callable nor an iterable, a statistic is not callable, or num_replications is not an integer. A kernel that is a law or a batch of laws, such as the model likelihood & prior, raises ApplicabilityError, a TypeError, before anything is sampled.

ValueError

If law has no output for some input of kernel, naming the missing inputs; if law has an output of the same name as an output of kernel; if test_fns is empty or holds two statistics of the same name; or if num_replications is not positive.

Notes

Each statistic's result is also recorded in law.annotations, as the next child check_N of the group predictive_check: a dataset with the variable replicated_statistics over the dimension replication, and the attributes test_fn_name and, when observed_data is given, observed_statistic and p_value.

Examples:

>>> import jax.numpy as jnp
>>> from probpipe import Normal, conditional_distribution, workflow_run
>>> prior = Normal("mu", 0.0, 1.0)
>>> likelihood = conditional_distribution(
...     lambda mu: Normal("y", mu * jnp.ones(10), 1.0),
...     label="y_given_mu",
...     given_spec=prior.event_spec.outputs,
... )
>>> with workflow_run(seed=0):
...     check = predictive_check(likelihood, prior, jnp.mean, jnp.zeros(10))
>>> check["replicated_statistics"].num_atoms
500
>>> 0.0 <= float(check["p_value"]) <= 1.0
True
Source code in probpipe/validation/_predictive_check.py
@function
def predictive_check[D](
    kernel: ConditionalDistribution,
    law: Distribution,
    test_fns: Callable[[D], float] | Sequence[Callable[[D], float]],
    observed_data: D | None = None,
    *,
    num_replications: int = 500,
) -> dict:
    """Compare replicated data with the observed data through test statistics.

    A replication is a draw of the kernel's event from the merge
    ``kernel & law``, which draws the inputs from *law* and then the
    kernel's event at those values. With the posterior as *law* the check is a
    posterior predictive check, and with the prior it is a prior predictive
    check. Each statistic is computed on the same replications and, when
    *observed_data* is given, on the observed data; its p-value is the fraction
    of replications whose statistic is at least the observed one.

    A statistic receives a replication in the form the kernel declares for its
    event: a whole term is its value, such as an array, and a record whose
    fields are the kernel's outputs is the mapping of its fields. A statistic
    that JAX can trace is computed on every replication in one ``jax.vmap``
    call, and any other in a loop.

    The replications are one workflow-owned random event of the enclosing
    workflow scope. A call inside ``workflow_run(seed=...)`` therefore
    reproduces them, and a call outside every scope draws fresh replications.

    Parameters
    ----------
    kernel : ConditionalDistribution
        The law of the observations given the parameters, such as the
        likelihood of a model ``likelihood & prior``.
    law : Distribution
        A law over the kernel's inputs: the posterior for a posterior
        predictive check, or the prior for a prior predictive check. A
        ``NumericRecord`` of stacked draws is read as the empirical law of its
        rows.
    test_fns : callable or sequence of callables
        One or more test statistics, each mapping a dataset to a scalar. A
        statistic is named by its ``__name__``, and the names in a sequence
        are distinct.
    observed_data : optional
        The observed data, in the form of a replication, or as a mapping from
        the kernel's outputs to their values, the form ``condition_on``
        takes.
    num_replications : int
        The number of replications.

    Returns
    -------
    Record
        For a single statistic, the record has the fields:

        - ``replicated_statistics``: an ``EmpiricalDistribution`` over the
          statistic's values at the replications, labeled by the statistic's
          name and declared under the output ``replicated_statistics``.
        - ``test_fn_name``: the statistic's name.
        - ``observed_statistic``: the statistic of *observed_data*, when
          *observed_data* is given.
        - ``p_value``: the fraction of replications whose statistic is at
          least ``observed_statistic``, when *observed_data* is given.

        For a sequence of statistics, each statistic's fields are nested
        under its name, so ``check["mean/p_value"]`` is the p-value of a
        statistic named ``mean``.

    Raises
    ------
    TypeError
        If *kernel* is not a ``ConditionalDistribution``, *law* does not
        sample, *test_fns* is neither a callable nor an iterable, a statistic
        is not callable, or *num_replications* is not an integer. A *kernel*
        that is a law or a batch of laws, such as the model ``likelihood &
        prior``, raises ``ApplicabilityError``, a ``TypeError``, before
        anything is sampled.
    ValueError
        If *law* has no output for some input of *kernel*, naming the
        missing inputs; if *law* has an output of the same name as an output
        of *kernel*; if *test_fns* is empty or holds two statistics of the same
        name; or if *num_replications* is not positive.

    Notes
    -----
    Each statistic's result is also recorded in ``law.annotations``, as the
    next child ``check_N`` of the group ``predictive_check``: a dataset with
    the variable ``replicated_statistics`` over the dimension
    ``replication``, and the attributes ``test_fn_name`` and, when
    *observed_data* is given, ``observed_statistic`` and ``p_value``.

    Examples
    --------
    >>> import jax.numpy as jnp
    >>> from probpipe import Normal, conditional_distribution, workflow_run
    >>> prior = Normal("mu", 0.0, 1.0)
    >>> likelihood = conditional_distribution(
    ...     lambda mu: Normal("y", mu * jnp.ones(10), 1.0),
    ...     label="y_given_mu",
    ...     given_spec=prior.event_spec.outputs,
    ... )
    >>> with workflow_run(seed=0):
    ...     check = predictive_check(likelihood, prior, jnp.mean, jnp.zeros(10))
    >>> check["replicated_statistics"].num_atoms
    500
    >>> 0.0 <= float(check["p_value"]) <= 1.0
    True
    """
    statistics = _planned_statistics(test_fns)
    num_replications = _validate_positive_int("num_replications", num_replications)
    # A NumericRecord of stacked draws is the empirical law of its rows.
    if isinstance(law, NumericRecord):
        name = getattr(law, "label", "posterior")
        row = _reshaped_template(law.event_template, lambda shape: shape[1:])
        law = EmpiricalDistribution(_batch_form(name, law, "draw", row), label=name)
    joint = _predictive_joint(kernel, law, "predictive_check")
    observed = None if observed_data is None else _observed_event(kernel, observed_data)

    # The merge is a ProbPipe law, so its draws follow the distribution ABI.
    key = _claim_validation_key(
        operation_kind="predictive-check",
        execution_mode="sampled",
        sample_shape=(num_replications,),
        provider_abi=_PROBPIPE_DISTRIBUTION_PROVIDER_ABI,
    )
    replicated = _replicated_statistics(joint, kernel, statistics, num_replications, key)

    results = {}
    for name, fn in statistics:
        stats_array = replicated[name]
        result: dict[str, Any] = {
            "replicated_statistics": EmpiricalDistribution(
                stats_array, output_name="replicated_statistics", label=name
            ),
            "test_fn_name": name,
        }
        if observed is not None:
            obs_stat = float(fn(observed))
            result["observed_statistic"] = obs_stat
            result["p_value"] = float(np.mean(stats_array >= obs_stat))
        results[name] = result
    # The law's annotations collect its validation history, one child per statistic.
    for name, result in results.items():
        _record_check_in_annotations(law, replicated[name], result)

    if callable(test_fns):
        return results[statistics[0][0]]
    return results

Scores against a reference posterior

probpipe.validation.Reference(mean=None, cov=None, draws=None, score_fn=None) dataclass

A reference posterior to score an approximation against.

Carries whichever pieces are available so analytic, long-NUTS, and sandwich references share one interface: high-precision moments (mean, cov) (for the moment metrics), draws (for the sample-based distances), and a score_fn = ∇ log π (for ksd).

Parameters:

Name Type Description Default
mean Array or None

Reference mean μ_ref, shape (d,).

None
cov Array or None

Reference covariance Σ_ref, shape (d, d).

None
draws Array or None

Reference draws, shape (n_ref, d).

None
score_fn callable or None

θ ↦ ∇ log π(θ) for a (d,) input.

None

from_draws(draws, *, score_fn=None) classmethod

Build a reference from draws, deriving (mean, cov) from them.

Source code in probpipe/validation/_comparison.py
@classmethod
def from_draws(
    cls, draws: DrawsLike, *, score_fn: Callable[[Array], Array] | None = None
) -> Reference:
    """Build a reference from draws, deriving ``(mean, cov)`` from them."""
    d = _as_draws(draws)
    return cls(mean=d.mean(axis=0), cov=_sample_cov(d), draws=d, score_fn=score_fn)

from_moments(mean, cov, *, draws=None, score_fn=None) classmethod

Build a reference from high-precision analytic/empirical moments.

Parameters:

Name Type Description Default
mean array - like

Reference mean μ_ref, shape (d,).

required
cov array - like

Reference covariance Σ_ref, shape (d, d).

required
draws array - like or EmpiricalDistribution

Reference draws for the sample-based distances: a raw (n_ref, d) array, or an empirical law whose atoms' flat coordinates are the draws.

None
score_fn callable

θ ↦ ∇ log π(θ) for a (d,) input, for ksd.

None

Returns:

Type Description
Reference

The reference, with mean and cov as JAX arrays and draws as an (n_ref, d) array.

Raises:

Type Description
ValueError

If mean is not 1-D or cov is not the matching (d, d).

Source code in probpipe/validation/_comparison.py
@classmethod
def from_moments(
    cls,
    mean: ArrayLike,
    cov: ArrayLike,
    *,
    draws: DrawsLike | None = None,
    score_fn: Callable[[Array], Array] | None = None,
) -> Reference:
    """Build a reference from high-precision analytic/empirical moments.

    Parameters
    ----------
    mean : array-like
        Reference mean ``μ_ref``, shape ``(d,)``.
    cov : array-like
        Reference covariance ``Σ_ref``, shape ``(d, d)``.
    draws : array-like or EmpiricalDistribution, optional
        Reference draws for the sample-based distances: a raw ``(n_ref, d)``
        array, or an empirical law whose atoms' flat coordinates are the draws.
    score_fn : callable, optional
        ``θ ↦ ∇ log π(θ)`` for a ``(d,)`` input, for :func:`ksd`.

    Returns
    -------
    Reference
        The reference, with *mean* and *cov* as JAX arrays and *draws* as an
        ``(n_ref, d)`` array.

    Raises
    ------
    ValueError
        If ``mean`` is not 1-D or ``cov`` is not the matching ``(d, d)``.
    """
    mean, cov = jnp.asarray(mean), jnp.asarray(cov)
    if mean.ndim != 1 or cov.shape != (mean.shape[0], mean.shape[0]):
        raise ValueError(
            f"mean must have shape (d,) and cov shape (d, d); got {mean.shape} and {cov.shape}"
        )
    return cls(
        mean=mean,
        cov=cov,
        draws=None if draws is None else _as_draws(draws),
        score_fn=score_fn,
    )

probpipe.validation.score_posterior(approx, reference, *, metrics=_DEFAULT_METRICS)

Score approx against reference on the named metrics → a scorecard dict.

Metrics whose required reference pieces are absent (e.g. ksd without a score_fn, or the sample distances without draws) are skipped rather than erroring, so one call serves analytic, long-NUTS, and sandwich references. Reused by the test suite and the probpipe-benchmark harness.

The random projections of sliced_wasserstein are one workflow-owned random event of the enclosing workflow scope, which a call claims only when it scores that metric. A call inside workflow_run(seed=...) therefore reproduces the scorecard, and a call outside every scope draws fresh projections.

Parameters:

Name Type Description Default
approx array - like or EmpiricalDistribution

The approximation's draws: an (n, d) array, a 1-D array of n scalars, or an empirical law, read as the flat coordinates of its atoms.

required
reference Reference

The reference posterior to score against.

required
metrics str or sequence of str

The metrics to score, among standardized_mean_error, relative_cov_error, std_ratios, sliced_wasserstein, mmd, and ksd. The default scores each metric but std_ratios. A str names one metric.

_DEFAULT_METRICS

Returns:

Type Description
dict of str to Array

The value of each scored metric under its name, in the order of metrics: a 0-d array, or a (d,) array for std_ratios.

Raises:

Type Description
ValueError

If metrics names an unknown metric, or if the draws a scored metric reads are not an (n, d) or 1-D array, differ in dimension from the reference, or are too few for the metric.

RuntimeError

If sliced Wasserstein scoring claims workflow-owned randomness inside a JAX transformation opened by the caller, such as jax.jit, jax.grad, or jax.vmap.

TypeError

If metrics is not a str or a sequence of str.

Notes

For JAX transformations, call sliced_wasserstein with an explicit key. Sharing a key across mapped inputs shares their random projections; passing a separate key to each input gives independent projections. The random-event guard checks only metrics that claim workflow-owned randomness.

Source code in probpipe/validation/_comparison.py
def score_posterior(
    approx: DrawsLike,
    reference: Reference,
    *,
    metrics: NamesLike = _DEFAULT_METRICS,
) -> dict[str, Array]:
    """Score *approx* against *reference* on the named metrics → a scorecard dict.

    Metrics whose required reference pieces are absent (e.g. ``ksd`` without a
    ``score_fn``, or the sample distances without ``draws``) are skipped rather
    than erroring, so one call serves analytic, long-NUTS, and sandwich
    references. Reused by the test suite and the ``probpipe-benchmark`` harness.

    The random projections of ``sliced_wasserstein`` are one workflow-owned
    random event of the enclosing workflow scope, which a call claims only when
    it scores that metric. A call inside ``workflow_run(seed=...)`` therefore
    reproduces the scorecard, and a call outside every scope draws fresh
    projections.

    Parameters
    ----------
    approx : array-like or EmpiricalDistribution
        The approximation's draws: an ``(n, d)`` array, a 1-D array of ``n``
        scalars, or an empirical law, read as the flat coordinates of its atoms.
    reference : Reference
        The reference posterior to score against.
    metrics : str or sequence of str
        The metrics to score, among ``standardized_mean_error``,
        ``relative_cov_error``, ``std_ratios``, ``sliced_wasserstein``,
        ``mmd``, and ``ksd``. The default scores each metric but
        ``std_ratios``. A str names one metric.

    Returns
    -------
    dict of str to Array
        The value of each scored metric under its name, in the order of
        *metrics*: a 0-d array, or a ``(d,)`` array for ``std_ratios``.

    Raises
    ------
    ValueError
        If *metrics* names an unknown metric, or if the draws a scored metric
        reads are not an ``(n, d)`` or 1-D array, differ in dimension from the
        reference, or are too few for the metric.
    RuntimeError
        If sliced Wasserstein scoring claims workflow-owned randomness inside
        a JAX transformation opened by the caller, such as ``jax.jit``,
        ``jax.grad``, or ``jax.vmap``.
    TypeError
        If *metrics* is not a str or a sequence of str.

    Notes
    -----
    For JAX transformations, call ``sliced_wasserstein`` with an explicit key.
    Sharing a key across mapped inputs shares their random projections;
    passing a separate key to each input gives independent projections.
    The random-event guard checks only metrics that claim workflow-owned randomness.
    """
    _context._assert_workflow_admission()
    metric_names = _as_names(metrics, what="score_posterior metrics")
    supported_metrics = {
        "standardized_mean_error",
        "relative_cov_error",
        "std_ratios",
        "sliced_wasserstein",
        "mmd",
        "ksd",
    }
    for name in metric_names:
        if name not in supported_metrics:
            raise ValueError(unknown_names("metric", [name], sorted(supported_metrics)))

    # Sliced Wasserstein scoring checks its draws before it claims the key of its projections.
    sliced: tuple[Array, Array, PRNGKey] | None = None
    if "sliced_wasserstein" in metric_names and reference.draws is not None:
        x, y = _as_draws(approx), _as_draws(reference.draws)
        if x.shape[1] != y.shape[1]:
            raise ValueError(
                f"approx draws have dimension {x.shape[1]}, but reference.draws have "
                f"dimension {y.shape[1]}; they must match"
            )
        key = _claim_validation_key(
            operation_kind="score-posterior",
            execution_mode="sliced-wasserstein",
            sample_shape=(128,),
            provider_abi=_SLICED_WASSERSTEIN_PROVIDER_ABI,
        )
        sliced = (x, y, key)

    out: dict[str, Array] = {}
    for name in metric_names:
        # The moment metrics ``_require`` their reference pieces and raise
        # ``_MissingReference`` when absent; catch that to skip them. The
        # sample/score metrics take the relevant piece directly, so guard on it.
        try:
            if name == "standardized_mean_error":
                out[name] = standardized_mean_error(approx, reference)
            elif name == "relative_cov_error":
                out[name] = relative_cov_error(approx, reference)
            elif name == "std_ratios":
                out[name] = std_ratios(approx, reference)
            elif name == "sliced_wasserstein":
                if sliced is not None:
                    x, y, key = sliced
                    out[name] = sliced_wasserstein(x, y, key=key)
            elif name == "mmd":
                if reference.draws is not None:
                    out[name] = mmd(approx, reference.draws)
            elif name == "ksd":
                if reference.score_fn is not None:
                    out[name] = ksd(approx, reference.score_fn)
        except _MissingReference:
            continue
    return out

probpipe.validation.standardized_mean_error(approx, ref)

Mean error in posterior-standard-deviation units: ‖Σ_ref^{-1/2}(μ̂ − μ_ref)‖₂.

The Mahalanobis distance between the approximate mean μ̂ and the reference mean μ_ref under Σ_ref — scale- and rotation-invariant, reported in units of reference posterior standard deviations. Computed as ‖L⁻¹(μ̂ − μ_ref)‖₂ with L = chol(Σ_ref).

Source code in probpipe/validation/_comparison.py
def standardized_mean_error(approx: DrawsLike, ref: Reference) -> Array:
    r"""Mean error in posterior-standard-deviation units: ``‖Σ_ref^{-1/2}(μ̂ − μ_ref)‖₂``.

    The Mahalanobis distance between the approximate mean ``μ̂`` and the
    reference mean ``μ_ref`` under ``Σ_ref`` — scale- and rotation-invariant,
    reported in units of reference posterior standard deviations. Computed as
    ``‖L⁻¹(μ̂ − μ_ref)‖₂`` with ``L = chol(Σ_ref)``.
    """
    _require(ref, "standardized_mean_error", "mean", "cov")
    mu_hat = _as_draws(approx).mean(axis=0)
    if mu_hat.shape != ref.mean.shape:
        raise ValueError(
            f"the approximation's mean has shape {mu_hat.shape}, but the reference mean has "
            f"shape {ref.mean.shape}; they must match"
        )
    diff = mu_hat - ref.mean
    chol = jnp.linalg.cholesky(ref.cov)
    z = jax.scipy.linalg.solve_triangular(chol, diff, lower=True)
    return jnp.linalg.norm(z)

probpipe.validation.relative_cov_error(approx, ref)

Operator-norm whitened covariance error: ‖I − Σ_ref^{-1/2} Σ̂ Σ_ref^{-1/2}‖₂.

The spectral norm of the symmetrically whitened covariance deviation from identity. Because the whitened matrix is symmetric, this equals the worst-direction variance-ratio error max_d |1 − λ_d|, where the λ_d are the eigenvalues of Σ_ref⁻¹ Σ̂ (the generalized variance ratios) — 0 iff Σ̂ = Σ_ref. The whitening Σ_ref^{-1/2} Σ̂ Σ_ref^{-1/2} is computed as L⁻¹ Σ̂ L⁻ᵀ via two triangular solves, L = chol(Σ_ref).

Source code in probpipe/validation/_comparison.py
def relative_cov_error(approx: DrawsLike, ref: Reference) -> Array:
    r"""Operator-norm whitened covariance error: ``‖I − Σ_ref^{-1/2} Σ̂ Σ_ref^{-1/2}‖₂``.

    The spectral norm of the symmetrically whitened covariance deviation from
    identity. Because the whitened matrix is symmetric, this *equals* the
    worst-direction variance-ratio error ``max_d |1 − λ_d|``, where the ``λ_d``
    are the eigenvalues of ``Σ_ref⁻¹ Σ̂`` (the generalized variance ratios) —
    ``0`` iff ``Σ̂ = Σ_ref``. The whitening ``Σ_ref^{-1/2} Σ̂ Σ_ref^{-1/2}`` is
    computed as ``L⁻¹ Σ̂ L⁻ᵀ`` via two triangular solves, ``L = chol(Σ_ref)``.
    """
    _require(ref, "relative_cov_error", "cov")
    cov_hat = _sample_cov(_as_draws(approx))
    if cov_hat.shape != ref.cov.shape:
        raise ValueError(
            f"the approximation's covariance has shape {cov_hat.shape}, but the reference "
            f"covariance has shape {ref.cov.shape}; they must match"
        )
    chol = jnp.linalg.cholesky(ref.cov)  # L, lower-triangular
    whitened = jax.scipy.linalg.solve_triangular(chol, cov_hat, lower=True)  # L⁻¹ Σ̂
    whitened = jax.scipy.linalg.solve_triangular(chol, whitened.T, lower=True)  # L⁻¹ Σ̂ L⁻ᵀ
    deviation = jnp.eye(whitened.shape[0]) - whitened
    return jnp.linalg.norm(deviation, ord=2)

probpipe.validation.std_ratios(approx, ref)

Per-coordinate standard-deviation ratios σ̂_d / σ_{ref,d} (a (d,) array).

A coordinate-wise readout for reporting; the full-covariance relative_cov_error subsumes it. A reference coordinate with zero variance yields inf for that ratio.

Source code in probpipe/validation/_comparison.py
def std_ratios(approx: DrawsLike, ref: Reference) -> Array:
    r"""Per-coordinate standard-deviation ratios ``σ̂_d / σ_{ref,d}`` (a ``(d,)`` array).

    A coordinate-wise readout for reporting; the full-covariance
    :func:`relative_cov_error` subsumes it. A reference coordinate with zero
    variance yields ``inf`` for that ratio.
    """
    _require(ref, "std_ratios", "cov")
    var_hat = jnp.diag(_sample_cov(_as_draws(approx)))
    var_ref = jnp.diag(ref.cov)
    if var_hat.shape != var_ref.shape:
        raise ValueError(
            f"the approximation has dimension {var_hat.shape[0]}, but the reference has "
            f"dimension {var_ref.shape[0]}; they must match"
        )
    return jnp.sqrt(var_hat / var_ref)

probpipe.validation.sliced_wasserstein(x, y, *, key, n_projections=128)

Sliced 2-Wasserstein distance between two sets of draws.

Projects x and y onto n_projections random unit directions and returns (mean_θ W₂²(P_θ x, P_θ y))^{1/2}. Each 1-D W₂² is computed exactly from the order statistics — including unequal sample sizes, by integrating (Q_x − Q_y)² over the union of the two empirical-CDF level sets (no quantile-grid approximation).

Source code in probpipe/validation/_comparison.py
def sliced_wasserstein(
    x: DrawsLike, y: DrawsLike, *, key: PRNGKey, n_projections: int = 128
) -> Array:
    r"""Sliced 2-Wasserstein distance between two sets of draws.

    Projects ``x`` and ``y`` onto ``n_projections`` random unit directions and
    returns ``(mean_θ W₂²(P_θ x, P_θ y))^{1/2}``. Each 1-D ``W₂²`` is computed
    *exactly* from the order statistics — including unequal sample sizes, by
    integrating ``(Q_x − Q_y)²`` over the union of the two empirical-CDF level
    sets (no quantile-grid approximation).
    """
    x, y = _as_draws(x), _as_draws(y)
    if x.shape[1] != y.shape[1]:
        raise ValueError(f"x and y must share a dimension; got {x.shape[1]} and {y.shape[1]}")
    n, m = x.shape[0], y.shape[0]
    proj = jax.random.normal(key, (n_projections, x.shape[1]))
    proj = proj / jnp.linalg.norm(proj, axis=-1, keepdims=True)
    xp = jnp.sort(x @ proj.T, axis=0)  # (n, P) sorted projections
    yp = jnp.sort(y @ proj.T, axis=0)  # (m, P)
    # 1-D W₂² = ∫₀¹ (Q_x − Q_y)² du, exact since both quantile functions are
    # piecewise-constant on the union of their CDF level sets {i/n} ∪ {j/m}.
    cx = jnp.arange(1, n + 1) / n  # right ends of x's CDF steps
    cy = jnp.arange(1, m + 1) / m
    levels = jnp.sort(jnp.concatenate([cx, cy]))  # (n + m,)
    widths = jnp.diff(levels, prepend=0.0)  # sub-interval lengths; duplicates get width 0
    ix = jnp.clip(jnp.searchsorted(cx, levels), 0, n - 1)  # quantile index per sub-interval
    iy = jnp.clip(jnp.searchsorted(cy, levels), 0, m - 1)
    w2_sq = jnp.sum(widths[:, None] * (xp[ix] - yp[iy]) ** 2, axis=0)  # (P,)
    return jnp.sqrt(jnp.mean(w2_sq))

probpipe.validation.mmd(x, y, *, bandwidth='median')

Unbiased squared MMD with an RBF kernel.

MMD²_u = mean_{i≠j} k(xᵢ,xⱼ) + mean_{i≠j} k(yᵢ,yⱼ) − 2·mean_{i,j} k(xᵢ,yⱼ), k(a,b) = exp(−‖a−b‖² / ℓ²). With bandwidth="median" the length-scale ℓ² is the median cross-pair squared distance (a fixed-shape, jit-safe heuristic). The unbiased estimator can be slightly negative.

Source code in probpipe/validation/_comparison.py
def mmd(x: DrawsLike, y: DrawsLike, *, bandwidth: float | Literal["median"] = "median") -> Array:
    r"""Unbiased squared MMD with an RBF kernel.

    ``MMD²_u = mean_{i≠j} k(xᵢ,xⱼ) + mean_{i≠j} k(yᵢ,yⱼ) − 2·mean_{i,j} k(xᵢ,yⱼ)``,
    ``k(a,b) = exp(−‖a−b‖² / ℓ²)``. With ``bandwidth="median"`` the length-scale
    ``ℓ²`` is the median cross-pair squared distance (a fixed-shape, jit-safe
    heuristic). The unbiased estimator can be slightly negative.
    """
    x, y = _as_draws(x), _as_draws(y)
    if x.shape[1] != y.shape[1]:
        raise ValueError(f"x and y must share a dimension; got {x.shape[1]} and {y.shape[1]}")
    m, n = x.shape[0], y.shape[0]
    if m < 2 or n < 2:
        raise ValueError(f"unbiased MMD needs >= 2 draws per sample; got {m} and {n}")
    dxx, dyy, dxy = _sq_dists(x, x), _sq_dists(y, y), _sq_dists(x, y)
    if bandwidth == "median":
        ell2 = jnp.median(dxy)
        ell2 = jnp.where(ell2 > 0, ell2, 1.0)  # unit fallback for a degenerate sample
    else:
        ell2 = jnp.asarray(bandwidth) ** 2
    kxx, kyy, kxy = jnp.exp(-dxx / ell2), jnp.exp(-dyy / ell2), jnp.exp(-dxy / ell2)
    off_xx = (jnp.sum(kxx) - jnp.trace(kxx)) / (m * (m - 1))
    off_yy = (jnp.sum(kyy) - jnp.trace(kyy)) / (n * (n - 1))
    return off_xx + off_yy - 2.0 * jnp.mean(kxy)

probpipe.validation.ksd(x, score_fn, *, bandwidth='median')

Kernel Stein discrepancy with the inverse-multiquadric (IMQ) kernel.

The U-statistic KSD = (mean_{i≠j} u_p(xᵢ,xⱼ))^{1/2} for the Stein kernel u_p of the IMQ base kernel k(a,b) = (c² + ‖a−b‖²)^{-1/2} and score sₚ = ∇ log π. With bandwidth="median", c² is the median off-diagonal squared distance. Needs no reference draws — a gradient-based goodness-of-fit to the target π; → 0 as the draws come to match π.

Source code in probpipe/validation/_comparison.py
def ksd(
    x: DrawsLike,
    score_fn: Callable[[Array], Array],
    *,
    bandwidth: float | Literal["median"] = "median",
) -> Array:
    r"""Kernel Stein discrepancy with the inverse-multiquadric (IMQ) kernel.

    The U-statistic ``KSD = (mean_{i≠j} u_p(xᵢ,xⱼ))^{1/2}`` for the Stein kernel
    ``u_p`` of the IMQ base kernel ``k(a,b) = (c² + ‖a−b‖²)^{-1/2}`` and score
    ``sₚ = ∇ log π``. With ``bandwidth="median"``, ``c²`` is the median
    off-diagonal squared distance. Needs no reference draws — a gradient-based
    goodness-of-fit to the target ``π``; ``→ 0`` as the draws come to match
    ``π``.
    """
    x = _as_draws(x)
    n, d = x.shape
    if n < 2:
        raise ValueError(f"KSD U-statistic needs >= 2 draws; got {n}")
    scores = jax.vmap(score_fn)(x)  # (n, d)
    diff = x[:, None, :] - x[None, :, :]  # (n, n, d)
    sq = jnp.sum(diff**2, axis=-1)  # (n, n)
    if bandwidth == "median":
        # NaN the diagonal so nanmedian ignores the (zero) self-distances.
        offdiag = sq + jnp.diag(jnp.full(n, jnp.nan))
        c2 = jnp.nanmedian(offdiag)
        c2 = jnp.where(c2 > 0, c2, 1.0)  # unit fallback for a degenerate sample
    else:
        c2 = jnp.asarray(bandwidth) ** 2
    beta = -0.5
    base = c2 + sq  # (n, n)
    k_b = base**beta
    k_b1 = base ** (beta - 1.0)
    k_b2 = base ** (beta - 2.0)
    s_dot_s = scores @ scores.T  # (n, n)  sₓ·s_y
    sx_r = jnp.einsum("id,ijd->ij", scores, diff)  # sₓ·(xᵢ−xⱼ)
    sy_r = jnp.einsum("jd,ijd->ij", scores, diff)  # s_y·(xᵢ−xⱼ)
    grad_term = 2.0 * beta * k_b1 * (sy_r - sx_r)
    trace_term = -2.0 * beta * d * k_b1 - 4.0 * beta * (beta - 1.0) * k_b2 * sq
    u = s_dot_s * k_b + grad_term + trace_term  # (n, n)
    ksd_sq = (jnp.sum(u) - jnp.trace(u)) / (n * (n - 1))
    return jnp.sqrt(jnp.maximum(ksd_sq, 0.0))

Calibration and coverage

probpipe.validation.simulation_based_calibration(model, *, observed, num_simulations, num_posterior_draws, posterior=None, method=None, method_options=None)

Simulation-based calibration of a posterior (Talts et al. 2018).

Each of num_simulations replications draws the parameters θ★ and the observed fields y from the joint model, forms the posterior at y, draws from it, and ranks each entry of the flattened θ★ among the draws. Under a calibrated posterior each rank is uniform on {0, …, num_posterior_draws}. The result summarizes each parameter's ranks by their KS distance from uniform and its p-value.

The posterior at y is formed in one of two ways:

  1. with posterior, it is the kernel's law at y, which condition_on(posterior, {input_name: y}) returns without a fit, as for an amortized posterior or a closed-form posterior;
  2. otherwise, it is the fit of model at y that condition_on.using(method=method, method_options=method_options)(model, y) returns.

posterior's inputs take the observed fields of their names, and a kernel with one input, such as an amortized posterior's observation, takes the one observed field. The draws are sample(posterior_at_y, sample_shape=(num_posterior_draws,)) for every kind of posterior: the atoms of a weighted empirical law, such as SMC-ABC's particles, are resampled by weight, a network posterior is evaluated, and an MCMC posterior's atoms are drawn at random.

The calibration takes its randomness from the enclosing workflow scope, whose workflow-owned random events it claims in program order: one sample(model, sample_shape=(num_simulations,)) draws the θ★ and y of every replication, and then each replication forms its posterior and draws from it. A call inside workflow_run(seed=...) therefore reproduces its ranks, and an unscoped call draws afresh.

Parameters:

Name Type Description Default
model Distribution

A joint that samples, over the parameters and the observed fields, such as likelihood & prior.

required
observed str or sequence of str

The fields of a draw that the posterior conditions on; the others are the parameters. A str names one field.

required
num_simulations int

The number of replications.

required
num_posterior_draws int

The number of draws of each replication's posterior, which is the largest rank. The ranks assume nearly independent draws, so for an empirical posterior, such as MCMC chains or weighted particles, it should not exceed the effective sample size of the atoms. For an MCMC method, set the chain length in method_options to make it so.

required
posterior ConditionalDistribution

A posterior kernel from the observed fields to the parameters, such as the amortized posterior that learn_amortized_posterior returns. Without it, each replication fits model at its observed values.

None
method str

The inference method of each fit, by name; None selects the method as condition_on does.

None
method_options Mapping

The options of each fit's method, such as {"num_warmup": 500, "num_results": 2000}. Each fit's seed is a workflow-owned random event of the enclosing scope.

None

Returns:

Type Description
SBCResult

The ranks, of shape (num_simulations, num_params), with the KS statistic and p-value of each parameter.

Raises:

Type Description
TypeError

If model does not sample; if posterior is not a ConditionalDistribution; if observed is not a str or a sequence of str; if a count is not an integer; or if method is not a non-empty string or method_options is not a mapping of option names. A method's TypeError for an option it does not read propagates.

ValueError

If a count is not positive; if an observed name is not a field of a draw, or no parameter is left; if method or method_options is given with posterior; if posterior's inputs do not take the observed fields; or if the posterior's draw does not hold the parameters: a record draw whose fields are the posterior's outputs names other fields, or a whole-term draw meets several parameters.

ResolutionError

If no route of condition_on forms the posterior at y, or that posterior does not sample.

ReplayCompatibilityError

If a replay_run scope is active, since a replay accepts one top-level Function call and the calibration makes several.

Notes

The draws of θ★ and y are one event, which the call claims first, so they do not depend on the posterior or the method. Two calls with the same model and num_simulations, at the same position of scopes with the same seed, therefore rank their posteriors' draws against the same θ★ and y.

Examples:

The exact posterior kernel of a conjugate normal model covers θ★ at about the nominal rates:

>>> import jax.numpy as jnp
>>> from probpipe import Normal, NumericArraySpec, conditional_distribution, workflow_run
>>> prior = Normal("mu", 0.0, 2.0)
>>> likelihood = conditional_distribution(
...     lambda mu: Normal("y", mu * jnp.ones(5), 1.0),
...     label="y_given_mu",
...     given_spec=prior.event_spec.outputs,
... )
>>> precision = 1 / 4 + 5
>>> exact = conditional_distribution(
...     lambda y: Normal("mu", jnp.sum(y) / precision, precision**-0.5),
...     label="posterior",
...     given_spec={"y": NumericArraySpec((5,))},
... )
>>> with workflow_run(seed=0):
...     result = simulation_based_calibration(
...         (likelihood & prior),
...         observed="y",
...         posterior=exact,
...         num_simulations=100,
...         num_posterior_draws=99,
...     )
>>> result.ranks.shape
(100, 1)
>>> result.coverage((0.5, 0.9))
{0.5: array([0.47]), 0.9: array([0.95])}
Source code in probpipe/validation/_calibration.py
def simulation_based_calibration(
    model: Distribution,
    *,
    observed: NamesLike,
    num_simulations: int,
    num_posterior_draws: int,
    posterior: ConditionalDistribution | None = None,
    method: str | None = None,
    method_options: Mapping[str, Any] | None = None,
) -> SBCResult:
    """Simulation-based calibration of a posterior (Talts et al. 2018).

    Each of *num_simulations* replications draws the parameters ``θ★`` and the
    *observed* fields ``y`` from the joint *model*, forms the posterior at
    ``y``, draws from it, and ranks each entry of the flattened ``θ★`` among the
    draws. Under a calibrated posterior each rank is uniform on
    ``{0, …, num_posterior_draws}``. The result summarizes each parameter's
    ranks by their KS distance from uniform and its p-value.

    The posterior at ``y`` is formed in one of two ways:

    1. with *posterior*, it is the kernel's law at ``y``, which
       ``condition_on(posterior, {input_name: y})`` returns without a fit, as for an
       amortized posterior or a closed-form posterior;
    2. otherwise, it is the fit of *model* at ``y`` that
       ``condition_on.using(method=method, method_options=method_options)(model, y)``
       returns.

    *posterior*'s inputs take the observed fields of their names, and a
    kernel with one input, such as an amortized posterior's
    ``observation``, takes the one observed field. The draws are
    ``sample(posterior_at_y, sample_shape=(num_posterior_draws,))`` for every
    kind of posterior: the atoms of a weighted empirical law, such as SMC-ABC's
    particles, are resampled by weight, a network posterior is evaluated, and an
    MCMC posterior's atoms are drawn at random.

    The calibration takes its randomness from the enclosing workflow scope,
    whose workflow-owned random events it claims in program order: one
    ``sample(model, sample_shape=(num_simulations,))`` draws the ``θ★`` and
    ``y`` of every replication, and then each replication forms its posterior
    and draws from it. A call inside ``workflow_run(seed=...)`` therefore
    reproduces its ranks, and an unscoped call draws afresh.

    Parameters
    ----------
    model : Distribution
        A joint that samples, over the parameters and the *observed* fields,
        such as ``likelihood & prior``.
    observed : str or sequence of str
        The fields of a draw that the posterior conditions on; the others are
        the parameters. A str names one field.
    num_simulations : int
        The number of replications.
    num_posterior_draws : int
        The number of draws of each replication's posterior, which is the
        largest rank. The ranks assume nearly independent draws, so for an
        empirical posterior, such as MCMC chains or weighted particles, it
        should not exceed the effective sample size of the atoms. For an MCMC
        method, set the chain length in *method_options* to make it so.
    posterior : ConditionalDistribution, optional
        A posterior kernel from the observed fields to the parameters, such as
        the amortized posterior that ``learn_amortized_posterior`` returns.
        Without it, each replication fits *model* at its observed values.
    method : str, optional
        The inference method of each fit, by name; ``None`` selects the method
        as :func:`condition_on` does.
    method_options : Mapping, optional
        The options of each fit's method, such as ``{"num_warmup": 500,
        "num_results": 2000}``. Each fit's seed is a workflow-owned random event
        of the enclosing scope.

    Returns
    -------
    SBCResult
        The ranks, of shape ``(num_simulations, num_params)``, with the KS
        statistic and p-value of each parameter.

    Raises
    ------
    TypeError
        If *model* does not sample; if *posterior* is not a
        ``ConditionalDistribution``; if *observed* is not a str or a sequence
        of str; if a count is not an integer; or if *method* is not a non-empty
        string or *method_options* is not a mapping of option names. A method's
        ``TypeError`` for an option it does not read propagates.
    ValueError
        If a count is not positive; if an *observed* name is not a field of a
        draw, or no parameter is left; if *method* or *method_options* is given
        with *posterior*; if *posterior*'s inputs do not take the observed
        fields; or if the posterior's draw does not hold the parameters: a record
        draw whose fields are the posterior's outputs names other fields, or a whole-term draw meets
        several parameters.
    ResolutionError
        If no route of :func:`condition_on` forms the posterior at ``y``, or
        that posterior does not sample.
    ReplayCompatibilityError
        If a ``replay_run`` scope is active, since a replay accepts one
        top-level ``Function`` call and the calibration makes several.

    Notes
    -----
    The draws of ``θ★`` and ``y`` are one event, which the call claims first,
    so they do not depend on the posterior or the method. Two calls with the
    same *model* and *num_simulations*, at the same position of scopes with the
    same seed, therefore rank their posteriors' draws against the same ``θ★``
    and ``y``.

    Examples
    --------
    The exact posterior kernel of a conjugate normal model covers ``θ★`` at
    about the nominal rates:

    >>> import jax.numpy as jnp
    >>> from probpipe import Normal, NumericArraySpec, conditional_distribution, workflow_run
    >>> prior = Normal("mu", 0.0, 2.0)
    >>> likelihood = conditional_distribution(
    ...     lambda mu: Normal("y", mu * jnp.ones(5), 1.0),
    ...     label="y_given_mu",
    ...     given_spec=prior.event_spec.outputs,
    ... )
    >>> precision = 1 / 4 + 5
    >>> exact = conditional_distribution(
    ...     lambda y: Normal("mu", jnp.sum(y) / precision, precision**-0.5),
    ...     label="posterior",
    ...     given_spec={"y": NumericArraySpec((5,))},
    ... )
    >>> with workflow_run(seed=0):
    ...     result = simulation_based_calibration(
    ...         (likelihood & prior),
    ...         observed="y",
    ...         posterior=exact,
    ...         num_simulations=100,
    ...         num_posterior_draws=99,
    ...     )
    >>> result.ranks.shape
    (100, 1)
    >>> result.coverage((0.5, 0.9))
    {0.5: array([0.47]), 0.9: array([0.95])}
    """
    _context._assert_workflow_admission()
    num_simulations = _validate_positive_int("num_simulations", num_simulations)
    num_posterior_draws = _validate_positive_int(
        "num_posterior_draws",
        num_posterior_draws,
    )
    if posterior is not None:
        if method is not None or method_options is not None:
            raise ValueError(
                "simulation_based_calibration takes either posterior or method and "
                "method_options, not both"
            )
        if not isinstance(posterior, ConditionalDistribution):
            raise TypeError(
                "posterior must be a ConditionalDistribution from the observed fields to "
                f"the parameters; got {type(posterior).__name__}"
            )
    # Configured before any draw, so a malformed method or option fails first.
    fit = condition_on.using(method=method, method_options=method_options)
    if not callable(getattr(model, "_sample", None)):
        raise TypeError(
            f"simulation_based_calibration: model must be a distribution that can be sampled; "
            f"got {type(model).__name__}"
        )
    observed = _as_names(observed, what="simulation_based_calibration observed")
    outputs = tuple(model.event_spec.outputs)
    unknown = [name for name in observed if name not in outputs]
    if unknown:
        raise ValueError(unknown_names("observed field", unknown, outputs, "fields"))
    parameters = tuple(name for name in outputs if name not in observed)
    if not parameters:
        raise ValueError(
            f"observed={list(observed)} includes every field of {model.label!r}, so no "
            f"parameters are left to calibrate"
        )
    binding: dict[str, str] = {}
    if posterior is not None:
        binding = _input_binding(posterior, observed)
        _check_parameters(posterior.event_spec, parameters, posterior.label)

    simulations = _raw_record(sample.using(raw=True)(model, sample_shape=(num_simulations,)))
    rank_rows: list[np.ndarray] = []
    entry_names: tuple[str, ...] | None = None
    for index in range(num_simulations):
        draw = jax.tree.map(lambda column, i=index: column[i], simulations)
        theta_star = {name: draw[name] for name in parameters}
        if posterior is None:
            law = fit(model, {name: draw[name] for name in observed})
        else:
            law = condition_on(
                posterior, {input_name: draw[field] for input_name, field in binding.items()}
            )
        draws = sample.using(raw=True)(law, sample_shape=(num_posterior_draws,))
        if entry_names is None:
            _check_parameters(law.event_spec, parameters, law.label)
            entry_names = _entry_names(law)
        # A whole-term posterior's draw is its one parameter's value.
        point = (
            theta_star if _has_record_outputs(law.event_spec) else next(iter(theta_star.values()))
        )
        flat_draws = _flatten(draws, law.event_spec, batch_ndim=1)  # (L, p)
        rank_rows.append(np.asarray(_ranks(flat_draws, _flatten(point, law.event_spec))))

    ranks = np.stack(rank_rows).astype(int)  # (num_simulations, p)
    ks_stat, ks_pvalue = _ks_uniform(ranks, num_posterior_draws)
    return SBCResult(
        ranks=ranks,
        num_posterior_draws=num_posterior_draws,
        param_names=entry_names,
        ks_statistic=ks_stat,
        ks_pvalue=ks_pvalue,
    )

probpipe.validation.SBCResult(ranks, num_posterior_draws, param_names, ks_statistic, ks_pvalue) dataclass

Result of simulation_based_calibration.

Attributes:

Name Type Description
ranks ndarray

Integer ranks of θ★ among the posterior draws, shape (num_simulations, num_params), each in {0, …, num_posterior_draws}. The rank counts draws strictly below θ★; this assumes continuous draws (ties are measure-zero for a continuous posterior, but would bias ranks low for a discrete-valued parameter).

num_posterior_draws int

L: the number of posterior draws of each replication, which is the largest rank.

param_names tuple[str, ...] or None

The name of each column of ranks and ks_*: field for a scalar leaf, and field[i] for each entry of a larger leaf, in the posterior's leaf order.

ks_statistic ndarray

Per-parameter KS distance of the normalized ranks from Uniform[0, 1].

ks_pvalue ndarray

Per-parameter KS p-value against Uniform[0, 1]; small ⇒ ranks are non-uniform ⇒ miscalibrated. This is a diagnostic — inspect it (and the rank histogram) and apply your own threshold, with a multiple-comparison correction across parameters, rather than reading off a pass/fail verdict.

rank_histogram(num_bins=20)

Rank histogram per parameter, shape (num_params, num_bins).

Bins the normalized ranks into num_bins equal-width bins over [0, 1]; a calibrated method gives approximately flat histograms.

Source code in probpipe/validation/_calibration.py
def rank_histogram(self, num_bins: int = 20) -> np.ndarray:
    """Rank histogram per parameter, shape ``(num_params, num_bins)``.

    Bins the normalized ranks into ``num_bins`` equal-width bins over
    ``[0, 1]``; a calibrated method gives approximately flat histograms.
    """
    u = (self.ranks + 0.5) / (self.num_posterior_draws + 1)
    edges = np.linspace(0.0, 1.0, num_bins + 1)
    return np.stack([np.histogram(u[:, j], bins=edges)[0] for j in range(u.shape[1])])

coverage(levels=(0.5, 0.8, 0.9, 0.95))

The share of replications whose θ★ lies in the central interval of each level.

θ★ lies in the central level interval of its posterior when its normalized rank u = (r + 0.5) / (L + 1) lies in [(1 − level) / 2, (1 + level) / 2], so the shares are computed from the ranks alone. Under a calibrated posterior the expected share is the level, within 1 / (L + 1). The shares match the mean of interval_coverage over the replications' posterior draws, except at a rank next to an end of the interval, where interval_coverage interpolates between two draws.

Parameters:

Name Type Description Default
levels sequence of float

The credible levels, each in (0, 1).

(0.5, 0.8, 0.9, 0.95)

Returns:

Type Description
dict of float to np.ndarray

For each level, the share of replications that cover θ★, one per parameter, of shape (num_params,).

Raises:

Type Description
TypeError

If levels is not a sequence of numbers.

ValueError

If a level is not in (0, 1).

Source code in probpipe/validation/_calibration.py
def coverage(self, levels: Sequence[float] = (0.5, 0.8, 0.9, 0.95)) -> dict[float, np.ndarray]:
    """The share of replications whose ``θ★`` lies in the central interval of each level.

    ``θ★`` lies in the central ``level`` interval of its posterior when its
    normalized rank ``u = (r + 0.5) / (L + 1)`` lies in
    ``[(1 − level) / 2, (1 + level) / 2]``, so the shares are computed from
    the ranks alone. Under a calibrated posterior the expected share is the
    level, within ``1 / (L + 1)``. The shares match the mean of
    :func:`interval_coverage` over the replications' posterior draws, except
    at a rank next to an end of the interval, where
    :func:`interval_coverage` interpolates between two draws.

    Parameters
    ----------
    levels : sequence of float
        The credible levels, each in ``(0, 1)``.

    Returns
    -------
    dict of float to np.ndarray
        For each level, the share of replications that cover ``θ★``, one per
        parameter, of shape ``(num_params,)``.

    Raises
    ------
    TypeError
        If *levels* is not a sequence of numbers.
    ValueError
        If a level is not in ``(0, 1)``.
    """
    u = (self.ranks + 0.5) / (self.num_posterior_draws + 1)
    shares: dict[float, np.ndarray] = {}
    for level in _credible_levels(levels):
        lo, hi = (1.0 - level) / 2.0, (1.0 + level) / 2.0
        shares[level] = np.mean((u >= lo) & (u <= hi), axis=0)
    return shares

probpipe.validation.interval_coverage(draws_or_dist, truth, *, levels=(0.5, 0.8, 0.9, 0.95))

Central-credible-interval coverage of truth, per parameter.

For each level, checks whether each entry of truth lies in the central level interval [q_{(1−level)/2}, q_{(1+level)/2}] of the per-parameter posterior. Returns {level: covered} with covered a boolean array over parameters. Averaging the indicators over many (posterior, truth) pairs gives the frequentist coverage, which matches the nominal level for a calibrated method.

draws_or_dist is an (n, d) (or 1-D (n,)) array of draws or an empirical law, read as the flat coordinates of its atoms (treated as equally weighted, as MCMC draws are); truth is the matching (d,).

Source code in probpipe/validation/_calibration.py
def interval_coverage(
    draws_or_dist: Any,
    truth: ArrayLike,
    *,
    levels: Sequence[float] = (0.5, 0.8, 0.9, 0.95),
) -> dict[float, Array]:
    """Central-credible-interval coverage of *truth*, per parameter.

    For each ``level``, checks whether each entry of *truth* lies in the
    central ``level`` interval ``[q_{(1−level)/2}, q_{(1+level)/2}]`` of the
    per-parameter posterior. Returns ``{level: covered}`` with ``covered`` a
    boolean array over parameters. Averaging the indicators over many
    ``(posterior, truth)`` pairs gives the frequentist coverage, which matches the
    nominal level for a calibrated method.

    *draws_or_dist* is an ``(n, d)`` (or 1-D ``(n,)``) array of draws or an
    empirical law, read as the flat coordinates of its atoms (treated as
    equally weighted, as MCMC draws are); *truth* is the matching ``(d,)``.
    """
    draws = jnp.asarray(
        _coordinates(draws_or_dist)
        if isinstance(draws_or_dist, EmpiricalDistribution)
        else draws_or_dist
    )
    if draws.ndim == 1:
        draws = draws[:, None]
    truth = jnp.atleast_1d(jnp.asarray(truth))
    if truth.shape[0] != draws.shape[1]:
        raise ValueError(
            f"truth has {truth.shape[0]} values, but the draws have dimension {draws.shape[1]}; "
            f"they must match"
        )
    out: dict[float, Array] = {}
    for level in levels:
        lo, hi = (1.0 - level) / 2.0, (1.0 + level) / 2.0
        q = jnp.quantile(draws, jnp.array([lo, hi]), axis=0)  # (2, d)
        out[float(level)] = (truth >= q[0]) & (truth <= q[1])
    return out