Skip to content

quivers.diagnostics.predictive_checks

A posterior predictive check compares a statistic of the observations with its distribution over replicated data (Gelman et al., 1996; Gelman et al., 2013). An observed upper quantile beyond the range of the replicated ones, for instance, exposes a poorly modeled tail. The module gives posterior predictive p-values and leave-one-out probability integral transform (LOO-PIT) checks of calibration for held-out observations.

predictive_checks

Posterior-predictive checks (PPCs) and calibration diagnostics.

ArviZ ships arviz.plot_ppc, arviz.loo_pit, and a broad family of PPC visualisations. This module exposes a small typed surface that delegates to those, and adds a registry of common test statistics that map cleanly onto quivers' plate-and- group structure (per-Verb mean, per-Subject sd, etc.).

STATISTICS module-attribute

STATISTICS: dict[str, Callable[[ndarray], float]] = {'mean': lambda v: float(np.mean(v)), 'median': lambda v: float(np.median(v)), 'sd': lambda v: float(np.std(v, ddof=1)), 'var': lambda v: float(np.var(v, ddof=1)), 'min': lambda v: float(np.min(v)), 'max': lambda v: float(np.max(v)), 'mad': lambda v: float(1.4826 * np.median(np.abs(v - np.median(v)))), 'IQR': lambda v: float(np.subtract(*np.quantile(v, [0.75, 0.25]))), 'q05': lambda v: float(np.quantile(v, 0.05)), 'q95': lambda v: float(np.quantile(v, 0.95))}

The built-in scalar test statistics T(y) -> scalar, keyed by the name that posterior_predictive_check and the ppc_* tables accept. They follow R's conventions: sd and var divide by n - 1, mad is scaled by 1.4826, and quantiles are type 7.

posterior_predictive_check

posterior_predictive_check(idata: DataTree, *, observed_name: str, statistic: str | Callable[[ndarray], float] = 'mean', by: str | None = None) -> Mapping[str, float | ndarray | str]

Compute a posterior-predictive p-value (PPP-value) for a user-chosen test statistic.

PARAMETER DESCRIPTION
idata

Fit produced by quivers.diagnostics.to_datatree, with both observed_data and posterior_predictive groups populated.

TYPE: DataTree

observed_name

Name of the observed site (must appear in both groups).

TYPE: str

statistic

Either a key into STATISTICS or a user-supplied Callable[[np.ndarray], float].

TYPE: str or callable DEFAULT: 'mean'

by

If given, computes the statistic per group along the named dim (e.g. by="Verb"); the PPP-value becomes a numpy array of shape (|by|,).

TYPE: str DEFAULT: None

RETURNS DESCRIPTION
Mapping[str, float or ndarray]

{"observed": T(y), "predictive_mean": E[T(y_rep)], "ppp": Pr(T(y_rep) >= T(y))}. The PPP-value is the canonical posterior-predictive p-value; values near 0 or 1 indicate model mis-fit on the chosen statistic.

Source code in src/quivers/diagnostics/predictive_checks.py
def posterior_predictive_check(
    idata: xr.DataTree,
    *,
    observed_name: str,
    statistic: str | Callable[[np.ndarray], float] = "mean",
    by: str | None = None,
) -> Mapping[str, float | np.ndarray | str]:
    """Compute a posterior-predictive p-value (PPP-value) for a
    user-chosen test statistic.

    Parameters
    ----------
    idata : xr.DataTree
        Fit produced by [`quivers.diagnostics.to_datatree`][quivers.diagnostics.to_datatree],
        with both ``observed_data`` and ``posterior_predictive``
        groups populated.
    observed_name : str
        Name of the observed site (must appear in both groups).
    statistic : str or callable
        Either a key into `STATISTICS` or a user-supplied
        ``Callable[[np.ndarray], float]``.
    by : str, optional
        If given, computes the statistic per group along the named
        dim (e.g. ``by="Verb"``); the PPP-value becomes a numpy
        array of shape ``(|by|,)``.

    Returns
    -------
    Mapping[str, float or numpy.ndarray]
        ``{"observed": T(y), "predictive_mean": E[T(y_rep)],
        "ppp": Pr(T(y_rep) >= T(y))}``.  The PPP-value is the
        canonical [posterior-predictive p-value](https://en.wikipedia.org/wiki/Posterior_predictive_p-value);
        values near 0 or 1 indicate model mis-fit on the chosen
        statistic.
    """
    if callable(statistic):
        stat_fn = statistic
        stat_name = getattr(statistic, "__name__", "user_statistic")
    else:
        if statistic not in STATISTICS:
            raise ValueError(
                f"unknown statistic {statistic!r}; choices are "
                f"{sorted(STATISTICS)} or a user-supplied callable"
            )
        stat_fn = STATISTICS[statistic]
        stat_name = statistic

    observed = idata["observed_data"][observed_name].values
    pp = idata["posterior_predictive"][observed_name].values
    # pp shape: (chain, draw, *site_shape).  Flatten chains for stat
    # computation across all draws.
    chains, draws = pp.shape[0], pp.shape[1]
    pp_flat = pp.reshape(chains * draws, *pp.shape[2:])

    if by is None:
        t_obs = stat_fn(observed)
        t_rep = np.array([stat_fn(pp_flat[i]) for i in range(pp_flat.shape[0])])
        return {
            "statistic": stat_name,
            "observed": t_obs,
            "predictive_mean": float(t_rep.mean()),
            "ppp": float((t_rep >= t_obs).mean()),
        }

    # Per-group statistic.  Locate the `by` dim in the observed array.
    dims = idata["observed_data"][observed_name].dims
    if by not in dims:
        raise ValueError(
            f"posterior_predictive_check: dim {by!r} not found in "
            f"observed_data/{observed_name} dims {dims}"
        )
    group_axis = dims.index(by)
    observed_groups = np.split(observed, observed.shape[group_axis], axis=group_axis)
    pp_axis = group_axis + 2  # +2 for the leading (chain, draw) axes
    pp_groups = np.split(pp_flat, pp_flat.shape[pp_axis - 1], axis=pp_axis - 1)
    t_obs = np.array([stat_fn(g.squeeze(group_axis)) for g in observed_groups])
    t_rep = np.array(
        [
            np.array([stat_fn(g[i].squeeze(pp_axis - 2)) for i in range(g.shape[0])])
            for g in pp_groups
        ]
    )  # (groups, n_draws)
    return {
        "statistic": stat_name,
        "by": by,
        "observed": t_obs,
        "predictive_mean": t_rep.mean(axis=1),
        "ppp": (t_rep >= t_obs[:, None]).mean(axis=1),
    }

loo_pit

loo_pit(idata: DataTree, *, observed_name: str) -> Dataset

Leave-one-out probability-integral-transform calibration.

Delegates to arviz.loo_pit. The canonical use of the PIT values is arviz.plot_loo_pit for the calibration diagnostic plot.

PARAMETER DESCRIPTION
idata

Fit produced by quivers.diagnostics.to_datatree, with posterior_predictive, log_likelihood, and observed_data groups populated.

TYPE: DataTree

observed_name

Name of the observed site, which must appear in those groups.

TYPE: str

RETURNS DESCRIPTION
Dataset

The LOO-PIT value at each observed data point, under the variable observed_name.

Source code in src/quivers/diagnostics/predictive_checks.py
def loo_pit(
    idata: xr.DataTree,
    *,
    observed_name: str,
) -> xr.Dataset:
    """Leave-one-out probability-integral-transform calibration.

    Delegates to `arviz.loo_pit`. The canonical use of the PIT values
    is `arviz.plot_loo_pit` for the calibration diagnostic plot.

    Parameters
    ----------
    idata : xr.DataTree
        Fit produced by [`quivers.diagnostics.to_datatree`][quivers.diagnostics.to_datatree],
        with ``posterior_predictive``, ``log_likelihood``, and
        ``observed_data`` groups populated.
    observed_name : str
        Name of the observed site, which must appear in those groups.

    Returns
    -------
    xr.Dataset
        The LOO-PIT value at each observed data point, under the
        variable ``observed_name``.
    """
    return az.loo_pit(idata, var_names=observed_name)

The data behind bayesplot's checks

The ppc_* functions of quivers.diagnostics compute the tables bayesplot draws its ppc_* plots from (Gabry et al., 2019), with bayesplot's column names and row order. pp_check on a fit selects the draws and data as brms does (see the analysis guide).

_ppc_data

The data behind graphical posterior predictive checks, as bayesplot computes it.

brms pp_check [@burkner2017brms] hands observed responses y and predictive draws yrep (an S x N matrix) to a bayesplot ppc_* function [@gabry2019visualization]. Each plot is drawn from a data frame that bayesplot computes first: the long table of observed and replicated values, test statistics of every replicate, predictive quantile intervals, predictive errors and their binned averages, frequency tables of discrete values, the rootogram table [@kleiber2016visualizing], the leave-one-out probability integral transform (LOO-PIT) under PSIS weights, Kaplan-Meier curves, and the empirical CDF of PIT values [@sailynoja2022graphical]. The functions here return those tables with bayesplot's column names and row order, so they can be plotted with any library or checked numerically. Quantiles are R's type 7.

STATISTICS module-attribute

STATISTICS: dict[str, Callable[[ndarray], float]] = {'mean': lambda v: float(np.mean(v)), 'median': lambda v: float(np.median(v)), 'sd': lambda v: float(np.std(v, ddof=1)), 'var': lambda v: float(np.var(v, ddof=1)), 'min': lambda v: float(np.min(v)), 'max': lambda v: float(np.max(v)), 'mad': lambda v: float(1.4826 * np.median(np.abs(v - np.median(v)))), 'IQR': lambda v: float(np.subtract(*np.quantile(v, [0.75, 0.25]))), 'q05': lambda v: float(np.quantile(v, 0.05)), 'q95': lambda v: float(np.quantile(v, 0.95))}

The built-in scalar test statistics T(y) -> scalar, keyed by the name that posterior_predictive_check and the ppc_* tables accept. They follow R's conventions: sd and var divide by n - 1, mad is scaled by 1.4826, and quantiles are type 7.

Statistic

Statistic = str | Callable[[ndarray], float]

A test statistic: a name of STATISTICS or a function of one vector.

GroupValues

GroupValues = Sequence[str | int | float | bool] | ndarray

Group labels, one per observation.

Cell

Cell = str | int | float | bool | None

One cell of a table row.

ppc_data

ppc_data(y: ndarray | None, yrep: ndarray, *, group: GroupValues | None = None) -> DataFrame

Return the long table of observed and replicated values (ppc_data).

PARAMETER DESCRIPTION
y

Observed values, or None for ppd_data.

TYPE: ndarray or None

yrep

Draws (S, N).

TYPE: ndarray

group

Group label per observation.

TYPE: Sequence or None DEFAULT: None

RETURNS DESCRIPTION
DataFrame

Replicated rows, replicate fastest, then the observed rows, with is_y and is_y_label when y is given; group first.

Source code in src/quivers/diagnostics/_ppc_data.py
def ppc_data(
    y: np.ndarray | None, yrep: np.ndarray, *, group: GroupValues | None = None
) -> pd.DataFrame:
    """Return the long table of observed and replicated values (``ppc_data``).

    Parameters
    ----------
    y : numpy.ndarray or None
        Observed values, or None for ``ppd_data``.
    yrep : numpy.ndarray
        Draws ``(S, N)``.
    group : Sequence or None
        Group label per observation.

    Returns
    -------
    pandas.DataFrame
        Replicated rows, replicate fastest, then the observed rows, with
        ``is_y`` and ``is_y_label`` when ``y`` is given; ``group`` first.
    """
    obs, pred = _check(y, yrep)
    labels = _groups(group, pred.shape[1])
    if obs is None:
        data = _melt(pred, "pred")
    else:
        data = _melt(pred)
        n = obs.shape[0]
        observed = pd.DataFrame(
            {
                "y_id": np.arange(1, n + 1),
                "y_name": [str(i) for i in range(1, n + 1)],
                "rep_id": np.full(n, np.nan),
                "rep_label": _Y,
                "value": obs,
            }
        )
        data = pd.concat([data, observed], ignore_index=True)
        data["is_y"] = data["rep_id"].isna()
        data["is_y_label"] = np.where(data["is_y"], _Y, _YREP)
        data = pd.DataFrame(
            data[
                ["y_id", "y_name", "rep_id", "rep_label", "is_y", "is_y_label", "value"]
            ]
        )
    if labels is not None:
        data.insert(0, "group", labels[data["y_id"].to_numpy() - 1])
    return data

ppc_stat_data

ppc_stat_data(y: ndarray | None, yrep: ndarray, *, stat: Statistic | tuple[Statistic, Statistic] = 'mean', group: GroupValues | None = None) -> DataFrame

Return test statistics of the observed and each replicated data set.

PARAMETER DESCRIPTION
y

Observed values, or None for ppd_stat_data.

TYPE: ndarray or None

yrep

Draws (S, N).

TYPE: ndarray

stat

One statistic, or two for stat_2d.

TYPE: str or Callable or tuple DEFAULT: 'mean'

group

Group label per observation; statistics are computed within groups.

TYPE: Sequence or None DEFAULT: None

RETURNS DESCRIPTION
DataFrame

group (when given), variable (y, yrep_<s> or ypred_<s>), value and, for two statistics, value2; rows by sorted group, then variable.

Source code in src/quivers/diagnostics/_ppc_data.py
def ppc_stat_data(
    y: np.ndarray | None,
    yrep: np.ndarray,
    *,
    stat: Statistic | tuple[Statistic, Statistic] = "mean",
    group: GroupValues | None = None,
) -> pd.DataFrame:
    """Return test statistics of the observed and each replicated data set.

    Parameters
    ----------
    y : numpy.ndarray or None
        Observed values, or None for ``ppd_stat_data``.
    yrep : numpy.ndarray
        Draws ``(S, N)``.
    stat : str or Callable or tuple
        One statistic, or two for ``stat_2d``.
    group : Sequence or None
        Group label per observation; statistics are computed within groups.

    Returns
    -------
    pandas.DataFrame
        ``group`` (when given), ``variable`` (``y``, ``yrep_<s>`` or
        ``ypred_<s>``), ``value`` and, for two statistics, ``value2``; rows by
        sorted group, then variable.
    """
    obs, pred = _check(y, yrep)
    labels = _groups(group, pred.shape[1])
    functions = (
        (_statistic(stat[0]), _statistic(stat[1]))
        if isinstance(stat, tuple)
        else (_statistic(stat),)
    )
    kind = "yrep" if obs is not None else "ypred"
    series = ([("y", obs)] if obs is not None else []) + [
        (f"{kind}_{s + 1}", pred[s]) for s in range(pred.shape[0])
    ]
    levels = [None] if labels is None else _factor_levels(labels)
    rows = []
    for level in levels:
        mask = slice(None) if labels is None else labels == level
        for name, values in series:
            row: dict[str, Cell] = {} if labels is None else {"group": level}
            row["variable"] = name
            row["value"] = functions[0](values[mask])
            if len(functions) == 2:
                row["value2"] = functions[-1](values[mask])
            rows.append(row)
    return pd.DataFrame(rows)

ppc_intervals_data

ppc_intervals_data(y: ndarray | None, yrep: ndarray, *, x: Sequence[float] | ndarray | None = None, group: GroupValues | None = None, prob: float = 0.5, prob_outer: float = 0.9) -> DataFrame

Return predictive quantile intervals per observation (ppc_intervals_data).

PARAMETER DESCRIPTION
y

Observed values, or None for ppd_intervals_data.

TYPE: ndarray or None

yrep

Draws (S, N).

TYPE: ndarray

x

Horizontal coordinate; the observation index by default.

TYPE: Sequence[float] or None DEFAULT: None

group

Group label per observation.

TYPE: Sequence or None DEFAULT: None

prob

Inner and outer interval probabilities.

TYPE: float DEFAULT: 0.5

prob_outer

Inner and outer interval probabilities.

TYPE: float DEFAULT: 0.5

RETURNS DESCRIPTION
DataFrame

y_id, y_obs, group, x, outer_width, inner_width, ll, l, m, h, hh.

RAISES DESCRIPTION
ValueError

If the probabilities are outside (0, 1].

Source code in src/quivers/diagnostics/_ppc_data.py
def ppc_intervals_data(
    y: np.ndarray | None,
    yrep: np.ndarray,
    *,
    x: Sequence[float] | np.ndarray | None = None,
    group: GroupValues | None = None,
    prob: float = 0.5,
    prob_outer: float = 0.9,
) -> pd.DataFrame:
    """Return predictive quantile intervals per observation (``ppc_intervals_data``).

    Parameters
    ----------
    y : numpy.ndarray or None
        Observed values, or None for ``ppd_intervals_data``.
    yrep : numpy.ndarray
        Draws ``(S, N)``.
    x : Sequence[float] or None
        Horizontal coordinate; the observation index by default.
    group : Sequence or None
        Group label per observation.
    prob, prob_outer : float
        Inner and outer interval probabilities.

    Returns
    -------
    pandas.DataFrame
        ``y_id``, ``y_obs``, ``group``, ``x``, ``outer_width``,
        ``inner_width``, ``ll``, ``l``, ``m``, ``h``, ``hh``.

    Raises
    ------
    ValueError
        If the probabilities are outside (0, 1].
    """
    if not (0 < prob < 1 and 0 < prob_outer <= 1):
        raise ValueError("prob must be in (0, 1) and prob_outer in (0, 1]")
    obs, pred = _check(y, yrep)
    n = pred.shape[1]
    labels = _groups(group, n)
    inner, outer = sorted((prob, prob_outer))
    alpha = [(1 - inner) / 2, (1 - outer) / 2]
    probs = sorted([*alpha, 0.5, *(1 - a for a in alpha)])
    quantiles = np.quantile(pred, probs, axis=0)
    coordinate = np.arange(1, n + 1) if x is None else np.asarray(x, dtype=np.float64)
    data: dict[str, np.ndarray | float] = {"y_id": np.arange(1, n + 1)}
    if obs is not None:
        data["y_obs"] = obs
    if labels is not None:
        data["group"] = labels
    data["x"] = coordinate
    data["outer_width"] = outer
    data["inner_width"] = inner
    for name, values in zip(("ll", "l", "m", "h", "hh"), quantiles, strict=True):
        data[name] = values
    return pd.DataFrame(data)

predictive_errors

predictive_errors(y: ndarray, yrep: ndarray) -> ndarray

Return predictive errors y - yrep (rstantools predictive_error).

PARAMETER DESCRIPTION
y

Observed values.

TYPE: ndarray

yrep

Draws (S, N).

TYPE: ndarray

RETURNS DESCRIPTION
ndarray

Errors (S, N).

Source code in src/quivers/diagnostics/_ppc_data.py
def predictive_errors(y: np.ndarray, yrep: np.ndarray) -> np.ndarray:
    """Return predictive errors ``y - yrep`` (rstantools ``predictive_error``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed values.
    yrep : numpy.ndarray
        Draws ``(S, N)``.

    Returns
    -------
    numpy.ndarray
        Errors ``(S, N)``.
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    return obs[None, :] - pred

ppc_error_data

ppc_error_data(y: ndarray, yrep: ndarray, *, group: GroupValues | None = None) -> DataFrame

Return the long table of predictive errors (ppc_error_data).

PARAMETER DESCRIPTION
y

Observed values.

TYPE: ndarray

yrep

Draws (S, N).

TYPE: ndarray

group

Group label per observation.

TYPE: Sequence or None DEFAULT: None

RETURNS DESCRIPTION
DataFrame

group, y_id, y_name, y_obs, rep_id, rep_label, value.

Source code in src/quivers/diagnostics/_ppc_data.py
def ppc_error_data(
    y: np.ndarray, yrep: np.ndarray, *, group: GroupValues | None = None
) -> pd.DataFrame:
    """Return the long table of predictive errors (``ppc_error_data``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed values.
    yrep : numpy.ndarray
        Draws ``(S, N)``.
    group : Sequence or None
        Group label per observation.

    Returns
    -------
    pandas.DataFrame
        ``group``, ``y_id``, ``y_name``, ``y_obs``, ``rep_id``,
        ``rep_label``, ``value``.
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    data = _melt(obs[None, :] - pred)
    data.insert(2, "y_obs", obs[data["y_id"].to_numpy() - 1])
    labels = _groups(group, pred.shape[1])
    if labels is not None:
        data.insert(0, "group", labels[data["y_id"].to_numpy() - 1])
    return data

ppc_error_binned_data

ppc_error_binned_data(y: ndarray, epred: ndarray, *, bins: int | None = None) -> DataFrame

Return binned errors per draw (ppc_error_binned).

PARAMETER DESCRIPTION
y

Observed values.

TYPE: ndarray

epred

Expected values (S, N) (brms uses posterior_epred).

TYPE: ndarray

bins

Bins; bayesplot's default by sample size.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
DataFrame

ey_bar, err_bar, se2, bin, rep_id.

Source code in src/quivers/diagnostics/_ppc_data.py
def ppc_error_binned_data(
    y: np.ndarray, epred: np.ndarray, *, bins: int | None = None
) -> pd.DataFrame:
    """Return binned errors per draw (``ppc_error_binned``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed values.
    epred : numpy.ndarray
        Expected values ``(S, N)`` (brms uses ``posterior_epred``).
    bins : int or None
        Bins; bayesplot's default by sample size.

    Returns
    -------
    pandas.DataFrame
        ``ey_bar``, ``err_bar``, ``se2``, ``bin``, ``rep_id``.
    """
    obs, pred = _check(y, epred)
    assert obs is not None
    count = _bins(obs.shape[0]) if bins is None else bins
    return pd.concat(
        [
            _bin_errors(pred[s], obs - pred[s], count, s + 1)
            for s in range(pred.shape[0])
        ],
        ignore_index=True,
    )

ppc_bars_data

ppc_bars_data(y: ndarray, yrep: ndarray, *, group: GroupValues | None = None, prob: float = 0.9, freq: bool = True) -> DataFrame

Return frequency tables of discrete values (ppc_bars_data).

PARAMETER DESCRIPTION
y

Observed whole numbers.

TYPE: ndarray

yrep

Draws (S, N) of whole numbers.

TYPE: ndarray

group

Group label per observation.

TYPE: Sequence or None DEFAULT: None

prob

Interval probability of the replicated counts.

TYPE: float DEFAULT: 0.9

freq

Counts; False gives proportions within each data set and group.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
DataFrame

group (when given), x, y_obs, l, m, h. As in bayesplot, replicate quantiles are taken over the replicates in which a value occurs.

RAISES DESCRIPTION
ValueError

If values are not whole numbers.

Source code in src/quivers/diagnostics/_ppc_data.py
def ppc_bars_data(
    y: np.ndarray,
    yrep: np.ndarray,
    *,
    group: GroupValues | None = None,
    prob: float = 0.9,
    freq: bool = True,
) -> pd.DataFrame:
    """Return frequency tables of discrete values (``ppc_bars_data``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed whole numbers.
    yrep : numpy.ndarray
        Draws ``(S, N)`` of whole numbers.
    group : Sequence or None
        Group label per observation.
    prob : float
        Interval probability of the replicated counts.
    freq : bool
        Counts; False gives proportions within each data set and group.

    Returns
    -------
    pandas.DataFrame
        ``group`` (when given), ``x``, ``y_obs``, ``l``, ``m``, ``h``. As in
        bayesplot, replicate quantiles are taken over the replicates in
        which a value occurs.

    Raises
    ------
    ValueError
        If values are not whole numbers.
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    if not (np.all(obs == np.round(obs)) and np.all(pred == np.round(pred))):
        raise ValueError("bars require discrete y and yrep")
    labels = _groups(group, obs.shape[0])
    levels = [None] if labels is None else _factor_levels(labels)
    lower = (1 - prob) / 2
    probs = sorted([lower, 0.5, 1 - lower])
    rows = []
    for level in levels:
        mask = np.ones(obs.shape[0], bool) if labels is None else labels == level
        observed: dict[float, float] = {}
        values, counts = np.unique(obs[mask], return_counts=True)
        total = counts.sum()
        for v, c in zip(values, counts, strict=True):
            observed[float(v)] = float(c) if freq else float(c / total)
        replicated: dict[float, list[float]] = {}
        for s in range(pred.shape[0]):
            values, counts = np.unique(pred[s, mask], return_counts=True)
            total = counts.sum()
            for v, c in zip(values, counts, strict=True):
                replicated.setdefault(float(v), []).append(
                    float(c) if freq else float(c / total)
                )
        keys = sorted(replicated) + sorted(set(observed) - set(replicated))
        for key in keys:
            row: dict[str, Cell] = {} if labels is None else {"group": level}
            row["x"] = key
            row["y_obs"] = observed.get(key, math.nan)
            if key in replicated:
                l, m, h = np.quantile(replicated[key], probs)
            else:
                l = m = h = math.nan
            row.update({"l": float(l), "m": float(m), "h": float(h)})
            rows.append(row)
    data = pd.DataFrame(rows)
    return data.sort_values("x", kind="stable").reset_index(drop=True)

ppc_rootogram_data

ppc_rootogram_data(y: ndarray, yrep: ndarray, *, style: str = 'standing', prob: float = 0.9) -> DataFrame

Return the rootogram table of count data (ppc_rootogram).

PARAMETER DESCRIPTION
y

Observed counts.

TYPE: ndarray

yrep

Draws (S, N) of counts.

TYPE: ndarray

style

Rootogram style [@kleiber2016visualizing].

TYPE: ('standing', 'hanging', 'suspended') DEFAULT: "standing"

prob

Interval probability of the replicated square-root frequencies.

TYPE: float DEFAULT: 0.9

RETURNS DESCRIPTION
DataFrame

xpos (0 to the largest count), ypos, ty (square-root observed frequency), tyexp (square root of the mean replicated frequency), tylower, tyupper.

RAISES DESCRIPTION
ValueError

If values are not nonnegative whole numbers or the style is unknown.

Source code in src/quivers/diagnostics/_ppc_data.py
def ppc_rootogram_data(
    y: np.ndarray,
    yrep: np.ndarray,
    *,
    style: str = "standing",
    prob: float = 0.9,
) -> pd.DataFrame:
    """Return the rootogram table of count data (``ppc_rootogram``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed counts.
    yrep : numpy.ndarray
        Draws ``(S, N)`` of counts.
    style : {"standing", "hanging", "suspended"}
        Rootogram style [@kleiber2016visualizing].
    prob : float
        Interval probability of the replicated square-root frequencies.

    Returns
    -------
    pandas.DataFrame
        ``xpos`` (0 to the largest count), ``ypos``, ``ty`` (square-root
        observed frequency), ``tyexp`` (square root of the mean replicated
        frequency), ``tylower``, ``tyupper``.

    Raises
    ------
    ValueError
        If values are not nonnegative whole numbers or the style is unknown.
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    if style not in {"standing", "hanging", "suspended"}:
        raise ValueError("style must be standing, hanging, or suspended")
    if (
        np.any(obs < 0)
        or np.any(pred < 0)
        or not (np.all(obs == np.round(obs)) and np.all(pred == np.round(pred)))
    ):
        raise ValueError("rootograms require counts")
    top = int(max(obs.max(), pred.max()))
    xpos = np.arange(top + 1)
    table = np.stack(
        [
            np.bincount(pred[s].astype(int), minlength=top + 1)
            for s in range(pred.shape[0])
        ]
    ).astype(float)
    tyexp = np.sqrt(table.mean(axis=0))
    alpha = (1 - prob) / 2
    lower, upper = np.sqrt(np.quantile(table, [alpha, 1 - alpha], axis=0))
    ty = np.sqrt(np.bincount(obs.astype(int), minlength=top + 1).astype(float))
    if style == "suspended":
        ty = tyexp - ty
    ypos = ty / 2
    if style == "hanging":
        ypos = tyexp - ypos
    return pd.DataFrame(
        {
            "xpos": xpos,
            "ypos": ypos,
            "ty": ty,
            "tyexp": tyexp,
            "tylower": lower,
            "tyupper": upper,
        }
    )

ppc_scatter_data

ppc_scatter_data(y: ndarray, yrep: ndarray) -> DataFrame

Return observed values against each replicate (ppc_scatter_data).

PARAMETER DESCRIPTION
y

Observed values.

TYPE: ndarray

yrep

Draws (S, N).

TYPE: ndarray

RETURNS DESCRIPTION
DataFrame

y_id, y_name, y_obs, rep_id, rep_label, value.

Source code in src/quivers/diagnostics/_ppc_data.py
def ppc_scatter_data(y: np.ndarray, yrep: np.ndarray) -> pd.DataFrame:
    """Return observed values against each replicate (``ppc_scatter_data``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed values.
    yrep : numpy.ndarray
        Draws ``(S, N)``.

    Returns
    -------
    pandas.DataFrame
        ``y_id``, ``y_name``, ``y_obs``, ``rep_id``, ``rep_label``, ``value``.
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    data = _melt(pred)
    data.insert(2, "y_obs", obs[data["y_id"].to_numpy() - 1])
    return data

ppc_scatter_avg_data

ppc_scatter_avg_data(y: ndarray, yrep: ndarray, *, group: GroupValues | None = None) -> DataFrame

Return observed values against the mean replicate (ppc_scatter_avg_data).

PARAMETER DESCRIPTION
y

Observed values (or a covariate for error_scatter_avg_vs_x).

TYPE: ndarray

yrep

Draws (S, N) (or predictive errors).

TYPE: ndarray

group

Group label per observation.

TYPE: Sequence or None DEFAULT: None

RETURNS DESCRIPTION
DataFrame

group, y_id, y_name, y_obs, rep_id (missing), rep_label, value (the mean over draws).

Source code in src/quivers/diagnostics/_ppc_data.py
def ppc_scatter_avg_data(
    y: np.ndarray, yrep: np.ndarray, *, group: GroupValues | None = None
) -> pd.DataFrame:
    """Return observed values against the mean replicate (``ppc_scatter_avg_data``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed values (or a covariate for ``error_scatter_avg_vs_x``).
    yrep : numpy.ndarray
        Draws ``(S, N)`` (or predictive errors).
    group : Sequence or None
        Group label per observation.

    Returns
    -------
    pandas.DataFrame
        ``group``, ``y_id``, ``y_name``, ``y_obs``, ``rep_id`` (missing),
        ``rep_label``, ``value`` (the mean over draws).
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    data = ppc_scatter_data(obs, pred.mean(axis=0, keepdims=True))
    data["rep_id"] = np.nan
    data["rep_label"] = "mean(italic(y)[rep]))"
    labels = _groups(group, obs.shape[0])
    if labels is not None:
        data.insert(0, "group", labels[data["y_id"].to_numpy() - 1])
    return data

loo_pit_values

loo_pit_values(y: ndarray, yrep: ndarray, log_weights: ndarray) -> ndarray

Return LOO-PIT values from PSIS log weights (rstantools loo_pit).

PARAMETER DESCRIPTION
y

Observed values.

TYPE: ndarray

yrep

Draws (S, N).

TYPE: ndarray

log_weights

Normalized PSIS log weights (S, N).

TYPE: ndarray

RETURNS DESCRIPTION
ndarray

:math:\sum_s w_{s i} 1[y^{rep}_{s i} \le y_i] per observation.

RAISES DESCRIPTION
ValueError

If the weights do not match the draws.

Source code in src/quivers/diagnostics/_ppc_data.py
def loo_pit_values(
    y: np.ndarray, yrep: np.ndarray, log_weights: np.ndarray
) -> np.ndarray:
    """Return LOO-PIT values from PSIS log weights (rstantools ``loo_pit``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed values.
    yrep : numpy.ndarray
        Draws ``(S, N)``.
    log_weights : numpy.ndarray
        Normalized PSIS log weights ``(S, N)``.

    Returns
    -------
    numpy.ndarray
        :math:`\\sum_s w_{s i} 1[y^{rep}_{s i} \\le y_i]` per observation.

    Raises
    ------
    ValueError
        If the weights do not match the draws.
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    weights = np.asarray(log_weights, dtype=np.float64)
    if weights.shape != pred.shape:
        raise ValueError("log weights must match the predictions")
    masked = np.where(pred <= obs[None, :], weights, -np.inf)
    top = masked.max(axis=0)
    finite = np.isfinite(top)
    out = np.zeros(obs.shape[0])
    out[finite] = np.exp(
        top[finite] + np.log(np.exp(masked[:, finite] - top[finite]).sum(axis=0))
    )
    return out

km_data

km_data(y: ndarray, yrep: ndarray, *, status: Sequence[float] | ndarray) -> DataFrame

Return Kaplan-Meier curves of observed and replicated data (ppc_km_overlay).

PARAMETER DESCRIPTION
y

Observed times.

TYPE: ndarray

yrep

Draws (S, N), all treated as events.

TYPE: ndarray

status

Event indicator of each observed time (one event, zero right censored).

TYPE: Sequence[float]

RETURNS DESCRIPTION
DataFrame

strata (rep_label=italic(y) first), time, n_risk, n_event, n_censor, surv at each distinct time, as survival::survfit.

RAISES DESCRIPTION
ValueError

If a status is not zero or one.

Source code in src/quivers/diagnostics/_ppc_data.py
def km_data(
    y: np.ndarray, yrep: np.ndarray, *, status: Sequence[float] | np.ndarray
) -> pd.DataFrame:
    """Return Kaplan-Meier curves of observed and replicated data (``ppc_km_overlay``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed times.
    yrep : numpy.ndarray
        Draws ``(S, N)``, all treated as events.
    status : Sequence[float]
        Event indicator of each observed time (one event, zero right censored).

    Returns
    -------
    pandas.DataFrame
        ``strata`` (``rep_label=italic(y)`` first), ``time``, ``n_risk``,
        ``n_event``, ``n_censor``, ``surv`` at each distinct time, as
        ``survival::survfit``.

    Raises
    ------
    ValueError
        If a status is not zero or one.
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    events = np.asarray(status, dtype=np.float64).reshape(-1)
    if events.shape != obs.shape or not np.isin(events, (0.0, 1.0)).all():
        raise ValueError("status must hold 0 or 1 for every observation")
    curves = [(f"rep_label={_Y}", obs, events)] + [
        (f"rep_label={_rep_label(s + 1)}", pred[s], np.ones(pred.shape[1]))
        for s in range(pred.shape[0])
    ]
    rows = []
    for name, times, indicator in curves:
        survival = 1.0
        for t in np.unique(times):
            at = times == t
            risk = int((times >= t).sum())
            died = int(indicator[at].sum())
            censored = int(at.sum()) - died
            survival *= 1.0 - died / risk
            rows.append(
                {
                    "strata": name,
                    "time": float(t),
                    "n_risk": risk,
                    "n_event": died,
                    "n_censor": censored,
                    "surv": survival,
                }
            )
    return pd.DataFrame(rows)

pit_values

pit_values(y: ndarray, yrep: ndarray) -> ndarray

Return posterior predictive PIT values, as bayesplot ppc_pit_ecdf.

PARAMETER DESCRIPTION
y

Observed values.

TYPE: ndarray

yrep

Draws (S, N).

TYPE: ndarray

RETURNS DESCRIPTION
ndarray

The share of draws with :math:y^{rep}_{s i} \le y_i, per observation.

Source code in src/quivers/diagnostics/_ppc_data.py
def pit_values(y: np.ndarray, yrep: np.ndarray) -> np.ndarray:
    """Return posterior predictive PIT values, as bayesplot ``ppc_pit_ecdf``.

    Parameters
    ----------
    y : numpy.ndarray
        Observed values.
    yrep : numpy.ndarray
        Draws ``(S, N)``.

    Returns
    -------
    numpy.ndarray
        The share of draws with :math:`y^{rep}_{s i} \\le y_i`, per observation.
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    return (obs[None, :] >= pred).mean(axis=0)

pit_ecdf_data

pit_ecdf_data(y: ndarray, yrep: ndarray, *, K: int | None = None) -> DataFrame

Return PIT values' empirical CDF on a uniform grid (ppc_pit_ecdf).

PARAMETER DESCRIPTION
y

Observed values.

TYPE: ndarray

yrep

Draws (S, N).

TYPE: ndarray

K

Grid size; min(S + 1, N) by default.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
DataFrame

x (k / K), grid (seq(0, 1, length.out = K)) and ecdf of the PIT values :math:\Pr(y^{rep}_i \le y_i) at the grid. bayesplot's simultaneous bands (adjust_gamma) are not included; ArviZ's plot_ppc_pit draws its own simultaneous bands.

Source code in src/quivers/diagnostics/_ppc_data.py
def pit_ecdf_data(
    y: np.ndarray, yrep: np.ndarray, *, K: int | None = None
) -> pd.DataFrame:
    """Return PIT values' empirical CDF on a uniform grid (``ppc_pit_ecdf``).

    Parameters
    ----------
    y : numpy.ndarray
        Observed values.
    yrep : numpy.ndarray
        Draws ``(S, N)``.
    K : int or None
        Grid size; ``min(S + 1, N)`` by default.

    Returns
    -------
    pandas.DataFrame
        ``x`` (``k / K``), ``grid`` (``seq(0, 1, length.out = K)``) and
        ``ecdf`` of the PIT values :math:`\\Pr(y^{rep}_i \\le y_i)` at the grid.
        bayesplot's simultaneous bands (``adjust_gamma``) are not included;
        ArviZ's ``plot_ppc_pit`` draws its own simultaneous bands.
    """
    obs, pred = _check(y, yrep)
    assert obs is not None
    pit = pit_values(obs, pred)
    size = min(pred.shape[0] + 1, obs.shape[0]) if K is None else K
    grid = np.linspace(0.0, 1.0, size)
    ecdf = (pit[None, :] <= grid[:, None]).mean(axis=1)
    return pd.DataFrame(
        {"x": np.arange(1, size + 1) / size, "grid": grid, "ecdf": ecdf}
    )

Cited sources

Andrew Gelman, Xiao-Li Meng, and Hal Stern. Posterior predictive assessment of model fitness via realized discrepancies. Statistica Sinica, 6(4):733–807, 1996. With discussion. URL: https://www3.stat.sinica.edu.tw/statistica/J6N4/J6N41/J6N41.htm.

Andrew Gelman, John B. Carlin, Hal S. Stern, David B. Dunson, Aki Vehtari, and Donald B. Rubin. Bayesian Data Analysis. Chapman and Hall/CRC, 3 edition, 2013. ISBN 9781439840955. URL: https://www.routledge.com/Bayesian-Data-Analysis/Gelman-Carlin-Stern-Dunson-Vehtari-Rubin/p/book/9781439840955.

Jonah Gabry, Daniel Simpson, Aki Vehtari, Michael Betancourt, and Andrew Gelman. Visualization in Bayesian Workflow. Journal of the Royal Statistical Society Series A: Statistics in Society, 182(2):389–402, 2019. doi:10.1111/rssa.12378.