Skip to content

quivers.diagnostics

The convergence estimators measure mixing and sampling precision for any tensor of shape (num_chains, num_draws, *event_shape), and simulation-based calibration (Talts et al., 2018) checks an inference procedure against the program it targets. Both need only PyTorch. Predictive checks compare simulated and observed data (Gelman et al., 2013), and model comparison estimates predictive accuracy on held-out observations. The ArviZ adapters convert inference records of quivers into xarray.DataTree objects for the ArviZ functions that accept them, including plot_trace, plot_forest, plot_ppc, loo, compare, and hdi, and need the diagnostics extra.

Shared posterior analysis retains draws and raw response scores from either source or formula fits. Its uncertainty summaries and empirical WAIC need only PyTorch; MCMC convergence diagnostics require recorded chains. DataTree conversion and PSIS-LOO use the optional ArviZ dependency.

Refit cross-validation retains explicit random, grouped, or stratified partitions and scores held-out likelihoods from existing fitters. It supports selected folds and joint response, fold, or group prediction units without requiring ArviZ.

Contrast summaries analyze derived retained draws, reporting strict-region probabilities and posterior odds separately from prior-corrected region Bayes factors. Equality frequencies remain descriptive.

Density ordinates estimate Gaussian KDE log densities from retained continuous contrasts. Posterior-to-prior ratios have a point-null Bayes-factor interpretation only under explicit proper-prior and compatible-null declarations.

diagnostics

Posterior diagnostics: convergence estimators and the ArviZ adapter.

Quivers' inference layer produces quivers.inference.MCMCResult records and quivers.inference.guides.base.Guide fits. This package holds two kinds of analysis over them.

The convergence estimators (rhat, ess, mcse, summary) take any (num_chains, num_draws, *event_shape) tensor and need only torch. MCMCResult reports its diagnostics through the same functions, so derived quantities and draws from custom sampling loops are diagnosed with the estimators a run reports.

The simulation-based calibration tools (sbc, sbc_ranks, sbc_uniformity, sbc_coverage) check an inference procedure against the program it targets; they also need only torch, and are bound on first access because they build on the inference layer.

Retained uncertainty, covariance, contrast-region evidence, and regression variance ratios also need only torch. They describe supplied or retained draws with explicit provenance; they do not infer convergence diagnostics for a variational approximation.

The ArviZ adapters convert quivers fits into the xarray.DataTree data model of ArviZ and wrap the canonical ArviZ entry points (arviz.compare, arviz.loo, arviz.plot_ppc) with shape-aware, quivers-typed signatures; ArviZ owns those analytics. They need the diagnostics extra and are bound on first access, which also keeps this package importable by the MCMC driver that the adapter itself imports.

EssMethod module-attribute

EssMethod = Literal['bulk', 'tail', 'mean', 'sd', 'quantile']

The quantity an effective sample size refers to: "bulk" (rank-normalized split chains, for location summaries), "tail" (the smaller of two tail-quantile ESS values), "mean" (the unnormalized split chains), "sd" (the squared deviations from the mean), or "quantile" (the indicator of falling at or below one quantile).

McseMethod module-attribute

McseMethod = Literal['mean', 'sd', 'quantile']

The posterior summary a Monte Carlo standard error refers to: the "mean", the standard deviation ("sd"), or one "quantile".

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.

MAD_CONSTANT module-attribute

MAD_CONSTANT = 1.4826

The consistency constant of R's mad, which scales the median absolute deviation to the standard deviation of a normal sample.

SBCPosterior module-attribute

SBCPosterior = MCMCResult | Guide | Mapping[str, torch.Tensor]

What a fit returns: an MCMCResult, a fitted Guide (sampled num_guide_draws times), or a mapping of site name to draws laid out (num_chains, num_draws, *constrained_shape).

SBCStatistic module-attribute

SBCStatistic = Callable[[Mapping[str, torch.Tensor], Mapping[str, torch.Tensor]], torch.Tensor]

A test quantity: statistic(parameters, data). parameters maps each latent site to a batch of draws with a leading draw axis, shape (n, *constrained_shape); data is the simulated observations together with the host data, as handed to the fit. The result has shape (n,) for one quantity or (n, *shape) for an array of them, one row per draw.

SBCThinning module-attribute

SBCThinning = Literal['ess'] | int

How posterior draws are thinned before ranking: "ess" keeps about one draw per effective sample, an integer keeps every k-th draw of each chain.

FoldLabel

FoldLabel = str | int

A retained group or stratum label; labels are never inferred from outcomes.

GridValue

GridValue = str | int | float | bool | None

A scalar predictor coordinate, preserving category and integer carriers.

BridgeMethod

BridgeMethod = Literal['normal', 'warp3']

Proposal of the bridge sampler: a fitted normal or the warp-3 transformation.

Criterion

Criterion = Literal['loo', 'waic', 'kfold', 'loo_subsample']

Predictive criterion of an ELPDEstimate.

ConvergenceSummary didactic-model

ConvergenceSummary(*, mean: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), sd: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), probs: tuple[float, ...], quantiles: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), r_hat: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), ess_bulk: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), ess_tail: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), mcse_mean: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), mcse_sd: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), mcse_quantiles: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Posterior summaries and convergence diagnostics for one site.

Every tensor field except quantiles and mcse_quantiles has the site's event shape (the shape after the chain and draw axes); those two have shape (len(probs), *event_shape). All are float64.

PARAMETER DESCRIPTION
mean

Posterior mean over all chains and draws; NaN for a coordinate with any nonfinite draw.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

sd

Posterior standard deviation over all chains and draws (one degree of freedom subtracted); NaN for a coordinate with any nonfinite draw.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

probs

The probabilities at which quantiles are taken.

TYPE: tuple[float, ...]

quantiles

Posterior quantiles at probs (linear interpolation between order statistics of the pooled draws); NaN for a coordinate with a non-finite draw.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

r_hat

Rank-normalized split :math:\hat R (see rhat).

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

ess_bulk

Bulk effective sample size (see ess).

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

ess_tail

Tail effective sample size at the 5% and 95% quantiles.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

mcse_mean

Monte Carlo standard error of the mean.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

mcse_sd

Monte Carlo standard error of the standard deviation.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

mcse_quantiles

Monte Carlo standard error of each quantile in quantiles.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

FoldSplit didactic-model

FoldSplit(*, fold: int, train: tuple[int, ...], test: tuple[int, ...], omitted: tuple[int, ...], seed: int)

Bases: ValueModel

Original row identities for one refit and its held-out prediction.

PARAMETER DESCRIPTION
fold

Zero-based fold identity in the complete plan.

TYPE: int

train

Original row positions supplied to the refitting procedure.

TYPE: tuple[int, ...]

test

Original row positions to predict, in their original order.

TYPE: tuple[int, ...]

omitted

Rows excluded from training, possibly including other group members.

TYPE: tuple[int, ...]

seed

Fold-specific seed independent of evaluation order or selected folds.

TYPE: int

FoldPlan didactic-model

FoldPlan(*, assignments: tuple[int, ...], seed: int = 0, omission_groups: tuple[FoldLabel, ...] = ())

Bases: ValueModel

A reusable complete partition, independent of model and fitting backend.

PARAMETER DESCRIPTION
assignments

One zero-based fold per original included row. Every fold must occur.

TYPE: tuple[int, ...]

seed

Nonnegative seed used to derive independent refit streams.

TYPE: int DEFAULT: 0

omission_groups

Optional grouping identities. A fold also omits every member of a held-out row's group, while predicting only its designated test rows. This expresses leave-one-out prediction with whole-group exclusion.

TYPE: tuple[str or int, ...] DEFAULT: ()

num_folds property

num_folds: int

Return the number of nonempty folds.

RETURNS DESCRIPTION
int

Complete partition size.

split

split(fold: int) -> FoldSplit

Resolve training, omitted, and prediction rows for one fold.

PARAMETER DESCRIPTION
fold

Zero-based fold identity.

TYPE: int

RETURNS DESCRIPTION
FoldSplit

Original positions; an explicitly omitted whole group can make training empty, in which case the refitter must support prior fits.

RAISES DESCRIPTION
ValueError

If the requested fold is outside the complete partition.

Source code in src/quivers/diagnostics/cross_validation.py
def split(self, fold: int) -> FoldSplit:
    """Resolve training, omitted, and prediction rows for one fold.

    Parameters
    ----------
    fold : int
        Zero-based fold identity.

    Returns
    -------
    FoldSplit
        Original positions; an explicitly omitted whole group can make
        training empty, in which case the refitter must support prior fits.

    Raises
    ------
    ValueError
        If the requested fold is outside the complete partition.
    """
    if type(fold) is not int or not 0 <= fold < self.num_folds:
        raise ValueError("fold index is outside the complete partition")
    test = tuple(i for i, value in enumerate(self.assignments) if value == fold)
    if self.omission_groups:
        excluded = {self.omission_groups[i] for i in test}
        omitted = tuple(
            i for i, group in enumerate(self.omission_groups) if group in excluded
        )
    else:
        omitted = test
    omit = set(omitted)
    return FoldSplit(
        fold=fold,
        train=tuple(i for i in range(len(self.assignments)) if i not in omit),
        test=test,
        omitted=omitted,
        seed=(self.seed + fold + 1) % 2**63,
    )

FoldPrediction didactic-model

FoldPrediction(*, log_likelihood: Mapping[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), fit: object | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Raw held-out likelihoods returned by a refitting adapter.

PARAMETER DESCRIPTION
log_likelihood

Response scores of shape (chain, draw, test row), unweighted and with each response event already reduced. Joint responses share draw axes.

TYPE: Mapping[str, Tensor] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

fit

Optional actual fitted result, retained only when save_fits is true.

TYPE: object or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

CrossValidationResult didactic-model

CrossValidationResult(*, plan: FoldPlan, fold_ids: tuple[int, ...], responses: tuple[str, ...], joint: Literal['observation', 'fold', 'group'], units: tuple[tuple[int, tuple[int, ...]], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), log_predictive_density: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), fits: Mapping[int, object] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Predictive scores from explicit refits on a retained partition.

PARAMETER DESCRIPTION
plan

Complete original partition.

TYPE: FoldPlan

fold_ids

Evaluated folds; a subset is never extrapolated to a full result.

TYPE: tuple[int, ...]

responses

Selected response names, summed within each joint posterior draw.

TYPE: tuple[str, ...]

joint

Predictive unit: observation, whole fold, or group within fold.

TYPE: str

units

Fold identity and original response positions for every scored unit.

TYPE: tuple[tuple[int, tuple[int, ...]], ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

log_predictive_density

Float64 log-mean likelihood per unit, preserving zero densities as -inf.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

fits

Optional actual refits keyed by complete-plan fold identity.

TYPE: Mapping[int, object] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

complete property

complete: bool

Report whether every fold in the retained partition was evaluated.

RETURNS DESCRIPTION
bool

False for a partial fold selection, regardless of score values.

elpd property

elpd: Tensor

Sum evaluated predictive units without extrapolating missing folds.

RETURNS DESCRIPTION
Tensor

Scalar score on the natural-log scale; -inf remains -inf.

se property

se: Tensor

Return sqrt(N times sample variance) across evaluated score units.

RETURNS DESCRIPTION
Tensor

Descriptive sampling-unit SE, not a Monte Carlo SE or a correction for overlapping training folds. Undefined for fewer than two units or nonfinite scores, in which case it is NaN.

PosteriorAnalysis didactic-model

PosteriorAnalysis(*, samples: Mapping[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_likelihood: Mapping[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), observed_data: Mapping[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), sample_stats: Mapping[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), kind: Literal['mcmc', 'variational', 'prior'] = 'mcmc', coords: Mapping[str, Sequence[object]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), dims: Mapping[str, Sequence[str]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), group_dims: Mapping[str, Mapping[str, Sequence[str]]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A reusable tensor posterior and its raw observation likelihoods.

PARAMETER DESCRIPTION
samples

Constrained draws with chain and draw axes.

TYPE: Mapping[str, Tensor] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

log_likelihood

Raw pointwise scores retaining observation axes.

TYPE: Mapping[str, Tensor] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

observed_data

Responses corresponding to the score units.

TYPE: Mapping[str, Tensor] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

sample_stats

Recorded per-draw sampler statistics, empty for variational draws.

TYPE: Mapping[str, Tensor] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

kind

Provenance of the draws. Variational and independent prior layout axes never supply MCMC convergence diagnostics.

TYPE: 'mcmc' or 'variational' or 'prior' DEFAULT: 'mcmc'

group_dims

Optional group-specific event dimensions, preserving observed vector events alongside their reduced pointwise likelihood axes.

TYPE: Mapping DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

coords

Retained coordinate labels and event dimension names, used by default for DataTree conversion and covariance. Explicit method arguments override them.

TYPE: Mapping DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

dims

Retained coordinate labels and event dimension names, used by default for DataTree conversion and covariance. Explicit method arguments override them.

TYPE: Mapping DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

Notes

Methods consume these retained tensors without replaying the model. Tensor mappings are held by identity; callers own their storage.

summary

summary(*, probs: Sequence[float] = (0.05, 0.5, 0.95)) -> dict[str, PosteriorSummary]

Summarize uncertainty, attaching diagnostics only to recorded chains.

PARAMETER DESCRIPTION
probs

Quantile probabilities strictly between zero and one.

TYPE: Sequence[float] DEFAULT: (0.05, 0.5, 0.95)

RETURNS DESCRIPTION
dict[str, PosteriorSummary]

Float64 summaries on each site's event axes. Any coordinate with a nonfinite draw has NaN location, dispersion, and quantiles; no draws are deleted. Original integer capacity is checked before conversion, including independent prior draws.

RAISES DESCRIPTION
ValueError

If sample axes or quantile probabilities are invalid, or an original integer exceeds exact Float64 capacity.

Source code in src/quivers/diagnostics/posterior.py
def summary(
    self, *, probs: Sequence[float] = (0.05, 0.5, 0.95)
) -> dict[str, PosteriorSummary]:
    """Summarize uncertainty, attaching diagnostics only to recorded chains.

    Parameters
    ----------
    probs : Sequence[float]
        Quantile probabilities strictly between zero and one.

    Returns
    -------
    dict[str, PosteriorSummary]
        Float64 summaries on each site's event axes. Any coordinate with
        a nonfinite draw has NaN location, dispersion, and quantiles;
        no draws are deleted. Original integer capacity is checked before
        conversion, including independent prior draws.

    Raises
    ------
    ValueError
        If sample axes or quantile probabilities are invalid, or an original
        integer exceeds exact Float64 capacity.
    """
    self._validate_axes()
    levels = probabilities(probs)
    diagnostics = (
        convergence_summary(self.samples, probs=levels)
        if self.kind == "mcmc"
        else {}
    )
    result = {}
    for name, values in self.samples.items():
        if (
            values.ndim < 2
            or (not values.is_floating_point() and self.kind != "prior")
            or not all(values.shape)
        ):
            raise ValueError(
                "posterior samples require nonempty chain and draw axes"
            )
        if name in diagnostics:
            d = diagnostics[name]
            mean, sd, quantiles = d.mean, d.sd, d.quantiles
        else:
            pooled = real_samples(
                values, label=f"summary {name!r}", finite=False
            ).flatten(0, 1)
            mean, sd, quantiles = empirical_summary(pooled, levels)
        result[name] = PosteriorSummary(
            mean=mean,
            sd=sd,
            probs=levels,
            quantiles=quantiles,
            convergence=diagnostics.get(name),
        )
    return result

covariance

covariance(var_names: Sequence[str] | None = None, *, ddof: int = 1, chainwise: bool = False, coords: Mapping[str, Sequence[object]] | None = None, dims: Mapping[str, Sequence[str]] | None = None) -> PosteriorCovariance

Summarize joint empirical dependence without replaying a posterior.

PARAMETER DESCRIPTION
var_names

Distinct selected sites, in matrix order; None selects insertion order. Each site's event coordinates flatten in row-major order.

TYPE: Sequence[str] or None DEFAULT: None

ddof

Nonnegative degrees of freedom, strictly below the reduced count.

TYPE: int DEFAULT: 1

chainwise

Retain a separate matrix per chain instead of pooling chain and draw.

TYPE: bool DEFAULT: False

coords

Labels for named event axes and optional chain/draw axes.

TYPE: Mapping[str, Sequence[object]] or None DEFAULT: None

dims

Event-axis names per site, following the DataTree convention.

TYPE: Mapping[str, Sequence[str]] or None DEFAULT: None

RETURNS DESCRIPTION
PosteriorCovariance

Float64 covariance and Pearson correlation, structural coordinate labels, sample-axis labels, and provenance. Constants have NaN correlations. No convergence statistics are manufactured.

RAISES DESCRIPTION
(ValueError, TypeError)

If axes, labels, selection, ddof, devices, or numeric carriers are invalid; missing/nonfinite draws are refused, without deletion. Integer values outside the exact Float64 range are refused before casting, as are unrepresentable covariance results.

Source code in src/quivers/diagnostics/posterior.py
def covariance(
    self,
    var_names: Sequence[str] | None = None,
    *,
    ddof: int = 1,
    chainwise: bool = False,
    coords: Mapping[str, Sequence[object]] | None = None,
    dims: Mapping[str, Sequence[str]] | None = None,
) -> PosteriorCovariance:
    """Summarize joint empirical dependence without replaying a posterior.

    Parameters
    ----------
    var_names : Sequence[str] or None
        Distinct selected sites, in matrix order; None selects insertion order.
        Each site's event coordinates flatten in row-major order.
    ddof : int
        Nonnegative degrees of freedom, strictly below the reduced count.
    chainwise : bool
        Retain a separate matrix per chain instead of pooling chain and draw.
    coords : Mapping[str, Sequence[object]] or None
        Labels for named event axes and optional chain/draw axes.
    dims : Mapping[str, Sequence[str]] or None
        Event-axis names per site, following the DataTree convention.

    Returns
    -------
    PosteriorCovariance
        Float64 covariance and Pearson correlation, structural coordinate
        labels, sample-axis labels, and provenance. Constants have NaN
        correlations. No convergence statistics are manufactured.

    Raises
    ------
    ValueError, TypeError
        If axes, labels, selection, ddof, devices, or numeric carriers are
        invalid; missing/nonfinite draws are refused, without deletion.
        Integer values outside the exact Float64 range are refused before
        casting, as are unrepresentable covariance results.
    """
    from quivers.diagnostics._coordinates import axis_labels, event_dimensions
    from quivers.diagnostics._numeric import real_samples

    self._validate_axes()
    coords = self.coords if coords is None else coords
    dims = self.dims if dims is None else dims
    if isinstance(var_names, str | bytes):
        raise TypeError("var_names must be a sequence of site names")
    names = tuple(self.samples) if var_names is None else tuple(var_names)
    if any(not isinstance(name, str) for name in names):
        raise TypeError("posterior variable names must be strings")
    if not names or len(set(names)) != len(names):
        raise ValueError("covariance requires a nonempty distinct site selection")
    unknown = set(names) - self.samples.keys()
    if unknown:
        raise ValueError(f"unknown posterior variables: {sorted(unknown)}")
    if isinstance(ddof, bool) or not isinstance(ddof, int) or ddof < 0:
        raise ValueError("ddof must be a nonnegative integer")
    if not isinstance(chainwise, bool):
        raise TypeError("chainwise must be Boolean")
    first = self.samples[names[0]]
    sample_shape = (first.shape[0], first.shape[1])
    chains, draws = sample_shape
    count = draws if chainwise else chains * draws
    if ddof >= count:
        raise ValueError("ddof must be smaller than the reduced sample count")
    shapes = {name: tuple(self.samples[name].shape[2:]) for name in names}
    dimensions = event_dimensions(shapes, coords=coords, dims=dims)
    chain_labels = axis_labels("chain", chains, coords)
    draw_labels = axis_labels("draw", draws, coords)
    columns, structural, dimension_names, labels = [], [], [], []
    device = self.samples[names[0]].device
    for name in names:
        values = self.samples[name]
        if values.device != device:
            raise ValueError("covariance requires samples on one device")
        columns.append(
            real_samples(values, label="covariance").reshape(chains, draws, -1)
        )
        dim_names = dimensions[name]
        dim_labels = [
            axis_labels(dim, size, coords)
            for dim, size in zip(dim_names, shapes[name], strict=True)
        ]
        for index in product(*(range(size) for size in shapes[name])):
            structural.append((name, index))
            dimension_names.append(dim_names)
            labels.append(
                tuple(
                    label[position]
                    for label, position in zip(dim_labels, index, strict=True)
                )
            )
    values = torch.cat(columns, dim=-1)
    if not chainwise:
        values = values.flatten(0, 1)
    # Anchor subtraction retains small differences around a large common
    # offset. Scaling also handles opposite finite endpoints whose
    # subtraction would overflow, without summing their raw magnitudes.
    delta = values - values[..., :1, :]
    working = torch.where(
        torch.isfinite(delta).all(dim=-2, keepdim=True), delta, values
    )
    scale = working.abs().amax(dim=-2, keepdim=True)
    normalized = working / torch.where(scale == 0, 1.0, scale)
    centered = normalized - normalized.mean(dim=-2, keepdim=True)
    gram = centered.transpose(-1, -2) @ centered / (count - ddof)
    mantissa, exponent = torch.frexp(scale.squeeze(-2))
    base_mantissa, base_exponent = torch.frexp(gram)
    covariance = torch.ldexp(
        base_mantissa * mantissa.unsqueeze(-1) * mantissa.unsqueeze(-2),
        base_exponent + exponent.unsqueeze(-1) + exponent.unsqueeze(-2),
    )
    if not bool(torch.isfinite(covariance).all()):
        raise ValueError("covariance exceeds Float64 capacity")
    sd = gram.diagonal(dim1=-2, dim2=-1).sqrt()
    correlation = (gram / sd.unsqueeze(-1) / sd.unsqueeze(-2)).clamp(-1.0, 1.0)
    return PosteriorCovariance(
        covariance=covariance,
        correlation=correlation,
        coordinates=tuple(structural),
        dimension_names=tuple(dimension_names),
        coordinate_labels=tuple(labels),
        variables=names,
        event_shapes=tuple(shapes.values()),
        sample_shape=sample_shape,
        chain_labels=chain_labels,
        draw_labels=draw_labels,
        ddof=ddof,
        chainwise=chainwise,
        kind=self.kind,
    )

hypothesis

hypothesis(expression: str | ContrastExpression, *, prior: PosteriorAnalysis | None = None, null: float | int | Tensor = 0.0, probs: Sequence[float] = (0.025, 0.975), robust: bool = False, point: PointNullSpec | None = None, name: str = 'contrast', dims: Mapping[str, Sequence[str]] | None = None, coords: Mapping[str, Sequence[object]] | None = None) -> HypothesisSummary

Evaluate one checked QVR contrast over retained joint draws.

PARAMETER DESCRIPTION
expression

QVR value expression and optional aliases to original site names.

TYPE: str or ContrastExpression

prior

Joint draws from the corresponding proper encompassing prior. Draw counts may differ; event shapes and devices must agree.

TYPE: PosteriorAnalysis or None DEFAULT: None

null

Finite comparison value on event axes only.

TYPE: float, int, or torch.Tensor DEFAULT: 0.0

probs

Requested quantile probabilities in output order.

TYPE: Sequence[float] DEFAULT: (0.025, 0.975)

robust

Use median and scaled MAD instead of mean and sample SD.

TYPE: bool DEFAULT: False

point

Optional marginal density comparison on the same joint prior and posterior contrast; requires a checked Real result and prior draws.

TYPE: PointNullSpec or None DEFAULT: None

name

Original label of the derived contrast.

TYPE: str DEFAULT: 'contrast'

dims

Input event-axis identities and labels, with optional sample labels. Distinct axes remain distinct even when their extents coincide.

TYPE: Mapping or None DEFAULT: None

coords

Input event-axis identities and labels, with optional sample labels. Distinct axes remain distinct even when their extents coincide.

TYPE: Mapping or None DEFAULT: None

RETURNS DESCRIPTION
HypothesisSummary

Existing uncertainty, strict-region posterior odds, and optional prior-corrected region evidence. Equality frequencies are descriptive; requested point_evidence retains a separate marginal density ratio.

Source code in src/quivers/diagnostics/posterior.py
def hypothesis(
    self,
    expression: str | ContrastExpression,
    *,
    prior: PosteriorAnalysis | None = None,
    null: float | int | torch.Tensor = 0.0,
    probs: Sequence[float] = (0.025, 0.975),
    robust: bool = False,
    point: PointNullSpec | None = None,
    name: str = "contrast",
    dims: Mapping[str, Sequence[str]] | None = None,
    coords: Mapping[str, Sequence[object]] | None = None,
) -> HypothesisSummary:
    """Evaluate one checked QVR contrast over retained joint draws.

    Parameters
    ----------
    expression : str or ContrastExpression
        QVR value expression and optional aliases to original site names.
    prior : PosteriorAnalysis or None
        Joint draws from the corresponding proper encompassing prior.
        Draw counts may differ; event shapes and devices must agree.
    null : float, int, or torch.Tensor
        Finite comparison value on event axes only.
    probs : Sequence[float]
        Requested quantile probabilities in output order.
    robust : bool
        Use median and scaled MAD instead of mean and sample SD.
    point : PointNullSpec or None
        Optional marginal density comparison on the same joint prior and
        posterior contrast; requires a checked Real result and prior draws.
    name : str
        Original label of the derived contrast.
    dims, coords : Mapping or None
        Input event-axis identities and labels, with optional sample labels.
        Distinct axes remain distinct even when their extents coincide.

    Returns
    -------
    HypothesisSummary
        Existing uncertainty, strict-region posterior odds, and optional
        prior-corrected region evidence. Equality frequencies are descriptive;
        requested point_evidence retains a separate marginal density ratio.
    """
    from quivers.diagnostics.contrast import _contrast_hypothesis

    self._validate_axes()
    if prior is not None:
        prior._validate_axes()
    return _contrast_hypothesis(
        self.samples,
        expression,
        prior=prior.samples if prior is not None else None,
        null=null,
        probs=probs,
        robust=robust,
        point=point,
        name=name,
        kind=self.kind,
        dims=dims,
        coords=coords,
    )

waic

waic(*, var_name: str | None = None) -> WAICResult

Compute WAIC for one response's retained raw observation scores.

PARAMETER DESCRIPTION
var_name

Observation variable; required for multiple response variables.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
WAICResult

Pointwise and aggregate WAIC estimates.

Source code in src/quivers/diagnostics/posterior.py
def waic(self, *, var_name: str | None = None) -> WAICResult:
    """Compute WAIC for one response's retained raw observation scores.

    Parameters
    ----------
    var_name : str or None
        Observation variable; required for multiple response variables.

    Returns
    -------
    WAICResult
        Pointwise and aggregate WAIC estimates.
    """
    self._validate_axes()
    return waic(self.log_likelihood[self._likelihood_name(var_name)])

to_datatree

to_datatree(*, coords: Mapping[str, list] | None = None, dims: Mapping[str, list[str]] | None = None) -> DataTree

Convert retained tensors for the optional ArviZ diagnostics package.

PARAMETER DESCRIPTION
coords

Coordinate labels for named event or observation dimensions.

TYPE: Mapping[str, list] or None DEFAULT: None

dims

Dimension names per variable, excluding chain and draw axes.

TYPE: Mapping[str, list[str]] or None DEFAULT: None

RETURNS DESCRIPTION
DataTree

Posterior, likelihood, observed-data, and sampler-stat groups. Chain and draw axes are retained for both posterior kinds.

Source code in src/quivers/diagnostics/posterior.py
def to_datatree(
    self,
    *,
    coords: Mapping[str, list] | None = None,
    dims: Mapping[str, list[str]] | None = None,
) -> _DataTree:
    """Convert retained tensors for the optional ArviZ diagnostics package.

    Parameters
    ----------
    coords : Mapping[str, list] or None
        Coordinate labels for named event or observation dimensions.
    dims : Mapping[str, list[str]] or None
        Dimension names per variable, excluding chain and draw axes.

    Returns
    -------
    xarray.DataTree
        Posterior, likelihood, observed-data, and sampler-stat groups.
        Chain and draw axes are retained for both posterior kinds.
    """
    self._validate_axes()
    from quivers.diagnostics.arviz_io import (
        _ARVIZ_SAMPLE_STATS,
        _groups_to_datatree,
    )

    groups = {
        "posterior": self.samples,
        "log_likelihood": self.log_likelihood,
        "observed_data": self.observed_data,
        "sample_stats": self.sample_stats,
    }
    tree = _groups_to_datatree(
        groups,
        coords={
            name: list(values)
            for name, values in (self.coords if coords is None else coords).items()
        },
        dims={
            name: list(values)
            for name, values in (self.dims if dims is None else dims).items()
        },
        group_dims={
            group: {name: list(axes) for name, axes in names.items()}
            for group, names in self.group_dims.items()
        }
        if dims is None
        else None,
    )
    tree.attrs["quivers_posterior_kind"] = self.kind
    tree.attrs["quivers_posterior_format"] = "qvr-posterior/v1"
    tree.attrs["quivers_sample_stat_names"] = json.dumps(
        {_ARVIZ_SAMPLE_STATS.get(name, name): name for name in self.sample_stats},
        sort_keys=True,
    )
    tree.attrs["quivers_tensor_dtypes"] = json.dumps(
        {
            group: {
                (
                    _ARVIZ_SAMPLE_STATS.get(name, name)
                    if group == "sample_stats"
                    else name
                ): str(value.dtype)
                for name, value in values.items()
            }
            for group, values in groups.items()
        },
        sort_keys=True,
    )
    return tree

from_datatree classmethod

from_datatree(tree: DataTree, *, kind: Literal['mcmc', 'variational', 'prior'] | None = None) -> PosteriorAnalysis

Restore retained analysis tensors and labels from an ArviZ DataTree.

PARAMETER DESCRIPTION
tree

Canonical posterior, likelihood, observed-data, and sample-stat groups.

TYPE: DataTree

kind

Explicit provenance for external trees. QVR trees retain it in metadata; an override must agree. Chain count never determines provenance.

TYPE: ('mcmc', 'variational', 'prior') DEFAULT: "mcmc"

RETURNS DESCRIPTION
PosteriorAnalysis

Independently owned CPU tensors, dimensions, labels, and provenance. This restores analysis, rather than an executable predictor or optimizer.

RAISES DESCRIPTION
(ValueError, TypeError)

If provenance, format, labels, groups, or sampled axes are inconsistent.

Source code in src/quivers/diagnostics/posterior.py
@classmethod
def from_datatree(
    cls,
    tree: _DataTree,
    *,
    kind: Literal["mcmc", "variational", "prior"] | None = None,
) -> PosteriorAnalysis:
    """Restore retained analysis tensors and labels from an ArviZ DataTree.

    Parameters
    ----------
    tree : xarray.DataTree
        Canonical posterior, likelihood, observed-data, and sample-stat groups.
    kind : {"mcmc", "variational", "prior"} or None
        Explicit provenance for external trees. QVR trees retain it in metadata;
        an override must agree. Chain count never determines provenance.

    Returns
    -------
    PosteriorAnalysis
        Independently owned CPU tensors, dimensions, labels, and provenance.
        This restores analysis, rather than an executable predictor or optimizer.

    Raises
    ------
    ValueError, TypeError
        If provenance, format, labels, groups, or sampled axes are inconsistent.
    """
    from quivers.diagnostics.arviz_io import _posterior_from_datatree

    return _posterior_from_datatree(tree, kind=kind)

to_netcdf

to_netcdf(path: str | Path) -> None

Write retained analysis through the existing DataTree NetCDF format.

PARAMETER DESCRIPTION
path

Output NetCDF file. Requires the diagnostics extra.

TYPE: str or Path

Source code in src/quivers/diagnostics/posterior.py
def to_netcdf(self, path: str | Path) -> None:
    """Write retained analysis through the existing DataTree NetCDF format.

    Parameters
    ----------
    path : str or Path
        Output NetCDF file. Requires the diagnostics extra.
    """
    from quivers._atomic import atomic_output

    tree = self.to_datatree()
    with atomic_output(Path(path)) as temporary:
        encoding = {
            f"/{group}": {
                name: {"dtype": "float32"}
                for name, variable in node.dataset.data_vars.items()
                if variable.dtype == "float16"
            }
            for group, node in tree.children.items()
        }
        tree.to_netcdf(temporary, engine="netcdf4", encoding=encoding)

from_netcdf classmethod

from_netcdf(path: str | Path) -> PosteriorAnalysis

Read a QVR retained analysis without reconstructing a fitted evaluator.

PARAMETER DESCRIPTION
path

NetCDF file written from a QVR posterior DataTree.

TYPE: str or Path

RETURNS DESCRIPTION
PosteriorAnalysis

Owned CPU tensors and coordinate metadata, after axis validation.

RAISES DESCRIPTION
(ValueError, TypeError)

If the stored tree does not satisfy the retained analysis contract.

OSError

If the input file is missing or cannot be opened as NetCDF.

Source code in src/quivers/diagnostics/posterior.py
@classmethod
def from_netcdf(cls, path: str | Path) -> PosteriorAnalysis:
    """Read a QVR retained analysis without reconstructing a fitted evaluator.

    Parameters
    ----------
    path : str or Path
        NetCDF file written from a QVR posterior DataTree.

    Returns
    -------
    PosteriorAnalysis
        Owned CPU tensors and coordinate metadata, after axis validation.

    Raises
    ------
    ValueError, TypeError
        If the stored tree does not satisfy the retained analysis contract.
    OSError
        If the input file is missing or cannot be opened as NetCDF.
    """
    import xarray as xr

    with xr.open_datatree(path, engine="netcdf4") as tree:
        return cls.from_datatree(tree)

reloo

reloo(refit: Callable[[FoldSplit], FoldPrediction], *, var_name: str | None = None, k_threshold: float | None = None, seed: int = 0, pointwise: bool = True) -> object

Replace problematic PSIS terms with raw held-out refit predictions.

PARAMETER DESCRIPTION
refit

Existing source, formula, or user refit adapter. Each requested split excludes one original observation and scores that row alone.

TYPE: Callable[[FoldSplit], FoldPrediction]

var_name

Selected response; required when several responses are retained.

TYPE: str or None DEFAULT: None

k_threshold

Refit Pareto shapes above this value. None uses ArviZ's threshold based on retained sample count. Negative infinity refits all rows. Undefined tail fits are refitted unless the threshold is infinity.

TYPE: float or None DEFAULT: None

seed

Nonnegative base seed for independent, order-invariant row refits.

TYPE: int DEFAULT: 0

pointwise

Retain individual ELPD values and Pareto diagnostics in the result.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
ELPDData

ArviZ's updated criterion, on the natural-log scale. Refit terms retain the supplied fitter's approximation and Monte Carlo error.

RAISES DESCRIPTION
(ValueError, TypeError)

If options, raw held-out scores, or observation axes are invalid.

ImportError

If the optional diagnostics dependencies are unavailable.

Source code in src/quivers/diagnostics/posterior.py
def reloo(
    self,
    refit: Callable[[FoldSplit], FoldPrediction],
    *,
    var_name: str | None = None,
    k_threshold: float | None = None,
    seed: int = 0,
    pointwise: bool = True,
) -> object:
    """Replace problematic PSIS terms with raw held-out refit predictions.

    Parameters
    ----------
    refit : Callable[[FoldSplit], FoldPrediction]
        Existing source, formula, or user refit adapter. Each requested
        split excludes one original observation and scores that row alone.
    var_name : str or None
        Selected response; required when several responses are retained.
    k_threshold : float or None
        Refit Pareto shapes above this value. None uses ArviZ's threshold
        based on retained sample count. Negative infinity refits all rows.
        Undefined tail fits are refitted unless the threshold is infinity.
    seed : int
        Nonnegative base seed for independent, order-invariant row refits.
    pointwise : bool
        Retain individual ELPD values and Pareto diagnostics in the result.

    Returns
    -------
    arviz.ELPDData
        ArviZ's updated criterion, on the natural-log scale. Refit terms
        retain the supplied fitter's approximation and Monte Carlo error.

    Raises
    ------
    ValueError, TypeError
        If options, raw held-out scores, or observation axes are invalid.
    ImportError
        If the optional diagnostics dependencies are unavailable.
    """
    from quivers.diagnostics._reloo import reloo

    return reloo(
        self,
        refit,
        var_name=var_name,
        k_threshold=k_threshold,
        seed=seed,
        pointwise=pointwise,
    )

loo

loo(*, var_name: str | None = None, pointwise: bool = True) -> object

Run optional ArviZ PSIS-LOO without recomputing model likelihoods.

PARAMETER DESCRIPTION
var_name

Observation variable; required for multiple responses.

TYPE: str or None DEFAULT: None

pointwise

Include observation-level ELPD and Pareto shape diagnostics.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
ELPDData

ArviZ's PSIS-LOO result. Variational draws use relative efficiency one; this does not correct variational approximation error. If every likelihood column is constant across draws, exact uniform weights replace an undefined tail fit, and Pareto shapes are NaN.

Source code in src/quivers/diagnostics/posterior.py
def loo(self, *, var_name: str | None = None, pointwise: bool = True) -> object:
    """Run optional ArviZ PSIS-LOO without recomputing model likelihoods.

    Parameters
    ----------
    var_name : str or None
        Observation variable; required for multiple responses.
    pointwise : bool
        Include observation-level ELPD and Pareto shape diagnostics.

    Returns
    -------
    arviz.ELPDData
        ArviZ's PSIS-LOO result. Variational draws use relative efficiency
        one; this does not correct variational approximation error.
        If every likelihood column is constant across draws, exact uniform
        weights replace an undefined tail fit, and Pareto shapes are NaN.
    """
    import arviz as az

    name = self._likelihood_name(var_name)
    tree = self.to_datatree()
    scores = self.log_likelihood[name]
    if (
        scores.numel()
        and bool(torch.isfinite(scores).all())
        and torch.equal(scores, scores[0, 0].expand_as(scores))
    ):
        # Constant likelihood columns have exactly uniform importance
        # weights. No tail distribution exists to fit or diagnose.
        import xarray as xr

        likelihood = tree["log_likelihood"].dataset[name]
        count = scores.shape[0] * scores.shape[1]
        return az.loo(
            tree,
            var_name=name,
            pointwise=pointwise,
            reff=1.0,
            log_weights=xr.full_like(
                likelihood.transpose(..., "chain", "draw"), -math.log(count)
            ),
            pareto_k=xr.full_like(
                likelihood.isel(chain=0, draw=0, drop=True), math.nan
            ),
        )
    return az.loo(
        tree,
        var_name=name,
        pointwise=pointwise,
        reff=1.0 if self.kind != "mcmc" or not self.samples else None,
    )

PosteriorCovariance didactic-model

PosteriorCovariance(*, covariance: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), correlation: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), coordinates: tuple[tuple[str, tuple[int, ...]], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), dimension_names: tuple[tuple[str, ...], ...], coordinate_labels: tuple[tuple[object, ...], ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), variables: tuple[str, ...], event_shapes: tuple[tuple[int, ...], ...], sample_shape: tuple[int, int] = field(opaque=True, extras=OPAQUE_BY_VALUE), chain_labels: tuple[object, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), draw_labels: tuple[object, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), ddof: int, chainwise: bool, kind: Literal['mcmc', 'variational', 'prior'])

Bases: ValueModel

Joint empirical covariance and correlation of retained coordinates.

PARAMETER DESCRIPTION
covariance

Float64 square matrices, or one matrix per chain when chainwise. A constant coordinate has zero covariance and NaN correlations.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

correlation

Float64 square matrices, or one matrix per chain when chainwise. A constant coordinate has zero covariance and NaN correlations.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

coordinates

Matrix columns as an exact variable name and row-major event index. The same coordinates label matrix rows; no string parsing is needed.

TYPE: tuple[tuple[str, tuple[int, ...]], ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

dimension_names

Event dimension names and their original labels for each matrix column.

TYPE: tuple

coordinate_labels

Event dimension names and their original labels for each matrix column.

TYPE: tuple

variables

Selected variable order and corresponding original event shapes.

TYPE: tuple

event_shapes

Selected variable order and corresponding original event shapes.

TYPE: tuple

sample_shape

Original chain and draw counts, before the empirical reduction.

TYPE: tuple[int, int] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

chain_labels

Original sample-axis labels, or their positional defaults.

TYPE: tuple DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

draw_labels

Original sample-axis labels, or their positional defaults.

TYPE: tuple DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

ddof

Degrees of freedom subtracted from the pooled or per-chain draw count.

TYPE: int

chainwise

Whether each chain was summarized separately.

TYPE: bool

kind

Original draw provenance; this record adds no convergence diagnostics.

TYPE: str

PosteriorSummary didactic-model

PosteriorSummary(*, mean: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), sd: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), probs: tuple[float, ...], quantiles: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), convergence: ConvergenceSummary | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Pooled uncertainty summaries, with MCMC diagnostics when applicable.

PARAMETER DESCRIPTION
mean

Mean and sample standard deviation on the site's event coordinates.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

sd

Mean and sample standard deviation on the site's event coordinates.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

probs

Requested quantile probabilities.

TYPE: tuple[float, ...]

quantiles

Quantiles with shape (len(probs), *event_shape).

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

convergence

Recorded-chain diagnostics, or None for variational draws.

TYPE: ConvergenceSummary or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

WAICResult didactic-model

WAICResult(*, elpd_waic: float, p_waic: float, waic: float, se: float, se_p_waic: float, elpd_i: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), variance_i: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), warning: bool, num_samples: int, num_observations: int)

Bases: ValueModel

Pointwise WAIC estimates using sample log-likelihood variances.

PARAMETER DESCRIPTION
elpd_waic

Expected log predictive density, effective parameter count, and deviance-scale criterion -2 * elpd_waic.

TYPE: float

p_waic

Expected log predictive density, effective parameter count, and deviance-scale criterion -2 * elpd_waic.

TYPE: float

waic

Expected log predictive density, effective parameter count, and deviance-scale criterion -2 * elpd_waic.

TYPE: float

se

Standard errors of elpd_waic and p_waic across observation units; NaN for one unit.

TYPE: float

se_p_waic

Standard errors of elpd_waic and p_waic across observation units; NaN for one unit.

TYPE: float

elpd_i

Pointwise ELPD and unbiased sample variance over pooled posterior draws.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

variance_i

Pointwise ELPD and unbiased sample variance over pooled posterior draws.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

warning

Whether any pointwise log-likelihood variance exceeds 0.4.

TYPE: bool

num_samples

Pooled posterior draw count and number of observation units.

TYPE: int

num_observations

Pooled posterior draw count and number of observation units.

TYPE: int

se_waic property

se_waic: float

Standard error of the deviance-scale WAIC estimate.

RETURNS DESCRIPTION
float

Twice the ELPD-scale standard error.

waic_i property

waic_i: Tensor

Deviance-scale contributions on the original observation axes.

RETURNS DESCRIPTION
Tensor

Negative twice each retained pointwise ELPD estimate.

PredictionGrid didactic-model

PredictionGrid(*, columns: tuple[str, ...], rows: tuple[tuple[GridValue, ...], ...], axes: tuple[str, ...], points: tuple[tuple[GridValue, ...], ...], num_conditions: int, marginalize: bool = False, weights: tuple[float, ...] = ())

Bases: ValueModel

Explicit predictor rows with a bounded Cartesian effect layout.

PARAMETER DESCRIPTION
columns

Predictor columns in generated-row order.

TYPE: tuple[str, ...]

rows

Immutable scalar rows, ordered by effect point then conditioning row.

TYPE: tuple[tuple[GridValue, ...], ...]

axes

Varied predictor names in Cartesian-product order.

TYPE: tuple[str, ...]

points

The varied predictor coordinates at each effect point.

TYPE: tuple[tuple[GridValue, ...], ...]

num_conditions

Explicit conditioning or empirical-reference row count per point.

TYPE: int

marginalize

Reduce reference rows within each joint posterior draw when true. False retains a separate effect for every conditioning row.

TYPE: bool DEFAULT: False

weights

Normalized empirical-reference weights; empty for conditional effects.

TYPE: tuple[float, ...] DEFAULT: ()

Notes

Construct with prediction_grid, which checks the allocation bound before generating the Cartesian product. It never substitutes means or reference categories implicitly. Prediction retains the fitted model's own checks.

to_frame

to_frame() -> IntoDataFrame

Build an independent dataframe for the existing prediction interface.

RETURNS DESCRIPTION
IntoDataFrame

Pandas rows in the checked effect-point/conditioning order.

Notes

This optional adapter requires pandas, as provided by the formula frontend's dependencies. Core source workflows use to_mapping.

Source code in src/quivers/diagnostics/conditional.py
def to_frame(self) -> IntoDataFrame:
    """Build an independent dataframe for the existing prediction interface.

    Returns
    -------
    IntoDataFrame
        Pandas rows in the checked effect-point/conditioning order.

    Notes
    -----
    This optional adapter requires pandas, as provided by the formula
    frontend's dependencies. Core source workflows use `to_mapping`.
    """
    import pandas as pd

    return pd.DataFrame.from_records(self.rows, columns=self.columns)

to_mapping

to_mapping() -> dict[str, tuple[GridValue, ...]]

Expose predictor columns without a dataframe dependency.

RETURNS DESCRIPTION
dict[str, tuple[GridValue, ...]]

Independent column tuples in the checked generated-row order.

Source code in src/quivers/diagnostics/conditional.py
def to_mapping(self) -> dict[str, tuple[GridValue, ...]]:
    """Expose predictor columns without a dataframe dependency.

    Returns
    -------
    dict[str, tuple[GridValue, ...]]
        Independent column tuples in the checked generated-row order.
    """
    return {
        name: tuple(row[index] for row in self.rows)
        for index, name in enumerate(self.columns)
    }

result

result(predictions: Tensor, *, kind: Literal['mcmc', 'variational', 'prior'], method: Literal['epred', 'linpred', 'predict'] = 'epred', labels: tuple[int | str, ...] = ()) -> ConditionalEffects

Retain joint predictions, reducing reference rows before summaries.

PARAMETER DESCRIPTION
predictions

One joint prediction request with chain, draw, row, and event axes.

TYPE: Tensor

kind

Actual draw provenance; a variational layout axis is not a chain.

TYPE: ('mcmc', 'variational', 'prior') DEFAULT: "mcmc"

method

Expected responses, linear predictors, or sampled responses.

TYPE: ('epred', 'linpred', 'predict') DEFAULT: "epred"

labels

Optional final response-component labels, in native output order.

TYPE: tuple[int or str, ...] DEFAULT: ()

RETURNS DESCRIPTION
ConditionalEffects

Draws on point/condition/event axes, or point/event axes after empirical marginalization. Cross-point dependence is retained.

RAISES DESCRIPTION
(ValueError, TypeError)

If prediction rows or sample axes disagree with this grid, or a numeric empirical reduction contains invalid values.

Source code in src/quivers/diagnostics/conditional.py
def result(
    self,
    predictions: torch.Tensor,
    *,
    kind: Literal["mcmc", "variational", "prior"],
    method: Literal["epred", "linpred", "predict"] = "epred",
    labels: tuple[int | str, ...] = (),
) -> ConditionalEffects:
    """Retain joint predictions, reducing reference rows before summaries.

    Parameters
    ----------
    predictions : torch.Tensor
        One joint prediction request with chain, draw, row, and event axes.
    kind : {"mcmc", "variational", "prior"}
        Actual draw provenance; a variational layout axis is not a chain.
    method : {"epred", "linpred", "predict"}
        Expected responses, linear predictors, or sampled responses.
    labels : tuple[int or str, ...]
        Optional final response-component labels, in native output order.

    Returns
    -------
    ConditionalEffects
        Draws on point/condition/event axes, or point/event axes after
        empirical marginalization. Cross-point dependence is retained.

    Raises
    ------
    ValueError, TypeError
        If prediction rows or sample axes disagree with this grid, or a
        numeric empirical reduction contains invalid values.
    """
    if (
        not isinstance(predictions, torch.Tensor)
        or predictions.ndim < 3
        or not all(predictions.shape[:2])
        or predictions.shape[2] != len(self.rows)
    ):
        raise ValueError(
            "grid predictions require matching chain, draw, and row axes"
        )
    values = predictions.reshape(
        *predictions.shape[:2],
        len(self.points),
        self.num_conditions,
        *predictions.shape[3:],
    )
    if self.marginalize:
        values = real_samples(values, label="empirical conditional effects")
        weights = values.new_tensor(self.weights).reshape(
            1, 1, 1, self.num_conditions, *((1,) * (values.ndim - 4))
        )
        values = (values * weights).sum(3)
    return ConditionalEffects(
        grid=self, draws=values, kind=kind, method=method, labels=labels
    )

ConditionalEffects didactic-model

ConditionalEffects(*, grid: PredictionGrid = field(opaque=True, extras=OPAQUE_BY_VALUE), draws: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), kind: Literal['mcmc', 'variational', 'prior'], method: Literal['epred', 'linpred', 'predict'] = 'epred', labels: tuple[int | str, ...] = ())

Bases: ValueModel

Joint posterior predictions over an explicit conditioning experiment.

PARAMETER DESCRIPTION
grid

Point labels, explicit reference rows, and reduction policy.

TYPE: PredictionGrid DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

draws

Chain/draw/point/condition/event axes, with the condition axis removed only for explicit empirical marginalization. Storage is held by identity.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

kind

Actual draw provenance, forwarded to existing posterior diagnostics.

TYPE: ('mcmc', 'variational', 'prior') DEFAULT: "mcmc"

method

Response expectations, linear predictors, or response replications.

TYPE: ('epred', 'linpred', 'predict') DEFAULT: "epred"

labels

Optional native response labels; category probabilities retain all labels.

TYPE: tuple[int or str, ...] DEFAULT: ()

analysis

analysis() -> PosteriorAnalysis

Reuse joint uncertainty, covariance, and checked contrast diagnostics.

RETURNS DESCRIPTION
PosteriorAnalysis

Existing diagnostics over the retained effect tensor, under the site name effect. No model replay or resampling occurs.

RAISES DESCRIPTION
(ValueError, TypeError)

If draws cannot be represented as real empirical samples.

Source code in src/quivers/diagnostics/conditional.py
def analysis(self) -> PosteriorAnalysis:
    """Reuse joint uncertainty, covariance, and checked contrast diagnostics.

    Returns
    -------
    PosteriorAnalysis
        Existing diagnostics over the retained effect tensor, under the
        site name ``effect``. No model replay or resampling occurs.

    Raises
    ------
    ValueError, TypeError
        If draws cannot be represented as real empirical samples.
    """
    return PosteriorAnalysis(
        samples={
            "effect": real_samples(
                self.draws, label="conditional effects", finite=False
            )
        },
        log_likelihood={},
        kind=self.kind,
    )

summary

summary(*, probs: Sequence[float] = (0.05, 0.5, 0.95)) -> PosteriorSummary

Summarize retained effects through the common posterior diagnostics.

PARAMETER DESCRIPTION
probs

Interior quantile probabilities, retaining their requested order.

TYPE: Sequence[float] DEFAULT: (0.05, 0.5, 0.95)

RETURNS DESCRIPTION
PosteriorSummary

Draw-wise uncertainty on point/condition/event coordinates.

RAISES DESCRIPTION
(ValueError, TypeError)

If sample axes, carriers, or requested probabilities are invalid.

Source code in src/quivers/diagnostics/conditional.py
def summary(
    self, *, probs: Sequence[float] = (0.05, 0.5, 0.95)
) -> PosteriorSummary:
    """Summarize retained effects through the common posterior diagnostics.

    Parameters
    ----------
    probs : Sequence[float]
        Interior quantile probabilities, retaining their requested order.

    Returns
    -------
    PosteriorSummary
        Draw-wise uncertainty on point/condition/event coordinates.

    Raises
    ------
    ValueError, TypeError
        If sample axes, carriers, or requested probabilities are invalid.
    """
    return self.analysis().summary(probs=probs)["effect"]

PointNullAssumptions didactic-model

PointNullAssumptions(*, proper_continuous_prior: bool, compatible_null_prior: bool)

Bases: ValueModel

Caller declarations needed to interpret a density ratio as point evidence.

PARAMETER DESCRIPTION
proper_continuous_prior

The encompassing prior is proper and induces a continuous contrast with a finite, positive density at the null. Its corresponding posterior also has a density there; neither distribution has an atom at the null.

TYPE: bool

compatible_null_prior

The null model uses the encompassing likelihood restricted to the null, and its nuisance prior equals the encompassing prior conditional on that null, with the same underlying dominating measures.

TYPE: bool

Notes

These declarations are not mechanically verified from the draws. They do not assert KDE accuracy. Arbitrary nonlinear contrasts may fail the density or compatibility assumptions even when each parameter has a proper prior.

PointNullSpec didactic-model

PointNullSpec(*, bandwidth: str | float | Tensor = field(default='nrd0', opaque=True, extras=OPAQUE_BY_IDENTITY), prior_bandwidth: str | float | Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), adjust: float = 1.0, assumptions: PointNullAssumptions | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), max_working_elements: int = 262144)

Bases: ValueModel

Request marginal density evidence from the shared joint contrast streams.

PARAMETER DESCRIPTION
bandwidth

Posterior Gaussian bandwidth: nrd0, scott, or a positive scalar/event tensor. Bandwidth tensors retain their original identity.

TYPE: str, float, or torch.Tensor DEFAULT: field(default='nrd0', opaque=True, extras=OPAQUE_BY_IDENTITY)

prior_bandwidth

Prior bandwidth policy; None estimates it separately under bandwidth.

TYPE: str, float, torch.Tensor, or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

adjust

Positive multiplier on both selected bandwidths.

TYPE: float DEFAULT: 1.0

assumptions

Optional explicit declarations allowing a point-null BF01 interpretation. Without both declarations the result remains a diagnostic density ratio.

TYPE: PointNullAssumptions or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

max_working_elements

Positive bound on each shared density estimator's kernel workspace.

TYPE: int DEFAULT: 262144

Notes

Every retained event coordinate is a separate scalar contrast; this request does not estimate a joint multivariate point-null density. The estimator's resource, finite-continuous-sample, and bandwidth checks apply when used.

DensityOrdinate didactic-model

DensityOrdinate(*, log_density: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), at: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_bandwidth: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), bandwidth_rule: str, adjust: float, sample_shape: tuple[int, ...], kernel_effective_count: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), name: str, dimension_names: tuple[str, ...], coordinate_labels: tuple[tuple[object, ...], ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), max_working_elements: int)

Bases: ValueModel

A marginal Gaussian KDE ordinate for each scalar event coordinate.

PARAMETER DESCRIPTION
log_density

Natural-log density in the original contrast units.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

at

Evaluation point broadcast only over event coordinates.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

log_bandwidth

Absolute Gaussian kernel bandwidth in log space, including adjustment. This representation remains authoritative at extreme numerical scales.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

bandwidth_rule

nrd0, scott, or explicit, describing bandwidth selection.

TYPE: str

adjust

Positive multiplier applied to the selected bandwidth.

TYPE: float

sample_shape

Retained chain and draw counts. Draws are equally weighted and pooled.

TYPE: tuple[int, ...]

kernel_effective_count

Squared sum of local kernel weights divided by their sum of squares. This measures local weight concentration, not MCMC effective sample size.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

name

Original contrast name, named event dimensions, and original labels.

TYPE: (str, tuple, tuple)

dimension_names

Original contrast name, named event dimensions, and original labels.

TYPE: (str, tuple, tuple)

coordinate_labels

Original contrast name, named event dimensions, and original labels.

TYPE: (str, tuple, tuple)

max_working_elements

Upper bound on each temporary kernel tile, excluding input storage, output coordinates, and the shared bandwidth-reduction workspace.

TYPE: int

bandwidth property

bandwidth: Tensor

Return the absolute bandwidth when representable in Float64.

RETURNS DESCRIPTION
Tensor

Exponentiated log bandwidth. Underflow or overflow may give zero or infinity; log_bandwidth retains the finite scale in those cases.

num_samples property

num_samples: int

Return the number of equally weighted pooled draws.

RETURNS DESCRIPTION
int

Product of original chain and draw counts.

DensityRatio didactic-model

DensityRatio(*, posterior: DensityOrdinate = field(opaque=True, extras=OPAQUE_BY_VALUE), prior: DensityOrdinate = field(opaque=True, extras=OPAQUE_BY_VALUE), log_ratio: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), assumptions: PointNullAssumptions | None = None, log_bayes_factor_01: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Posterior-to-prior density evidence, separate from probability odds.

PARAMETER DESCRIPTION
posterior

Marginal KDE ordinates at the same original-coordinate null.

TYPE: DensityOrdinate DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

prior

Marginal KDE ordinates at the same original-coordinate null.

TYPE: DensityOrdinate DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

log_ratio

Posterior minus prior log density. This always describes the empirical density ratio, independently of any Bayesian interpretation.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

assumptions

Caller declarations, retained without claiming mechanical verification.

TYPE: PointNullAssumptions or None DEFAULT: None

log_bayes_factor_01

Point-null versus encompassing-alternative log Bayes factor only when both declarations are true. KDE approximation error remains; this is neither a region-odds ratio nor a posterior model probability.

TYPE: Tensor or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

ContrastExpression didactic-model

ContrastExpression(*, expression: str, bindings: dict[str, str] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

One QVR value expression over jointly aligned retained variables.

PARAMETER DESCRIPTION
expression

Existing QVR arithmetic, functions, and event-axis indexing. Chain and draw axes are protected from indexing and reductions. Original Int and Bool carriers retain QVR integer arithmetic and predicate typing; conversion to diagnostic Float64 values follows expression evaluation.

TYPE: str

bindings

Optional expression aliases mapped to original variable labels. This permits labels such as condition[a] without changing their spelling. Unused aliases and unknown variables are errors.

TYPE: dict[str, str] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

HypothesisSummary didactic-model

HypothesisSummary(*, estimate: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), est_error: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), probs: tuple[float, ...], quantiles: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), null: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), below: RegionEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), above: RegionEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), equal_probability: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), prior_equal_probability: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), name: str, dimension_names: tuple[str, ...], coordinate_labels: tuple[tuple[object, ...], ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), sample_shape: tuple[int, ...], prior_sample_shape: tuple[int, ...] | None = None, chain_labels: tuple[object, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), draw_labels: tuple[object, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), robust: bool, kind: Literal['mcmc', 'variational', 'prior', 'unspecified'], point_evidence: DensityRatio | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Uncertainty and strict-region evidence for an empirical contrast.

PARAMETER DESCRIPTION
estimate

Mean and sample standard deviation, or median and normal-consistent median absolute deviation when robust. These describe the supplied contrast in its original units, without subtracting the null.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

est_error

Mean and sample standard deviation, or median and normal-consistent median absolute deviation when robust. These describe the supplied contrast in its original units, without subtracting the null.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

probs

Requested type-7 quantile probabilities and values with a leading probability axis. Remaining axes are the original event coordinates.

TYPE: (tuple[float, ...], Tensor)

quantiles

Requested type-7 quantile probabilities and values with a leading probability axis. Remaining axes are the original event coordinates.

TYPE: (tuple[float, ...], Tensor)

null

Finite comparison value broadcast only across event coordinates.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

below

Evidence for the strict regions contrast < null and contrast > null. Each complement includes exact ties.

TYPE: RegionEvidence DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

above

Evidence for the strict regions contrast < null and contrast > null. Each complement includes exact ties.

TYPE: RegionEvidence DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

equal_probability

Descriptive equality frequencies, without a point-null Bayes factor.

TYPE: (Tensor, Tensor or None) DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

prior_equal_probability

Descriptive equality frequencies, without a point-null Bayes factor.

TYPE: (Tensor, Tensor or None) DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

name

Original contrast name, named event axes, and their original labels.

TYPE: (str, tuple, tuple)

dimension_names

Original contrast name, named event axes, and their original labels.

TYPE: (str, tuple, tuple)

coordinate_labels

Original contrast name, named event axes, and their original labels.

TYPE: (str, tuple, tuple)

sample_shape

Original chain and draw counts; prior counts may differ.

TYPE: (tuple[int, ...], tuple[int, ...] or None)

prior_sample_shape

Original chain and draw counts; prior counts may differ.

TYPE: (tuple[int, ...], tuple[int, ...] or None)

chain_labels

Original posterior sample-axis labels or their positional defaults.

TYPE: tuple DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

draw_labels

Original posterior sample-axis labels or their positional defaults.

TYPE: tuple DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

robust

Whether location and dispersion use median and scaled MAD.

TYPE: bool

kind

Caller-supplied provenance; no convergence diagnostics are inferred.

TYPE: str

point_evidence

Optional marginal posterior/prior density comparison at the null, separate from strict-region evidence and descriptive equality frequency.

TYPE: DensityRatio or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

RegionEvidence didactic-model

RegionEvidence(*, probability: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_odds: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), prior_probability: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), prior_log_odds: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), log_bayes_factor: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Empirical evidence for a strict region against its complement.

PARAMETER DESCRIPTION
probability

Posterior region frequency and its natural-log odds. Zero and unit frequencies give negative and positive infinity, without pseudocounts.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

log_odds

Posterior region frequency and its natural-log odds. Zero and unit frequencies give negative and positive infinity, without pseudocounts.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

prior_probability

Corresponding frequencies and log odds from jointly aligned prior draws.

TYPE: Tensor or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

prior_log_odds

Corresponding frequencies and log odds from jointly aligned prior draws.

TYPE: Tensor or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

log_bayes_factor

Posterior minus prior log odds. NaN when the empirical prior region has probability zero or one: both restricted prior models cannot be formed. This empirical region comparison is not point-null density evidence.

TYPE: Tensor or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

SummaryTable didactic-model

SummaryTable(*, rows: tuple[RowLabel, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), columns: tuple[str, ...], components: tuple[RowLabel, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), values: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A labeled summary matrix or three-way array of retained draws.

Two-way tables have shape (row, column); three-way tables, which brms returns for vector-valued predictions and per-level coefficients, have shape (row, column, component).

PARAMETER DESCRIPTION
rows

Row labels: variable names or observation identities.

TYPE: tuple[str or int, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

columns

Statistic labels, for instance ("Estimate", "Est.Error", "Q2.5", "Q97.5").

TYPE: tuple[str, ...]

components

Labels of the third axis, empty for a two-way table.

TYPE: tuple[str or int, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

values

Float64 statistics in row, column, and component order.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

value

value(row: RowLabel, column: str, component: RowLabel | None = None) -> float

Read one statistic by its labels.

PARAMETER DESCRIPTION
row

Row label.

TYPE: str or int

column

Statistic label.

TYPE: str

component

Component label of a three-way table; None for a two-way table.

TYPE: str or int or None DEFAULT: None

RETURNS DESCRIPTION
float

The selected statistic.

RAISES DESCRIPTION
KeyError

If a label is unknown, or a component is required or not allowed.

Source code in src/quivers/diagnostics/posterior_tables.py
def value(
    self, row: RowLabel, column: str, component: RowLabel | None = None
) -> float:
    """Read one statistic by its labels.

    Parameters
    ----------
    row : str or int
        Row label.
    column : str
        Statistic label.
    component : str or int or None
        Component label of a three-way table; None for a two-way table.

    Returns
    -------
    float
        The selected statistic.

    Raises
    ------
    KeyError
        If a label is unknown, or a component is required or not allowed.
    """
    if (component is None) != (not self.components):
        raise KeyError("select a component exactly for a three-way table")
    try:
        index = (self.rows.index(row), self.columns.index(column))
        if component is not None:
            index += (self.components.index(component),)
    except ValueError as error:
        raise KeyError(f"unknown summary label: {error}") from error
    return float(self.values[index].item())

to_frame

to_frame(component: RowLabel | None = None) -> DataFrame

Return a two-way table, or one component slice, as a DataFrame.

PARAMETER DESCRIPTION
component

Component of a three-way table; None for a two-way table.

TYPE: str or int or None DEFAULT: None

RETURNS DESCRIPTION
DataFrame

Rows indexed by rows, columns named by columns.

RAISES DESCRIPTION
KeyError

If a component is required, not allowed, or unknown.

Source code in src/quivers/diagnostics/posterior_tables.py
def to_frame(self, component: RowLabel | None = None) -> pd.DataFrame:
    """Return a two-way table, or one component slice, as a DataFrame.

    Parameters
    ----------
    component : str or int or None
        Component of a three-way table; None for a two-way table.

    Returns
    -------
    pandas.DataFrame
        Rows indexed by `rows`, columns named by `columns`.

    Raises
    ------
    KeyError
        If a component is required, not allowed, or unknown.
    """
    if (component is None) != (not self.components):
        raise KeyError("select a component exactly for a three-way table")
    values = self.values
    if component is not None:
        if component not in self.components:
            raise KeyError(f"unknown component {component!r}")
        values = values[..., self.components.index(component)]
    return pd.DataFrame(
        values.cpu().numpy(), index=list(self.rows), columns=list(self.columns)
    )

ELPDEstimate didactic-model

ELPDEstimate(*, criterion: Criterion, elpd: float, se_elpd: float, p: float, se_p: float, pointwise_elpd: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), pointwise_p: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), pareto_k: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), num_samples: int, good_k: float | None = None, responses: tuple[str, ...], response_hash: str, moment_matched: tuple[int, ...] = (), refitted: tuple[int, ...] = (), subsample: tuple[int, ...] = (), subsampling_se: float | None = None, subsampling_se_p: float | None = None, approximation: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), approximation_method: str | None = None, folds: tuple[int, ...] = (), joint: str | None = None)

Bases: ValueModel

One ELPD estimate with pointwise terms, as a brms loo object.

PARAMETER DESCRIPTION
criterion

Estimator that produced the values.

TYPE: ('loo', 'waic', 'kfold', 'loo_subsample') DEFAULT: "loo"

elpd

ELPD estimate and its standard error over observations.

TYPE: float

se_elpd

ELPD estimate and its standard error over observations.

TYPE: float

p

Effective number of parameters and its standard error.

TYPE: float

se_p

Effective number of parameters and its standard error.

TYPE: float

pointwise_elpd

Float64 terms per scored unit. Subsampled estimates hold exact terms on the subsample and NaN elsewhere.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

pointwise_p

Float64 terms per scored unit. Subsampled estimates hold exact terms on the subsample and NaN elsewhere.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

pareto_k

Pareto shape diagnostic per unit for PSIS estimates (NaN where not computed), None for WAIC and k-fold.

TYPE: Tensor or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

num_samples

Pooled posterior draws behind the estimate.

TYPE: int

good_k

Pareto shape threshold, min(1 - 1 / log10(S), 0.7).

TYPE: float or None DEFAULT: None

responses

Scored response names.

TYPE: tuple[str, ...]

response_hash

Hash of the scored responses, checked before comparisons.

TYPE: str

moment_matched

Units whose terms were improved by moment matching.

TYPE: tuple[int, ...] DEFAULT: ()

refitted

Units whose terms come from exact refits.

TYPE: tuple[int, ...] DEFAULT: ()

subsample

Units scored exactly by subsampled PSIS-LOO.

TYPE: tuple[int, ...] DEFAULT: ()

subsampling_se

Standard errors of the ELPD and of p from subsampling alone.

TYPE: float or None DEFAULT: None

subsampling_se_p

Standard errors of the ELPD and of p from subsampling alone.

TYPE: float or None DEFAULT: None

approximation

Approximate pointwise ELPD of every unit for subsampled PSIS-LOO.

TYPE: Tensor or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

approximation_method

"plpd" or "lpd" for subsampled PSIS-LOO.

TYPE: str or None DEFAULT: None

folds

Zero-based fold of every observation for k-fold estimates.

TYPE: tuple[int, ...] DEFAULT: ()

joint

k-fold predictive unit: "obs", "fold" or "group".

TYPE: str or None DEFAULT: None

num_observations property

num_observations: int

Number of scored units.

RETURNS DESCRIPTION
int

Length of the pointwise terms.

ic property

ic: float

Deviance-scale criterion -2 * elpd (looic, waic, kfoldic).

RETURNS DESCRIPTION
float

The information criterion.

se_ic property

se_ic: float

Standard error of the deviance-scale criterion.

RETURNS DESCRIPTION
float

2 * se_elpd.

estimates

estimates() -> SummaryTable

Return the loo package's estimates table.

RETURNS DESCRIPTION
SummaryTable

Rows elpd_<c>, p_<c>, <c>ic and columns Estimate, SE (and subsampling SE for subsampled estimates).

Source code in src/quivers/diagnostics/elpd.py
def estimates(self) -> SummaryTable:
    """Return the loo package's estimates table.

    Returns
    -------
    SummaryTable
        Rows ``elpd_<c>``, ``p_<c>``, ``<c>ic`` and columns
        ``Estimate``, ``SE`` (and ``subsampling SE`` for subsampled
        estimates).
    """
    rows = _LABELS[self.criterion]
    values = [[self.elpd, self.se_elpd], [self.p, self.se_p], [self.ic, self.se_ic]]
    columns: tuple[str, ...] = ("Estimate", "SE")
    if self.criterion == "loo_subsample":
        assert self.subsampling_se is not None
        columns = (*columns, "subsampling SE")
        values[0].append(self.subsampling_se)
        assert self.subsampling_se_p is not None
        values[1].append(self.subsampling_se_p)
        values[2].append(2 * self.subsampling_se)
    return SummaryTable(
        rows=rows,
        columns=columns,
        values=torch.tensor(values, dtype=torch.float64),
    )

bad_observations

bad_observations(threshold: float | None = None) -> tuple[int, ...]

List units whose Pareto shape exceeds a threshold.

PARAMETER DESCRIPTION
threshold

Shape threshold; None uses good_k.

TYPE: float or None DEFAULT: None

RETURNS DESCRIPTION
tuple[int, ...]

Zero-based unit positions, as loo's pareto_k_ids.

RAISES DESCRIPTION
ValueError

If the estimate has no Pareto diagnostics.

Source code in src/quivers/diagnostics/elpd.py
def bad_observations(self, threshold: float | None = None) -> tuple[int, ...]:
    """List units whose Pareto shape exceeds a threshold.

    Parameters
    ----------
    threshold : float or None
        Shape threshold; None uses `good_k`.

    Returns
    -------
    tuple[int, ...]
        Zero-based unit positions, as loo's ``pareto_k_ids``.

    Raises
    ------
    ValueError
        If the estimate has no Pareto diagnostics.
    """
    if self.pareto_k is None:
        raise ValueError(f"{self.criterion} estimates have no Pareto diagnostics")
    limit = self.good_k if threshold is None else threshold
    if limit is None:
        raise ValueError("select a Pareto threshold")
    return tuple(int(i) for i in torch.nonzero(self.pareto_k > limit).flatten())

to_arviz

to_arviz() -> ELPDData

Convert to ArviZ's ELPDData for ArviZ comparisons.

RETURNS DESCRIPTION
ELPDData

The same estimate, pointwise terms and diagnostics.

Source code in src/quivers/diagnostics/elpd.py
def to_arviz(self) -> ELPDData:
    """Convert to ArviZ's ``ELPDData`` for ArviZ comparisons.

    Returns
    -------
    arviz_stats.utils.ELPDData
        The same estimate, pointwise terms and diagnostics.
    """
    pointwise = xr.DataArray(self.pointwise_elpd.cpu().numpy(), dims=("__obs__",))
    pareto = (
        xr.DataArray(self.pareto_k.cpu().numpy(), dims=("__obs__",))
        if self.pareto_k is not None
        else None
    )
    warning = bool(
        self.pareto_k is not None
        and self.good_k is not None
        and bool((self.pareto_k > self.good_k).any())
    )
    fields: dict[str, _ArvizField] = {
        "elpd": self.elpd,
        "se": self.se_elpd,
        "p": self.p,
        "n_samples": self.num_samples,
        "n_data_points": self.num_observations,
        "scale": "log",
        "warning": warning,
        "good_k": self.good_k if self.good_k is not None else 0.7,
        "elpd_i": pointwise,
        "pareto_k": pareto,
    }
    if self.criterion == "loo_subsample":
        assert self.approximation is not None
        fields["subsampling_se"] = self.subsampling_se
        fields["subsample_size"] = len(self.subsample)
        fields["loo_subsample_observations"] = np.asarray(self.subsample)
        fields["elpd_loo_approx"] = xr.DataArray(
            self.approximation.cpu().numpy(), dims=("__obs__",)
        )
    if self.criterion == "kfold":
        fields["n_folds"] = len(set(self.folds)) if self.folds else None
    return _arviz_container(self.criterion, fields)

LooExpectation didactic-model

LooExpectation(*, table: SummaryTable = field(opaque=True, extras=OPAQUE_BY_VALUE), pareto_k: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

PSIS-weighted leave-one-out expectations, as brms loo_predict.

PARAMETER DESCRIPTION
table

One row per unit and one column per statistic (mean, var, sd, median or q<100 p>), with a component axis for vector-valued draws.

TYPE: SummaryTable DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

pareto_k

Function-specific Pareto shape per unit (and component).

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

PSISWeights didactic-model

PSISWeights(*, log_weights: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), pareto_k: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), r_eff: float, good_k: float)

Bases: ValueModel

Pareto smoothed importance weights for leave-one-out, as loo's psis.

PARAMETER DESCRIPTION
log_weights

Float64 normalized smoothed log weights (chain, draw, unit); each unit's weights sum to one.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

pareto_k

Pareto shape diagnostic per unit [@vehtari2024psis].

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

r_eff

Relative efficiency used for the tail length.

TYPE: float

good_k

Threshold min(1 - 1 / log10(S), 0.7) for S pooled draws.

TYPE: float

BridgeRelativeError didactic-model

BridgeRelativeError(*, re2: float, cv: float)

Bases: ValueModel

Approximate error of one "normal" bridge estimate.

PARAMETER DESCRIPTION
re2

Approximate relative mean-squared error of the marginal likelihood estimate, :math:E[(\hat p(y) - p(y))^2] / p(y)^2.

TYPE: float

cv

Coefficient of variation, the square root of re2.

TYPE: float

percentage property

percentage: str

Return the coefficient of variation as a percentage label.

RETURNS DESCRIPTION
str

cv times 100 with a percent sign, as scales::percent.

BridgeRepetitionSpread didactic-model

BridgeRepetitionSpread(*, min: float, max: float, iqr: float)

Bases: ValueModel

Spread of the log marginal likelihood over independent repetitions.

PARAMETER DESCRIPTION
min

Smallest and largest log marginal likelihood.

TYPE: float

max

Smallest and largest log marginal likelihood.

TYPE: float

iqr

Interquartile range (R IQR, quantile type 7).

TYPE: float

BridgeResult didactic-model

BridgeResult(*, logml_repetitions: tuple[float, ...], niter: tuple[int, ...], method: BridgeMethod, neff: float, q11: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), q12: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), q21: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), q22: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_det_warp: float = 0.0, nonfinite_posterior: int = 0, nonfinite_proposal: int = 0)

Bases: ValueModel

A bridge-sampling estimate, as a bridge or bridge_list object.

PARAMETER DESCRIPTION
logml_repetitions

Log marginal likelihood of each independent proposal draw.

TYPE: tuple[float, ...]

niter

Fixed-point iterations of each repetition, counting a restart's iterations after the maxiter of the first scheme.

TYPE: tuple[int, ...]

method

Proposal used.

TYPE: ('normal', 'warp3') DEFAULT: "normal"

neff

Effective sample size of the iteration draws used in s1.

TYPE: float

q11

Log unnormalized posterior at the iteration draws (N1,), warped for "warp3".

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

q12

Log proposal density at the iteration draws (N1,).

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

q21

Log unnormalized posterior at each repetition's proposal draws (R, N2).

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

q22

Log proposal density at each repetition's proposal draws (R, N2).

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

log_det_warp

Log determinant of the warp's Cholesky factor; zero for "normal".

TYPE: float DEFAULT: 0.0

nonfinite_posterior

Iteration draws whose log posterior was -inf or undefined.

TYPE: int DEFAULT: 0

nonfinite_proposal

Proposal draws whose log posterior was -inf or undefined.

TYPE: int DEFAULT: 0

logml property

logml: float

Return the log marginal likelihood (median over repetitions).

RETURNS DESCRIPTION
float

The estimate, as bridgesampling::logml.

repetitions property

repetitions: int

Return the number of independent proposal draws.

RETURNS DESCRIPTION
int

Repetition count.

error_measures

Return the estimator's approximate error, as error_measures.

RETURNS DESCRIPTION
BridgeRelativeError or BridgeRepetitionSpread

The relative mean-squared error of one "normal" estimate [@fruhwirth2004estimating], or the spread of several repetitions.

RAISES DESCRIPTION
ValueError

For one "warp3" repetition, for which the package defines no approximate error; run several repetitions instead.

Notes

With :math:p = q / \hat p(y) the normalized posterior, :math:f_1 = p(\tilde\theta) / (s_1 p(\tilde\theta) + s_2 g(\tilde\theta)) at proposal draws and :math:f_2 = g(\theta) / (s_1 p(\theta) + s_2 g(\theta)) at posterior draws, both with :math:s_i = N_i / (N_1 + N_2),

.. math::

\widehat{RE}^2 = \frac{V(f_1)}{N_2 \bar f_1^2}
+ \frac{\rho_{f_2}(0)}{N_1} \frac{V(f_2)}{\bar f_2^2},

where :math:\rho_{f_2}(0) is the autoregressive spectral density of :math:f_2 at frequency zero (coda spectrum0.ar).

Source code in src/quivers/diagnostics/bridge.py
def error_measures(self) -> BridgeRelativeError | BridgeRepetitionSpread:
    """Return the estimator's approximate error, as ``error_measures``.

    Returns
    -------
    BridgeRelativeError or BridgeRepetitionSpread
        The relative mean-squared error of one ``"normal"`` estimate
        [@fruhwirth2004estimating], or the spread of several repetitions.

    Raises
    ------
    ValueError
        For one ``"warp3"`` repetition, for which the package defines no
        approximate error; run several repetitions instead.

    Notes
    -----
    With :math:`p = q / \\hat p(y)` the normalized posterior,
    :math:`f_1 = p(\\tilde\\theta) / (s_1 p(\\tilde\\theta) + s_2 g(\\tilde\\theta))`
    at proposal draws and
    :math:`f_2 = g(\\theta) / (s_1 p(\\theta) + s_2 g(\\theta))` at
    posterior draws, both with :math:`s_i = N_i / (N_1 + N_2)`,

    .. math::

        \\widehat{RE}^2 = \\frac{V(f_1)}{N_2 \\bar f_1^2}
        + \\frac{\\rho_{f_2}(0)}{N_1} \\frac{V(f_2)}{\\bar f_2^2},

    where :math:`\\rho_{f_2}(0)` is the autoregressive spectral density
    of :math:`f_2` at frequency zero (coda ``spectrum0.ar``).
    """
    if self.repetitions > 1:
        values = np.asarray(self.logml_repetitions, dtype=np.float64)
        q75, q25 = np.quantile(values, [0.75, 0.25])
        return BridgeRepetitionSpread(
            min=float(values.min()), max=float(values.max()), iqr=float(q75 - q25)
        )
    if self.method == "warp3":
        raise ValueError(
            "error_measures is not defined for the warp3 method with one "
            "repetition; run bridge_sampler with repetitions > 1 to assess "
            "the uncertainty of the estimate"
        )
    logml = self.logml_repetitions[0]
    q11 = self.q11.double().numpy()
    q12 = self.q12.double().numpy()
    q21 = self.q21[0].double().numpy()
    q22 = self.q22[0].double().numpy()
    n1, n2 = q11.shape[0], q22.shape[0]
    log_s1 = math.log(n1 / (n1 + n2))
    log_s2 = math.log(n2 / (n1 + n2))
    log_pg = q21 - logml
    log_pp = q11 - logml
    f1 = np.exp(log_pg - np.logaddexp(log_s1 + log_pg, log_s2 + q22))
    f2 = np.exp(q12 - np.logaddexp(log_s1 + log_pp, log_s2 + q12))
    rho = ar_spectrum0(f2)
    term1 = np.var(f1, ddof=1) / np.mean(f1) ** 2 / n2
    term2 = rho / n1 * np.var(f2, ddof=1) / np.mean(f2) ** 2
    re2 = float(term1 + term2)
    return BridgeRelativeError(re2=re2, cv=math.sqrt(re2))

SBCCoverage didactic-model

SBCCoverage(*, mass: float, null_mass: float, lower_rank: int, upper_rank: int, family_error: float, coverage: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), lower: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), upper: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), consistent: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Coverage of the central rank band, per statistic.

A rank in the band [lower_rank, upper_rank] means the true value lies inside the central posterior interval spanned by the corresponding order statistics. Under calibration the probability of that event is exactly null_mass, which differs from the requested mass because ranks are discrete.

ATTRIBUTE DESCRIPTION
mass

The requested central mass.

TYPE: float

null_mass

The band's exact probability under uniform ranks, (upper_rank - lower_rank + 1) / (num_draws + 1).

TYPE: float

lower_rank

The smallest rank in the band.

TYPE: int

upper_rank

The largest rank in the band.

TYPE: int

family_error

The error rate shared by all statistics' intervals; each interval has confidence 1 - family_error / num_statistics.

TYPE: float

coverage

Float64, shape (num_statistics,): the fraction of simulations whose rank lies in the band.

TYPE: Tensor

lower

Float64, shape (num_statistics,): the Clopper-Pearson lower bound of each coverage.

TYPE: Tensor

upper

Float64, shape (num_statistics,): the Clopper-Pearson upper bound of each coverage.

TYPE: Tensor

consistent

Bool, shape (num_statistics,): whether null_mass lies inside each interval.

TYPE: Tensor

SBCResult didactic-model

SBCResult(*, ranks: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), num_draws: int, statistic_names: tuple[str, ...], truths: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), thinning: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), retained: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), seed: int)

Bases: ValueModel

The rank statistics of a simulation-based calibration run.

ATTRIBUTE DESCRIPTION
ranks

Int64, shape (num_simulations, num_statistics): the rank of each true quantity among num_draws posterior draws, in {0, ..., num_draws}, with ties broken uniformly at random.

TYPE: Tensor

num_draws

L, the posterior draws each rank is taken against, after thinning and equalizing across simulations.

TYPE: int

statistic_names

The name of each column of ranks: "site" for a scalar site, "site[i,j]" for one coordinate of an array site, and likewise for a named test quantity.

TYPE: tuple[str, ...]

truths

Float64, shape (num_simulations, num_statistics): the value of each quantity at the parameters drawn from the prior.

TYPE: Tensor

thinning

Int64, shape (num_simulations,): the interval each simulation's chains were thinned by.

TYPE: Tensor

retained

Int64, shape (num_simulations,): the draws each simulation kept after thinning, before all are cut to num_draws.

TYPE: Tensor

seed

The seed that reproduces the run.

TYPE: int

ess

ess(draws: Tensor, *, method: EssMethod = 'bulk', prob: float | None = None) -> Tensor

Effective sample size per event coordinate.

All methods split each chain in half and pool the autocorrelations across chains (Vehtari et al., 2021):

  • "bulk": ESS of the rank-normalized draws, the measure for location summaries such as the mean and median.
  • "tail": the smaller of the "quantile" ESS at prob and 1 - prob (prob defaults to 0.05, giving the 5% and 95% quantiles), the measure for interval endpoints.
  • "mean": ESS of the untransformed draws.
  • "sd": ESS of the squared deviations from the mean.
  • "quantile": ESS of the indicator of falling at or below the prob quantile; prob is required.
PARAMETER DESCRIPTION
draws

Draws laid out (num_chains, num_draws, *event_shape).

TYPE: Tensor

method

Which effective sample size to compute.

TYPE: EssMethod DEFAULT: 'bulk'

prob

The tail probability for "tail" (default 0.05) or the quantile's probability for "quantile" (required). Must be None for the other methods.

TYPE: float or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Float64 tensor of shape event_shape on draws.device. NaN for a coordinate with fewer than four draws per chain, a non-finite draw, or a constant value.

RAISES DESCRIPTION
TypeError

If draws is not a real tensor.

ValueError

If draws has fewer than two axes or no chains or draws, if method is unknown, or if prob is missing, out of (0, 1), or given to a method that takes none.

Source code in src/quivers/diagnostics/convergence.py
def ess(
    draws: torch.Tensor,
    *,
    method: EssMethod = "bulk",
    prob: float | None = None,
) -> torch.Tensor:
    """Effective sample size per event coordinate.

    All methods split each chain in half and pool the autocorrelations
    across chains (Vehtari et al., 2021):

    * ``"bulk"``: ESS of the rank-normalized draws, the measure for
      location summaries such as the mean and median.
    * ``"tail"``: the smaller of the ``"quantile"`` ESS at ``prob``
      and ``1 - prob`` (``prob`` defaults to 0.05, giving the 5% and
      95% quantiles), the measure for interval endpoints.
    * ``"mean"``: ESS of the untransformed draws.
    * ``"sd"``: ESS of the squared deviations from the mean.
    * ``"quantile"``: ESS of the indicator of falling at or below the
      ``prob`` quantile; ``prob`` is required.

    Parameters
    ----------
    draws : torch.Tensor
        Draws laid out ``(num_chains, num_draws, *event_shape)``.
    method : EssMethod
        Which effective sample size to compute.
    prob : float or None
        The tail probability for ``"tail"`` (default 0.05) or the
        quantile's probability for ``"quantile"`` (required). Must be
        ``None`` for the other methods.

    Returns
    -------
    torch.Tensor
        Float64 tensor of shape ``event_shape`` on ``draws.device``.
        NaN for a coordinate with fewer than four draws per chain, a
        non-finite draw, or a constant value.

    Raises
    ------
    TypeError
        If ``draws`` is not a real tensor.
    ValueError
        If ``draws`` has fewer than two axes or no chains or draws, if
        ``method`` is unknown, or if ``prob`` is missing, out of
        ``(0, 1)``, or given to a method that takes none.
    """
    statistic: Callable[[torch.Tensor], float]
    if method == "tail":
        tail_prob = _check_prob(_DEFAULT_TAIL_PROB if prob is None else prob, "prob")
        statistic = partial(_ess_tail, prob=tail_prob)
    elif method == "quantile":
        if prob is None:
            raise ValueError('ess(method="quantile") requires prob')
        statistic = partial(_ess_quantile, prob=_check_prob(prob, "prob"))
    elif method in ("bulk", "mean", "sd"):
        if prob is not None:
            raise ValueError(f'ess(method="{method}") takes no prob')
        statistic = {"bulk": _ess_bulk, "mean": _ess_mean, "sd": _ess_sd}[method]
    else:
        raise ValueError(
            f"unknown ESS method {method!r}; expected one of "
            "'bulk', 'tail', 'mean', 'sd', 'quantile'"
        )
    return _per_coordinate(draws, statistic, min_chains=1)

mcse

mcse(draws: Tensor, *, method: McseMethod = 'mean', prob: float | None = None) -> Tensor

Monte Carlo standard error per event coordinate.

  • "mean": the posterior standard deviation over the square root of the "mean" ESS.
  • "sd": the delta-method error of the standard deviation, from the fourth central moment and the ESS of the squared deviations.
  • "quantile": half the distance between the order statistics at the central one-sd interval of the beta distribution that the quantile's ESS implies for its probability level (Vehtari et al., 2021); prob is required.
PARAMETER DESCRIPTION
draws

Draws laid out (num_chains, num_draws, *event_shape).

TYPE: Tensor

method

Which summary's standard error to compute.

TYPE: McseMethod DEFAULT: 'mean'

prob

The quantile's probability for "quantile" (required). Must be None for the other methods.

TYPE: float or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Float64 tensor of shape event_shape on draws.device. NaN for a coordinate with fewer than four draws per chain, a non-finite draw, or a constant value.

RAISES DESCRIPTION
TypeError

If draws is not a real tensor.

ValueError

If draws has fewer than two axes or no chains or draws, if method is unknown, or if prob is missing, out of (0, 1), or given to a method that takes none.

Source code in src/quivers/diagnostics/convergence.py
def mcse(
    draws: torch.Tensor,
    *,
    method: McseMethod = "mean",
    prob: float | None = None,
) -> torch.Tensor:
    """Monte Carlo standard error per event coordinate.

    * ``"mean"``: the posterior standard deviation over the square
      root of the ``"mean"`` ESS.
    * ``"sd"``: the delta-method error of the standard deviation, from
      the fourth central moment and the ESS of the squared deviations.
    * ``"quantile"``: half the distance between the order statistics
      at the central one-sd interval of the beta distribution that the
      quantile's ESS implies for its probability level (Vehtari et
      al., 2021); ``prob`` is required.

    Parameters
    ----------
    draws : torch.Tensor
        Draws laid out ``(num_chains, num_draws, *event_shape)``.
    method : McseMethod
        Which summary's standard error to compute.
    prob : float or None
        The quantile's probability for ``"quantile"`` (required).
        Must be ``None`` for the other methods.

    Returns
    -------
    torch.Tensor
        Float64 tensor of shape ``event_shape`` on ``draws.device``.
        NaN for a coordinate with fewer than four draws per chain, a
        non-finite draw, or a constant value.

    Raises
    ------
    TypeError
        If ``draws`` is not a real tensor.
    ValueError
        If ``draws`` has fewer than two axes or no chains or draws, if
        ``method`` is unknown, or if ``prob`` is missing, out of
        ``(0, 1)``, or given to a method that takes none.
    """
    statistic: Callable[[torch.Tensor], float]
    if method == "quantile":
        if prob is None:
            raise ValueError('mcse(method="quantile") requires prob')
        statistic = partial(_mcse_quantile, prob=_check_prob(prob, "prob"))
    elif method in ("mean", "sd"):
        if prob is not None:
            raise ValueError(f'mcse(method="{method}") takes no prob')
        statistic = {"mean": _mcse_mean, "sd": _mcse_sd}[method]
    else:
        raise ValueError(
            f"unknown MCSE method {method!r}; expected one of 'mean', 'sd', 'quantile'"
        )
    return _per_coordinate(draws, statistic, min_chains=1)

rhat

rhat(draws: Tensor) -> Tensor

Rank-normalized split :math:\hat R per event coordinate.

Each chain is split in half (the middle draw is dropped when the draw count is odd), the pooled draws are replaced by the normal scores of their average ranks, and the potential scale reduction factor is computed for those scores (the bulk statistic) and for the scores of the absolute deviations from the median (the tail statistic). The reported value is the larger of the two, following Vehtari et al. (2021). Values near 1 are consistent with the chains sampling one distribution; the authors suggest 1.01 as a threshold.

PARAMETER DESCRIPTION
draws

Draws laid out (num_chains, num_draws, *event_shape).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Float64 tensor of shape event_shape on draws.device. NaN for a coordinate with fewer than two chains, fewer than four draws per chain, a non-finite draw, or a constant value. inf when each split chain is constant but the chains differ.

RAISES DESCRIPTION
TypeError

If draws is not a real tensor.

ValueError

If draws has fewer than two axes, or no chains or draws.

Source code in src/quivers/diagnostics/convergence.py
def rhat(draws: torch.Tensor) -> torch.Tensor:
    """Rank-normalized split :math:`\\hat R` per event coordinate.

    Each chain is split in half (the middle draw is dropped when the
    draw count is odd), the pooled draws are replaced by the normal
    scores of their average ranks, and the potential scale reduction
    factor is computed for those scores (the bulk statistic) and for
    the scores of the absolute deviations from the median (the tail
    statistic). The reported value is the larger of the two, following
    Vehtari et al. (2021). Values near 1 are consistent with the chains
    sampling one distribution; the authors suggest 1.01 as a threshold.

    Parameters
    ----------
    draws : torch.Tensor
        Draws laid out ``(num_chains, num_draws, *event_shape)``.

    Returns
    -------
    torch.Tensor
        Float64 tensor of shape ``event_shape`` on ``draws.device``.
        NaN for a coordinate with fewer than two chains, fewer than
        four draws per chain, a non-finite draw, or a constant value.
        ``inf`` when each split chain is constant but the chains
        differ.

    Raises
    ------
    TypeError
        If ``draws`` is not a real tensor.
    ValueError
        If ``draws`` has fewer than two axes, or no chains or draws.
    """
    return _per_coordinate(draws, _rank_rhat, min_chains=2)

summary

summary(samples: Mapping[str, Tensor], *, probs: Sequence[float] = (0.05, 0.5, 0.95)) -> dict[str, ConvergenceSummary]

Posterior summaries and convergence diagnostics for every site.

PARAMETER DESCRIPTION
samples

Per-site draws, each laid out (num_chains, num_draws, *event_shape), such as quivers.inference.MCMCResult.samples.

TYPE: Mapping[str, Tensor]

probs

Probabilities of the quantiles to report, each in (0, 1).

TYPE: Sequence[float] DEFAULT: (0.05, 0.5, 0.95)

RETURNS DESCRIPTION
dict[str, ConvergenceSummary]

One summary per site, in the order of samples.

RAISES DESCRIPTION
TypeError

If a site's draws are not a real tensor.

ValueError

If a site's draws have fewer than two axes or no chains or draws, a probability lies outside (0, 1), or an original integer exceeds exact Float64 capacity.

Source code in src/quivers/diagnostics/convergence.py
def summary(
    samples: Mapping[str, torch.Tensor],
    *,
    probs: Sequence[float] = (0.05, 0.5, 0.95),
) -> dict[str, ConvergenceSummary]:
    """Posterior summaries and convergence diagnostics for every site.

    Parameters
    ----------
    samples : Mapping[str, torch.Tensor]
        Per-site draws, each laid out
        ``(num_chains, num_draws, *event_shape)``, such as
        `quivers.inference.MCMCResult.samples`.
    probs : Sequence[float]
        Probabilities of the quantiles to report, each in ``(0, 1)``.

    Returns
    -------
    dict[str, ConvergenceSummary]
        One summary per site, in the order of ``samples``.

    Raises
    ------
    TypeError
        If a site's draws are not a real tensor.
    ValueError
        If a site's draws have fewer than two axes or no chains or
        draws, a probability lies outside ``(0, 1)``, or an original
        integer exceeds exact Float64 capacity.
    """
    levels = tuple(_check_prob(p, "probs") for p in probs)
    summaries: dict[str, ConvergenceSummary] = {}
    for name, draws in samples.items():
        pooled = _as_chains(draws)
        event_shape = draws.shape[2:]
        mean, sd, quantiles = empirical_summary(
            pooled.reshape(-1, pooled.shape[2]), levels
        )
        mcse_rows = [mcse(draws, method="quantile", prob=p) for p in levels]
        summaries[name] = ConvergenceSummary(
            mean=mean.reshape(event_shape).to(device=draws.device),
            sd=sd.reshape(event_shape).to(device=draws.device),
            probs=levels,
            quantiles=quantiles.reshape(len(levels), *event_shape).to(
                device=draws.device
            ),
            r_hat=rhat(draws),
            ess_bulk=ess(draws, method="bulk"),
            ess_tail=ess(draws, method="tail"),
            mcse_mean=mcse(draws, method="mean"),
            mcse_sd=mcse(draws, method="sd"),
            mcse_quantiles=(
                torch.stack(mcse_rows)
                if mcse_rows
                else torch.empty((0, *event_shape), dtype=torch.float64)
            ).to(device=draws.device),
        )
    return summaries

fold_plan

fold_plan(size: int, *, folds: int = 10, groups: Sequence[FoldLabel] | None = None, strata: Sequence[FoldLabel] | None = None, seed: int = 0) -> FoldPlan

Construct seeded balanced random, grouped, or stratified folds.

PARAMETER DESCRIPTION
size

Number of original included response rows.

TYPE: int

folds

Number of nonempty folds, at most the number of independent groups. Setting this to size gives leave-one-out when groups are absent.

TYPE: int DEFAULT: 10

groups

Indivisible units assigned wholly to one fold.

TYPE: Sequence[str or int] or None DEFAULT: None

strata

Labels balanced across folds. Every indivisible group must have one stratum; small strata need not occur in every fold.

TYPE: Sequence[str or int] or None DEFAULT: None

seed

Local random stream; the caller's RNG is preserved.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
FoldPlan

Original row order and exact assignments for reuse across models.

RAISES DESCRIPTION
ValueError

If counts, labels, or group/stratum combinations are invalid.

Source code in src/quivers/diagnostics/cross_validation.py
def fold_plan(
    size: int,
    *,
    folds: int = 10,
    groups: Sequence[FoldLabel] | None = None,
    strata: Sequence[FoldLabel] | None = None,
    seed: int = 0,
) -> FoldPlan:
    """Construct seeded balanced random, grouped, or stratified folds.

    Parameters
    ----------
    size : int
        Number of original included response rows.
    folds : int
        Number of nonempty folds, at most the number of independent groups.
        Setting this to size gives leave-one-out when groups are absent.
    groups : Sequence[str or int] or None
        Indivisible units assigned wholly to one fold.
    strata : Sequence[str or int] or None
        Labels balanced across folds. Every indivisible group must have one
        stratum; small strata need not occur in every fold.
    seed : int
        Local random stream; the caller's RNG is preserved.

    Returns
    -------
    FoldPlan
        Original row order and exact assignments for reuse across models.

    Raises
    ------
    ValueError
        If counts, labels, or group/stratum combinations are invalid.
    """
    if type(size) is not int or size < 2 or type(folds) is not int or folds < 2:
        raise ValueError("fold construction requires at least two rows and two folds")
    if type(seed) is not int or not 0 <= seed < 2**63:
        raise ValueError("fold seed must lie in [0, 2**63)")
    group_values = (
        tuple(range(size)) if groups is None else _labels(groups, size, "groups")
    )
    stratum_values = (0,) * size if strata is None else _labels(strata, size, "strata")
    units: dict[FoldLabel, list[int]] = {}
    for row, group in enumerate(group_values):
        units.setdefault(group, []).append(row)
    if folds > len(units):
        raise ValueError("fold count exceeds the number of indivisible groups")
    by_stratum: dict[FoldLabel, list[list[int]]] = {}
    for rows in units.values():
        stratum = stratum_values[rows[0]]
        if any(stratum_values[row] != stratum for row in rows):
            raise ValueError("each indivisible group must belong to one stratum")
        by_stratum.setdefault(stratum, []).append(rows)
    generator = torch.Generator().manual_seed(seed)
    totals = [0] * folds
    assignments = [0] * size
    priorities = torch.randperm(folds, generator=generator).tolist()
    global_heap = [(0, priorities[i], i) for i in range(folds)]
    heapq.heapify(global_heap)
    for values in by_stratum.values():
        # Shuffle equal-size units before balancing large groups first.
        order = torch.randperm(len(values), generator=generator).tolist()
        ordered = sorted((values[i] for i in order), key=len, reverse=True)
        if len(ordered) < folds:
            # Every group can occupy a distinct fold in this stratum. Holding
            # selected folds out of the heap avoids O(K) work per small stratum.
            used = []
            for rows in ordered:
                _, priority, fold = heapq.heappop(global_heap)
                totals[fold] += len(rows)
                used.append((totals[fold], priority, fold))
                for row in rows:
                    assignments[row] = fold
            for item in used:
                heapq.heappush(global_heap, item)
        else:
            local_heap = [(0, totals[i], priorities[i], i) for i in range(folds)]
            heapq.heapify(local_heap)
            for rows in ordered:
                count, _, priority, fold = heapq.heappop(local_heap)
                totals[fold] += len(rows)
                heapq.heappush(
                    local_heap, (count + len(rows), totals[fold], priority, fold)
                )
                for row in rows:
                    assignments[row] = fold
            global_heap = [(totals[i], priorities[i], i) for i in range(folds)]
            heapq.heapify(global_heap)
    return FoldPlan(assignments=tuple(assignments), seed=seed)

cross_validate

cross_validate(plan: FoldPlan, refit: Callable[[FoldSplit], FoldPrediction], *, fold_ids: Sequence[int] | None = None, responses: Sequence[str] | None = None, joint: Literal['observation', 'fold', 'group'] = 'observation', groups: Sequence[FoldLabel] | None = None, save_fits: bool = False) -> CrossValidationResult

Refit selected partitions and score held-out units within joint draws.

PARAMETER DESCRIPTION
plan

Explicit reusable partition of original included rows.

TYPE: FoldPlan

refit

Adapter that fits only split.train and scores exactly split.test. It owns preprocessing, prior/basis policy, inference quality, and raw observation semantics; the runner does not fit another model itself.

TYPE: Callable[[FoldSplit], FoldPrediction]

fold_ids

Nonempty unique subset of complete-plan folds, or all folds.

TYPE: Sequence[int] or None DEFAULT: None

responses

Explicit joint response selection; required with multiple scored names.

TYPE: Sequence[str] or None DEFAULT: None

joint

Sum row/response log likelihoods within a draw before log-mean-exp.

TYPE: ('observation', 'fold', 'group') DEFAULT: "observation"

groups

Original row labels for joint group-within-fold prediction units.

TYPE: Sequence[str or int] or None DEFAULT: None

save_fits

Retain actual callback results and their omitted-row metadata in plan.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
CrossValidationResult

Conditional predictive scores from refits, retaining exact row units. Leave-one-out partitions still have the supplied fitter's approximation.

RAISES DESCRIPTION
ValueError

If selections, response shapes, or scores are invalid or inconsistent.

TypeError

If a refitter does not return raw real floating-point likelihoods.

Source code in src/quivers/diagnostics/cross_validation.py
def cross_validate(
    plan: FoldPlan,
    refit: Callable[[FoldSplit], FoldPrediction],
    *,
    fold_ids: Sequence[int] | None = None,
    responses: Sequence[str] | None = None,
    joint: Literal["observation", "fold", "group"] = "observation",
    groups: Sequence[FoldLabel] | None = None,
    save_fits: bool = False,
) -> CrossValidationResult:
    """Refit selected partitions and score held-out units within joint draws.

    Parameters
    ----------
    plan : FoldPlan
        Explicit reusable partition of original included rows.
    refit : Callable[[FoldSplit], FoldPrediction]
        Adapter that fits only split.train and scores exactly split.test.
        It owns preprocessing, prior/basis policy, inference quality, and raw
        observation semantics; the runner does not fit another model itself.
    fold_ids : Sequence[int] or None
        Nonempty unique subset of complete-plan folds, or all folds.
    responses : Sequence[str] or None
        Explicit joint response selection; required with multiple scored names.
    joint : {"observation", "fold", "group"}
        Sum row/response log likelihoods within a draw before log-mean-exp.
    groups : Sequence[str or int] or None
        Original row labels for joint group-within-fold prediction units.
    save_fits : bool
        Retain actual callback results and their omitted-row metadata in plan.

    Returns
    -------
    CrossValidationResult
        Conditional predictive scores from refits, retaining exact row units.
        Leave-one-out partitions still have the supplied fitter's approximation.

    Raises
    ------
    ValueError
        If selections, response shapes, or scores are invalid or inconsistent.
    TypeError
        If a refitter does not return raw real floating-point likelihoods.
    """
    from quivers._rng import seeded_rng

    chosen = tuple(range(plan.num_folds)) if fold_ids is None else tuple(fold_ids)
    if not chosen or len(set(chosen)) != len(chosen):
        raise ValueError("select a nonempty set of unique fold identities")
    count = plan.num_folds
    if any(type(fold) is not int or not 0 <= fold < count for fold in chosen):
        raise ValueError("fold index is outside the complete partition")
    if joint not in {"observation", "fold", "group"} or type(save_fits) is not bool:
        raise ValueError("invalid predictive unit or save_fits policy")
    labels = (
        None
        if groups is None
        else _labels(groups, len(plan.assignments), "score groups")
    )
    if (joint == "group") != (labels is not None):
        raise ValueError("score groups must be supplied exactly when joint='group'")
    selected = None if responses is None else tuple(responses)
    if selected is not None and (
        not selected
        or len(set(selected)) != len(selected)
        or any(not isinstance(name, str) or not name for name in selected)
    ):
        raise ValueError("response selection must contain unique nonempty names")
    values: list[torch.Tensor] = []
    units: list[tuple[int, tuple[int, ...]]] = []
    fits: dict[int, object] = {}
    device: torch.device | None = None
    for fold in chosen:
        split = plan.split(fold)
        with seeded_rng(split.seed):
            prediction = refit(split)
        score, selected = _prediction_scores(prediction, split, selected, device)
        device = score.device
        positions: list[list[int]]
        if joint == "observation":
            positions = [[i] for i in range(len(split.test))]
        elif joint == "fold":
            positions = [list(range(len(split.test)))]
        else:
            assert labels is not None
            buckets: dict[FoldLabel, list[int]] = {}
            for i, original in enumerate(split.test):
                buckets.setdefault(labels[original], []).append(i)
            positions = list(buckets.values())
        # Pool sample axes only after summing each predictive unit within draw.
        per_unit = (
            score
            if joint == "observation"
            else torch.stack([score[..., rows].sum(-1) for rows in positions], -1)
        )
        pooled = per_unit.flatten(0, 1)
        values.append(torch.logsumexp(pooled, 0) - math.log(pooled.shape[0]))
        units.extend(
            (split.fold, tuple(split.test[i] for i in rows)) for rows in positions
        )
        if save_fits:
            if prediction.fit is None:
                raise ValueError(
                    "save_fits requires an actual fitted result from every refitter"
                )
            fits[split.fold] = prediction.fit
        del prediction
    assert selected is not None
    return CrossValidationResult(
        plan=plan,
        fold_ids=chosen,
        responses=selected,
        joint=joint,
        units=tuple(units),
        log_predictive_density=torch.cat(values),
        fits=fits,
    )

to_datatree

to_datatree(posterior: MCMCResult, *, observed_data: Mapping[str, Tensor] | None = None, posterior_predictive: Mapping[str, Tensor] | None = None, log_likelihood: Mapping[str, Tensor] | None = None, constant_data: Mapping[str, Tensor] | None = None, coords: Mapping[str, list] | None = None, dims: Mapping[str, list[str]] | None = None) -> DataTree

Convert an MCMCResult into an ArviZ-style DataTree.

PARAMETER DESCRIPTION
posterior

Sampler output. posterior.samples[name] carries an (num_chains, num_samples, *site_shape) tensor; each becomes a posterior variable. log_densities populates sample_stats/lp, and each per-draw entry of MCMCResult.sample_stats a sample_stats variable under ArviZ's canonical name: diverged as diverging (boolean), tree_depth (integer), num_steps as n_steps (integer), energy, step_size, and accept_prob as acceptance_rate. A composite kernel's component-prefixed entries keep their names.

TYPE: MCMCResult

observed_data

Site name to observed tensor (the original data used at fit time). Becomes the observed_data group.

TYPE: Mapping[str, Tensor] DEFAULT: None

posterior_predictive

Site name to posterior-predictive draws of shape (num_chains, num_samples, *site_shape). Becomes the posterior_predictive group.

TYPE: Mapping[str, Tensor] DEFAULT: None

log_likelihood

Site name to per-observation log-likelihood of shape (num_chains, num_samples, *obs_shape). Becomes the log_likelihood group; required for arviz.loo / arviz.waic.

TYPE: Mapping[str, Tensor] DEFAULT: None

constant_data

Site name to fixed covariate tensor (e.g. design matrix). Becomes the constant_data group.

TYPE: Mapping[str, Tensor] DEFAULT: None

coords

Coordinate values per named axis (e.g. {"Verb": ["eat", "drink", "run"]}). Forwarded to ArviZ.

TYPE: Mapping[str, list] DEFAULT: None

dims

Per-site axis names (e.g. {"beta": ["Verb"]}). Forwarded to ArviZ.

TYPE: Mapping[str, list[str]] DEFAULT: None

RETURNS DESCRIPTION
DataTree

Canonical ArviZ DataTree consumable by every plotting and diagnostic function in the ArviZ 1.x API.

Source code in src/quivers/diagnostics/arviz_io.py
def to_datatree(
    posterior: MCMCResult,
    *,
    observed_data: Mapping[str, torch.Tensor] | None = None,
    posterior_predictive: Mapping[str, torch.Tensor] | None = None,
    log_likelihood: Mapping[str, torch.Tensor] | None = None,
    constant_data: Mapping[str, torch.Tensor] | None = None,
    coords: Mapping[str, list] | None = None,
    dims: Mapping[str, list[str]] | None = None,
) -> xr.DataTree:
    """Convert an `MCMCResult` into an ArviZ-style DataTree.

    Parameters
    ----------
    posterior : MCMCResult
        Sampler output.  ``posterior.samples[name]`` carries an
        ``(num_chains, num_samples, *site_shape)`` tensor; each
        becomes a posterior variable.  ``log_densities`` populates
        ``sample_stats/lp``, and each per-draw entry of
        `MCMCResult.sample_stats` a ``sample_stats`` variable under
        ArviZ's canonical name: ``diverged`` as ``diverging``
        (boolean), ``tree_depth`` (integer), ``num_steps`` as
        ``n_steps`` (integer), ``energy``, ``step_size``, and
        ``accept_prob`` as ``acceptance_rate``. A composite kernel's
        component-prefixed entries keep their names.
    observed_data : Mapping[str, torch.Tensor], optional
        Site name to observed tensor (the original data used at
        fit time).  Becomes the ``observed_data`` group.
    posterior_predictive : Mapping[str, torch.Tensor], optional
        Site name to posterior-predictive draws of shape
        ``(num_chains, num_samples, *site_shape)``.  Becomes the
        ``posterior_predictive`` group.
    log_likelihood : Mapping[str, torch.Tensor], optional
        Site name to per-observation log-likelihood of shape
        ``(num_chains, num_samples, *obs_shape)``.  Becomes the
        ``log_likelihood`` group; required for
        `arviz.loo` / `arviz.waic`.
    constant_data : Mapping[str, torch.Tensor], optional
        Site name to fixed covariate tensor (e.g. design matrix).
        Becomes the ``constant_data`` group.
    coords : Mapping[str, list], optional
        Coordinate values per named axis (e.g.
        ``{"Verb": ["eat", "drink", "run"]}``).  Forwarded to ArviZ.
    dims : Mapping[str, list[str]], optional
        Per-site axis names (e.g. ``{"beta": ["Verb"]}``).
        Forwarded to ArviZ.

    Returns
    -------
    xr.DataTree
        Canonical ArviZ DataTree consumable by every plotting and
        diagnostic function in the ArviZ 1.x API.
    """
    return _groups_to_datatree(
        {
            "posterior": posterior.samples,
            "sample_stats": {
                "lp": posterior.log_densities,
                **posterior.sample_stats,
            },
            "observed_data": observed_data or {},
            "posterior_predictive": posterior_predictive or {},
            "log_likelihood": log_likelihood or {},
            "constant_data": constant_data or {},
        },
        coords=coords,
        dims=dims,
    )

to_datatree_any

to_datatree_any(fit: MCMCResult | Mapping[str, Tensor] | tuple[Mapping[str, Tensor], Tensor], *, observed_data: Mapping[str, Tensor] | None = None, posterior_predictive: Mapping[str, Tensor] | None = None, log_likelihood: Mapping[str, Tensor] | None = None, constant_data: Mapping[str, Tensor] | None = None, coords: Mapping[str, list] | None = None, dims: Mapping[str, list[str]] | None = None) -> DataTree

Dispatch a DataTree conversion on the fit type.

Accepts:

  • an MCMCResult, converted by to_datatree with its chain and draw semantics;
  • a mapping of site name to tensor (SVI or Predictive draws), converted by to_datatree_from_svi with a single pseudo-chain;
  • a tuple (samples, log_densities), converted like the mapping form with sample_stats/lp populated from the second entry.

Consumers with a custom fit-container type can call the specific to_datatree or to_datatree_from_svi entry point directly.

PARAMETER DESCRIPTION
fit

The fit to convert, in one of the forms above.

TYPE: MCMCResult or Mapping[str, Tensor] or tuple

observed_data

Site name to observed tensor; becomes observed_data.

TYPE: Mapping[str, Tensor] DEFAULT: None

posterior_predictive

Site name to posterior-predictive draws; becomes posterior_predictive.

TYPE: Mapping[str, Tensor] DEFAULT: None

log_likelihood

Site name to per-observation log-likelihood; becomes log_likelihood.

TYPE: Mapping[str, Tensor] DEFAULT: None

constant_data

Site name to fixed covariate tensor; becomes constant_data.

TYPE: Mapping[str, Tensor] DEFAULT: None

coords

Coordinate values per named axis, forwarded to ArviZ.

TYPE: Mapping[str, list] DEFAULT: None

dims

Per-site axis names, forwarded to ArviZ.

TYPE: Mapping[str, list[str]] DEFAULT: None

RETURNS DESCRIPTION
DataTree

The ArviZ DataTree of the fit.

RAISES DESCRIPTION
TypeError

If fit is none of the accepted forms.

Source code in src/quivers/diagnostics/arviz_io.py
def to_datatree_any(
    fit: MCMCResult
    | Mapping[str, torch.Tensor]
    | tuple[Mapping[str, torch.Tensor], torch.Tensor],
    *,
    observed_data: Mapping[str, torch.Tensor] | None = None,
    posterior_predictive: Mapping[str, torch.Tensor] | None = None,
    log_likelihood: Mapping[str, torch.Tensor] | None = None,
    constant_data: Mapping[str, torch.Tensor] | None = None,
    coords: Mapping[str, list] | None = None,
    dims: Mapping[str, list[str]] | None = None,
) -> xr.DataTree:
    """Dispatch a DataTree conversion on the fit type.

    Accepts:

    * an [`MCMCResult`][quivers.inference.MCMCResult], converted by
      `to_datatree` with its chain and draw semantics;
    * a mapping of site name to tensor (SVI or Predictive draws),
      converted by `to_datatree_from_svi` with a single pseudo-chain;
    * a tuple ``(samples, log_densities)``, converted like the mapping
      form with ``sample_stats/lp`` populated from the second entry.

    Consumers with a custom fit-container type can call the specific
    `to_datatree` or `to_datatree_from_svi` entry point directly.

    Parameters
    ----------
    fit : MCMCResult or Mapping[str, torch.Tensor] or tuple
        The fit to convert, in one of the forms above.
    observed_data : Mapping[str, torch.Tensor], optional
        Site name to observed tensor; becomes ``observed_data``.
    posterior_predictive : Mapping[str, torch.Tensor], optional
        Site name to posterior-predictive draws; becomes
        ``posterior_predictive``.
    log_likelihood : Mapping[str, torch.Tensor], optional
        Site name to per-observation log-likelihood; becomes
        ``log_likelihood``.
    constant_data : Mapping[str, torch.Tensor], optional
        Site name to fixed covariate tensor; becomes ``constant_data``.
    coords : Mapping[str, list], optional
        Coordinate values per named axis, forwarded to ArviZ.
    dims : Mapping[str, list[str]], optional
        Per-site axis names, forwarded to ArviZ.

    Returns
    -------
    xr.DataTree
        The ArviZ DataTree of the fit.

    Raises
    ------
    TypeError
        If ``fit`` is none of the accepted forms.
    """
    if isinstance(fit, MCMCResult):
        return to_datatree(
            fit,
            observed_data=observed_data,
            posterior_predictive=posterior_predictive,
            log_likelihood=log_likelihood,
            constant_data=constant_data,
            coords=coords,
            dims=dims,
        )
    if isinstance(fit, tuple) and len(fit) == 2:
        samples, log_densities = fit
        return to_datatree_from_svi(
            samples,
            log_densities=log_densities,
            observed_data=observed_data,
            posterior_predictive=posterior_predictive,
            log_likelihood=log_likelihood,
            constant_data=constant_data,
            coords=coords,
            dims=dims,
        )
    if isinstance(fit, Mapping):
        return to_datatree_from_svi(
            fit,
            observed_data=observed_data,
            posterior_predictive=posterior_predictive,
            log_likelihood=log_likelihood,
            constant_data=constant_data,
            coords=coords,
            dims=dims,
        )
    raise TypeError(
        f"to_datatree_any: cannot dispatch on fit type "
        f"{type(fit).__name__}; supported: MCMCResult, "
        "Mapping[str, Tensor] (SVI / Predictive), "
        "tuple[Mapping, Tensor] (samples + log-densities)."
    )

to_datatree_from_sbc

to_datatree_from_sbc(result: SBCResult) -> DataTree

Convert simulation-based calibration ranks for ArviZ's PIT plots.

The ranks go into a prior_sbc group, the group arviz_plots.plot_ecdf_pit reads by default, with one variable per statistic laid out (chain=1, draw=num_simulations). Each rank r in {0, ..., L} is mapped to (r + 1/2) / (L + 1), the midpoint of its cell in an even partition of [0, 1]: under calibration the values are uniform on those midpoints, so their ECDF meets the uniform CDF at every cell boundary, and the mapping is symmetric about one half, as the plot's coverage view assumes.

PARAMETER DESCRIPTION
result

The result of quivers.diagnostics.calibration.

TYPE: SBCResult

RETURNS DESCRIPTION
DataTree

A DataTree with the prior_sbc group.

Source code in src/quivers/diagnostics/arviz_io.py
def to_datatree_from_sbc(result: SBCResult) -> xr.DataTree:
    """Convert simulation-based calibration ranks for ArviZ's PIT plots.

    The ranks go into a ``prior_sbc`` group, the group
    ``arviz_plots.plot_ecdf_pit`` reads by default, with one variable
    per statistic laid out ``(chain=1, draw=num_simulations)``. Each
    rank ``r`` in ``{0, ..., L}`` is mapped to ``(r + 1/2) / (L + 1)``,
    the midpoint of its cell in an even partition of ``[0, 1]``: under
    calibration the values are uniform on those midpoints, so their
    ECDF meets the uniform CDF at every cell boundary, and the mapping
    is symmetric about one half, as the plot's coverage view assumes.

    Parameters
    ----------
    result : SBCResult
        The result of `quivers.diagnostics.calibration`.

    Returns
    -------
    xr.DataTree
        A DataTree with the ``prior_sbc`` group.
    """
    pit = (result.ranks.to(dtype=torch.float64) + 0.5) / (result.num_draws + 1)
    values = _tensor_to_numpy(pit)
    group = {
        name: values[None, :, column]
        for column, name in enumerate(result.statistic_names)
    }
    return az.from_dict({"prior_sbc": group})

to_datatree_from_svi

to_datatree_from_svi(samples: Mapping[str, Tensor], *, log_densities: Tensor | None = None, observed_data: Mapping[str, Tensor] | None = None, posterior_predictive: Mapping[str, Tensor] | None = None, log_likelihood: Mapping[str, Tensor] | None = None, constant_data: Mapping[str, Tensor] | None = None, coords: Mapping[str, list] | None = None, dims: Mapping[str, list[str]] | None = None) -> DataTree

Convert a set of SVI or Predictive draws into an ArviZ-style DataTree with a single pseudo-chain.

Each entry in samples is a (num_samples, *site_shape) tensor (the standard shape produced by Predictive(model, guide, num_samples=...)). A leading chain dimension of size 1 is inserted so the resulting DataTree matches the (chain, draw, *event) shape ArviZ expects. log_densities, when supplied, becomes sample_stats/lp; ArviZ diagnostic functions (loo, waic, plot_trace) work uniformly on the resulting object.

PARAMETER DESCRIPTION
samples

Site name to draws of shape (num_samples, *site_shape); becomes the posterior group.

TYPE: Mapping[str, Tensor]

log_densities

Per-draw log densities; becomes sample_stats/lp.

TYPE: Tensor DEFAULT: None

observed_data

Site name to observed tensor; becomes observed_data.

TYPE: Mapping[str, Tensor] DEFAULT: None

posterior_predictive

Site name to posterior-predictive draws of shape (num_samples, *site_shape); becomes posterior_predictive.

TYPE: Mapping[str, Tensor] DEFAULT: None

log_likelihood

Site name to per-observation log-likelihood of shape (num_samples, *obs_shape); becomes log_likelihood.

TYPE: Mapping[str, Tensor] DEFAULT: None

constant_data

Site name to fixed covariate tensor; becomes constant_data.

TYPE: Mapping[str, Tensor] DEFAULT: None

coords

Coordinate values per named axis, forwarded to ArviZ.

TYPE: Mapping[str, list] DEFAULT: None

dims

Per-site axis names, forwarded to ArviZ.

TYPE: Mapping[str, list[str]] DEFAULT: None

RETURNS DESCRIPTION
DataTree

The ArviZ DataTree, with a chain dimension of size 1.

Source code in src/quivers/diagnostics/arviz_io.py
def to_datatree_from_svi(
    samples: Mapping[str, torch.Tensor],
    *,
    log_densities: torch.Tensor | None = None,
    observed_data: Mapping[str, torch.Tensor] | None = None,
    posterior_predictive: Mapping[str, torch.Tensor] | None = None,
    log_likelihood: Mapping[str, torch.Tensor] | None = None,
    constant_data: Mapping[str, torch.Tensor] | None = None,
    coords: Mapping[str, list] | None = None,
    dims: Mapping[str, list[str]] | None = None,
) -> xr.DataTree:
    """Convert a set of SVI or Predictive draws into an ArviZ-style
    DataTree with a single pseudo-chain.

    Each entry in `samples` is a `(num_samples, *site_shape)` tensor
    (the standard shape produced by `Predictive(model, guide,
    num_samples=...)`). A leading chain dimension of size 1 is
    inserted so the resulting DataTree matches the `(chain, draw,
    *event)` shape ArviZ expects. `log_densities`, when supplied,
    becomes `sample_stats/lp`; ArviZ diagnostic functions (`loo`,
    `waic`, `plot_trace`) work uniformly on the resulting object.

    Parameters
    ----------
    samples : Mapping[str, torch.Tensor]
        Site name to draws of shape ``(num_samples, *site_shape)``;
        becomes the ``posterior`` group.
    log_densities : torch.Tensor, optional
        Per-draw log densities; becomes ``sample_stats/lp``.
    observed_data : Mapping[str, torch.Tensor], optional
        Site name to observed tensor; becomes ``observed_data``.
    posterior_predictive : Mapping[str, torch.Tensor], optional
        Site name to posterior-predictive draws of shape
        ``(num_samples, *site_shape)``; becomes
        ``posterior_predictive``.
    log_likelihood : Mapping[str, torch.Tensor], optional
        Site name to per-observation log-likelihood of shape
        ``(num_samples, *obs_shape)``; becomes ``log_likelihood``.
    constant_data : Mapping[str, torch.Tensor], optional
        Site name to fixed covariate tensor; becomes ``constant_data``.
    coords : Mapping[str, list], optional
        Coordinate values per named axis, forwarded to ArviZ.
    dims : Mapping[str, list[str]], optional
        Per-site axis names, forwarded to ArviZ.

    Returns
    -------
    xr.DataTree
        The ArviZ DataTree, with a chain dimension of size 1.
    """
    # The public SVI adapter accepts draw-first tensors. Promote those axes
    # once; every downstream conversion consumes canonical chain/draw groups.
    posterior_group = {
        name: (value.reshape(1) if value.ndim == 0 else value).unsqueeze(0)
        for name, value in samples.items()
    }
    stats = {}
    if log_densities is not None:
        values = log_densities
        stats["lp"] = (values.reshape(1) if values.ndim == 0 else values).unsqueeze(0)
    return _groups_to_datatree(
        {
            "posterior": posterior_group,
            "sample_stats": stats,
            "observed_data": observed_data or {},
            "posterior_predictive": {
                name: value.unsqueeze(0)
                for name, value in (posterior_predictive or {}).items()
            },
            "log_likelihood": {
                name: value.unsqueeze(0)
                for name, value in (log_likelihood or {}).items()
            },
            "constant_data": constant_data or {},
        },
        coords=coords,
        dims=dims,
    )

waic

waic(log_likelihood: Tensor) -> WAICResult

Estimate WAIC from raw conditional log likelihoods.

PARAMETER DESCRIPTION
log_likelihood

Finite real scores with shape (chain, draw, *observation_shape). Event dimensions must already be reduced. Scores must refer to the same observation units across draws and exclude likelihood weights.

TYPE: Tensor

RETURNS DESCRIPTION
WAICResult

Log-mean-exp predictive scores minus sample log-score variances. The variance convention matches R's loo::waic (divisor S - 1).

RAISES DESCRIPTION
ValueError

If scores are nonfinite, empty, or supply fewer than two pooled draws.

TypeError

If scores are not a real floating-point tensor.

Source code in src/quivers/diagnostics/posterior.py
def waic(log_likelihood: torch.Tensor) -> WAICResult:
    """Estimate WAIC from raw conditional log likelihoods.

    Parameters
    ----------
    log_likelihood : torch.Tensor
        Finite real scores with shape ``(chain, draw, *observation_shape)``.
        Event dimensions must already be reduced. Scores must refer to the
        same observation units across draws and exclude likelihood weights.

    Returns
    -------
    WAICResult
        Log-mean-exp predictive scores minus sample log-score variances.
        The variance convention matches R's loo::waic (divisor S - 1).

    Raises
    ------
    ValueError
        If scores are nonfinite, empty, or supply fewer than two pooled draws.
    TypeError
        If scores are not a real floating-point tensor.
    """
    if (
        not isinstance(log_likelihood, torch.Tensor)
        or not log_likelihood.is_floating_point()
    ):
        raise TypeError("WAIC requires a real floating-point log-likelihood tensor")
    if log_likelihood.ndim < 3 or not all(log_likelihood.shape):
        raise ValueError("WAIC requires nonempty chain, draw, and observation axes")
    values = log_likelihood.detach().to(dtype=torch.float64)
    if not bool(torch.isfinite(values).all()):
        raise ValueError("WAIC requires finite log likelihoods at every posterior draw")
    draws = values.shape[0] * values.shape[1]
    if draws < 2:
        raise ValueError("WAIC requires at least two pooled posterior draws")
    pooled = values.flatten(0, 1)
    variance = pooled.var(dim=0, correction=1)
    elpd = torch.logsumexp(pooled, dim=0) - math.log(draws) - variance
    count = elpd.numel()
    return WAICResult(
        elpd_waic=elpd.sum().item(),
        p_waic=variance.sum().item(),
        waic=-2 * elpd.sum().item(),
        se=(count * elpd.flatten().var(correction=1)).sqrt().item()
        if count > 1
        else math.nan,
        se_p_waic=(count * variance.flatten().var(correction=1)).sqrt().item()
        if count > 1
        else math.nan,
        elpd_i=elpd,
        variance_i=variance,
        warning=bool((variance > 0.4).any()),
        num_samples=draws,
        num_observations=count,
    )

bayesian_r2

bayesian_r2(expected: Tensor, *, observed: Tensor | None = None, residual_variance: Tensor | float | None = None) -> Tensor

Compute a variance ratio for each retained posterior draw and event.

PARAMETER DESCRIPTION
expected

Conditional response means, shaped chain x draw x row x event axes.

TYPE: Tensor

observed

Responses shaped row x event axes. Their centered residual variance supplies the denominator's unexplained component.

TYPE: Tensor or None DEFAULT: None

residual_variance

Conditional response variances broadcastable to expected. Their mean over rows instead supplies the unexplained component. Exactly one of observed and residual_variance is required.

TYPE: Tensor or float or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Float64 ratios on chain, draw, and event axes. A constant prediction has ratio zero when unexplained variance is positive; both components being zero gives NaN because no response variation is defined. Values are detached, as with the other retained-sample diagnostics.

RAISES DESCRIPTION
TypeError

If moments or observations are not real tensors.

ValueError

If axes, finiteness, devices, integer capacity, or variances are invalid.

Notes

Prediction variance uses the unbiased row variance. The residual method uses the same row variance of observed minus predicted values; the model method uses the average conditional variance. A common scale prevents overflow in either variance and cancels from their ratio.

Source code in src/quivers/diagnostics/regression.py
def bayesian_r2(
    expected: torch.Tensor,
    *,
    observed: torch.Tensor | None = None,
    residual_variance: torch.Tensor | float | None = None,
) -> torch.Tensor:
    """Compute a variance ratio for each retained posterior draw and event.

    Parameters
    ----------
    expected : torch.Tensor
        Conditional response means, shaped chain x draw x row x event axes.
    observed : torch.Tensor or None
        Responses shaped row x event axes. Their centered residual variance
        supplies the denominator's unexplained component.
    residual_variance : torch.Tensor or float or None
        Conditional response variances broadcastable to expected. Their mean
        over rows instead supplies the unexplained component. Exactly one
        of observed and residual_variance is required.

    Returns
    -------
    torch.Tensor
        Float64 ratios on chain, draw, and event axes. A constant prediction
        has ratio zero when unexplained variance is positive; both components
        being zero gives NaN because no response variation is defined.
        Values are detached, as with the other retained-sample diagnostics.

    Raises
    ------
    TypeError
        If moments or observations are not real tensors.
    ValueError
        If axes, finiteness, devices, integer capacity, or variances are invalid.

    Notes
    -----
    Prediction variance uses the unbiased row variance. The residual method
    uses the same row variance of observed minus predicted values; the model
    method uses the average conditional variance. A common scale prevents
    overflow in either variance and cancels from their ratio.
    """
    if (observed is None) == (residual_variance is None):
        raise ValueError("provide exactly one of observed and residual_variance")
    means = real_samples(expected, label="R-squared expected responses")
    if means.ndim < 3 or not all(means.shape) or means.shape[2] < 2:
        raise ValueError(
            "R-squared requires chain, draw, and at least two response rows"
        )
    scale = means.abs().amax(2, keepdim=True)
    response = None
    variances = None
    if observed is not None:
        response = real_samples(observed, label="R-squared observed responses")
        if response.shape != means.shape[2:] or response.device != means.device:
            raise ValueError(
                "R-squared responses must match the row/event axes and device"
            )
        scale = torch.maximum(scale, response.abs().amax(0, keepdim=True))
    else:
        assert residual_variance is not None
        raw = (
            residual_variance
            if isinstance(residual_variance, torch.Tensor)
            else torch.tensor(
                residual_variance, device=means.device, dtype=torch.float64
            )
        )
        variances = real_samples(raw, label="R-squared conditional variances")
        if variances.device != means.device or bool((variances < 0).any()):
            raise ValueError(
                "R-squared conditional variances must be nonnegative on the same device"
            )
        try:
            variances = variances.broadcast_to(means.shape)
        except RuntimeError as error:
            raise ValueError(
                "R-squared conditional variances must broadcast to response moments"
            ) from error
        scale = torch.maximum(scale, variances.sqrt().amax(2, keepdim=True))
    scale = torch.where(scale > 0, scale, 1.0)
    normalized = means / scale
    predicted_variance = (normalized - normalized.mean(2, keepdim=True)).square().sum(
        2
    ) / (means.shape[2] - 1)
    if response is not None:
        residuals = response / scale - normalized
        unexplained = (residuals - residuals.mean(2, keepdim=True)).square().sum(2) / (
            means.shape[2] - 1
        )
    else:
        assert variances is not None
        unexplained = (variances.sqrt() / scale).square().mean(2)
    total = predicted_variance + unexplained
    return torch.where(
        total > 0,
        predicted_variance / torch.where(total > 0, total, 1.0),
        torch.nan,
    )

prediction_grid

prediction_grid(axes: Mapping[str, Sequence[GridValue]], *, conditions: Mapping[str, Sequence[GridValue]] | IntoDataFrame, marginalize: bool = False, weights: Sequence[float] | None = None, max_rows: int = 10000) -> PredictionGrid

Cross explicit effect coordinates with bounded conditioning rows.

PARAMETER DESCRIPTION
axes

Nonempty varied predictor values; insertion order defines point order.

TYPE: Mapping[str, Sequence[GridValue]]

conditions

Explicit conditioning rows, or an empirical reference population. Varied columns are replaced at every effect point. Other columns, including groups, offsets, trial counts, and auxiliaries, are retained. A mapping needs only core dependencies; an empty mapping specifies one empty conditioning row. Dataframes use the optional data adapter while retaining their selected backend, without requiring pandas.

TYPE: Mapping[str, Sequence[GridValue]] or IntoDataFrame

marginalize

Average reference-row predictions within each posterior draw. False conditions separately on each supplied row and never averages them.

TYPE: bool DEFAULT: False

weights

Optional finite nonnegative reference-population weights, normalized only for empirical averaging. These are not likelihood weights.

TYPE: Sequence[float] or None DEFAULT: None

max_rows

Positive upper bound on points times reference rows, checked before Cartesian allocation. Larger requests require an explicit larger budget.

TYPE: int DEFAULT: 10000

RETURNS DESCRIPTION
PredictionGrid

Immutable scalar rows and their exact reduction/layout contract.

RAISES DESCRIPTION
(ValueError, TypeError)

If names, values, weights, dimensions, or allocation budgets are invalid.

Source code in src/quivers/diagnostics/conditional.py
def prediction_grid(
    axes: Mapping[str, Sequence[GridValue]],
    *,
    conditions: Mapping[str, Sequence[GridValue]] | IntoDataFrame,
    marginalize: bool = False,
    weights: Sequence[float] | None = None,
    max_rows: int = 10000,
) -> PredictionGrid:
    """Cross explicit effect coordinates with bounded conditioning rows.

    Parameters
    ----------
    axes : Mapping[str, Sequence[GridValue]]
        Nonempty varied predictor values; insertion order defines point order.
    conditions : Mapping[str, Sequence[GridValue]] or IntoDataFrame
        Explicit conditioning rows, or an empirical reference population.
        Varied columns are replaced at every effect point. Other columns,
        including groups, offsets, trial counts, and auxiliaries, are retained.
        A mapping needs only core dependencies; an empty mapping specifies
        one empty conditioning row. Dataframes use the optional data adapter
        while retaining their selected backend, without requiring pandas.
    marginalize : bool
        Average reference-row predictions within each posterior draw. False
        conditions separately on each supplied row and never averages them.
    weights : Sequence[float] or None
        Optional finite nonnegative reference-population weights, normalized
        only for empirical averaging. These are not likelihood weights.
    max_rows : int
        Positive upper bound on points times reference rows, checked before
        Cartesian allocation. Larger requests require an explicit larger budget.

    Returns
    -------
    PredictionGrid
        Immutable scalar rows and their exact reduction/layout contract.

    Raises
    ------
    ValueError, TypeError
        If names, values, weights, dimensions, or allocation budgets are invalid.
    """
    if isinstance(max_rows, bool) or not isinstance(max_rows, int) or max_rows < 1:
        raise ValueError("max_rows must be a positive integer")
    if not isinstance(marginalize, bool):
        raise TypeError("marginalize must be a bool")
    if not axes or any(not isinstance(name, str) or not name for name in axes):
        raise ValueError("grid axes require nonempty predictor names")
    if any(isinstance(values, (str, bytes)) for values in axes.values()):
        raise TypeError("each grid axis requires a sequence of scalar values")
    sizes = tuple(len(values) for values in axes.values())
    if any(size < 1 for size in sizes):
        raise ValueError("each grid axis requires at least one value")
    if isinstance(conditions, Mapping):
        if any(isinstance(values, (str, bytes)) for values in conditions.values()):
            raise TypeError("conditioning columns require sequences of scalar values")
        condition_columns = tuple(conditions)
        counts = {len(values) for values in conditions.values()}
        if len(counts) > 1:
            raise ValueError("conditioning columns must have equal row counts")
        num_conditions = next(iter(counts), 1)
        frame = None
    else:
        import narwhals as nw

        frame = nw.from_native(conditions, eager_only=True)
        condition_columns = tuple(frame.columns)
        num_conditions = len(frame)
    if num_conditions < 1 or len(set(condition_columns)) != len(condition_columns):
        raise ValueError("conditions require nonempty rows and unique column names")
    count = math.prod(sizes) * num_conditions
    if count > max_rows:
        raise ValueError(
            f"prediction grid requires {count} rows, exceeding max_rows={max_rows}"
        )

    def scalar(value: object, *, allow_missing: bool = False) -> GridValue:
        """Retain a checked scalar coordinate without inventing an encoding.

        Parameters
        ----------
        value : object
            Native scalar from an explicit axis or reference frame.
        allow_missing : bool
            Retain a missing reference coordinate as None; the fitted input
            contract decides whether it can denote a new grouping identity.

        Returns
        -------
        GridValue
            Python scalar, preserving integer and Boolean carriers.

        Raises
        ------
        TypeError, ValueError
            If the coordinate is structured, unsupported, or nonfinite.
        """
        if value is None or isinstance(value, (str, bool)):
            return value
        if isinstance(value, Integral):
            return int(value)
        if isinstance(value, Real):
            numeric = float(value)
            if allow_missing and math.isnan(numeric):
                return None
            if math.isfinite(numeric):
                return numeric
        raise ValueError(
            "grid coordinates must be finite scalar numbers, strings, bools, or None"
        )

    names = tuple(axes)
    columns = condition_columns + tuple(
        name for name in names if name not in condition_columns
    )
    if any(not isinstance(name, str) or not name for name in columns):
        raise ValueError("condition columns require nonempty string names")
    normalized = ()
    if weights is not None and not marginalize:
        raise ValueError("reference weights require empirical marginalization")
    if marginalize:
        supplied = tuple(weights) if weights is not None else (1.0,) * num_conditions
        if (
            len(supplied) != num_conditions
            or any(
                isinstance(w, bool)
                or not isinstance(w, (int, float))
                or not math.isfinite(w)
                or w < 0
                for w in supplied
            )
            or sum(supplied) <= 0
        ):
            raise ValueError(
                "reference weights require one finite nonnegative value per row and positive total"
            )
        scale = max(supplied)
        total = sum(w / scale for w in supplied)
        normalized = tuple((w / scale) / total for w in supplied)
    points = tuple(
        product(*(tuple(scalar(v) for v in values) for values in axes.values()))
    )
    if isinstance(conditions, Mapping):
        raw_rows = zip(*(conditions[name] for name in condition_columns), strict=True)
    else:
        assert frame is not None
        import narwhals as nw

        # Backend-native null masks avoid importing pandas or numpy to
        # recognize extension scalars such as pd.NA.
        raw_rows = (
            tuple(
                None if missing else value
                for value, missing in zip(row, mask, strict=True)
            )
            for row, mask in zip(
                frame.rows(), frame.select(nw.all().is_null()).rows(), strict=True
            )
        )
    reference = (
        tuple(
            tuple(
                None if name in axes else scalar(v, allow_missing=True)
                for name, v in zip(condition_columns, row, strict=True)
            )
            for row in raw_rows
        )
        if condition_columns
        else ((),) * num_conditions
    )
    rows = []
    for point in points:
        replacements = dict(zip(names, point, strict=True))
        for row in reference:
            base = dict(zip(condition_columns, row, strict=True))
            base.update(replacements)
            rows.append(tuple(base[name] for name in columns))
    return PredictionGrid(
        columns=columns,
        rows=tuple(rows),
        axes=names,
        points=points,
        num_conditions=num_conditions,
        marginalize=marginalize,
        weights=normalized,
    )

log_density_ordinate

log_density_ordinate(samples: Tensor, *, at: float | int | Tensor = 0.0, bandwidth: str | float | Tensor = 'nrd0', adjust: float = 1.0, name: str = 'contrast', dims: Sequence[str] | None = None, coords: Mapping[str, Sequence[object]] | None = None, max_working_elements: int = 262144) -> DensityOrdinate

Estimate one marginal Gaussian log density per retained event coordinate.

PARAMETER DESCRIPTION
samples

Finite floating draws shaped (chain, draw, *event). At least two pooled draws and nonzero spread on every coordinate are required.

TYPE: Tensor

at

Finite evaluation point, broadcasting only over event axes.

TYPE: float, int, or torch.Tensor DEFAULT: 0.0

bandwidth

nrd0 selects 0.9 * min(SD, IQR/1.34) * N**(-1/5), falling back to SD when IQR is zero. scott selects SD * N**(-1/5). A positive scalar or event tensor selects an absolute bandwidth.

TYPE: str, float, or torch.Tensor DEFAULT: 'nrd0'

adjust

Positive finite multiplier applied to the selected bandwidth.

TYPE: float DEFAULT: 1.0

name

Original contrast name, retained without parsing.

TYPE: str DEFAULT: 'contrast'

dims

Event dimension names using the retained-analysis coordinate policy.

TYPE: Sequence[str] or None DEFAULT: None

coords

Original labels of event dimensions.

TYPE: Mapping[str, Sequence[object]] or None DEFAULT: None

max_working_elements

Positive integer bound on temporary kernel tiles, including both sample and event-coordinate tiling. Automatic bandwidth reduction uses the shared input-sized summary workspace; nrd0 also sorts for quartiles.

TYPE: int DEFAULT: 262144

RETURNS DESCRIPTION
DensityOrdinate

Detached Float64 marginal log density, bandwidth, sample counts, and local kernel-weight concentration on the original device. This is a smoothing estimate, not a jointly multivariate density or evidence claim.

RAISES DESCRIPTION
(TypeError, ValueError)

If samples are integer/Boolean, nonfinite, empty, constant, or too few; metadata or settings disagree; or log-score capacity is exceeded.

Notes

The direct Gaussian sum has no FFT interpolation or negative-density clipping. Finite-sample KDE error depends on bandwidth, tails, dependence, and coordinate choice. Floating storage does not establish a continuous underlying law. No inference, density gradient, or convergence diagnostic is computed.

Source code in src/quivers/diagnostics/density.py
def log_density_ordinate(
    samples: torch.Tensor,
    *,
    at: float | int | torch.Tensor = 0.0,
    bandwidth: str | float | torch.Tensor = "nrd0",
    adjust: float = 1.0,
    name: str = "contrast",
    dims: Sequence[str] | None = None,
    coords: Mapping[str, Sequence[object]] | None = None,
    max_working_elements: int = 262144,
) -> DensityOrdinate:
    """Estimate one marginal Gaussian log density per retained event coordinate.

    Parameters
    ----------
    samples : torch.Tensor
        Finite floating draws shaped ``(chain, draw, *event)``. At least two
        pooled draws and nonzero spread on every coordinate are required.
    at : float, int, or torch.Tensor
        Finite evaluation point, broadcasting only over event axes.
    bandwidth : str, float, or torch.Tensor
        ``nrd0`` selects ``0.9 * min(SD, IQR/1.34) * N**(-1/5)``, falling back
        to SD when IQR is zero. ``scott`` selects ``SD * N**(-1/5)``.
        A positive scalar or event tensor selects an absolute bandwidth.
    adjust : float
        Positive finite multiplier applied to the selected bandwidth.
    name : str
        Original contrast name, retained without parsing.
    dims : Sequence[str] or None
        Event dimension names using the retained-analysis coordinate policy.
    coords : Mapping[str, Sequence[object]] or None
        Original labels of event dimensions.
    max_working_elements : int
        Positive integer bound on temporary kernel tiles, including both sample
        and event-coordinate tiling. Automatic bandwidth reduction uses the
        shared input-sized summary workspace; nrd0 also sorts for quartiles.

    Returns
    -------
    DensityOrdinate
        Detached Float64 marginal log density, bandwidth, sample counts, and
        local kernel-weight concentration on the original device. This is a
        smoothing estimate, not a jointly multivariate density or evidence claim.

    Raises
    ------
    TypeError, ValueError
        If samples are integer/Boolean, nonfinite, empty, constant, or too few;
        metadata or settings disagree; or log-score capacity is exceeded.

    Notes
    -----
    The direct Gaussian sum has no FFT interpolation or negative-density clipping.
    Finite-sample KDE error depends on bandwidth, tails, dependence, and coordinate
    choice. Floating storage does not establish a continuous underlying law.
    No inference, density gradient, or convergence diagnostic is computed.
    """
    values = _draws(samples)
    multiplier = _settings(adjust, max_working_elements)
    return _ordinate(
        values,
        tuple(samples.shape[:2]),
        at=at,
        bandwidth=bandwidth,
        adjust=multiplier,
        name=name,
        dims=dims,
        coords=coords,
        budget=max_working_elements,
    )[0]

density_ratio

density_ratio(posterior: Tensor, prior: Tensor, *, null: float | int | Tensor = 0.0, bandwidth: str | float | Tensor = 'nrd0', prior_bandwidth: str | float | Tensor | None = None, adjust: float = 1.0, assumptions: PointNullAssumptions | None = None, name: str = 'contrast', dims: Sequence[str] | None = None, coords: Mapping[str, Sequence[object]] | None = None, max_working_elements: int = 262144) -> DensityRatio

Compare posterior and joint-prior ordinates at the same scalar contrast null.

PARAMETER DESCRIPTION
posterior

Finite floating contrast draws with aligned event shapes and devices. Chain and draw counts may differ. Form derived prior contrasts jointly, preserving hierarchical dependence; draws are never permuted here.

TYPE: Tensor

prior

Finite floating contrast draws with aligned event shapes and devices. Chain and draw counts may differ. Form derived prior contrasts jointly, preserving hierarchical dependence; draws are never permuted here.

TYPE: Tensor

null

Finite scalar or event-shaped evaluation point.

TYPE: float, int, or torch.Tensor DEFAULT: 0.0

bandwidth

Posterior bandwidth rule or positive absolute value.

TYPE: str, float, or torch.Tensor DEFAULT: 'nrd0'

prior_bandwidth

Prior bandwidth; None applies the same policy separately to each input. Automatic rules use each distribution's own count and scale.

TYPE: str, float, torch.Tensor, or None DEFAULT: None

adjust

Positive multiplier applied to both selected bandwidths.

TYPE: float DEFAULT: 1.0

assumptions

Explicit declarations enabling a point-null BF01 interpretation when both are true. These declarations cannot be verified from sample arrays.

TYPE: PointNullAssumptions or None DEFAULT: None

name

Original derived-contrast label.

TYPE: str DEFAULT: 'contrast'

dims

Shared event dimensions and original labels.

TYPE: Sequence or Mapping or None DEFAULT: None

coords

Shared event dimensions and original labels.

TYPE: Sequence or Mapping or None DEFAULT: None

max_working_elements

Positive kernel-tile element bound, as for log_density_ordinate.

TYPE: int DEFAULT: 262144

RETURNS DESCRIPTION
DensityRatio

Posterior/prior log density ratio and separate declaration-dependent BF01 field. It never supplies a posterior null-model probability.

RAISES DESCRIPTION
(TypeError, ValueError)

If alignment, domains, samples, settings, or declarations are invalid. Known integer or Boolean laws and constant samples are refused.

Notes

Under the declared proper continuous prior and compatible null nuisance prior, posterior density divided by prior density gives the Savage-Dickey point-null BF01. KDE only approximates those densities. An atom at the null, a singular contrast, or incompatible nuisance prior invalidates this argument; an empirical equality frequency or region odds cannot replace an ordinate.

Source code in src/quivers/diagnostics/density.py
def density_ratio(
    posterior: torch.Tensor,
    prior: torch.Tensor,
    *,
    null: float | int | torch.Tensor = 0.0,
    bandwidth: str | float | torch.Tensor = "nrd0",
    prior_bandwidth: str | float | torch.Tensor | None = None,
    adjust: float = 1.0,
    assumptions: PointNullAssumptions | None = None,
    name: str = "contrast",
    dims: Sequence[str] | None = None,
    coords: Mapping[str, Sequence[object]] | None = None,
    max_working_elements: int = 262144,
) -> DensityRatio:
    """Compare posterior and joint-prior ordinates at the same scalar contrast null.

    Parameters
    ----------
    posterior, prior : torch.Tensor
        Finite floating contrast draws with aligned event shapes and devices.
        Chain and draw counts may differ. Form derived prior contrasts jointly,
        preserving hierarchical dependence; draws are never permuted here.
    null : float, int, or torch.Tensor
        Finite scalar or event-shaped evaluation point.
    bandwidth : str, float, or torch.Tensor
        Posterior bandwidth rule or positive absolute value.
    prior_bandwidth : str, float, torch.Tensor, or None
        Prior bandwidth; None applies the same policy separately to each input.
        Automatic rules use each distribution's own count and scale.
    adjust : float
        Positive multiplier applied to both selected bandwidths.
    assumptions : PointNullAssumptions or None
        Explicit declarations enabling a point-null BF01 interpretation when
        both are true. These declarations cannot be verified from sample arrays.
    name : str
        Original derived-contrast label.
    dims, coords : Sequence or Mapping or None
        Shared event dimensions and original labels.
    max_working_elements : int
        Positive kernel-tile element bound, as for log_density_ordinate.

    Returns
    -------
    DensityRatio
        Posterior/prior log density ratio and separate declaration-dependent
        BF01 field. It never supplies a posterior null-model probability.

    Raises
    ------
    TypeError, ValueError
        If alignment, domains, samples, settings, or declarations are invalid.
        Known integer or Boolean laws and constant samples are refused.

    Notes
    -----
    Under the declared proper continuous prior and compatible null nuisance
    prior, posterior density divided by prior density gives the Savage-Dickey
    point-null BF01. KDE only approximates those densities. An atom at the null,
    a singular contrast, or incompatible nuisance prior invalidates this argument;
    an empirical equality frequency or region odds cannot replace an ordinate.
    """
    post_values, prior_values = _draws(posterior), _draws(prior)
    if post_values.shape[1:] != prior_values.shape[1:]:
        raise ValueError("posterior and prior require the same event shape")
    if post_values.device != prior_values.device:
        raise ValueError("posterior and prior must use the same device")
    if assumptions is not None and not isinstance(assumptions, PointNullAssumptions):
        raise TypeError("assumptions must be PointNullAssumptions or None")
    multiplier = _settings(adjust, max_working_elements)
    post, post_terms = _ordinate(
        post_values,
        tuple(posterior.shape[:2]),
        at=null,
        bandwidth=bandwidth,
        adjust=multiplier,
        name=name,
        dims=dims,
        coords=coords,
        budget=max_working_elements,
    )
    baseline, prior_terms = _ordinate(
        prior_values,
        tuple(prior.shape[:2]),
        at=null,
        bandwidth=bandwidth if prior_bandwidth is None else prior_bandwidth,
        adjust=multiplier,
        name=name,
        dims=dims,
        coords=coords,
        budget=max_working_elements,
    )
    smaller = post.log_bandwidth <= baseline.log_bandwidth
    small_reference = torch.where(smaller, post_terms[0], prior_terms[0])
    large_reference = torch.where(smaller, prior_terms[0], post_terms[0])
    small_width = torch.minimum(post.log_bandwidth, baseline.log_bandwidth)
    large_width = torch.maximum(post.log_bandwidth, baseline.log_bandwidth)
    quadratic = _quadratic_difference(
        post.at, small_reference, large_reference, small_width, large_width
    )
    base_difference = torch.where(smaller, -0.5 * quadratic, 0.5 * quadratic)
    ratio = base_difference + (post_terms[1] - prior_terms[1])
    ratio = ratio + (baseline.log_bandwidth - post.log_bandwidth)
    if not bool(torch.isfinite(ratio).all()):
        raise ValueError("KDE log density ratio exceeds Float64 capacity")
    enabled = (
        assumptions is not None
        and assumptions.proper_continuous_prior
        and assumptions.compatible_null_prior
    )
    return DensityRatio(
        posterior=post,
        prior=baseline,
        log_ratio=ratio,
        assumptions=assumptions,
        log_bayes_factor_01=ratio if enabled else None,
    )

hypothesis_summary

hypothesis_summary(contrast: Tensor, *, null: float | int | Tensor = 0.0, probs: Sequence[float] = (0.025, 0.975), prior: Tensor | None = None, robust: bool = False, point: PointNullSpec | None = None, name: str = 'contrast', kind: Literal['mcmc', 'variational', 'prior', 'unspecified'] = 'unspecified', dims: Sequence[str] | None = None, coords: Mapping[str, Sequence[object]] | None = None) -> HypothesisSummary

Summarize a retained contrast and evidence for each strict null region.

PARAMETER DESCRIPTION
contrast

Finite real draws shaped (chain, draw, *event_shape). Construct any derived contrast jointly within each retained draw before calling.

TYPE: Tensor

null

Finite null value, scalar or broadcastable over event axes only.

TYPE: float, int, or torch.Tensor DEFAULT: 0.0

probs

Quantile probabilities strictly between zero and one, in requested order.

TYPE: Sequence[float] DEFAULT: (0.025, 0.975)

prior

Joint prior contrast draws with the same event shape and device. Its chain and draw counts may differ. No permutation or inference is run.

TYPE: Tensor or None DEFAULT: None

robust

Return median and MAD divided by the standard-normal 0.75 quantile instead of mean and sample SD. Quantiles do not depend on this flag.

TYPE: bool DEFAULT: False

point

Explicit marginal point-density request. Requires finite continuous floating posterior and prior draws; the two strict regions are unchanged.

TYPE: PointNullSpec or None DEFAULT: None

name

Nonempty contrast name, retained without parsing.

TYPE: str DEFAULT: 'contrast'

kind

Explicit provenance of the supplied contrast draws.

TYPE: ('mcmc', 'variational', 'prior', 'unspecified') DEFAULT: "mcmc"

dims

Named event axes, using the shared retained-analysis coordinate policy.

TYPE: Sequence[str] or None DEFAULT: None

coords

Labels for event, chain, or draw axes; labels retain their original values.

TYPE: Mapping[str, Sequence[object]] or None DEFAULT: None

RETURNS DESCRIPTION
HypothesisSummary

Detached Float64 summaries on the original device. Equality frequencies are descriptive. Optional point_evidence retains the shared density estimator's bandwidths and assumption declarations, without inferring posterior model probabilities. Single-draw SD is NaN; constant SD is zero.

RAISES DESCRIPTION
(ValueError, TypeError)

If axes, alignment, domains, numeric capacity, or metadata disagree. Missing values are refused without deletion. Dispersion overflow is refused; values below Float64 resolution may underflow to zero.

Notes

A region Bayes factor compares a common proper encompassing prior restricted and renormalized to that region and its complement, under the same likelihood. Supplied prior draws must represent that prior jointly. A zero empirical prior region frequency makes this estimate undefined (NaN), even though the true prior might assign positive mass. No pseudocounts are added. A posterior zero frequency may instead produce infinite empirical log evidence; finite draws do not establish an exact population probability of zero.

Source code in src/quivers/diagnostics/hypothesis.py
def hypothesis_summary(
    contrast: torch.Tensor,
    *,
    null: float | int | torch.Tensor = 0.0,
    probs: Sequence[float] = (0.025, 0.975),
    prior: torch.Tensor | None = None,
    robust: bool = False,
    point: PointNullSpec | None = None,
    name: str = "contrast",
    kind: Literal["mcmc", "variational", "prior", "unspecified"] = "unspecified",
    dims: Sequence[str] | None = None,
    coords: Mapping[str, Sequence[object]] | None = None,
) -> HypothesisSummary:
    """Summarize a retained contrast and evidence for each strict null region.

    Parameters
    ----------
    contrast : torch.Tensor
        Finite real draws shaped ``(chain, draw, *event_shape)``. Construct any
        derived contrast jointly within each retained draw before calling.
    null : float, int, or torch.Tensor
        Finite null value, scalar or broadcastable over event axes only.
    probs : Sequence[float]
        Quantile probabilities strictly between zero and one, in requested order.
    prior : torch.Tensor or None
        Joint prior contrast draws with the same event shape and device. Its
        chain and draw counts may differ. No permutation or inference is run.
    robust : bool
        Return median and MAD divided by the standard-normal 0.75 quantile
        instead of mean and sample SD. Quantiles do not depend on this flag.
    point : PointNullSpec or None
        Explicit marginal point-density request. Requires finite continuous
        floating posterior and prior draws; the two strict regions are unchanged.
    name : str
        Nonempty contrast name, retained without parsing.
    kind : {"mcmc", "variational", "prior", "unspecified"}
        Explicit provenance of the supplied contrast draws.
    dims : Sequence[str] or None
        Named event axes, using the shared retained-analysis coordinate policy.
    coords : Mapping[str, Sequence[object]] or None
        Labels for event, chain, or draw axes; labels retain their original values.

    Returns
    -------
    HypothesisSummary
        Detached Float64 summaries on the original device. Equality frequencies
        are descriptive. Optional point_evidence retains the shared density
        estimator's bandwidths and assumption declarations, without inferring
        posterior model probabilities. Single-draw SD is NaN; constant SD is zero.

    Raises
    ------
    ValueError, TypeError
        If axes, alignment, domains, numeric capacity, or metadata disagree.
        Missing values are refused without deletion. Dispersion overflow is refused;
        values below Float64 resolution may underflow to zero.

    Notes
    -----
    A region Bayes factor compares a common proper encompassing prior restricted
    and renormalized to that region and its complement, under the same likelihood.
    Supplied prior draws must represent that prior jointly. A zero empirical
    prior region frequency makes this estimate undefined (NaN), even though the
    true prior might assign positive mass. No pseudocounts are added. A posterior
    zero frequency may instead produce infinite empirical log evidence; finite
    draws do not establish an exact population probability of zero.
    """
    if point is not None and not isinstance(point, PointNullSpec):
        raise TypeError("point must be PointNullSpec or None")
    if point is not None and prior is None:
        raise ValueError("point-density evidence requires joint prior draws")
    values = _contrasts(contrast, "contrast")
    levels = probabilities(probs)
    if not isinstance(robust, bool):
        raise TypeError("robust must be Boolean")
    if not isinstance(name, str) or not name:
        raise ValueError("contrast name must be a nonempty string")
    if kind not in {"mcmc", "variational", "prior", "unspecified"}:
        raise ValueError("contrast kind must identify its draw provenance")
    cutoff = _null_value(null, values)
    prior_values = None
    if prior is not None:
        prior_values = _contrasts(prior, "prior contrast")
        if prior_values.device != values.device:
            raise ValueError("prior and posterior contrasts must use the same device")
        if prior_values.shape[1:] != values.shape[1:]:
            raise ValueError(
                "prior and posterior contrasts require the same event shape"
            )
    dimension_names = event_dimensions(
        {name: values.shape[1:]},
        dims={name: dims} if dims is not None else None,
        coords=coords,
    )[name]
    estimate, dispersion, quantiles = empirical_summary(values, levels, robust=robust)
    if bool(torch.isinf(dispersion).any()):
        raise ValueError("contrast dispersion exceeds Float64 capacity")
    return HypothesisSummary(
        estimate=estimate,
        est_error=dispersion,
        probs=levels,
        quantiles=quantiles,
        null=cutoff,
        below=_region(
            values < cutoff, prior_values < cutoff if prior_values is not None else None
        ),
        above=_region(
            values > cutoff, prior_values > cutoff if prior_values is not None else None
        ),
        equal_probability=(values == cutoff).to(torch.float64).mean(0),
        prior_equal_probability=(prior_values == cutoff).to(torch.float64).mean(0)
        if prior_values is not None
        else None,
        name=name,
        dimension_names=dimension_names,
        coordinate_labels=tuple(
            axis_labels(dimension, extent, coords)
            for dimension, extent in zip(dimension_names, values.shape[1:], strict=True)
        ),
        sample_shape=tuple(contrast.shape[:2]),
        prior_sample_shape=tuple(prior.shape[:2]) if prior is not None else None,
        chain_labels=axis_labels("chain", contrast.shape[0], coords),
        draw_labels=axis_labels("draw", contrast.shape[1], coords),
        robust=robust,
        kind=kind,
        point_evidence=(
            density_ratio(
                contrast,
                prior,
                null=null,
                bandwidth=point.bandwidth,
                prior_bandwidth=point.prior_bandwidth,
                adjust=point.adjust,
                assumptions=point.assumptions,
                name=name,
                dims=dimension_names,
                coords=coords,
                max_working_elements=point.max_working_elements,
            )
            if point is not None and prior is not None
            else None
        ),
    )

compare

compare(fits: Mapping[str, DataTree | PosteriorAnalysis], *, method: Literal['stacking', 'BB-pseudo-BMA', 'pseudo-BMA'] = 'stacking', var_name: str | None = None, reference: str | None = None, round_to: int | Literal['auto', 'none', 'None'] | None = 'auto') -> object

Rank candidate models by expected log predictive density.

Delegates to ArviZ, which computes PSIS-LOO on each fit's log-likelihood group and combines the results into a ranked comparison table.

PARAMETER DESCRIPTION
fits

Per-model retained analyses or DataTrees. Each supplies raw observation log likelihoods. Retained analyses are checked for matching response values and observation units before their PSIS-LOO estimates are ranked. Variational analyses use relative efficiency one.

TYPE: Mapping[str, DataTree or PosteriorAnalysis]

method

Model-weight estimator. Default "stacking" follows Yao, Vehtari, Simpson, and Gelman (2018) Yao et al. (2018).

TYPE: "stacking", "BB-pseudo-BMA", or "pseudo-BMA" DEFAULT: 'stacking'

var_name

Observed variable in the log-likelihood group; required when a fit carries multiple log-likelihood variables.

TYPE: str DEFAULT: None

reference

Fit name used as the reference for ELPD differences. Default is the top-ranked model.

TYPE: str DEFAULT: None

round_to

ArviZ rounding policy. Default "auto" retains display rounding. An integer specifies decimal places, while "none" or "None" preserves full numeric precision. None uses ArviZ's configured default.

TYPE: int, "auto", "none", "None", or None DEFAULT: 'auto'

RETURNS DESCRIPTION
DataFrame

ArviZ ranking table with one row per model.

Source code in src/quivers/diagnostics/comparison.py
def compare(
    fits: Mapping[str, xr.DataTree | PosteriorAnalysis],
    *,
    method: Literal["stacking", "BB-pseudo-BMA", "pseudo-BMA"] = "stacking",
    var_name: str | None = None,
    reference: str | None = None,
    round_to: int | Literal["auto", "none", "None"] | None = "auto",
) -> object:
    """Rank candidate models by expected log predictive density.

    Delegates to ArviZ, which computes PSIS-LOO on each fit's
    log-likelihood group and combines the results into a ranked
    comparison table.

    Parameters
    ----------
    fits : Mapping[str, xr.DataTree or PosteriorAnalysis]
        Per-model retained analyses or DataTrees. Each supplies raw observation
        log likelihoods. Retained analyses are checked for matching response
        values and observation units before their PSIS-LOO estimates are ranked.
        Variational analyses use relative efficiency one.
    method : "stacking", "BB-pseudo-BMA", or "pseudo-BMA"
        Model-weight estimator. Default "stacking" follows Yao,
        Vehtari, Simpson, and Gelman (2018) [Yao et al. (2018)](<https://doi.org/10.1214/17-BA1091>).
    var_name : str, optional
        Observed variable in the log-likelihood group; required
        when a fit carries multiple log-likelihood variables.
    reference : str, optional
        Fit name used as the reference for ELPD differences.
        Default is the top-ranked model.
    round_to : int, "auto", "none", "None", or None, optional
        ArviZ rounding policy. Default "auto" retains display
        rounding. An integer specifies decimal places, while
        "none" or "None" preserves full numeric precision. None
        uses ArviZ's configured default.

    Returns
    -------
    pandas.DataFrame
        ArviZ ranking table with one row per model.
    """
    analyses = [fit for fit in fits.values() if isinstance(fit, PosteriorAnalysis)]
    if analyses:
        # Matching response values catch accidental comparison of different
        # datasets; callers still choose a common predictive unit/design.
        selected = [fit._likelihood_name(var_name) for fit in analyses]
        reference_analysis, reference_name = analyses[0], selected[0]
        reference_scores = reference_analysis.log_likelihood[reference_name]
        for fit, name in zip(analyses[1:], selected[1:]):
            if fit.log_likelihood[name].shape[2:] != reference_scores.shape[2:]:
                raise ValueError("model comparisons require matching observation units")
            reference_data = reference_analysis.observed_data.get(reference_name)
            values = fit.observed_data.get(name)
            if reference_data is None or values is None:
                raise ValueError("model comparisons require observed response data")
            if not torch.equal(reference_data, values):
                raise ValueError(
                    "model comparisons require the same observed responses"
                )
    prepared = {
        name: fit.loo(var_name=var_name, pointwise=True)
        if isinstance(fit, PosteriorAnalysis)
        else fit
        for name, fit in fits.items()
    }
    return az.compare(
        prepared,
        method=method,
        var_name=var_name,
        reference=reference,
        round_to=round_to,
    )

loo

loo(fit: DataTree, *, pointwise: bool | None = None, var_name: str | None = None) -> object

Estimate expected log predictive density with PSIS-LOO.

This thin wrapper delegates all computation to ArviZ. It preserves ArviZ's canonical log scale and, with pointwise=True, returns its per-observation elpd_i and pareto_k arrays unchanged, including nonfinite Pareto estimates. PSIS follows Vehtari, Simpson, Gelman, Yao, and Gabry (2024) Vehtari et al. (2024); its use for leave-one-out evaluation follows Vehtari, Gelman, and Gabry (2017) Vehtari et al. (2017).

PARAMETER DESCRIPTION
fit

Fit containing posterior and log-likelihood groups.

TYPE: DataTree

pointwise

Whether to include one elpd_i and pareto_k value per observation. None uses ArviZ's configured default.

TYPE: bool DEFAULT: None

var_name

Log-likelihood variable to evaluate. Required when the log-likelihood group contains multiple variables.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION
ELPDData

ArviZ's canonical PSIS-LOO result.

Source code in src/quivers/diagnostics/comparison.py
def loo(
    fit: xr.DataTree,
    *,
    pointwise: bool | None = None,
    var_name: str | None = None,
) -> object:
    """Estimate expected log predictive density with PSIS-LOO.

    This thin wrapper delegates all computation to ArviZ. It
    preserves ArviZ's canonical log scale and, with pointwise=True,
    returns its per-observation elpd_i and pareto_k arrays unchanged,
    including nonfinite Pareto estimates. PSIS follows Vehtari, Simpson,
    Gelman, Yao, and Gabry (2024) [Vehtari et al. (2024)](<https://www.jmlr.org/papers/v25/19-556.html>); its use for
    leave-one-out evaluation follows Vehtari, Gelman, and Gabry (2017)
    [Vehtari et al. (2017)](<https://link.springer.com/article/10.1007/s11222-016-9696-4>).

    Parameters
    ----------
    fit : xr.DataTree
        Fit containing posterior and log-likelihood groups.
    pointwise : bool, optional
        Whether to include one elpd_i and pareto_k value per
        observation. None uses ArviZ's configured default.
    var_name : str, optional
        Log-likelihood variable to evaluate. Required when the
        log-likelihood group contains multiple variables.

    Returns
    -------
    arviz.ELPDData
        ArviZ's canonical PSIS-LOO result.
    """
    _require_log_likelihood_variable(fit, var_name)
    return az.loo(fit, pointwise=pointwise, var_name=var_name)

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)

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),
    }

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)

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

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}
    )

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)

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_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_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_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_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)

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_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

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_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)

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

posterior_interval

posterior_interval(draws: Mapping[str, Tensor] | Tensor, *, prob: float = 0.95, labels: Sequence[RowLabel] | None = None) -> SummaryTable

Compute central posterior intervals, as brms posterior_interval.

PARAMETER DESCRIPTION
draws

Named variables (chain, draw, *event) or positional draws (chain, draw, row).

TYPE: Mapping[str, Tensor] or Tensor

prob

Central probability mass, 0.95 by default as in brms.

TYPE: float DEFAULT: 0.95

labels

Row labels of a positional tensor.

TYPE: Sequence[str or int] or None DEFAULT: None

RETURNS DESCRIPTION
SummaryTable

Columns 2.5% and 97.5% for the default mass.

Source code in src/quivers/diagnostics/posterior_tables.py
def posterior_interval(
    draws: Mapping[str, torch.Tensor] | torch.Tensor,
    *,
    prob: float = 0.95,
    labels: Sequence[RowLabel] | None = None,
) -> SummaryTable:
    """Compute central posterior intervals, as brms ``posterior_interval``.

    Parameters
    ----------
    draws : Mapping[str, torch.Tensor] or torch.Tensor
        Named variables ``(chain, draw, *event)`` or positional draws
        ``(chain, draw, row)``.
    prob : float
        Central probability mass, 0.95 by default as in brms.
    labels : Sequence[str or int] or None
        Row labels of a positional tensor.

    Returns
    -------
    SummaryTable
        Columns ``2.5%`` and ``97.5%`` for the default mass.
    """
    return _interval(draws, prob, labels, "posterior_interval")

posterior_summary

posterior_summary(draws: Mapping[str, Tensor] | Tensor, *, probs: Sequence[float] = (0.025, 0.975), robust: bool = False, labels: Sequence[RowLabel] | None = None, components: Sequence[RowLabel] | None = None) -> SummaryTable

Summarize draws with brms's posterior_summary layout.

PARAMETER DESCRIPTION
draws

Named variables (chain, draw, *event), or positional draws (chain, draw, row) or (chain, draw, row, component).

TYPE: Mapping[str, Tensor] or Tensor

probs

Quantile probabilities strictly between zero and one.

TYPE: Sequence[float] DEFAULT: (0.025, 0.975)

robust

Report the median and R's mad instead of the mean and SD.

TYPE: bool DEFAULT: False

labels

Row labels of a positional tensor; 0-based positions by default.

TYPE: Sequence[str or int] or None DEFAULT: None

components

Labels of a positional tensor's component axis; 0-based by default.

TYPE: Sequence[str or int] or None DEFAULT: None

RETURNS DESCRIPTION
SummaryTable

Columns Estimate, Est.Error and Q<100 p>. A four-axis tensor gives brms's N x E x C array with a component axis.

RAISES DESCRIPTION
ValueError

If probabilities, labels, or draw axes are invalid.

TypeError

If draws are not real tensors.

Notes

Cost is O(S M log S) for S pooled draws and M summarized coordinates.

Source code in src/quivers/diagnostics/posterior_tables.py
def posterior_summary(
    draws: Mapping[str, torch.Tensor] | torch.Tensor,
    *,
    probs: Sequence[float] = (0.025, 0.975),
    robust: bool = False,
    labels: Sequence[RowLabel] | None = None,
    components: Sequence[RowLabel] | None = None,
) -> SummaryTable:
    """Summarize draws with brms's ``posterior_summary`` layout.

    Parameters
    ----------
    draws : Mapping[str, torch.Tensor] or torch.Tensor
        Named variables ``(chain, draw, *event)``, or positional draws
        ``(chain, draw, row)`` or ``(chain, draw, row, component)``.
    probs : Sequence[float]
        Quantile probabilities strictly between zero and one.
    robust : bool
        Report the median and R's ``mad`` instead of the mean and SD.
    labels : Sequence[str or int] or None
        Row labels of a positional tensor; 0-based positions by default.
    components : Sequence[str or int] or None
        Labels of a positional tensor's component axis; 0-based by default.

    Returns
    -------
    SummaryTable
        Columns ``Estimate``, ``Est.Error`` and ``Q<100 p>``. A four-axis
        tensor gives brms's ``N x E x C`` array with a component axis.

    Raises
    ------
    ValueError
        If probabilities, labels, or draw axes are invalid.
    TypeError
        If draws are not real tensors.

    Notes
    -----
    Cost is O(S M log S) for S pooled draws and M summarized coordinates.
    """
    levels = probabilities(probs)
    if type(robust) is not bool:
        raise TypeError("robust must be Boolean")
    rows, pooled = _matrix(draws, labels, "posterior_summary")
    statistics = _statistics(pooled, levels, robust).transpose(0, 1)
    columns = ("Estimate", "Est.Error", *(f"Q{_percent(100 * p)}" for p in levels))
    if pooled.ndim == 3:
        names = (
            tuple(range(pooled.shape[2])) if components is None else tuple(components)
        )
        if len(names) != pooled.shape[2]:
            raise ValueError("posterior_summary requires one label per component")
        return SummaryTable(
            rows=rows, columns=columns, components=names, values=statistics
        )
    if components is not None:
        raise ValueError("component labels require a component axis")
    return SummaryTable(rows=rows, columns=columns, values=statistics)

posterior_table

posterior_table(draws: Tensor, *, levels: Sequence[float | int | str] | None = None, labels: Sequence[RowLabel] | None = None) -> SummaryTable

Tabulate relative frequencies of discrete draws, as brms posterior_table.

PARAMETER DESCRIPTION
draws

Discrete draws (chain, draw, row), such as ordinal predictions.

TYPE: Tensor

levels

Possible values in column order; None uses every distinct non-missing value in ascending order. A string sequence labels the columns of integer codes 0..K-1.

TYPE: Sequence or None DEFAULT: None

labels

Row labels; 0-based positions by default.

TYPE: Sequence[str or int] or None DEFAULT: None

RETURNS DESCRIPTION
SummaryTable

Columns P(Y = <level>) holding each row's frequencies among its non-missing draws.

RAISES DESCRIPTION
ValueError

If draws contain a value outside the given levels.

Source code in src/quivers/diagnostics/posterior_tables.py
def posterior_table(
    draws: torch.Tensor,
    *,
    levels: Sequence[float | int | str] | None = None,
    labels: Sequence[RowLabel] | None = None,
) -> SummaryTable:
    """Tabulate relative frequencies of discrete draws, as brms ``posterior_table``.

    Parameters
    ----------
    draws : torch.Tensor
        Discrete draws ``(chain, draw, row)``, such as ordinal predictions.
    levels : Sequence or None
        Possible values in column order; None uses every distinct non-missing
        value in ascending order. A string sequence labels the columns of
        integer codes ``0..K-1``.
    labels : Sequence[str or int] or None
        Row labels; 0-based positions by default.

    Returns
    -------
    SummaryTable
        Columns ``P(Y = <level>)`` holding each row's frequencies among its
        non-missing draws.

    Raises
    ------
    ValueError
        If draws contain a value outside the given levels.
    """
    rows, pooled = _matrix(draws, labels, "posterior_table")
    if pooled.ndim != 2:
        raise ValueError("posterior_table requires one value per row and draw")
    present = ~torch.isnan(pooled)
    if levels is None:
        values = torch.unique(pooled[present]).tolist()
        names = [
            _percent(v) if not float(v).is_integer() else str(int(v)) for v in values
        ]
    else:
        given = tuple(levels)
        if all(isinstance(level, str) for level in given):
            values = [float(code) for code in range(len(given))]
            names = [str(level) for level in given]
        else:
            values = [float(level) for level in given]
            names = [
                _percent(float(v)) if not float(v).is_integer() else str(int(v))
                for v in given
            ]
    counts = torch.stack([(pooled == value).sum(0) for value in values], dim=1)
    total = present.sum(0)
    if bool((counts.sum(1) != total).any()):
        raise ValueError("posterior_table draws contain values outside the levels")
    return SummaryTable(
        rows=rows,
        columns=tuple(f"P(Y = {name})" for name in names),
        values=counts.to(torch.float64) / total.unsqueeze(1),
    )

predictive_interval

predictive_interval(draws: Tensor, *, prob: float = 0.9, labels: Sequence[RowLabel] | None = None) -> SummaryTable

Compute central predictive intervals, as brms predictive_interval.

PARAMETER DESCRIPTION
draws

Predictive draws (chain, draw, row).

TYPE: Tensor

prob

Central probability mass, 0.9 by default as in brms.

TYPE: float DEFAULT: 0.9

labels

Row labels; 0-based positions by default.

TYPE: Sequence[str or int] or None DEFAULT: None

RETURNS DESCRIPTION
SummaryTable

Columns 5% and 95% for the default mass.

Source code in src/quivers/diagnostics/posterior_tables.py
def predictive_interval(
    draws: torch.Tensor,
    *,
    prob: float = 0.9,
    labels: Sequence[RowLabel] | None = None,
) -> SummaryTable:
    """Compute central predictive intervals, as brms ``predictive_interval``.

    Parameters
    ----------
    draws : torch.Tensor
        Predictive draws ``(chain, draw, row)``.
    prob : float
        Central probability mass, 0.9 by default as in brms.
    labels : Sequence[str or int] or None
        Row labels; 0-based positions by default.

    Returns
    -------
    SummaryTable
        Columns ``5%`` and ``95%`` for the default mass.
    """
    return _interval(draws, prob, labels, "predictive_interval")

ar_spectrum0

ar_spectrum0(series: ndarray) -> float

Return the AR spectral density at frequency zero, as coda spectrum0.ar.

PARAMETER DESCRIPTION
series

One real series of length at least two.

TYPE: ndarray

RETURNS DESCRIPTION
float

var.pred / (1 - sum(ar))^2 of the Yule-Walker autoregression whose order minimizes the AIC (R ar(x, aic = TRUE)), or zero when the residuals of a linear trend have zero standard deviation.

RAISES DESCRIPTION
ValueError

If the series is not finite or has fewer than two values.

Notes

The autocovariances are the biased (divisor n) estimates of R acf; the Levinson-Durbin recursion gives the innovation variances of orders zero to min(n - 1, floor(10 log10 n)). Cost is O(n p + p^2) for order bound p.

Source code in src/quivers/diagnostics/bridge.py
def ar_spectrum0(series: np.ndarray) -> float:
    """Return the AR spectral density at frequency zero, as coda ``spectrum0.ar``.

    Parameters
    ----------
    series : numpy.ndarray
        One real series of length at least two.

    Returns
    -------
    float
        ``var.pred / (1 - sum(ar))^2`` of the Yule-Walker autoregression whose
        order minimizes the AIC (R ``ar(x, aic = TRUE)``), or zero when the
        residuals of a linear trend have zero standard deviation.

    Raises
    ------
    ValueError
        If the series is not finite or has fewer than two values.

    Notes
    -----
    The autocovariances are the biased (divisor ``n``) estimates of R
    ``acf``; the Levinson-Durbin recursion gives the innovation variances
    of orders zero to ``min(n - 1, floor(10 log10 n))``. Cost is
    O(n p + p^2) for order bound p.
    """
    x = np.asarray(series, dtype=np.float64).reshape(-1)
    n = x.shape[0]
    if n < 2 or not np.isfinite(x).all():
        raise ValueError("spectrum0.ar requires at least two finite values")
    time = np.arange(1, n + 1, dtype=np.float64)
    design = np.column_stack([np.ones(n), time])
    coefficients, *_ = np.linalg.lstsq(design, x, rcond=None)
    residuals = x - design @ coefficients
    if np.std(residuals, ddof=1) <= _ALL_EQUAL:
        return 0.0
    order_max = min(n - 1, math.floor(10.0 * math.log10(n)))
    centered = x - x.mean()
    acov = np.array(
        [np.dot(centered[: n - k], centered[k:]) / n for k in range(order_max + 1)]
    )
    if acov[0] == 0.0:
        raise ValueError("spectrum0.ar requires a series with nonzero variance")
    variances = [acov[0]]
    phi = np.zeros(0)
    fits = [phi]
    for k in range(1, order_max + 1):
        reflection = (acov[k] - np.dot(phi, acov[k - 1 : 0 : -1])) / variances[-1]
        phi = np.concatenate([phi - reflection * phi[::-1], [reflection]])
        fits.append(phi)
        variances.append(variances[-1] * (1.0 - reflection**2))
    aic = n * np.log(np.asarray(variances)) + 2.0 * np.arange(order_max + 1) + 2.0
    order = int(np.argmin(aic))
    var_pred = variances[order] * n / (n - (order + 1))
    return float(var_pred / (1.0 - fits[order].sum()) ** 2)

bayes_factor_from_logml

bayes_factor_from_logml(logml1: float, logml2: float, *, log: bool = False) -> float

Return the Bayes factor of model 1 over model 2.

PARAMETER DESCRIPTION
logml1

Log marginal likelihoods.

TYPE: float

logml2

Log marginal likelihoods.

TYPE: float

log

Return the log Bayes factor.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
float

:math:p(y \mid M_1) / p(y \mid M_2) [@kass1995bayes], or its log.

Source code in src/quivers/diagnostics/bridge.py
def bayes_factor_from_logml(
    logml1: float, logml2: float, *, log: bool = False
) -> float:
    """Return the Bayes factor of model 1 over model 2.

    Parameters
    ----------
    logml1, logml2 : float
        Log marginal likelihoods.
    log : bool
        Return the log Bayes factor.

    Returns
    -------
    float
        :math:`p(y \\mid M_1) / p(y \\mid M_2)` [@kass1995bayes], or its log.
    """
    difference = logml1 - logml2
    return difference if log else math.exp(difference)

bridge_sampler

bridge_sampler(log_posterior: Callable[[ndarray], ndarray], chains: ndarray, *, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> BridgeResult

Estimate a log marginal likelihood from unconstrained posterior chains.

PARAMETER DESCRIPTION
log_posterior

Log unnormalized posterior density on the unconstrained scale, including every normalizing constant of the prior and likelihood and the log Jacobian of the constraining transforms, evaluated row-wise at (N, D) points.

TYPE: Callable[[ndarray], ndarray]

chains

Unconstrained posterior draws (chain, draw, D).

TYPE: ndarray

method

Proposal: a normal with the moments of the fitting half, or the standard normal after the warp-3 transformation.

TYPE: ('normal', 'warp3') DEFAULT: "normal"

repetitions

Independent proposal draws, each giving one estimate.

TYPE: int DEFAULT: 1

use_neff

Use the median coda effective size of the iteration draws in s1; otherwise their count.

TYPE: bool DEFAULT: True

maxiter

Iteration bound of the fixed-point scheme.

TYPE: int DEFAULT: 1000

seed

Seed of the proposal draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
BridgeResult

Estimates, iteration counts, and the retained log densities.

RAISES DESCRIPTION
ValueError

If the draws, method, or settings are invalid, a parameter is constant across draws, or the log posterior is undefined at every proposal draw.

RuntimeError

If the scheme does not converge.

Notes

Cost is N1 + R N2 log-posterior evaluations for "normal" and twice that for "warp3", plus O(N D^2 + D^3) for the proposal and O(N D p) for the effective sizes with autoregression order p.

Source code in src/quivers/diagnostics/bridge.py
def bridge_sampler(
    log_posterior: Callable[[np.ndarray], np.ndarray],
    chains: np.ndarray,
    *,
    method: BridgeMethod = "normal",
    repetitions: int = 1,
    use_neff: bool = True,
    maxiter: int = 1000,
    seed: int = 0,
) -> BridgeResult:
    """Estimate a log marginal likelihood from unconstrained posterior chains.

    Parameters
    ----------
    log_posterior : Callable[[numpy.ndarray], numpy.ndarray]
        Log unnormalized posterior density on the unconstrained scale,
        including every normalizing constant of the prior and likelihood and
        the log Jacobian of the constraining transforms, evaluated row-wise
        at ``(N, D)`` points.
    chains : numpy.ndarray
        Unconstrained posterior draws ``(chain, draw, D)``.
    method : {"normal", "warp3"}
        Proposal: a normal with the moments of the fitting half, or the
        standard normal after the warp-3 transformation.
    repetitions : int
        Independent proposal draws, each giving one estimate.
    use_neff : bool
        Use the median coda effective size of the iteration draws in
        ``s1``; otherwise their count.
    maxiter : int
        Iteration bound of the fixed-point scheme.
    seed : int
        Seed of the proposal draws.

    Returns
    -------
    BridgeResult
        Estimates, iteration counts, and the retained log densities.

    Raises
    ------
    ValueError
        If the draws, method, or settings are invalid, a parameter is constant
        across draws, or the log posterior is undefined at every proposal draw.
    RuntimeError
        If the scheme does not converge.

    Notes
    -----
    Cost is ``N1 + R N2`` log-posterior evaluations for ``"normal"`` and
    twice that for ``"warp3"``, plus O(N D^2 + D^3) for the proposal and
    O(N D p) for the effective sizes with autoregression order p.
    """
    if method not in ("normal", "warp3"):
        raise ValueError("bridge_sampler method must be 'normal' or 'warp3'")
    if (
        isinstance(repetitions, bool)
        or not isinstance(repetitions, int)
        or repetitions < 1
    ):
        raise ValueError("repetitions must be a positive integer")
    if isinstance(maxiter, bool) or not isinstance(maxiter, int) or maxiter < 1:
        raise ValueError("maxiter must be a positive integer")
    draws = np.asarray(chains, dtype=np.float64)
    if draws.ndim != 3 or draws.shape[2] < 1 or not np.isfinite(draws).all():
        raise ValueError(
            "bridge sampling requires finite unconstrained draws (chain, draw, D)"
        )
    count = draws.shape[1]
    split = round(count / 2)
    if split < 2 or count - split < 2:
        raise ValueError("bridge sampling requires at least four draws per chain")
    fit_draws = draws[:, :split].reshape(-1, draws.shape[2])
    iteration_chains = draws[:, split:]
    iteration = iteration_chains.reshape(-1, draws.shape[2])
    if np.any(np.ptp(fit_draws, axis=0) == 0.0):
        raise ValueError(
            "bridge sampling requires every unconstrained parameter to vary "
            "across the posterior draws"
        )
    n_post = iteration.shape[0]
    neff = (
        float(np.median(effective_size(list(iteration_chains))))
        if use_neff
        else float(n_post)
    )
    mean = fit_draws.mean(axis=0)
    covariance = near_pd(np.atleast_2d(np.cov(fit_draws, rowvar=False)))
    chol = np.linalg.cholesky(covariance)
    dim = mean.shape[0]
    generator = torch.Generator().manual_seed(seed)
    standard = [
        torch.randn(n_post, dim, generator=generator, dtype=torch.float64).numpy()
        for _ in range(repetitions)
    ]

    def evaluate(points: np.ndarray) -> np.ndarray:
        """Evaluate the log posterior, mapping undefined values to ``-inf``.

        Parameters
        ----------
        points : numpy.ndarray
            Unconstrained points ``(N, D)``.

        Returns
        -------
        numpy.ndarray
            Log densities ``(N,)``.
        """
        values = np.asarray(log_posterior(points), dtype=np.float64).reshape(-1)
        if values.shape[0] != points.shape[0]:
            raise ValueError("log_posterior must return one value per row")
        return np.where(np.isnan(values), -np.inf, values)

    identity = np.eye(dim)
    zero = np.zeros(dim)
    if method == "normal":
        q12 = _mvn_logpdf(iteration, mean, chol)
        q11 = evaluate(iteration)
        proposals = [mean + z @ chol.T for z in standard]
        q22 = [_mvn_logpdf(p, mean, chol) for p in proposals]
        q21 = [evaluate(p) for p in proposals]
        log_det = 0.0
    else:
        q12 = _mvn_logpdf(np.linalg.solve(chol, (iteration - mean).T).T, zero, identity)
        q11 = np.logaddexp(evaluate(iteration), evaluate(2.0 * mean - iteration))
        q22 = [_mvn_logpdf(z, zero, identity) for z in standard]
        q21 = [
            np.logaddexp(evaluate(mean - z @ chol.T), evaluate(mean + z @ chol.T))
            for z in standard
        ]
        log_det = float(np.log(np.diag(chol)).sum())
    if any(np.all(~np.isfinite(q)) for q in q21):
        raise ValueError(
            "the log posterior is undefined or -inf at every proposal draw"
        )
    offset = -math.log(2.0) + log_det if method == "warp3" else 0.0
    l1 = offset + (q11 - q12)
    estimates: list[float] = []
    iterations: list[int] = []
    for q21_i, q22_i in zip(q21, q22, strict=True):
        logml, niter = _solve(l1, offset + (q21_i - q22_i), neff=neff, maxiter=maxiter)
        estimates.append(logml)
        iterations.append(niter)
    return BridgeResult(
        logml_repetitions=tuple(estimates),
        niter=tuple(iterations),
        method=method,
        neff=neff,
        q11=torch.from_numpy(q11),
        q12=torch.from_numpy(q12),
        q21=torch.from_numpy(np.stack(q21)),
        q22=torch.from_numpy(np.stack(q22)),
        log_det_warp=log_det,
        nonfinite_posterior=int((~np.isfinite(q11)).sum()),
        nonfinite_proposal=int(sum((~np.isfinite(q)).sum() for q in q21)),
    )

effective_size

effective_size(chains: Sequence[ndarray]) -> ndarray

Return coda effectiveSize of an mcmc.list.

PARAMETER DESCRIPTION
chains

One (draws, parameters) array per chain.

TYPE: Sequence[ndarray]

RETURNS DESCRIPTION
ndarray

Per-parameter effective sizes summed over chains, each chain contributing n var(x) / spectrum0.ar(x) (zero for a constant).

Source code in src/quivers/diagnostics/bridge.py
def effective_size(chains: Sequence[np.ndarray]) -> np.ndarray:
    """Return coda ``effectiveSize`` of an ``mcmc.list``.

    Parameters
    ----------
    chains : Sequence[numpy.ndarray]
        One ``(draws, parameters)`` array per chain.

    Returns
    -------
    numpy.ndarray
        Per-parameter effective sizes summed over chains, each chain
        contributing ``n var(x) / spectrum0.ar(x)`` (zero for a constant).
    """
    total = np.zeros(chains[0].shape[1], dtype=np.float64)
    for chain in chains:
        n = chain.shape[0]
        for column in range(chain.shape[1]):
            spec = ar_spectrum0(chain[:, column])
            if spec != 0.0:
                total[column] += n * np.var(chain[:, column], ddof=1) / spec
    return total

near_pd

near_pd(matrix: ndarray) -> ndarray

Return the nearest positive-definite matrix, as Matrix nearPD.

PARAMETER DESCRIPTION
matrix

Square real matrix.

TYPE: ndarray

RETURNS DESCRIPTION
ndarray

Higham's alternating projection with Dykstra's correction (eig.tol = 1e-6, conv.tol = 1e-7, maxit = 100, infinity norm), followed by the posd.tol = 1e-8 eigenvalue floor, as nearPD with its defaults.

RAISES DESCRIPTION
ValueError

If the matrix is negative semidefinite or the projection does not converge within 100 iterations.

Source code in src/quivers/diagnostics/bridge.py
def near_pd(matrix: np.ndarray) -> np.ndarray:
    """Return the nearest positive-definite matrix, as Matrix ``nearPD``.

    Parameters
    ----------
    matrix : numpy.ndarray
        Square real matrix.

    Returns
    -------
    numpy.ndarray
        Higham's alternating projection with Dykstra's correction
        (``eig.tol = 1e-6``, ``conv.tol = 1e-7``, ``maxit = 100``, infinity
        norm), followed by the ``posd.tol = 1e-8`` eigenvalue floor, as
        ``nearPD`` with its defaults.

    Raises
    ------
    ValueError
        If the matrix is negative semidefinite or the projection does not
        converge within 100 iterations.
    """
    x = np.asarray(matrix, dtype=np.float64)
    if not np.array_equal(x, x.T):
        x = (x + x.T) / 2.0
    n = x.shape[0]
    correction = np.zeros_like(x)
    current = x
    converged = False
    for _ in range(100):
        previous = current
        residual = previous - correction
        values, vectors = np.linalg.eigh(residual)
        values, vectors = values[::-1], vectors[:, ::-1]
        keep = values > 1e-6 * values[0]
        if not keep.any():
            raise ValueError("nearPD: the matrix seems negative semidefinite")
        kept = vectors[:, keep]
        current = (kept * values[keep]) @ kept.T
        correction = current - residual
        change = np.abs(previous - current).sum(axis=1).max()
        scale = np.abs(previous).sum(axis=1).max()
        if change / scale <= 1e-7:
            converged = True
            break
    if not converged:
        raise ValueError("nearPD did not converge in 100 iterations")
    values, vectors = np.linalg.eigh(current)
    values, vectors = values[::-1].copy(), vectors[:, ::-1]
    floor = 1e-8 * abs(values[0])
    if values[n - 1] < floor:
        values[values < floor] = floor
        diagonal = np.diag(current).copy()
        current = vectors @ (values[:, None] * vectors.T)
        scale = np.sqrt(np.maximum(floor, diagonal) / np.diag(current))
        current = scale[:, None] * current * scale[None, :]
    return current

posterior_model_probabilities

posterior_model_probabilities(logml: Mapping[str, float], *, prior_prob: Sequence[float] | None = None) -> dict[str, float]

Return posterior model probabilities, as bridgesampling::post_prob.

PARAMETER DESCRIPTION
logml

Log marginal likelihood of each named model, at least two.

TYPE: Mapping[str, float]

prior_prob

Prior model probabilities in the order of logml; uniform when None.

TYPE: Sequence[float] or None DEFAULT: None

RETURNS DESCRIPTION
dict[str, float]

:math:p(M_k \mid y) \propto p(y \mid M_k) p(M_k), summing to one.

RAISES DESCRIPTION
ValueError

If fewer than two models are given, prior probabilities do not match the models or do not sum to one (R all.equal), or an estimate is not finite.

Source code in src/quivers/diagnostics/bridge.py
def posterior_model_probabilities(
    logml: Mapping[str, float], *, prior_prob: Sequence[float] | None = None
) -> dict[str, float]:
    """Return posterior model probabilities, as ``bridgesampling::post_prob``.

    Parameters
    ----------
    logml : Mapping[str, float]
        Log marginal likelihood of each named model, at least two.
    prior_prob : Sequence[float] or None
        Prior model probabilities in the order of ``logml``; uniform when None.

    Returns
    -------
    dict[str, float]
        :math:`p(M_k \\mid y) \\propto p(y \\mid M_k) p(M_k)`, summing to one.

    Raises
    ------
    ValueError
        If fewer than two models are given, prior probabilities do not match
        the models or do not sum to one (R ``all.equal``), or an estimate is
        not finite.
    """
    if len(logml) < 2:
        raise ValueError("post_prob requires at least two models")
    values = np.asarray(list(logml.values()), dtype=np.float64)
    if not np.isfinite(values).all():
        raise ValueError("post_prob requires finite log marginal likelihoods")
    prior = (
        np.full(values.shape[0], 1.0 / values.shape[0])
        if prior_prob is None
        else np.asarray(prior_prob, dtype=np.float64)
    )
    if prior.shape != values.shape:
        raise ValueError(
            "the number of prior model probabilities must match the number of models"
        )
    if np.any(prior < 0) or abs(prior.sum() - 1.0) > _ALL_EQUAL:
        raise ValueError("prior model probabilities must be nonnegative and sum to one")
    log_weight = values + np.log(prior)
    posterior = np.exp(log_weight - np.logaddexp.reduce(log_weight))
    return {name: float(p) for name, p in zip(logml, posterior, strict=True)}

compare_estimates

compare_estimates(estimates: Mapping[str, ELPDEstimate]) -> SummaryTable

Rank models by ELPD with the loo package's loo_compare layout.

PARAMETER DESCRIPTION
estimates

Named estimates of one criterion on the same responses.

TYPE: Mapping[str, ELPDEstimate]

RETURNS DESCRIPTION
SummaryTable

Rows ordered from best to worst; columns elpd_diff, se_diff, elpd_<c>, se_elpd_<c>, p_<c>, se_p_<c>, <c>ic, se_<c>ic. Differences are elpd_model - elpd_best (zero or negative) with paired standard errors sqrt(n var(diff_i)) as loo, and ArviZ's difference estimator when an estimate is subsampled.

RAISES DESCRIPTION
ValueError

If fewer than two models are given, criteria differ, or the models score different responses or unit counts.

Source code in src/quivers/diagnostics/elpd.py
def compare_estimates(estimates: Mapping[str, ELPDEstimate]) -> SummaryTable:
    """Rank models by ELPD with the loo package's ``loo_compare`` layout.

    Parameters
    ----------
    estimates : Mapping[str, ELPDEstimate]
        Named estimates of one criterion on the same responses.

    Returns
    -------
    SummaryTable
        Rows ordered from best to worst; columns ``elpd_diff``, ``se_diff``,
        ``elpd_<c>``, ``se_elpd_<c>``, ``p_<c>``, ``se_p_<c>``, ``<c>ic``,
        ``se_<c>ic``. Differences are ``elpd_model - elpd_best`` (zero or
        negative) with paired standard errors ``sqrt(n var(diff_i))`` as loo,
        and ArviZ's difference estimator when an estimate is subsampled.

    Raises
    ------
    ValueError
        If fewer than two models are given, criteria differ, or the models
        score different responses or unit counts.
    """
    if len(estimates) < 2:
        raise ValueError("loo_compare requires at least two models")
    criteria = {estimate.criterion for estimate in estimates.values()}
    kinds = {"loo" if c == "loo_subsample" else c for c in criteria}
    if len(kinds) != 1:
        raise ValueError(f"cannot compare different criteria {sorted(criteria)}")
    if len({e.response_hash for e in estimates.values()}) != 1:
        raise ValueError("models must score the same response values")
    if len({e.num_observations for e in estimates.values()}) != 1:
        raise ValueError("models have different numbers of observations")
    labels = _LABELS[next(iter(criteria))]
    order = sorted(estimates, key=lambda name: -estimates[name].elpd)
    best = estimates[order[0]]
    subsampled = "loo_subsample" in criteria
    table = (
        az.compare(
            {name: estimate.to_arviz() for name, estimate in estimates.items()},
            round_to="none",
        )
        if subsampled
        else None
    )
    rows: list[str] = []
    values: list[list[float]] = []
    for name in order:
        estimate = estimates[name]
        if table is not None:
            # ArviZ's difference estimator for subsampled terms, which it
            # reports as this model's ELPD minus the best model's.
            difference = float(table.loc[name, "elpd_diff"])
            se_difference = float(table.loc[name, "dse"])
        else:
            # loo_compare: paired pointwise differences, sqrt(n var) with n - 1.
            terms = estimate.pointwise_elpd - best.pointwise_elpd
            difference = float(terms.sum())
            se_difference = 0.0 if name == order[0] else _standard_error(terms)
        rows.append(name)
        values.append(
            [
                difference,
                se_difference,
                estimate.elpd,
                estimate.se_elpd,
                estimate.p,
                estimate.se_p,
                estimate.ic,
                estimate.se_ic,
            ]
        )
    return SummaryTable(
        rows=tuple(rows),
        columns=(
            "elpd_diff",
            "se_diff",
            labels[0],
            f"se_{labels[0]}",
            labels[1],
            f"se_{labels[1]}",
            labels[2],
            f"se_{labels[2]}",
        ),
        values=torch.tensor(values, dtype=torch.float64),
    )

from_arviz

from_arviz(result: ELPDData, log_likelihood: Tensor, *, criterion: Criterion, responses: tuple[str, ...], hashed: str, moment_matched: tuple[int, ...] = (), refitted: tuple[int, ...] = ()) -> ELPDEstimate

Convert a pointwise ArviZ PSIS-LOO result to an ELPDEstimate.

PARAMETER DESCRIPTION
result

Pointwise ArviZ result.

TYPE: ELPDData

log_likelihood

The scores (chain, draw, unit) behind the result, for p_i.

TYPE: Tensor

criterion

Estimator label.

TYPE: ('loo', 'waic', 'kfold', 'loo_subsample') DEFAULT: "loo"

responses

Scored response names.

TYPE: tuple[str, ...]

hashed

Response hash.

TYPE: str

moment_matched

Units changed by moment matching or exact refits.

TYPE: tuple[int, ...] DEFAULT: ()

refitted

Units changed by moment matching or exact refits.

TYPE: tuple[int, ...] DEFAULT: ()

RETURNS DESCRIPTION
ELPDEstimate

The estimate with p_i = lpd_i - elpd_i and its standard error.

RAISES DESCRIPTION
ValueError

If the result has no pointwise terms.

Source code in src/quivers/diagnostics/elpd.py
def from_arviz(
    result: ELPDData,
    log_likelihood: torch.Tensor,
    *,
    criterion: Criterion,
    responses: tuple[str, ...],
    hashed: str,
    moment_matched: tuple[int, ...] = (),
    refitted: tuple[int, ...] = (),
) -> ELPDEstimate:
    """Convert a pointwise ArviZ PSIS-LOO result to an `ELPDEstimate`.

    Parameters
    ----------
    result : arviz_stats.utils.ELPDData
        Pointwise ArviZ result.
    log_likelihood : torch.Tensor
        The scores ``(chain, draw, unit)`` behind the result, for ``p_i``.
    criterion : {"loo", "waic", "kfold", "loo_subsample"}
        Estimator label.
    responses : tuple[str, ...]
        Scored response names.
    hashed : str
        Response hash.
    moment_matched, refitted : tuple[int, ...]
        Units changed by moment matching or exact refits.

    Returns
    -------
    ELPDEstimate
        The estimate with ``p_i = lpd_i - elpd_i`` and its standard error.

    Raises
    ------
    ValueError
        If the result has no pointwise terms.
    """
    if result.elpd_i is None:
        raise ValueError("an ELPD estimate requires pointwise ArviZ terms")
    pointwise = torch.as_tensor(
        np.asarray(result.elpd_i.values, dtype=np.float64).reshape(-1)
    )
    p_i = pointwise_lpd(log_likelihood).reshape(-1).cpu() - pointwise
    pareto = (
        torch.as_tensor(
            np.asarray(result.pareto_k.values, dtype=np.float64).reshape(-1)
        )
        if result.pareto_k is not None
        else None
    )
    return ELPDEstimate(
        criterion=criterion,
        elpd=float(result.elpd),
        # loo's standard error uses the unbiased variance of the terms;
        # ArviZ's divides by n.
        se_elpd=_standard_error(pointwise),
        p=float(p_i.sum()),
        se_p=_standard_error(p_i),
        pointwise_elpd=pointwise,
        pointwise_p=p_i,
        pareto_k=pareto,
        num_samples=int(result.n_samples),
        good_k=float(result.good_k),
        responses=responses,
        response_hash=hashed,
        moment_matched=moment_matched,
        refitted=refitted,
    )

good_k

good_k(num_samples: int) -> float

Return the sample-size dependent Pareto shape threshold.

PARAMETER DESCRIPTION
num_samples

Pooled draw count S.

TYPE: int

RETURNS DESCRIPTION
float

min(1 - 1 / log10(S), 0.7) [@vehtari2024psis].

Source code in src/quivers/diagnostics/elpd.py
def good_k(num_samples: int) -> float:
    """Return the sample-size dependent Pareto shape threshold.

    Parameters
    ----------
    num_samples : int
        Pooled draw count S.

    Returns
    -------
    float
        ``min(1 - 1 / log10(S), 0.7)`` [@vehtari2024psis].
    """
    return min(1 - 1 / math.log10(num_samples), 0.7) if num_samples > 1 else 0.7

information_weights

information_weights(estimates: Mapping[str, ELPDEstimate]) -> dict[str, float]

Return Akaike-type weights exp(-ic_diff / 2) as brms model_weights.

PARAMETER DESCRIPTION
estimates

Estimates of one criterion (loo, waic or kfold).

TYPE: Mapping[str, ELPDEstimate]

RETURNS DESCRIPTION
dict[str, float]

Normalized weights in input order.

RAISES DESCRIPTION
ValueError

If criteria differ.

Source code in src/quivers/diagnostics/elpd.py
def information_weights(estimates: Mapping[str, ELPDEstimate]) -> dict[str, float]:
    """Return Akaike-type weights ``exp(-ic_diff / 2)`` as brms ``model_weights``.

    Parameters
    ----------
    estimates : Mapping[str, ELPDEstimate]
        Estimates of one criterion (loo, waic or kfold).

    Returns
    -------
    dict[str, float]
        Normalized weights in input order.

    Raises
    ------
    ValueError
        If criteria differ.
    """
    if len({e.criterion for e in estimates.values()}) != 1:
        raise ValueError("information-criterion weights need one criterion")
    ics = {name: estimate.ic for name, estimate in estimates.items()}
    best = min(ics.values())
    raw = {name: math.exp(-(value - best) / 2) for name, value in ics.items()}
    total = sum(raw.values())
    return {name: value / total for name, value in raw.items()}

kfold_estimate

kfold_estimate(elpd: Tensor, lpd: Tensor, *, num_samples: int, folds: tuple[int, ...], joint: Literal['obs', 'fold', 'group'], responses: tuple[str, ...], hashed: str) -> ELPDEstimate

Assemble brms's k-fold criterion from held-out and full-data scores.

PARAMETER DESCRIPTION
elpd

Held-out log predictive density per predictive unit.

TYPE: Tensor

lpd

Full-data log predictive density of the same units.

TYPE: Tensor

num_samples

Pooled draws of the full-data fit.

TYPE: int

folds

Zero-based fold of every observation.

TYPE: tuple[int, ...]

joint

Predictive unit.

TYPE: ('obs', 'fold', 'group') DEFAULT: "obs"

responses

Scored response names.

TYPE: tuple[str, ...]

hashed

Response hash.

TYPE: str

RETURNS DESCRIPTION
ELPDEstimate

elpd_kfold, p_kfold = lpd - elpd_kfold and their standard errors sqrt(n var) over units, as brms's kfold.

Source code in src/quivers/diagnostics/elpd.py
def kfold_estimate(
    elpd: torch.Tensor,
    lpd: torch.Tensor,
    *,
    num_samples: int,
    folds: tuple[int, ...],
    joint: Literal["obs", "fold", "group"],
    responses: tuple[str, ...],
    hashed: str,
) -> ELPDEstimate:
    """Assemble brms's k-fold criterion from held-out and full-data scores.

    Parameters
    ----------
    elpd : torch.Tensor
        Held-out log predictive density per predictive unit.
    lpd : torch.Tensor
        Full-data log predictive density of the same units.
    num_samples : int
        Pooled draws of the full-data fit.
    folds : tuple[int, ...]
        Zero-based fold of every observation.
    joint : {"obs", "fold", "group"}
        Predictive unit.
    responses : tuple[str, ...]
        Scored response names.
    hashed : str
        Response hash.

    Returns
    -------
    ELPDEstimate
        ``elpd_kfold``, ``p_kfold = lpd - elpd_kfold`` and their standard
        errors ``sqrt(n var)`` over units, as brms's ``kfold``.
    """
    e = elpd.detach().to(torch.float64).reshape(-1).cpu()
    p_i = lpd.detach().to(torch.float64).reshape(-1).cpu() - e
    return ELPDEstimate(
        criterion="kfold",
        elpd=float(e.sum()),
        se_elpd=_standard_error(e),
        p=float(p_i.sum()),
        se_p=_standard_error(p_i),
        pointwise_elpd=e,
        pointwise_p=p_i,
        num_samples=num_samples,
        responses=responses,
        response_hash=hashed,
        folds=folds,
        joint=joint,
    )

loo_expectation

loo_expectation(draws: Tensor, weights: PSISWeights, *, kind: Literal['mean', 'var', 'sd', 'median', 'quantile'], probs: Sequence[float] = (0.5,), labels: Sequence[str | int] | None = None, components: Sequence[str | int] | None = None) -> LooExpectation

Compute leave-one-out expectations of draws with ArviZ.

PARAMETER DESCRIPTION
draws

Draws (chain, draw, unit) or (chain, draw, unit, component) aligned with the weights' units.

TYPE: Tensor

weights

Leave-one-out weights of the same units.

TYPE: PSISWeights

kind

Weighted statistic. The weighted variance divides by 1 - sum(w^2) and quantiles interpolate the weighted cumulative distribution, both as loo's E_loo.

TYPE: ('mean', 'var', 'sd', 'median', 'quantile') DEFAULT: "mean"

probs

Probabilities for kind="quantile".

TYPE: Sequence[float] DEFAULT: (0.5,)

labels

Unit and component labels; 0-based positions by default.

TYPE: Sequence or None DEFAULT: None

components

Unit and component labels; 0-based positions by default.

TYPE: Sequence or None DEFAULT: None

RETURNS DESCRIPTION
LooExpectation

Statistics and ArviZ's function-specific Pareto diagnostics.

RAISES DESCRIPTION
ValueError

If draws and weights disagree or probabilities are invalid.

Notes

Cost is O(S U) for S pooled draws and U units, plus a sort per unit for quantiles. The estimates assume that PSIS is reliable for the unit (its Pareto shape below PSISWeights.good_k).

Source code in src/quivers/diagnostics/elpd.py
def loo_expectation(
    draws: torch.Tensor,
    weights: PSISWeights,
    *,
    kind: Literal["mean", "var", "sd", "median", "quantile"],
    probs: Sequence[float] = (0.5,),
    labels: Sequence[str | int] | None = None,
    components: Sequence[str | int] | None = None,
) -> LooExpectation:
    """Compute leave-one-out expectations of draws with ArviZ.

    Parameters
    ----------
    draws : torch.Tensor
        Draws ``(chain, draw, unit)`` or ``(chain, draw, unit, component)``
        aligned with the weights' units.
    weights : PSISWeights
        Leave-one-out weights of the same units.
    kind : {"mean", "var", "sd", "median", "quantile"}
        Weighted statistic. The weighted variance divides by
        ``1 - sum(w^2)`` and quantiles interpolate the weighted cumulative
        distribution, both as loo's ``E_loo``.
    probs : Sequence[float]
        Probabilities for ``kind="quantile"``.
    labels, components : Sequence or None
        Unit and component labels; 0-based positions by default.

    Returns
    -------
    LooExpectation
        Statistics and ArviZ's function-specific Pareto diagnostics.

    Raises
    ------
    ValueError
        If draws and weights disagree or probabilities are invalid.

    Notes
    -----
    Cost is O(S U) for S pooled draws and U units, plus a sort per unit
    for quantiles. The estimates assume that PSIS is reliable for the unit
    (its Pareto shape below `PSISWeights.good_k`).
    """
    if tuple(draws.shape[:3]) != tuple(weights.log_weights.shape):
        raise ValueError("expectation draws must align with the PSIS weights")
    values = draws.detach().to(torch.float64).cpu().numpy()
    vector = values.ndim == 4
    dims = ("chain", "draw", "__obs__", "__component__")[: values.ndim]
    h_draws = xr.DataArray(values, dims=dims)
    log_weights = xr.DataArray(
        weights.log_weights.cpu().numpy(), dims=("chain", "draw", "__obs__")
    )
    pareto = xr.DataArray(weights.pareto_k.cpu().numpy(), dims=("__obs__",))
    if vector:
        log_weights = log_weights.broadcast_like(h_draws)
        pareto = pareto.broadcast_like(h_draws.isel(chain=0, draw=0, drop=True))
    tree = xr.DataTree.from_dict(
        {
            "posterior_predictive": xr.Dataset({"h": h_draws}),
            "log_likelihood": xr.Dataset({"h": -log_weights}),
            "posterior": xr.Dataset({"h": h_draws}),
        }
    )
    levels = tuple(probs)
    if kind == "quantile":
        if not levels or any(not 0 < p < 1 for p in levels):
            raise ValueError("quantile probabilities must lie strictly inside (0, 1)")
        # ArviZ supplies the tail diagnostic; the quantiles follow loo's E_loo,
        # which brms uses, rather than ArviZ's effective-size quantile.
        _, khat = az.loo_expectations(
            tree,
            var_name="h",
            kind="quantile",
            probs=list(levels),
            log_weights=log_weights,
            pareto_k=pareto,
        )
        columns = tuple(f"q{_percent_label(p)}" for p in levels)
        weights_array = np.exp(weights.log_weights.cpu().numpy()).reshape(
            -1, values.shape[2]
        )
        flat = values.reshape(-1, *values.shape[2:])
        statistic = np.empty((values.shape[2], len(levels), *values.shape[3:]))
        for unit in range(values.shape[2]):
            for index in np.ndindex(*values.shape[3:]):
                statistic[(unit, slice(None), *index)] = weighted_quantile(
                    flat[(slice(None), unit, *index)], weights_array[:, unit], levels
                )
    else:
        result, khat = az.loo_expectations(
            tree, var_name="h", kind=kind, log_weights=log_weights, pareto_k=pareto
        )
        columns = (kind,)
        statistic = np.expand_dims(np.asarray(result.values), 1)
    rows = tuple(range(values.shape[2])) if labels is None else tuple(labels)
    names = (
        (tuple(range(values.shape[3])) if components is None else tuple(components))
        if vector
        else ()
    )
    return LooExpectation(
        table=SummaryTable(
            rows=rows,
            columns=columns,
            components=names,
            values=torch.as_tensor(np.ascontiguousarray(statistic, dtype=np.float64)),
        ),
        pareto_k=torch.as_tensor(np.asarray(khat.values, dtype=np.float64)),
    )

loo_r2_draws

loo_r2_draws(observed: Tensor, loo_mean: Tensor, generator: Generator, num_draws: int) -> Tensor

Draw brms's leave-one-out R-squared by the Bayesian bootstrap.

PARAMETER DESCRIPTION
observed

Observed responses (unit,).

TYPE: Tensor

loo_mean

Leave-one-out expected responses (unit,).

TYPE: Tensor

generator

Stream of the Dirichlet weights.

TYPE: Generator

num_draws

Bootstrap draws, the posterior draw count S in brms.

TYPE: int

RETURNS DESCRIPTION
Tensor

1 - var_w(e) / var_w(y) per Dirichlet weight vector, with e = loo_mean - y and weighted variances scaled by N / (N - 1), clipped to [-1, 1] as brms does [@gelman2019rsquared].

RAISES DESCRIPTION
ValueError

If fewer than two units are given.

Source code in src/quivers/diagnostics/elpd.py
def loo_r2_draws(
    observed: torch.Tensor,
    loo_mean: torch.Tensor,
    generator: torch.Generator,
    num_draws: int,
) -> torch.Tensor:
    """Draw brms's leave-one-out R-squared by the Bayesian bootstrap.

    Parameters
    ----------
    observed : torch.Tensor
        Observed responses ``(unit,)``.
    loo_mean : torch.Tensor
        Leave-one-out expected responses ``(unit,)``.
    generator : torch.Generator
        Stream of the Dirichlet weights.
    num_draws : int
        Bootstrap draws, the posterior draw count S in brms.

    Returns
    -------
    torch.Tensor
        ``1 - var_w(e) / var_w(y)`` per Dirichlet weight vector, with
        ``e = loo_mean - y`` and weighted variances scaled by ``N / (N - 1)``,
        clipped to ``[-1, 1]`` as brms does [@gelman2019rsquared].

    Raises
    ------
    ValueError
        If fewer than two units are given.
    """
    y = observed.detach().to(torch.float64).reshape(-1)
    error = loo_mean.detach().to(torch.float64).reshape(-1) - y
    count = y.numel()
    if count < 2:
        raise ValueError("loo R-squared requires at least two observations")
    exponential = torch.empty(num_draws, count, dtype=torch.float64).exponential_(
        generator=generator
    )
    weights = exponential / exponential.sum(1, keepdim=True)
    scale = count / (count - 1)
    var_y = scale * ((weights * y**2).sum(1) - (weights * y).sum(1) ** 2)
    var_e = scale * ((weights * error**2).sum(1) - (weights * error).sum(1) ** 2)
    return (1 - var_e / var_y).clamp(-1.0, 1.0)

pointwise_lpd

pointwise_lpd(log_likelihood: Tensor) -> Tensor

Return the log pointwise predictive density over pooled draws.

PARAMETER DESCRIPTION
log_likelihood

Scores (chain, draw, unit).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Float64 log(mean_s exp(ll_s)) per unit.

Source code in src/quivers/diagnostics/elpd.py
def pointwise_lpd(log_likelihood: torch.Tensor) -> torch.Tensor:
    """Return the log pointwise predictive density over pooled draws.

    Parameters
    ----------
    log_likelihood : torch.Tensor
        Scores ``(chain, draw, unit)``.

    Returns
    -------
    torch.Tensor
        Float64 ``log(mean_s exp(ll_s))`` per unit.
    """
    pooled = log_likelihood.detach().to(torch.float64).flatten(0, 1)
    return torch.logsumexp(pooled, dim=0) - math.log(pooled.shape[0])

psis_weights

psis_weights(log_likelihood: Tensor, *, r_eff: float) -> PSISWeights

Smooth leave-one-out importance ratios with ArviZ's PSIS.

PARAMETER DESCRIPTION
log_likelihood

Scores (chain, draw, unit); the raw log ratios are their negatives.

TYPE: Tensor

r_eff

Relative efficiency of the draws, one for independent draws.

TYPE: float

RETURNS DESCRIPTION
PSISWeights

Normalized smoothed log weights and Pareto diagnostics.

RAISES DESCRIPTION
ValueError

If the scores are not three-dimensional, the efficiency is not positive, fewer than 25 draws are pooled, or a score is missing.

Source code in src/quivers/diagnostics/elpd.py
def psis_weights(log_likelihood: torch.Tensor, *, r_eff: float) -> PSISWeights:
    """Smooth leave-one-out importance ratios with ArviZ's PSIS.

    Parameters
    ----------
    log_likelihood : torch.Tensor
        Scores ``(chain, draw, unit)``; the raw log ratios are their negatives.
    r_eff : float
        Relative efficiency of the draws, one for independent draws.

    Returns
    -------
    PSISWeights
        Normalized smoothed log weights and Pareto diagnostics.

    Raises
    ------
    ValueError
        If the scores are not three-dimensional, the efficiency is not
        positive, fewer than 25 draws are pooled, or a score is missing.
    """
    if log_likelihood.ndim != 3:
        raise ValueError("PSIS requires scores shaped (chain, draw, unit)")
    if not r_eff > 0:
        raise ValueError("relative efficiency must be positive")
    require_psis_draws(log_likelihood.shape[0] * log_likelihood.shape[1])
    require_scores(log_likelihood, criterion="PSIS")
    # ArviZ's psislw takes log-likelihoods and smooths their negatives.
    scores = xr.DataArray(
        log_likelihood.detach().to(torch.float64).cpu().numpy(),
        dims=("chain", "draw", "__obs__"),
    )
    log_weights, pareto_k = scores.azstats.psislw(r_eff=r_eff, dim=["chain", "draw"])
    weights = torch.as_tensor(
        np.ascontiguousarray(
            log_weights.transpose("chain", "draw", "__obs__").values, dtype=np.float64
        )
    )
    count = log_likelihood.shape[0] * log_likelihood.shape[1]
    return PSISWeights(
        log_weights=weights,
        pareto_k=torch.as_tensor(np.asarray(pareto_k.values, dtype=np.float64)),
        r_eff=float(r_eff),
        good_k=good_k(count),
    )

require_psis_draws

require_psis_draws(count: int) -> None

Refuse Pareto smoothing with too few draws for a tail fit.

PSIS fits a generalized Pareto distribution to the largest fifth of the importance ratios of each unit and needs at least five of them [@vehtari2024psis].

PARAMETER DESCRIPTION
count

Pooled posterior draws.

TYPE: int

RAISES DESCRIPTION
ValueError

If fewer than 25 draws are pooled.

Source code in src/quivers/diagnostics/elpd.py
def require_psis_draws(count: int) -> None:
    """Refuse Pareto smoothing with too few draws for a tail fit.

    PSIS fits a generalized Pareto distribution to the largest fifth of the
    importance ratios of each unit and needs at least five of them
    [@vehtari2024psis].

    Parameters
    ----------
    count : int
        Pooled posterior draws.

    Raises
    ------
    ValueError
        If fewer than 25 draws are pooled.
    """
    if count < PSIS_MIN_DRAWS:
        raise ValueError(
            "Pareto-smoothed importance sampling fits a generalized Pareto "
            "tail to the largest fifth of the importance ratios and needs at "
            f"least five of them; {count} pooled draws are fewer than "
            f"{PSIS_MIN_DRAWS}, so request more draws"
        )

require_scores

require_scores(log_likelihood: Tensor, *, criterion: str) -> None

Refuse an importance-sampling criterion over missing pointwise scores.

PARAMETER DESCRIPTION
log_likelihood

Scores (chain, draw, unit).

TYPE: Tensor

criterion

Criterion named in the error.

TYPE: str

RAISES DESCRIPTION
ValueError

If a score is missing (nan), as the scores of a missing mi() response are.

Source code in src/quivers/diagnostics/elpd.py
def require_scores(log_likelihood: torch.Tensor, *, criterion: str) -> None:
    """Refuse an importance-sampling criterion over missing pointwise scores.

    Parameters
    ----------
    log_likelihood : torch.Tensor
        Scores ``(chain, draw, unit)``.
    criterion : str
        Criterion named in the error.

    Raises
    ------
    ValueError
        If a score is missing (``nan``), as the scores of a missing ``mi()``
        response are.
    """
    missing = log_likelihood.isnan().any(dim=0).any(dim=0)
    if bool(missing.any()):
        raise ValueError(
            f"{criterion} requires finite log likelihoods at every posterior "
            f"draw; {int(missing.sum())} of {missing.numel()} units have "
            "missing scores (rows with a missing mi() response). brms "
            "reports NA for them too: score the responses without missing "
            "values through resp, or the complete rows through "
            "log_likelihood(new_data=...)"
        )

response_hash

response_hash(values: Sequence[Tensor]) -> str

Hash observed responses to check that criteria score the same data.

PARAMETER DESCRIPTION
values

Observed response tensors in a fixed order.

TYPE: Sequence[Tensor]

RETURNS DESCRIPTION
str

SHA-1 digest of the Float64 values, their shapes, and NaN positions. brms stores the same check as a hash of its response data.

Source code in src/quivers/diagnostics/elpd.py
def response_hash(values: Sequence[torch.Tensor]) -> str:
    """Hash observed responses to check that criteria score the same data.

    Parameters
    ----------
    values : Sequence[torch.Tensor]
        Observed response tensors in a fixed order.

    Returns
    -------
    str
        SHA-1 digest of the Float64 values, their shapes, and NaN positions.
        brms stores the same check as a hash of its response data.
    """
    digest = hashlib.sha1()
    for value in values:
        array = value.detach().to(torch.float64).cpu().contiguous().numpy()
        digest.update(str(array.shape).encode())
        digest.update(np.nan_to_num(array, nan=np.inf).tobytes())
        digest.update(np.isnan(array).tobytes())
    return digest.hexdigest()

stacking_weights

stacking_weights(estimates: Mapping[str, ELPDEstimate], *, method: Literal['stacking', 'pseudobma'], bayesian_bootstrap: bool, seed: int) -> dict[str, float]

Return ArviZ's stacking or pseudo-BMA weights, as loo_model_weights.

PARAMETER DESCRIPTION
estimates

PSIS-LOO estimates of the candidate models on the same responses.

TYPE: Mapping[str, ELPDEstimate]

method

Stacking of predictive distributions [@yao2018stacking] or pseudo-BMA weights.

TYPE: ('stacking', 'pseudobma') DEFAULT: "stacking"

bayesian_bootstrap

Regularize pseudo-BMA weights with the Bayesian bootstrap (loo's BB = TRUE, its default).

TYPE: bool

seed

Seed of the Bayesian bootstrap.

TYPE: int

RETURNS DESCRIPTION
dict[str, float]

Normalized weights in input order.

RAISES DESCRIPTION
ValueError

If the estimates are not comparable PSIS-LOO estimates.

Source code in src/quivers/diagnostics/elpd.py
def stacking_weights(
    estimates: Mapping[str, ELPDEstimate],
    *,
    method: Literal["stacking", "pseudobma"],
    bayesian_bootstrap: bool,
    seed: int,
) -> dict[str, float]:
    """Return ArviZ's stacking or pseudo-BMA weights, as loo_model_weights.

    Parameters
    ----------
    estimates : Mapping[str, ELPDEstimate]
        PSIS-LOO estimates of the candidate models on the same responses.
    method : {"stacking", "pseudobma"}
        Stacking of predictive distributions [@yao2018stacking] or pseudo-BMA
        weights.
    bayesian_bootstrap : bool
        Regularize pseudo-BMA weights with the Bayesian bootstrap (loo's
        ``BB = TRUE``, its default).
    seed : int
        Seed of the Bayesian bootstrap.

    Returns
    -------
    dict[str, float]
        Normalized weights in input order.

    Raises
    ------
    ValueError
        If the estimates are not comparable PSIS-LOO estimates.
    """
    if any(e.criterion not in {"loo", "loo_subsample"} for e in estimates.values()):
        raise ValueError("stacking and pseudo-BMA weights require PSIS-LOO estimates")
    if len({e.response_hash for e in estimates.values()}) != 1:
        raise ValueError("models must score the same response values")
    arviz_method = (
        "stacking"
        if method == "stacking"
        else "BB-pseudo-BMA"
        if bayesian_bootstrap
        else "pseudo-BMA"
    )
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        table = az.compare(
            {name: estimate.to_arviz() for name, estimate in estimates.items()},
            method=arviz_method,
            round_to="none",
        )
    finally:
        np.random.set_state(state)
    return {name: float(table.loc[name, "weight"]) for name in estimates}

subsample_estimate

subsample_estimate(exact: Tensor, approximation: Tensor, subsample: Sequence[int], lpd: Tensor, pareto_k: Tensor, *, num_samples: int, responses: tuple[str, ...], hashed: str, method: Literal['plpd', 'lpd']) -> ELPDEstimate

Combine exact subsample PSIS-LOO terms with an approximation of all units.

The difference estimator of [@magnusson2020leave] under simple random sampling without replacement estimates the total ELPD as sum_i a_i + N mean_j (e_j - a_j) over subsample units j, with a the approximation and e the exact PSIS-LOO terms, and its variance with the finite-population correction 1 - m / N.

PARAMETER DESCRIPTION
exact

Exact PSIS-LOO terms of the subsample, (m,).

TYPE: Tensor

approximation

Approximate terms of every unit, (N,).

TYPE: Tensor

subsample

Zero-based subsample units, aligned with exact.

TYPE: Sequence[int]

lpd

Log predictive densities of the subsample, (m,), for p_loo.

TYPE: Tensor

pareto_k

Pareto shapes of the subsample, (m,).

TYPE: Tensor

num_samples

Pooled draw count.

TYPE: int

responses

Scored response names.

TYPE: tuple[str, ...]

hashed

Response hash.

TYPE: str

method

Approximation behind approximation.

TYPE: ('plpd', 'lpd') DEFAULT: "plpd"

RETURNS DESCRIPTION
ELPDEstimate

The subsampled estimate with total and subsampling-only standard errors; p_loo uses the simple random sampling estimator.

RAISES DESCRIPTION
ValueError

If the subsample has fewer than two units, repeats a unit, or terms are not finite.

Source code in src/quivers/diagnostics/elpd.py
def subsample_estimate(
    exact: torch.Tensor,
    approximation: torch.Tensor,
    subsample: Sequence[int],
    lpd: torch.Tensor,
    pareto_k: torch.Tensor,
    *,
    num_samples: int,
    responses: tuple[str, ...],
    hashed: str,
    method: Literal["plpd", "lpd"],
) -> ELPDEstimate:
    """Combine exact subsample PSIS-LOO terms with an approximation of all units.

    The difference estimator of [@magnusson2020leave] under simple random
    sampling without replacement estimates the total ELPD as
    ``sum_i a_i + N mean_j (e_j - a_j)`` over subsample units ``j``, with
    ``a`` the approximation and ``e`` the exact PSIS-LOO terms, and its
    variance with the finite-population correction ``1 - m / N``.

    Parameters
    ----------
    exact : torch.Tensor
        Exact PSIS-LOO terms of the subsample, ``(m,)``.
    approximation : torch.Tensor
        Approximate terms of every unit, ``(N,)``.
    subsample : Sequence[int]
        Zero-based subsample units, aligned with ``exact``.
    lpd : torch.Tensor
        Log predictive densities of the subsample, ``(m,)``, for ``p_loo``.
    pareto_k : torch.Tensor
        Pareto shapes of the subsample, ``(m,)``.
    num_samples : int
        Pooled draw count.
    responses : tuple[str, ...]
        Scored response names.
    hashed : str
        Response hash.
    method : {"plpd", "lpd"}
        Approximation behind ``approximation``.

    Returns
    -------
    ELPDEstimate
        The subsampled estimate with total and subsampling-only standard
        errors; ``p_loo`` uses the simple random sampling estimator.

    Raises
    ------
    ValueError
        If the subsample has fewer than two units, repeats a unit, or
        terms are not finite.
    """
    units = tuple(subsample)
    total = approximation.numel()
    m = len(units)
    if m < 2 or len(set(units)) != m or any(not 0 <= u < total for u in units):
        raise ValueError("a subsample needs at least two distinct valid units")
    e = exact.detach().to(torch.float64).reshape(-1).cpu()
    a_all = approximation.detach().to(torch.float64).reshape(-1).cpu()
    index = torch.tensor(units, dtype=torch.long)
    a = a_all[index]
    if not bool(torch.isfinite(e).all() and torch.isfinite(a_all).all()):
        raise ValueError("subsampled PSIS-LOO requires finite pointwise terms")
    difference = e - a
    estimate = float(a_all.sum() + total * difference.mean())
    variance = float(difference.var(correction=1))
    sub_variance = total**2 * (1 - m / total) * variance / m
    # Total variance of the pointwise ELPD distribution (Magnusson et al., 2020).
    sigma2 = (
        float((a_all**2).sum())
        + total * float((e**2 - a**2).mean())
        - (
            (total * float(difference.mean())) ** 2
            - sub_variance
            + 2 * float(a_all.sum()) * estimate
            - float(a_all.sum()) ** 2
        )
        / total
    )
    p_terms = lpd.detach().to(torch.float64).reshape(-1).cpu() - e
    p = total * float(p_terms.mean())
    p_variance = total * float(p_terms.var(correction=1))
    p_sub_variance = total**2 * (1 - m / total) * float(p_terms.var(correction=1)) / m
    pointwise = torch.full((total,), math.nan, dtype=torch.float64)
    pointwise[index] = e
    p_pointwise = torch.full((total,), math.nan, dtype=torch.float64)
    p_pointwise[index] = p_terms
    pareto = torch.full((total,), math.nan, dtype=torch.float64)
    pareto[index] = pareto_k.detach().to(torch.float64).reshape(-1).cpu()
    return ELPDEstimate(
        criterion="loo_subsample",
        elpd=estimate,
        se_elpd=math.sqrt(max(sigma2, 0.0)),
        p=p,
        se_p=math.sqrt(p_variance),
        pointwise_elpd=pointwise,
        pointwise_p=p_pointwise,
        pareto_k=pareto,
        num_samples=num_samples,
        good_k=good_k(num_samples),
        responses=responses,
        response_hash=hashed,
        subsample=units,
        subsampling_se=math.sqrt(sub_variance),
        subsampling_se_p=math.sqrt(p_sub_variance),
        approximation=a_all,
        approximation_method=method,
    )

waic_estimate

waic_estimate(log_likelihood: Tensor, *, responses: tuple[str, ...], hashed: str) -> ELPDEstimate

Estimate WAIC with the loo package's conventions.

PARAMETER DESCRIPTION
log_likelihood

Finite scores (chain, draw, unit).

TYPE: Tensor

responses

Scored response names.

TYPE: tuple[str, ...]

hashed

Response hash.

TYPE: str

RETURNS DESCRIPTION
ELPDEstimate

elpd_waic_i = lpd_i - p_waic_i with p_waic_i the sample variance (divisor S - 1) of the pointwise log-likelihood [@vehtari2017loo].

Source code in src/quivers/diagnostics/elpd.py
def waic_estimate(
    log_likelihood: torch.Tensor, *, responses: tuple[str, ...], hashed: str
) -> ELPDEstimate:
    """Estimate WAIC with the loo package's conventions.

    Parameters
    ----------
    log_likelihood : torch.Tensor
        Finite scores ``(chain, draw, unit)``.
    responses : tuple[str, ...]
        Scored response names.
    hashed : str
        Response hash.

    Returns
    -------
    ELPDEstimate
        ``elpd_waic_i = lpd_i - p_waic_i`` with ``p_waic_i`` the sample
        variance (divisor S - 1) of the pointwise log-likelihood
        [@vehtari2017loo].
    """
    result = waic(log_likelihood)
    pointwise = result.elpd_i.reshape(-1).to(torch.float64)
    variance = result.variance_i.reshape(-1).to(torch.float64)
    return ELPDEstimate(
        criterion="waic",
        elpd=result.elpd_waic,
        se_elpd=result.se,
        p=result.p_waic,
        se_p=result.se_p_waic,
        pointwise_elpd=pointwise,
        pointwise_p=variance,
        num_samples=result.num_samples,
        responses=responses,
        response_hash=hashed,
    )

weighted_quantile

weighted_quantile(values: ndarray, weights: ndarray, probs: Sequence[float]) -> ndarray

Interpolate quantiles of a weighted sample as loo's E_loo.

PARAMETER DESCRIPTION
values

Draws (S,).

TYPE: ndarray

weights

Nonnegative weights (S,).

TYPE: ndarray

probs

Probabilities in the open unit interval.

TYPE: Sequence[float]

RETURNS DESCRIPTION
ndarray

Linear interpolation of the normalized cumulative weights at each probability, from the largest draw below it; R's type-7 quantile when all weights are equal.

Source code in src/quivers/diagnostics/elpd.py
def weighted_quantile(
    values: np.ndarray, weights: np.ndarray, probs: Sequence[float]
) -> np.ndarray:
    """Interpolate quantiles of a weighted sample as loo's ``E_loo``.

    Parameters
    ----------
    values : numpy.ndarray
        Draws ``(S,)``.
    weights : numpy.ndarray
        Nonnegative weights ``(S,)``.
    probs : Sequence[float]
        Probabilities in the open unit interval.

    Returns
    -------
    numpy.ndarray
        Linear interpolation of the normalized cumulative weights at each
        probability, from the largest draw below it; R's type-7 quantile
        when all weights are equal.
    """
    if np.all(weights == weights[0]):
        return np.quantile(values, probs)
    order = np.argsort(values, kind="stable")
    x = values[order]
    cumulative = np.cumsum(weights[order])
    cumulative = cumulative / cumulative[-1]
    result = np.empty(len(probs))
    for j, prob in enumerate(probs):
        index = int(np.argmax(cumulative >= prob))
        if index == 0:
            result[j] = x[0]
        else:
            low, below = cumulative[index - 1], x[index - 1]
            result[j] = below + (x[index] - below) * (prob - low) / (
                cumulative[index] - low
            )
    return result

sbc

sbc(model: MonadicProgram, x: Tensor, fit: Callable[[dict[str, Tensor], int], SBCPosterior], *, observed_names: Iterable[str], num_simulations: int, seed: int, data: Mapping[str, Tensor] | None = None, statistics: Mapping[str, SBCStatistic] | None = None, thin: SBCThinning = 'ess', num_guide_draws: int = 1000) -> SBCResult

Run simulation-based calibration of an inference procedure.

Each of num_simulations simulations

  1. runs model forward at the one-row input x and the host data, drawing every latent from its prior and every site in observed_names from the model given those latents;
  2. calls fit(observations, fit_seed) with the simulated observations merged with data, and reads its posterior draws (see SBCPosterior);
  3. evaluates the test quantities at the prior draw and at every posterior draw, thins the posterior draws (thin), and keeps them.

The posterior draws of all simulations are then cut to the smallest retained count L (taking evenly spaced draws), and each true quantity is ranked among its L draws with sbc_ranks. Following Talts et al. (2018), thin="ess" keeps about one draw per effective sample, since autocorrelated draws make the ranks of even an exact sampler non-uniform.

The procedure is reproducible from seed: it derives three seeds per simulation, for the prior simulation, the fit, and the tie-breaks; the prior simulation and the fit run with Torch's CPU and available accelerator generators forked and initialized from locally seeded generators. Neither scope depends on or changes the caller's random state, and a fit that draws from global generators is reproducible too. States are restored even if the fit raises.

PARAMETER DESCRIPTION
model

The program whose inference is checked.

TYPE: MonadicProgram

x

A one-row program input: one run, as MCMC and the guides take.

TYPE: Tensor

fit

The inference procedure: fit(observations, seed), where observations holds the simulated observed sites and the host data, and seed is an integer the procedure may pass to a seeded sampler (for instance MCMC(..., seed=seed)).

TYPE: Callable[[dict[str, Tensor], int], SBCPosterior]

observed_names

The sites treated as data.

TYPE: Iterable[str]

num_simulations

Number of simulations.

TYPE: int

seed

Seed of the whole procedure.

TYPE: int

data

Host data the program reads by name (covariates), held fixed.

TYPE: Mapping[str, Tensor] or None DEFAULT: None

statistics

Named test quantities; None ranks every coordinate of every latent site. Quantities that read the data, such as a log-likelihood, can detect miscalibration that the parameters alone miss (Modrák et al., 2025, doi:10.1214/23-BA1404 <https://doi.org/10.1214/23-BA1404>_).

TYPE: Mapping[str, SBCStatistic] or None DEFAULT: None

thin

"ess" (the default) or a fixed interval; use 1 for a fit whose draws are independent.

TYPE: SBCThinning DEFAULT: 'ess'

num_guide_draws

Draws taken from a fit that returns a Guide.

TYPE: int DEFAULT: 1000

RETURNS DESCRIPTION
SBCResult

The ranks and the bookkeeping that reproduces them.

RAISES DESCRIPTION
ValueError

If x has more than one row, num_simulations or num_guide_draws is less than one, an observed name is not a site of the model, thin is invalid, a simulation's latent sites or statistics differ from the first simulation's, or a true value or posterior draw is non-finite.

TypeError

If fit returns none of the accepted posterior forms.

Source code in src/quivers/diagnostics/calibration.py
def sbc(
    model: MonadicProgram,
    x: torch.Tensor,
    fit: Callable[[dict[str, torch.Tensor], int], SBCPosterior],
    *,
    observed_names: Iterable[str],
    num_simulations: int,
    seed: int,
    data: Mapping[str, torch.Tensor] | None = None,
    statistics: Mapping[str, SBCStatistic] | None = None,
    thin: SBCThinning = "ess",
    num_guide_draws: int = 1000,
) -> SBCResult:
    """Run simulation-based calibration of an inference procedure.

    Each of ``num_simulations`` simulations

    1. runs ``model`` forward at the one-row input ``x`` and the host
       ``data``, drawing every latent from its prior and every site in
       ``observed_names`` from the model given those latents;
    2. calls ``fit(observations, fit_seed)`` with the simulated
       observations merged with ``data``, and reads its posterior
       draws (see `SBCPosterior`);
    3. evaluates the test quantities at the prior draw and at every
       posterior draw, thins the posterior draws (``thin``), and keeps
       them.

    The posterior draws of all simulations are then cut to the
    smallest retained count ``L`` (taking evenly spaced draws), and
    each true quantity is ranked among its ``L`` draws with
    `sbc_ranks`. Following Talts et al. (2018), ``thin="ess"`` keeps
    about one draw per effective sample, since autocorrelated draws
    make the ranks of even an exact sampler non-uniform.

    The procedure is reproducible from ``seed``: it derives three
    seeds per simulation, for the prior simulation, the fit, and the
    tie-breaks; the prior simulation and the fit run with Torch's
    CPU and available accelerator generators forked and initialized from
    locally seeded generators. Neither scope depends on or changes the
    caller's random state, and a fit that draws from global generators is
    reproducible too. States are restored even if the fit raises.

    Parameters
    ----------
    model : MonadicProgram
        The program whose inference is checked.
    x : torch.Tensor
        A one-row program input: one run, as MCMC and the guides take.
    fit : Callable[[dict[str, torch.Tensor], int], SBCPosterior]
        The inference procedure: ``fit(observations, seed)``, where
        ``observations`` holds the simulated observed sites and the
        host data, and ``seed`` is an integer the procedure may pass
        to a seeded sampler (for instance ``MCMC(..., seed=seed)``).
    observed_names : Iterable[str]
        The sites treated as data.
    num_simulations : int
        Number of simulations.
    seed : int
        Seed of the whole procedure.
    data : Mapping[str, torch.Tensor] or None
        Host data the program reads by name (covariates), held fixed.
    statistics : Mapping[str, SBCStatistic] or None
        Named test quantities; None ranks every coordinate of every
        latent site. Quantities that read the data, such as a
        log-likelihood, can detect miscalibration that the parameters
        alone miss (Modrák et al., 2025,
        `doi:10.1214/23-BA1404 <https://doi.org/10.1214/23-BA1404>`_).
    thin : SBCThinning
        ``"ess"`` (the default) or a fixed interval; use ``1`` for a
        fit whose draws are independent.
    num_guide_draws : int
        Draws taken from a fit that returns a `Guide`.

    Returns
    -------
    SBCResult
        The ranks and the bookkeeping that reproduces them.

    Raises
    ------
    ValueError
        If ``x`` has more than one row, ``num_simulations`` or
        ``num_guide_draws`` is less than one, an observed name is not a
        site of the model, ``thin`` is invalid, a simulation's latent
        sites or statistics differ from the first simulation's, or a
        true value or posterior draw is non-finite.
    TypeError
        If ``fit`` returns none of the accepted posterior forms.
    """
    _require_one_run(x, "sbc")
    if num_simulations < 1:
        raise ValueError(f"sbc: num_simulations must be >= 1, got {num_simulations}")
    if num_guide_draws < 1:
        raise ValueError(f"sbc: num_guide_draws must be >= 1, got {num_guide_draws}")
    observed = frozenset(observed_names)
    host = dict(data or {})
    master = torch.Generator().manual_seed(seed)
    seeds: list[list[int]] = torch.randint(
        0, _INT64_MAX, (num_simulations, 3), generator=master
    ).tolist()

    statistic_names: list[str] | None = None
    truths: list[torch.Tensor] = []
    kept: list[torch.Tensor] = []
    intervals: list[int] = []
    for simulation_seed, fit_seed, _ in seeds:
        with _seeded_rng(simulation_seed):
            with torch.no_grad():
                simulated = trace(model, x, observations=dict(host))
                missing = sorted(observed - simulated.sites.keys())
                if missing:
                    raise ValueError(
                        f"sbc: observed names {missing} are not sample sites "
                        "of the model"
                    )
                observations = {
                    name: simulated.sites[name].value.detach() for name in observed
                }
                fit_data = {**host, **observations}
                registry = LatentRegistry.from_trace(
                    model, trace(model, x, observations=dict(fit_data))
                )
        truth = {
            site.name: _site_value(simulated, site.name, site.constrained_shape)
            for site in registry.sites.values()
        }
        with _seeded_rng(fit_seed):
            posterior = _posterior_draws(
                fit(dict(fit_data), fit_seed), x, num_guide_draws
            )
        names, truth_values = _evaluate_statistics(
            statistics,
            registry,
            {name: value.unsqueeze(0) for name, value in truth.items()},
            fit_data,
        )
        num_chains, num_draws = next(iter(posterior.values())).shape[:2]
        flat_posterior = {
            name: values.reshape(num_chains * num_draws, *values.shape[2:])
            for name, values in posterior.items()
        }
        _, draw_values = _evaluate_statistics(
            statistics, registry, flat_posterior, fit_data
        )
        if statistic_names is None:
            statistic_names = names
        elif names != statistic_names:
            raise ValueError(
                "sbc: the simulations disagree on the latent sites or statistics: "
                f"{names} against {statistic_names}"
            )
        if not bool(torch.isfinite(truth_values).all()):
            raise ValueError("sbc: a prior draw of a statistic is not finite")
        if not bool(torch.isfinite(draw_values).all()):
            raise ValueError("sbc: the fit returned a non-finite posterior draw")
        chains = draw_values.reshape(num_chains, num_draws, -1)
        interval = _thinning_interval(chains, thin)
        intervals.append(interval)
        truths.append(truth_values[0])
        kept.append(chains[:, ::interval].reshape(-1, chains.shape[2]))

    retained = [int(draws.shape[0]) for draws in kept]
    common = min(retained)
    ranks: list[torch.Tensor] = []
    for (_, _, tie_seed), truth_row, draws in zip(seeds, truths, kept, strict=True):
        positions = (torch.arange(common) * draws.shape[0]) // common
        ranks.append(
            sbc_ranks(
                truth_row,
                draws[positions],
                generator=torch.Generator().manual_seed(tie_seed),
            )
        )
    return SBCResult(
        ranks=torch.stack(ranks),
        num_draws=common,
        statistic_names=tuple(statistic_names or ()),
        truths=torch.stack(truths),
        thinning=torch.tensor(intervals, dtype=torch.int64),
        retained=torch.tensor(retained, dtype=torch.int64),
        seed=seed,
    )

sbc_coverage

sbc_coverage(ranks: Tensor, num_draws: int, *, mass: float = 0.9, family_error: float = 0.05) -> SBCCoverage

Coverage of the central rank band against its exact null mass.

The band holds the ranks lower_rank, ..., L - lower_rank with lower_rank = floor((1 - mass) / 2 * (L + 1)), the narrowest symmetric band whose null mass is at least mass. With L finite, that exact mass, null_mass, is the reference the observed coverage is judged against, not mass itself. Each statistic's coverage gets a Clopper-Pearson interval (Clopper and Pearson, 1934, doi:10.1093/biomet/26.4.404 <https://doi.org/10.1093/biomet/26.4.404>_) at confidence 1 - family_error / num_statistics (a Bonferroni adjustment), so that under calibration every interval holds null_mass with probability at least 1 - family_error.

PARAMETER DESCRIPTION
ranks

Integer ranks, shape (num_simulations,) or (num_simulations, num_statistics), in {0, ..., num_draws}.

TYPE: Tensor

num_draws

L.

TYPE: int

mass

Requested central mass, in (0, 1).

TYPE: float DEFAULT: 0.9

family_error

Error rate shared by all statistics' intervals, in (0, 1).

TYPE: float DEFAULT: 0.05

RETURNS DESCRIPTION
SBCCoverage

The band, its null mass, and each statistic's coverage and interval.

RAISES DESCRIPTION
ValueError

If ranks is malformed, or mass or family_error lies outside (0, 1).

Source code in src/quivers/diagnostics/calibration.py
def sbc_coverage(
    ranks: torch.Tensor,
    num_draws: int,
    *,
    mass: float = 0.9,
    family_error: float = 0.05,
) -> SBCCoverage:
    """Coverage of the central rank band against its exact null mass.

    The band holds the ranks ``lower_rank, ..., L - lower_rank`` with
    ``lower_rank = floor((1 - mass) / 2 * (L + 1))``, the narrowest
    symmetric band whose null mass is at least ``mass``. With ``L``
    finite, that exact mass, ``null_mass``, is the reference the
    observed coverage is judged against, not ``mass`` itself. Each
    statistic's coverage gets a Clopper-Pearson interval (Clopper and
    Pearson, 1934, `doi:10.1093/biomet/26.4.404
    <https://doi.org/10.1093/biomet/26.4.404>`_) at confidence
    ``1 - family_error / num_statistics`` (a Bonferroni adjustment),
    so that under calibration every interval holds ``null_mass``
    with probability at least ``1 - family_error``.

    Parameters
    ----------
    ranks : torch.Tensor
        Integer ranks, shape ``(num_simulations,)`` or
        ``(num_simulations, num_statistics)``, in ``{0, ..., num_draws}``.
    num_draws : int
        ``L``.
    mass : float
        Requested central mass, in ``(0, 1)``.
    family_error : float
        Error rate shared by all statistics' intervals, in ``(0, 1)``.

    Returns
    -------
    SBCCoverage
        The band, its null mass, and each statistic's coverage and
        interval.

    Raises
    ------
    ValueError
        If ``ranks`` is malformed, or ``mass`` or ``family_error`` lies
        outside ``(0, 1)``.
    """
    table = _check_ranks(ranks, num_draws, "sbc_coverage")
    if not 0.0 < mass < 1.0:
        raise ValueError(f"sbc_coverage: mass must lie in (0, 1), got {mass}")
    if not 0.0 < family_error < 1.0:
        raise ValueError(
            f"sbc_coverage: family_error must lie in (0, 1), got {family_error}"
        )
    # The band edge is computed in exact rational arithmetic on the
    # shortest decimal spelling of ``mass``, so that a mass such as 0.8
    # with L = 9 yields the band 1..8 rather than losing a rank to
    # binary rounding.
    tail_mass = (1 - Fraction(repr(float(mass)))) / 2
    lower_rank = math.floor(tail_mass * (num_draws + 1))
    upper_rank = num_draws - lower_rank
    null_mass = (upper_rank - lower_rank + 1) / (num_draws + 1)
    trials, num_statistics = table.shape
    inside = ((table >= lower_rank) & (table <= upper_rank)).sum(dim=0).tolist()
    confidence = 1.0 - family_error / num_statistics
    bounds = [_clopper_pearson(int(k), trials, confidence) for k in inside]
    low = torch.tensor([b[0] for b in bounds], dtype=torch.float64)
    high = torch.tensor([b[1] for b in bounds], dtype=torch.float64)
    return SBCCoverage(
        mass=float(mass),
        null_mass=null_mass,
        lower_rank=lower_rank,
        upper_rank=upper_rank,
        family_error=float(family_error),
        coverage=torch.tensor(inside, dtype=torch.float64) / trials,
        lower=low,
        upper=high,
        consistent=(low <= null_mass) & (null_mass <= high),
    )

sbc_ranks

sbc_ranks(truth: Tensor, draws: Tensor, *, generator: Generator) -> Tensor

Rank true values among posterior draws, breaking ties at random.

The rank of a true value t among draws d_1, ..., d_L is #{d_l < t} + U, with U uniform on {0, ..., #{d_l = t}}. With continuous draws ties have probability zero and U = 0; with discrete or mixed quantities the random tie-break is what makes the rank uniform on {0, ..., L} under calibration.

PARAMETER DESCRIPTION
truth

True values, any shape S.

TYPE: Tensor

draws

Posterior draws, shape (L, *S).

TYPE: Tensor

generator

Source of the tie-breaking draws.

TYPE: Generator

RETURNS DESCRIPTION
Tensor

Int64 ranks, shape S, in {0, ..., L}.

RAISES DESCRIPTION
ValueError

If draws is not shaped (L, *truth.shape) with L >= 1, or either tensor holds a non-finite value.

Source code in src/quivers/diagnostics/calibration.py
def sbc_ranks(
    truth: torch.Tensor,
    draws: torch.Tensor,
    *,
    generator: torch.Generator,
) -> torch.Tensor:
    """Rank true values among posterior draws, breaking ties at random.

    The rank of a true value ``t`` among draws ``d_1, ..., d_L`` is
    ``#{d_l < t} + U``, with ``U`` uniform on ``{0, ..., #{d_l = t}}``.
    With continuous draws ties have probability zero and ``U = 0``;
    with discrete or mixed quantities the random tie-break is what
    makes the rank uniform on ``{0, ..., L}`` under calibration.

    Parameters
    ----------
    truth : torch.Tensor
        True values, any shape ``S``.
    draws : torch.Tensor
        Posterior draws, shape ``(L, *S)``.
    generator : torch.Generator
        Source of the tie-breaking draws.

    Returns
    -------
    torch.Tensor
        Int64 ranks, shape ``S``, in ``{0, ..., L}``.

    Raises
    ------
    ValueError
        If ``draws`` is not shaped ``(L, *truth.shape)`` with ``L >= 1``,
        or either tensor holds a non-finite value.
    """
    if draws.dim() != truth.dim() + 1 or tuple(draws.shape[1:]) != tuple(truth.shape):
        raise ValueError(
            f"sbc_ranks: draws must have shape (L, *truth.shape) = "
            f"(L, *{tuple(truth.shape)}); got {tuple(draws.shape)}"
        )
    if draws.shape[0] < 1:
        raise ValueError("sbc_ranks: need at least one posterior draw")
    if not bool(torch.isfinite(truth).all()) or not bool(torch.isfinite(draws).all()):
        raise ValueError("sbc_ranks: truth and draws must be finite")
    below = (draws < truth).sum(dim=0)
    ties = (draws == truth).sum(dim=0)
    uniform = torch.rand(
        truth.shape, generator=generator, dtype=torch.float64, device="cpu"
    ).to(device=truth.device)
    tie_share = torch.floor(uniform * (ties + 1).to(dtype=torch.float64))
    return (below + tie_share.to(dtype=below.dtype)).to(dtype=torch.int64)

sbc_uniformity

sbc_uniformity(ranks: Tensor, num_draws: int, *, num_reference: int = 10000, seed: int = 0) -> Tensor

Monte Carlo p-values for the uniformity of SBC ranks.

The test statistic is the smallest two-sided binomial tail probability of the rank ECDF over every threshold, the quantity behind the simultaneous ECDF bands of Säilynoja, Bürkner, and Vehtari (2022). Its null distribution is simulated from num_reference sets of ranks drawn exactly from the discrete uniform distribution on {0, ..., L}, so the test has its nominal size at any L and any number of simulations, where a continuous Kolmogorov-Smirnov test or an unequal-bin histogram would not. The p-value is (1 + #{reference <= observed}) / (num_reference + 1), a valid p-value for a Monte Carlo test.

Each column is tested separately; with several statistics, adjust for multiplicity (for instance by comparing the smallest p-value with alpha / num_statistics).

PARAMETER DESCRIPTION
ranks

Integer ranks, shape (num_simulations,) or (num_simulations, num_statistics), in {0, ..., num_draws}.

TYPE: Tensor

num_draws

L, the number of posterior draws each rank is taken against.

TYPE: int

num_reference

Monte Carlo draws of the null distribution.

TYPE: int DEFAULT: 10000

seed

Seed of the reference draws, so the p-values are reproducible.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Tensor

Float64 p-values, shape () for one-dimensional ranks and (num_statistics,) otherwise.

RAISES DESCRIPTION
ValueError

If ranks is not an integer tensor of the stated layout with values in {0, ..., num_draws}, or num_reference < 1.

Source code in src/quivers/diagnostics/calibration.py
def sbc_uniformity(
    ranks: torch.Tensor,
    num_draws: int,
    *,
    num_reference: int = 10_000,
    seed: int = 0,
) -> torch.Tensor:
    """Monte Carlo p-values for the uniformity of SBC ranks.

    The test statistic is the smallest two-sided binomial tail
    probability of the rank ECDF over every threshold, the quantity
    behind the simultaneous ECDF bands of Säilynoja, Bürkner, and
    Vehtari (2022). Its null distribution is simulated from
    ``num_reference`` sets of ranks drawn exactly from the discrete
    uniform distribution on ``{0, ..., L}``, so the test has its
    nominal size at any ``L`` and any number of simulations, where a
    continuous Kolmogorov-Smirnov test or an unequal-bin histogram
    would not. The p-value is ``(1 + #{reference <= observed}) /
    (num_reference + 1)``, a valid p-value for a Monte Carlo test.

    Each column is tested separately; with several statistics, adjust
    for multiplicity (for instance by comparing the smallest p-value
    with ``alpha / num_statistics``).

    Parameters
    ----------
    ranks : torch.Tensor
        Integer ranks, shape ``(num_simulations,)`` or
        ``(num_simulations, num_statistics)``, in ``{0, ..., num_draws}``.
    num_draws : int
        ``L``, the number of posterior draws each rank is taken
        against.
    num_reference : int
        Monte Carlo draws of the null distribution.
    seed : int
        Seed of the reference draws, so the p-values are reproducible.

    Returns
    -------
    torch.Tensor
        Float64 p-values, shape ``()`` for one-dimensional ``ranks``
        and ``(num_statistics,)`` otherwise.

    Raises
    ------
    ValueError
        If ``ranks`` is not an integer tensor of the stated layout with
        values in ``{0, ..., num_draws}``, or ``num_reference < 1``.
    """
    table = _check_ranks(ranks, num_draws, "sbc_uniformity")
    if num_reference < 1:
        raise ValueError(
            f"sbc_uniformity: num_reference must be >= 1, got {num_reference}"
        )
    num_simulations = table.shape[0]
    lower, upper = _binomial_tails(num_simulations, num_draws)
    observed = _ecdf_statistic(table, num_draws, lower, upper)
    generator = torch.Generator().manual_seed(seed)
    reference_parts: list[torch.Tensor] = []
    remaining = num_reference
    while remaining > 0:
        size = min(remaining, _REFERENCE_CHUNK)
        reference_ranks = torch.randint(
            0, num_draws + 1, (num_simulations, size), generator=generator
        )
        reference_parts.append(
            _ecdf_statistic(reference_ranks, num_draws, lower, upper)
        )
        remaining -= size
    reference = torch.cat(reference_parts)
    at_most = (reference.unsqueeze(0) <= observed.unsqueeze(1)).sum(dim=1)
    p_values = (1.0 + at_most.to(dtype=torch.float64)) / (num_reference + 1.0)
    return p_values[0] if ranks.dim() == 1 else p_values

__getattr__

__getattr__(name: str) -> _LazyExport

Bind an SBC or ArviZ-backed export on first access.

PARAMETER DESCRIPTION
name

The attribute requested.

TYPE: str

RETURNS DESCRIPTION
_LazyExport

The function, class, type alias, or statistic table the defining module binds under that name.

RAISES DESCRIPTION
AttributeError

If name is not a lazily bound export.

ModuleNotFoundError

If the diagnostics extra (ArviZ, xarray) is not installed.

Source code in src/quivers/diagnostics/__init__.py
def __getattr__(name: str) -> _LazyExport:
    """Bind an SBC or ArviZ-backed export on first access.

    Parameters
    ----------
    name : str
        The attribute requested.

    Returns
    -------
    _LazyExport
        The function, class, type alias, or statistic table the
        defining module binds under that name.

    Raises
    ------
    AttributeError
        If ``name`` is not a lazily bound export.
    ModuleNotFoundError
        If the ``diagnostics`` extra (ArviZ, xarray) is not installed.
    """
    module_name = _LAZY_EXPORTS.get(name)
    if module_name is None:
        raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
    value: _LazyExport = getattr(importlib.import_module(module_name), name)
    globals()[name] = value
    return value

Cited sources

Sean Talts, Michael Betancourt, Daniel Simpson, Aki Vehtari, and Andrew Gelman. Validating Bayesian Inference Algorithms with Simulation-Based Calibration. arXiv preprint arXiv:1804.06788, 2018. doi:10.48550/arXiv.1804.06788.

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.