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.

Diagnostics

The diagnostic functions compute a diagnostic of a posterior and record it in the posterior's annotations, and posterior.diagnostics returns a view that reads them. This page documents the MCMC, predictive, and leave-one-out diagnostics and the views, and the checks of an approximation against a reference posterior are on Validation.

MCMC diagnostics

probpipe.diagnostics.add_rhat(posterior, *, method='rank', threshold=_RHAT_THRESHOLD, force=False)

Compute R-hat and attach to _annotations/diagnostics/mcmc/.

This is the in-place wrapper around _compute_rhat_op.

Skips computation if R-hat is already present unless force=True. Emits one warning per parameter with R-hat > threshold, reporting a scalar parameter's R-hat, or an array parameter's number of coordinates above the threshold and its maximum R-hat.

Source code in probpipe/diagnostics/_mcmc.py
def add_rhat(
    posterior: EmpiricalDistribution,
    *,
    method: str = "rank",
    threshold: float = _RHAT_THRESHOLD,
    force: bool = False,
) -> None:
    """Compute R-hat and attach to ``_annotations/diagnostics/mcmc/``.

    This is the in-place wrapper around :func:`_compute_rhat_op`.

    Skips computation if R-hat is already present unless ``force=True``.
    Emits one warning per parameter with R-hat > ``threshold``, reporting a
    scalar parameter's R-hat, or an array parameter's number of coordinates
    above the threshold and its maximum R-hat.
    """
    from ._datatree import _mcmc_has_field

    if not force and _mcmc_has_field(posterior, "rhat"):
        return None

    payload = _compute_rhat_op(
        posterior,
        method=method,
        threshold=threshold,
    )

    _emit_payload_warnings(payload)
    _write_mcmc_payload(posterior, payload)

    return None

probpipe.diagnostics.add_ess(posterior, *, threshold=_ESS_THRESHOLD, force=False)

Compute bulk and tail ESS and attach to _annotations/diagnostics/mcmc/.

This is the in-place wrapper around _compute_ess_op.

Skips computation if ESS is already present unless force=True. Emits one warning per parameter and ESS kind below threshold, reporting a scalar parameter's ESS, or an array parameter's number of coordinates below the threshold and its minimum ESS.

Source code in probpipe/diagnostics/_mcmc.py
def add_ess(
    posterior: EmpiricalDistribution,
    *,
    threshold: int = _ESS_THRESHOLD,
    force: bool = False,
) -> None:
    """Compute bulk and tail ESS and attach to ``_annotations/diagnostics/mcmc/``.

    This is the in-place wrapper around :func:`_compute_ess_op`.

    Skips computation if ESS is already present unless ``force=True``.
    Emits one warning per parameter and ESS kind below ``threshold``, reporting
    a scalar parameter's ESS, or an array parameter's number of coordinates
    below the threshold and its minimum ESS.
    """
    from ._datatree import _mcmc_has_field

    if not force and _mcmc_has_field(posterior, "ess_bulk"):
        return None

    payload = _compute_ess_op(
        posterior,
        threshold=threshold,
    )

    _emit_payload_warnings(payload)
    _write_mcmc_payload(posterior, payload)

    return None

probpipe.diagnostics.add_mcse(posterior, *, force=False)

Compute MCSE and attach to _annotations/diagnostics/mcmc/.

This is the in-place wrapper around _compute_mcse_op.

Skips computation if MCSE is already present unless force=True.

Source code in probpipe/diagnostics/_mcmc.py
def add_mcse(
    posterior: EmpiricalDistribution,
    *,
    force: bool = False,
) -> None:
    """Compute MCSE and attach to ``_annotations/diagnostics/mcmc/``.

    This is the in-place wrapper around :func:`_compute_mcse_op`.

    Skips computation if MCSE is already present unless ``force=True``.
    """
    from ._datatree import _mcmc_has_field

    if not force and _mcmc_has_field(posterior, "mcse_mean"):
        return None

    payload = _compute_mcse_op(posterior)

    _emit_payload_warnings(payload)
    _write_mcmc_payload(posterior, payload)

    return None

probpipe.diagnostics.add_mcmc_diagnostics(posterior, *, metrics=None, rhat_method='rank', rhat_threshold=_RHAT_THRESHOLD, ess_threshold=_ESS_THRESHOLD, force=False)

Compute MCMC diagnostics and attach to _annotations/diagnostics/mcmc/.

Computes R-hat, bulk ESS, tail ESS, and MCSE by default, and records the number of divergent transitions when the run's sample statistics hold the ArviZ variable diverging, which posterior.diagnostics.mcmc.n_divergences reads. Skips any metric already present unless force=True.

Parameters:

Name Type Description Default
posterior EmpiricalDistribution

The fitted posterior. Mutated in place.

required
metrics str, sequence of str, or None

The metrics to compute, among "rhat", "ess", "mcse", and "divergences". A str names one metric, and None computes all four.

None
rhat_method str

ArviZ R-hat variant: "rank" by default.

'rank'
rhat_threshold float

R-hat warning threshold.

_RHAT_THRESHOLD
ess_threshold int

ESS warning threshold.

_ESS_THRESHOLD
force bool

Recompute even if metrics are already stored.

False

Raises:

Type Description
TypeError

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

ValueError

If metrics names an unknown metric.

Source code in probpipe/diagnostics/_mcmc.py
def add_mcmc_diagnostics(
    posterior: EmpiricalDistribution,
    *,
    metrics: NamesLike | None = None,
    rhat_method: str = "rank",
    rhat_threshold: float = _RHAT_THRESHOLD,
    ess_threshold: int = _ESS_THRESHOLD,
    force: bool = False,
) -> None:
    """Compute MCMC diagnostics and attach to ``_annotations/diagnostics/mcmc/``.

    Computes R-hat, bulk ESS, tail ESS, and MCSE by default, and records the
    number of divergent transitions when the run's sample statistics hold the
    ArviZ variable ``diverging``, which ``posterior.diagnostics.mcmc.n_divergences``
    reads. Skips any metric already present unless ``force=True``.

    Parameters
    ----------
    posterior : EmpiricalDistribution
        The fitted posterior. Mutated in place.
    metrics : str, sequence of str, or None
        The metrics to compute, among ``"rhat"``, ``"ess"``, ``"mcse"``, and
        ``"divergences"``. A str names one metric, and ``None`` computes all
        four.
    rhat_method : str
        ArviZ R-hat variant: ``"rank"`` by default.
    rhat_threshold : float
        R-hat warning threshold.
    ess_threshold : int
        ESS warning threshold.
    force : bool
        Recompute even if metrics are already stored.

    Raises
    ------
    TypeError
        If *metrics* is not a str, a sequence of str, or ``None``.
    ValueError
        If *metrics* names an unknown metric.
    """
    if metrics is None:
        compute = _MCMC_METRICS
    else:
        compute = _as_names(metrics, what="add_mcmc_diagnostics metrics")
        unknown = [name for name in compute if name not in _MCMC_METRICS]
        if unknown:
            raise ValueError(unknown_names("metric", unknown, _MCMC_METRICS))

    if "rhat" in compute:
        add_rhat(
            posterior,
            method=rhat_method,
            threshold=rhat_threshold,
            force=force,
        )

    if "ess" in compute:
        add_ess(
            posterior,
            threshold=ess_threshold,
            force=force,
        )

    if "mcse" in compute:
        add_mcse(
            posterior,
            force=force,
        )

    if "divergences" in compute:
        _record_divergences(posterior)

    return None

Predictive and leave-one-out diagnostics

probpipe.diagnostics.add_ppc(posterior, test_fns, observed_data=None, *, kernel, n_replications=500)

Compute a PPC and write results into posterior._annotations.

This is the in-place wrapper around _ppc_op. Calls _ppc_op and writes the resulting payload into posterior._annotations, then returns None. The replications are draws of the kernel's event from kernel * posterior, as predictive_check draws them, and every test statistic is computed on the same replications.

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
posterior Distribution

Prior or posterior over the kernel's inputs.

required
test_fns callable or sequence of callables

One or more test statistics mapping data to a scalar.

required
observed_data optional

If provided, the statistics of the observed data and their p-values are computed. It takes the forms predictive_check takes.

None
kernel ConditionalDistribution

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

required
n_replications int

Number of replicated datasets.

500

Raises:

Type Description
TypeError

If kernel is not a ConditionalDistribution, posterior does not sample, test_fns is neither a callable nor an iterable, a test function is not callable, or n_replications is not an integer.

ValueError

If posterior has no output for some input of kernel, naming the missing inputs; if posterior has an output of the same name as an output of kernel; if test_fns is empty or holds two test functions of the same name; or if n_replications is not positive. Use distinct named functions instead of multiple lambdas so result keys cannot collide.

Source code in probpipe/diagnostics/_ppc_spc.py
def add_ppc(
    posterior: Distribution,
    test_fns: Callable | Sequence[Callable],
    observed_data: Any | None = None,
    *,
    kernel: ConditionalDistribution,
    n_replications: int = 500,
) -> None:
    """Compute a PPC and write results into ``posterior._annotations``.

    This is the in-place wrapper around :func:`_ppc_op`. Calls ``_ppc_op``
    and writes the resulting payload into ``posterior._annotations``,
    then returns ``None``. The replications are draws of the kernel's event
    from ``kernel * posterior``, as :func:`~probpipe.validation.predictive_check`
    draws them, and every test statistic is computed on the same replications.

    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
    ----------
    posterior : Distribution
        Prior or posterior over the kernel's inputs.
    test_fns : callable or sequence of callables
        One or more test statistics mapping data to a scalar.
    observed_data : optional
        If provided, the statistics of the observed data and their p-values
        are computed. It takes the forms
        :func:`~probpipe.validation.predictive_check` takes.
    kernel : ConditionalDistribution
        The law of the observations given the parameters, such as the
        likelihood of a model ``likelihood & prior``.
    n_replications : int
        Number of replicated datasets.

    Raises
    ------
    TypeError
        If *kernel* is not a ``ConditionalDistribution``, *posterior* does not
        sample, *test_fns* is neither a callable nor an iterable, a test
        function is not callable, or *n_replications* is not an integer.
    ValueError
        If *posterior* has no output for some input of *kernel*, naming
        the missing inputs; if *posterior* has an output of the same name as
        an output of *kernel*; if *test_fns* is empty or holds two test
        functions of the same name; or if *n_replications* is not positive.
        Use distinct named functions instead of multiple lambdas so result
        keys cannot collide.
    """
    payload = _ppc_op(
        posterior,
        test_fns=test_fns,
        observed_data=observed_data,
        kernel=kernel,
        n_replications=n_replications,
    )

    _write_ppc_payload(posterior, payload)

    return None

probpipe.diagnostics.add_loo(posterior, *, log_likelihood=None, model=None, data=None, var_name='y', pointwise=True, scale=None, reff=None, force=False, store_pointwise=True)

Compute PSIS-LOO and attach results to posterior._annotations.

This function mutates posterior._annotations in place and returns None.

Parameters:

Name Type Description Default
posterior Distribution

Posterior distribution whose ArviZ-compatible xarray DataTree data are stored under posterior._annotations["arviz"].

required
log_likelihood optional

Pointwise log likelihood. If provided, it is written to _annotations/arviz/log_likelihood before calling ArviZ. This is an advanced override; the normal user-facing workflow is add_loo(posterior).

None
model Distribution

The factored joint the posterior was conditioned from, such as likelihood & prior. When _annotations/arviz/log_likelihood is missing, add_loo computes the pointwise log likelihoods from model and data, and needs no separate precomputation step.

None
data Record or Mapping

The observed values the posterior was conditioned on, keyed by field, at which model scores each observation.

None
var_name str

Variable name to use when converting raw log-likelihood arrays into an xarray Dataset.

'y'
pointwise bool

Passed to az.loo. If True, ArviZ returns pointwise quantities such as loo_i and pareto_k when available.

True
scale str or None

Optional ArviZ scale argument, e.g. "log", "negative_log", or "deviance" depending on ArviZ version.

None
reff float or None

Optional relative MCMC efficiency passed to az.loo.

None
force bool

If False and diagnostics/runs/loo already exists, skip computation. If True, recompute and overwrite the existing LOO diagnostic node.

False
store_pointwise bool

If True, store pointwise pareto_k and loo_i values as 1D arrays when available. These are stored in the diagnostic run dataset.

True

Returns:

Type Description
None

Raises:

Type Description
ValueError

If log_likelihood holds a one-dimensional array, or if the annotations hold no pointwise log likelihood and model and data are not both given.

TypeError

If model at data has no likelihood factor that scores each observation, or if reff is None and the annotations hold no ArviZ posterior group to estimate it from.

Source code in probpipe/diagnostics/_loo.py
def add_loo(
    posterior: Distribution,
    *,
    log_likelihood: Any | None = None,
    model: Any | None = None,
    data: Any | None = None,
    var_name: str = "y",
    pointwise: bool = True,
    scale: str | None = None,
    reff: float | None = None,
    force: bool = False,
    store_pointwise: bool = True,
) -> None:
    """Compute PSIS-LOO and attach results to ``posterior._annotations``.

    This function mutates ``posterior._annotations`` in place and returns
    ``None``.

    Parameters
    ----------
    posterior : Distribution
        Posterior distribution whose ArviZ-compatible xarray DataTree data are
        stored under ``posterior._annotations["arviz"]``.

    log_likelihood : optional
        Pointwise log likelihood. If provided, it is written to
        ``_annotations/arviz/log_likelihood`` before calling ArviZ. This is an
        advanced override; the normal user-facing workflow is
        ``add_loo(posterior)``.

    model : Distribution, optional
        The factored joint the posterior was conditioned from, such as
        ``likelihood & prior``. When ``_annotations/arviz/log_likelihood`` is
        missing, ``add_loo`` computes the pointwise log likelihoods from *model*
        and *data*, and needs no separate precomputation step.

    data : Record or Mapping, optional
        The observed values the posterior was conditioned on, keyed by field,
        at which *model* scores each observation.

    var_name : str
        Variable name to use when converting raw log-likelihood arrays into an
        xarray Dataset.

    pointwise : bool
        Passed to ``az.loo``. If True, ArviZ returns pointwise quantities such
        as ``loo_i`` and ``pareto_k`` when available.

    scale : str or None
        Optional ArviZ scale argument, e.g. ``"log"``, ``"negative_log"``, or
        ``"deviance"`` depending on ArviZ version.

    reff : float or None
        Optional relative MCMC efficiency passed to ``az.loo``.

    force : bool
        If False and ``diagnostics/runs/loo`` already exists, skip computation.
        If True, recompute and overwrite the existing LOO diagnostic node.

    store_pointwise : bool
        If True, store pointwise ``pareto_k`` and ``loo_i`` values as 1D arrays
        when available. These are stored in the diagnostic run dataset.

    Returns
    -------
    None

    Raises
    ------
    ValueError
        If *log_likelihood* holds a one-dimensional array, or if the
        annotations hold no pointwise log likelihood and *model* and *data*
        are not both given.
    TypeError
        If *model* at *data* has no likelihood factor that scores each
        observation, or if *reff* is ``None`` and the annotations hold no
        ArviZ ``posterior`` group to estimate it from.
    """
    if not force and _has_group(getattr(posterior, "_annotations", None), "diagnostics/runs/loo"):
        return None

    # ------------------------------------------------------------------
    # Add/update log_likelihood group under /arviz/
    # ------------------------------------------------------------------

    if log_likelihood is not None:
        log_lik_ds = _log_likelihood_to_dataset(log_likelihood, var_name=var_name)
        _add_group(posterior, "arviz/log_likelihood", log_lik_ds)

    arviz_tree = _get_arviz_tree(posterior)

    if arviz_tree is None:
        if model is not None and data is not None:
            _add_log_likelihood(posterior, model, data, var_name=var_name)
            arviz_tree = _get_arviz_tree(posterior)

        if arviz_tree is None:
            raise ValueError(_no_log_likelihood(posterior))

    if not _has_group(arviz_tree, "log_likelihood"):
        if model is not None and data is not None:
            _add_log_likelihood(posterior, model, data, var_name=var_name)
            arviz_tree = _get_arviz_tree(posterior)

        if arviz_tree is None or not _has_group(arviz_tree, "log_likelihood"):
            raise ValueError(_no_log_likelihood(posterior))

    # ------------------------------------------------------------------
    # Run ArviZ LOO
    # ------------------------------------------------------------------

    loo_kwargs: dict[str, Any] = {
        "pointwise": pointwise,
    }

    if scale is not None:
        loo_kwargs["scale"] = scale

    if reff is not None:
        loo_kwargs["reff"] = reff

    loo_result = az.loo(arviz_tree, **loo_kwargs)

    # ------------------------------------------------------------------
    # Extract scalar summaries
    # ------------------------------------------------------------------

    elpd_loo = _safe_float(_record_get(loo_result, "elpd_loo", _record_get(loo_result, "elpd")))
    se = _safe_float(_record_get(loo_result, "se"))
    p_loo = _safe_float(_record_get(loo_result, "p_loo", _record_get(loo_result, "p")))

    # Some ArviZ versions expose looic; others only expose elpd_loo.
    looic_raw = _record_get(loo_result, "looic", None)
    looic = _safe_float(looic_raw)

    if np.isnan(looic) and not np.isnan(elpd_loo):
        looic = float(-2.0 * elpd_loo)

    n_samples = _safe_int(_record_get(loo_result, "n_samples"))
    n_data_points = _safe_int(_record_get(loo_result, "n_data_points"))

    warning_value = _record_get(loo_result, "warning", False)
    warning_numeric = 1.0 if bool(warning_value) else 0.0

    good_k = _safe_float(_record_get(loo_result, "good_k", np.nan))

    pareto_k = _record_get(loo_result, "pareto_k", None)
    loo_i = _record_get(loo_result, "loo_i", _record_get(loo_result, "elpd_i", None))

    pk_summary = _pareto_k_summary(
        pareto_k,
        good_k=None if np.isnan(good_k) else good_k,
    )

    # ------------------------------------------------------------------
    # Build diagnostics dataset
    # ------------------------------------------------------------------

    data_vars: dict[str, xr.DataArray] = {
        "elpd_loo": xr.DataArray(elpd_loo),
        "se": xr.DataArray(se),
        "p_loo": xr.DataArray(p_loo),
        "looic": xr.DataArray(looic),
        "n_samples": xr.DataArray(float(n_samples)),
        "n_data_points": xr.DataArray(float(n_data_points)),
        "warning": xr.DataArray(warning_numeric),
        "good_k": xr.DataArray(good_k),
        "pareto_k_max": xr.DataArray(pk_summary["pareto_k_max"]),
        "pareto_k_mean": xr.DataArray(pk_summary["pareto_k_mean"]),
        "pareto_k_bad_count": xr.DataArray(float(pk_summary["pareto_k_bad_count"])),
        "pareto_k_bad_fraction": xr.DataArray(pk_summary["pareto_k_bad_fraction"]),
    }

    if store_pointwise:
        pareto_k_da = _pointwise_dataarray(pareto_k, name="pareto_k", dim="obs")
        if pareto_k_da is not None:
            data_vars["pareto_k"] = pareto_k_da

        loo_i_da = _pointwise_dataarray(loo_i, name="loo_i", dim="obs")
        if loo_i_da is not None:
            data_vars["loo_i"] = loo_i_da

    run_ds = xr.Dataset(data_vars)

    plot_ready = _has_required_loo_pit_groups(arviz_tree)

    run_ds.attrs = {
        "kind": "loo",
        "timestamp": datetime.now(UTC).isoformat(),
        "backend": "arviz",
        "pointwise": bool(pointwise),
        "scale": "" if scale is None else str(scale),
        "reff": float("nan") if reff is None else float(reff),
        "var_name": str(var_name),
        "plot_fn": "az.plot_loo_pit",
        "plot_groups": json.dumps(
            ["posterior", "log_likelihood", "posterior_predictive", "observed_data"]
        ),
        "plot_ready": bool(plot_ready),
        "compare_ready": True,
        "warning_bool": bool(warning_value),
        "loo_result_repr": repr(loo_result),
        "loo_result_json": _json_dumps_safe(
            {
                "elpd_loo": elpd_loo,
                "se": se,
                "p_loo": p_loo,
                "looic": looic,
                "n_samples": n_samples,
                "n_data_points": n_data_points,
                "warning": bool(warning_value),
                "good_k": good_k,
                **pk_summary,
            }
        ),
    }

    _add_group(posterior, "diagnostics/runs/loo", run_ds)

    return None

Views

probpipe.diagnostics.DiagnosticsView(tree)

Bases: DataTreeView

Structured read-only accessor over the /diagnostics subtree.

Source code in probpipe/diagnostics/_view_base.py
def __init__(self, tree: Any | None) -> None:
    self._tree = tree

summary_table()

Pretty-printed table of MCMC metrics for notebook display.

The table ends with the warnings, and then with a line that reports the run as not passed when a transition diverged or an R-hat is not computed, or else, when no warning was issued, as passed.

Source code in probpipe/diagnostics/_views.py
def summary_table(self) -> str:
    """Pretty-printed table of MCMC metrics for notebook display.

    The table ends with the warnings, and then with a line that reports the
    run as not passed when a transition diverged or an R-hat is not
    computed, or else, when no warning was issued, as passed.
    """
    rhat = self.rhat
    ess_b = self.ess_bulk
    ess_t = self.ess_tail
    mcse_m = self.mcse_mean

    params = list(rhat.keys()) or list(ess_b.keys())
    if not params:
        return "No MCMC diagnostics computed yet."

    def _fmt(d: dict, k: str, width: int) -> str:
        v = d.get(k, "—")
        if isinstance(v, NotComputed):
            s = "N/A"
        elif isinstance(v, float):
            s = f"{v:.4f}"
        else:
            s = str(v)
        return s.ljust(width)

    col_w = [max(14, max(map(len, params)) + 2), 10, 12, 12, 12]

    header = (
        "Parameter".ljust(col_w[0])
        + "R-hat".ljust(col_w[1])
        + "ESS bulk".ljust(col_w[2])
        + "ESS tail".ljust(col_w[3])
        + "MCSE mean".ljust(col_w[4])
    )

    sep = "-" * len(header)
    rows = [header, sep]

    for p in params:
        rows.append(
            p.ljust(col_w[0])
            + _fmt(rhat, p, col_w[1])
            + _fmt(ess_b, p, col_w[2])
            + _fmt(ess_t, p, col_w[3])
            + _fmt(mcse_m, p, col_w[4])
        )

    rows.append("")

    warns = self.warnings
    rows.extend(f"âš   {w}" for w in warns)
    reasons = []
    n_divergences = self.n_divergences
    if not isinstance(n_divergences, NotComputed) and n_divergences > 0:
        reasons.append(f"{n_divergences} divergent transitions")
    no_rhat = [p for p, v in rhat.items() if isinstance(v, NotComputed)]
    if no_rhat:
        reasons.append(f"R-hat not computed for {', '.join(no_rhat)}")
    if reasons:
        rows.append(f"✗  Not passed: {' and '.join(reasons)}.")
    elif not warns:
        rows.append("✓  All available diagnostics passed.")

    return "\n".join(rows)

to_dict()

JSON-serializable summary of all diagnostics.

Source code in probpipe/diagnostics/_views.py
def to_dict(self) -> dict[str, Any]:
    """JSON-serializable summary of all diagnostics."""

    def _ser(v: Any) -> Any:
        if isinstance(v, NotComputed):
            return {"not_computed": v.reason}
        if isinstance(v, dict):
            return {k: _ser(vv) for k, vv in v.items()}
        return v

    return {
        "mcmc": {
            "rhat": _ser(self.rhat),
            "ess_bulk": _ser(self.ess_bulk),
            "ess_tail": _ser(self.ess_tail),
            "mcse_mean": _ser(self.mcse_mean),
            "mcse_sd": _ser(self.mcse_sd),
            "n_divergences": _ser(self.n_divergences),
            "warnings": self.mcmc.warnings,
        },
        "ppc": _ser(self.ppc.result),
        "loo": {
            "elpd_loo": _ser(self.loo.elpd_loo),
            "se": _ser(self.loo.se),
            "p_loo": _ser(self.loo.p_loo),
            "looic": _ser(self.loo.looic),
            "pareto_k_max": _ser(self.loo.pareto_k_max),
            "warnings": self.loo.warnings,
        },
        "runs": [
            {
                "name": r.name,
                "result": _ser(r.result),
                "plot_fn": r.plot_fn,
                "plot_ready": r.plot_ready,
                "plot_groups": r.plot_groups,
                "timestamp": r.timestamp,
            }
            for r in self.runs
        ],
    }

probpipe.diagnostics.MCMCView(tree)

Bases: DatasetView

Structured read-only accessor for /diagnostics/mcmc.

Source code in probpipe/diagnostics/_view_base.py
def __init__(self, tree: Any | None) -> None:
    self._tree = tree

probpipe.diagnostics.PPCView(tree)

Bases: DatasetView

Structured read-only accessor for /diagnostics/runs/ppc.

Source code in probpipe/diagnostics/_view_base.py
def __init__(self, tree: Any | None) -> None:
    self._tree = tree

result property

PPC result keyed by test function.

Example

{ "var_mean_ratio": { "p_value": 0.43, "observed": 3.2, } }

probpipe.diagnostics.LOOView(tree)

Bases: DatasetView

Structured read-only accessor for /diagnostics/runs/loo.

Source code in probpipe/diagnostics/_view_base.py
def __init__(self, tree: Any | None) -> None:
    self._tree = tree

probpipe.diagnostics.DiagnosticRunView(name, tree)

Bases: DatasetView

Generic accessor for one /diagnostics/runs/<name>/ node.

This class is generic. It does not know whether the run is PPC, LOO, etc.

Source code in probpipe/diagnostics/_view_base.py
def __init__(self, name: str, tree: Any | None) -> None:
    super().__init__(tree)
    self.name = name

result property

The run's variables as a plain Python dict keyed by variable name.

A scalar variable becomes its value, as read_scalar reads it. A one-dimensional variable becomes the dict that read_indexed reads, such as {"0": 0.12, "1": 0.31} for the pointwise pareto_k of a LOO run. A variable of two or more dimensions becomes NotComputed. The dict is empty when the run's node holds no dataset.

probpipe.diagnostics.NotComputed(reason)

Sentinel for a diagnostic value that is unavailable or not computed.

Parameters:

Name Type Description Default
reason str

Human-readable explanation.

required
Source code in probpipe/diagnostics/_view_base.py
def __init__(self, reason: str) -> None:
    self.reason = reason

View helpers

probpipe.diagnostics.views.DataTreeView(tree)

Generic read-only view over an xarray DataTree node.

This base class intentionally contains only generic DataTree navigation helpers. Concrete diagnostic semantics belong in subclasses.

Source code in probpipe/diagnostics/_view_base.py
def __init__(self, tree: Any | None) -> None:
    self._tree = tree

exists property

Whether this view points to an existing tree node.

attrs property

Node attributes, or an empty dict.

children property

Child nodes, or an empty dict.

has_child(name)

Return True if the node has a child with this name.

Source code in probpipe/diagnostics/_view_base.py
def has_child(self, name: str) -> bool:
    """Return True if the node has a child with this name."""
    return name in self.children

child(name)

Return child DataTree node or None.

Source code in probpipe/diagnostics/_view_base.py
def child(self, name: str) -> Any | None:
    """Return child DataTree node or None."""
    if not self.has_child(name):
        return None
    try:
        return self._tree[name]
    except Exception:
        return None

dataset()

Return this node's dataset, if available.

Source code in probpipe/diagnostics/_view_base.py
def dataset(self) -> Any | None:
    """Return this node's dataset, if available."""
    if self._tree is None:
        return None

    try:
        return self._tree.to_dataset()
    except Exception:
        pass

    for attr in ("ds", "dataset"):
        ds = getattr(self._tree, attr, None)
        if ds is not None:
            return ds

    return None

attr(key, default=None)

Read an attribute from the node.

Source code in probpipe/diagnostics/_view_base.py
def attr(self, key: str, default: Any = None) -> Any:
    """Read an attribute from the node."""
    return self.attrs.get(key, default)

probpipe.diagnostics.views.DatasetView(tree)

Bases: DataTreeView

Generic view over a DataTree node that is expected to hold a Dataset.

Source code in probpipe/diagnostics/_view_base.py
def __init__(self, tree: Any | None) -> None:
    self._tree = tree

scalar(field)

Read a scalar variable from this node's dataset.

Source code in probpipe/diagnostics/_view_base.py
def scalar(self, field: str) -> float | NotComputed:
    """Read a scalar variable from this node's dataset."""
    ds = self.dataset()
    if ds is None:
        return NotComputed("dataset not available")
    if field not in ds.data_vars:
        return NotComputed(f"{field!r} not recorded")
    return read_scalar(ds[field])

indexed(field, *, dim)

Read a one-dimensional indexed variable.

Source code in probpipe/diagnostics/_view_base.py
def indexed(
    self,
    field: str,
    *,
    dim: str,
) -> dict[str, float | NotComputed]:
    """Read a one-dimensional indexed variable."""
    return read_indexed(self.dataset(), field, dim=dim)

probpipe.diagnostics.views.read_scalar(da, *, label=None)

Extract one scalar value from an xarray DataArray-like object.

Returns NotComputed instead of raising when the value is missing, non-scalar, NaN, or marked with a not_computed attr.

Source code in probpipe/diagnostics/_view_base.py
def read_scalar(da: Any | None, *, label: str | None = None) -> float | NotComputed:
    """Extract one scalar value from an xarray DataArray-like object.

    Returns ``NotComputed`` instead of raising when the value is missing,
    non-scalar, NaN, or marked with a ``not_computed`` attr.
    """
    if da is None:
        return NotComputed("not available")

    nc_key = f"not_computed_{label}" if label else "not_computed"

    attrs = getattr(da, "attrs", {}) or {}
    if nc_key in attrs or "not_computed" in attrs:
        reason = attrs.get(nc_key) or attrs.get("not_computed", "unknown")
        return NotComputed(reason)

    try:
        arr = np.asarray(da, dtype=float).squeeze()
    except Exception:
        return NotComputed("could not convert value to float")

    if arr.size != 1:
        return NotComputed(f"expected scalar, got shape {arr.shape}")

    val = float(arr.item())

    if np.isnan(val):
        return NotComputed("value is NaN")

    return val

probpipe.diagnostics.views.read_indexed(ds, field, *, dim)

Read a one-dimensional variable of a dataset as a dict keyed by its labels.

Each element is keyed by the string form of its coordinate value along dim, or of its position when dim has no coordinate. Its value is read with read_scalar.

Parameters:

Name Type Description Default
ds Dataset or None

The dataset that holds the variable.

required
field str

The name of the variable.

required
dim str

The dimension that indexes the variable.

required

Returns:

Type Description
dict of str to float or NotComputed

One entry per element, in the order of dim. The dict is empty when ds is None, when ds has no variable field, and when dim is not a dimension of that variable.

Examples:

A variable p_value over the coordinate test_fn = ["var_mean_ratio", "zero_fraction"] reads as {"var_mean_ratio": 0.43, "zero_fraction": 0.81}. A variable pareto_k over the integer coordinate obs = [0, 1] reads as {"0": 0.12, "1": 0.31}.

Source code in probpipe/diagnostics/_view_base.py
def read_indexed(
    ds: Any | None,
    field: str,
    *,
    dim: str,
) -> dict[str, float | NotComputed]:
    """Read a one-dimensional variable of a dataset as a dict keyed by its labels.

    Each element is keyed by the string form of its coordinate value along
    *dim*, or of its position when *dim* has no coordinate. Its value is read
    with :func:`read_scalar`.

    Parameters
    ----------
    ds : xarray.Dataset or None
        The dataset that holds the variable.
    field : str
        The name of the variable.
    dim : str
        The dimension that indexes the variable.

    Returns
    -------
    dict of str to float or NotComputed
        One entry per element, in the order of *dim*. The dict is empty when
        *ds* is ``None``, when *ds* has no variable *field*, and when *dim* is
        not a dimension of that variable.

    Examples
    --------
    A variable ``p_value`` over the coordinate
    ``test_fn = ["var_mean_ratio", "zero_fraction"]`` reads as
    ``{"var_mean_ratio": 0.43, "zero_fraction": 0.81}``. A variable
    ``pareto_k`` over the integer coordinate ``obs = [0, 1]`` reads as
    ``{"0": 0.12, "1": 0.31}``.
    """
    if ds is None:
        return {}

    if field not in ds.data_vars:
        return {}

    da = ds[field]

    if dim not in da.dims:
        return {}

    labels = [str(x) for x in da[dim].values]

    # Selecting by a string label fails on a coordinate of another dtype, such as
    # the integer observation index of a LOO run, so each element is read by position.
    return {label: read_scalar(da.isel({dim: i}), label=label) for i, label in enumerate(labels)}

probpipe.diagnostics.views.read_json_attr(attrs, key, default=None)

Read a JSON-encoded attribute safely.

Source code in probpipe/diagnostics/_view_base.py
def read_json_attr(attrs: dict[str, Any], key: str, default: Any = None) -> Any:
    """Read a JSON-encoded attribute safely."""
    if default is None:
        default = []

    raw = attrs.get(key)

    if raw is None:
        return default

    try:
        return json.loads(raw)
    except (json.JSONDecodeError, TypeError):
        return default