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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
A retained group or stratum label; labels are never inferred from outcomes.
GridValue
¶
A scalar predictor coordinate, preserving category and integer carriers.
BridgeMethod
¶
Proposal of the bridge sampler: a fitted normal or the warp-3 transformation.
Criterion
¶
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:
|
sd
|
Posterior standard deviation over all chains and draws (one degree of freedom subtracted); NaN for a coordinate with any nonfinite draw.
TYPE:
|
probs
|
The probabilities at which
TYPE:
|
quantiles
|
Posterior quantiles at
TYPE:
|
r_hat
|
Rank-normalized split :math:
TYPE:
|
ess_bulk
|
Bulk effective sample size (see
TYPE:
|
ess_tail
|
Tail effective sample size at the 5% and 95% quantiles.
TYPE:
|
mcse_mean
|
Monte Carlo standard error of the mean.
TYPE:
|
mcse_sd
|
Monte Carlo standard error of the standard deviation.
TYPE:
|
mcse_quantiles
|
Monte Carlo standard error of each quantile in
TYPE:
|
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:
|
train
|
Original row positions supplied to the refitting procedure.
TYPE:
|
test
|
Original row positions to predict, in their original order.
TYPE:
|
omitted
|
Rows excluded from training, possibly including other group members.
TYPE:
|
seed
|
Fold-specific seed independent of evaluation order or selected folds.
TYPE:
|
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:
|
seed
|
Nonnegative seed used to derive independent refit streams.
TYPE:
|
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:
|
num_folds
property
¶
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:
|
| 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
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:
|
fit
|
Optional actual fitted result, retained only when save_fits is true.
TYPE:
|
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:
|
fold_ids
|
Evaluated folds; a subset is never extrapolated to a full result.
TYPE:
|
responses
|
Selected response names, summed within each joint posterior draw.
TYPE:
|
joint
|
Predictive unit: observation, whole fold, or group within fold.
TYPE:
|
units
|
Fold identity and original response positions for every scored unit.
TYPE:
|
log_predictive_density
|
Float64 log-mean likelihood per unit, preserving zero densities as -inf.
TYPE:
|
fits
|
Optional actual refits keyed by complete-plan fold identity.
TYPE:
|
complete
property
¶
Report whether every fold in the retained partition was evaluated.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
False for a partial fold selection, regardless of score values. |
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:
|
log_likelihood
|
Raw pointwise scores retaining observation axes.
TYPE:
|
observed_data
|
Responses corresponding to the score units.
TYPE:
|
sample_stats
|
Recorded per-draw sampler statistics, empty for variational draws.
TYPE:
|
kind
|
Provenance of the draws. Variational and independent prior layout axes never supply MCMC convergence diagnostics.
TYPE:
|
group_dims
|
Optional group-specific event dimensions, preserving observed vector events alongside their reduced pointwise likelihood axes.
TYPE:
|
coords
|
Retained coordinate labels and event dimension names, used by default for DataTree conversion and covariance. Explicit method arguments override them.
TYPE:
|
dims
|
Retained coordinate labels and event dimension names, used by default for DataTree conversion and covariance. Explicit method arguments override them.
TYPE:
|
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:
|
| 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
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:
|
ddof
|
Nonnegative degrees of freedom, strictly below the reduced count.
TYPE:
|
chainwise
|
Retain a separate matrix per chain instead of pooling chain and draw.
TYPE:
|
coords
|
Labels for named event axes and optional chain/draw axes.
TYPE:
|
dims
|
Event-axis names per site, following the DataTree convention.
TYPE:
|
| 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
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | |
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:
|
prior
|
Joint draws from the corresponding proper encompassing prior. Draw counts may differ; event shapes and devices must agree.
TYPE:
|
null
|
Finite comparison value on event axes only.
TYPE:
|
probs
|
Requested quantile probabilities in output order.
TYPE:
|
robust
|
Use median and scaled MAD instead of mean and sample SD.
TYPE:
|
point
|
Optional marginal density comparison on the same joint prior and posterior contrast; requires a checked Real result and prior draws.
TYPE:
|
name
|
Original label of the derived contrast.
TYPE:
|
dims
|
Input event-axis identities and labels, with optional sample labels. Distinct axes remain distinct even when their extents coincide.
TYPE:
|
coords
|
Input event-axis identities and labels, with optional sample labels. Distinct axes remain distinct even when their extents coincide.
TYPE:
|
| 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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
WAICResult
|
Pointwise and aggregate WAIC estimates. |
Source code in src/quivers/diagnostics/posterior.py
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:
|
dims
|
Dimension names per variable, excluding chain and draw axes.
TYPE:
|
| 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
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:
|
kind
|
Explicit provenance for external trees. QVR trees retain it in metadata; an override must agree. Chain count never determines provenance.
TYPE:
|
| 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
to_netcdf
¶
Write retained analysis through the existing DataTree NetCDF format.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Output NetCDF file. Requires the diagnostics extra.
TYPE:
|
Source code in src/quivers/diagnostics/posterior.py
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:
|
| 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
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:
|
var_name
|
Selected response; required when several responses are retained.
TYPE:
|
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:
|
seed
|
Nonnegative base seed for independent, order-invariant row refits.
TYPE:
|
pointwise
|
Retain individual ELPD values and Pareto diagnostics in the result.
TYPE:
|
| 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
loo
¶
Run optional ArviZ PSIS-LOO without recomputing model likelihoods.
| PARAMETER | DESCRIPTION |
|---|---|
var_name
|
Observation variable; required for multiple responses.
TYPE:
|
pointwise
|
Include observation-level ELPD and Pareto shape diagnostics.
TYPE:
|
| 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
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
TYPE:
|
correlation
|
Float64 square matrices, or one matrix per chain when
TYPE:
|
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:
|
dimension_names
|
Event dimension names and their original labels for each matrix column.
TYPE:
|
coordinate_labels
|
Event dimension names and their original labels for each matrix column.
TYPE:
|
variables
|
Selected variable order and corresponding original event shapes.
TYPE:
|
event_shapes
|
Selected variable order and corresponding original event shapes.
TYPE:
|
sample_shape
|
Original chain and draw counts, before the empirical reduction.
TYPE:
|
chain_labels
|
Original sample-axis labels, or their positional defaults.
TYPE:
|
draw_labels
|
Original sample-axis labels, or their positional defaults.
TYPE:
|
ddof
|
Degrees of freedom subtracted from the pooled or per-chain draw count.
TYPE:
|
chainwise
|
Whether each chain was summarized separately.
TYPE:
|
kind
|
Original draw provenance; this record adds no convergence diagnostics.
TYPE:
|
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:
|
sd
|
Mean and sample standard deviation on the site's event coordinates.
TYPE:
|
probs
|
Requested quantile probabilities.
TYPE:
|
quantiles
|
Quantiles with shape
TYPE:
|
convergence
|
Recorded-chain diagnostics, or None for variational draws.
TYPE:
|
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
TYPE:
|
p_waic
|
Expected log predictive density, effective parameter count, and
deviance-scale criterion
TYPE:
|
waic
|
Expected log predictive density, effective parameter count, and
deviance-scale criterion
TYPE:
|
se
|
Standard errors of elpd_waic and p_waic across observation units; NaN for one unit.
TYPE:
|
se_p_waic
|
Standard errors of elpd_waic and p_waic across observation units; NaN for one unit.
TYPE:
|
elpd_i
|
Pointwise ELPD and unbiased sample variance over pooled posterior draws.
TYPE:
|
variance_i
|
Pointwise ELPD and unbiased sample variance over pooled posterior draws.
TYPE:
|
warning
|
Whether any pointwise log-likelihood variance exceeds 0.4.
TYPE:
|
num_samples
|
Pooled posterior draw count and number of observation units.
TYPE:
|
num_observations
|
Pooled posterior draw count and number of observation units.
TYPE:
|
se_waic
property
¶
Standard error of the deviance-scale WAIC estimate.
| RETURNS | DESCRIPTION |
|---|---|
float
|
Twice the ELPD-scale standard error. |
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:
|
rows
|
Immutable scalar rows, ordered by effect point then conditioning row.
TYPE:
|
axes
|
Varied predictor names in Cartesian-product order.
TYPE:
|
points
|
The varied predictor coordinates at each effect point.
TYPE:
|
num_conditions
|
Explicit conditioning or empirical-reference row count per point.
TYPE:
|
marginalize
|
Reduce reference rows within each joint posterior draw when true. False retains a separate effect for every conditioning row.
TYPE:
|
weights
|
Normalized empirical-reference weights; empty for conditional effects.
TYPE:
|
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
¶
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
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
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:
|
kind
|
Actual draw provenance; a variational layout axis is not a chain.
TYPE:
|
method
|
Expected responses, linear predictors, or sampled responses.
TYPE:
|
labels
|
Optional final response-component labels, in native output order.
TYPE:
|
| 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
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:
|
draws
|
Chain/draw/point/condition/event axes, with the condition axis removed only for explicit empirical marginalization. Storage is held by identity.
TYPE:
|
kind
|
Actual draw provenance, forwarded to existing posterior diagnostics.
TYPE:
|
method
|
Response expectations, linear predictors, or response replications.
TYPE:
|
labels
|
Optional native response labels; category probabilities retain all labels.
TYPE:
|
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 |
| RAISES | DESCRIPTION |
|---|---|
(ValueError, TypeError)
|
If draws cannot be represented as real empirical samples. |
Source code in src/quivers/diagnostics/conditional.py
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:
|
| 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
PointNullAssumptions
didactic-model
¶
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:
|
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:
|
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:
|
prior_bandwidth
|
Prior bandwidth policy; None estimates it separately under bandwidth.
TYPE:
|
adjust
|
Positive multiplier on both selected bandwidths.
TYPE:
|
assumptions
|
Optional explicit declarations allowing a point-null BF01 interpretation. Without both declarations the result remains a diagnostic density ratio.
TYPE:
|
max_working_elements
|
Positive bound on each shared density estimator's kernel workspace.
TYPE:
|
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:
|
at
|
Evaluation point broadcast only over event coordinates.
TYPE:
|
log_bandwidth
|
Absolute Gaussian kernel bandwidth in log space, including adjustment. This representation remains authoritative at extreme numerical scales.
TYPE:
|
bandwidth_rule
|
TYPE:
|
adjust
|
Positive multiplier applied to the selected bandwidth.
TYPE:
|
sample_shape
|
Retained chain and draw counts. Draws are equally weighted and pooled.
TYPE:
|
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:
|
name
|
Original contrast name, named event dimensions, and original labels.
TYPE:
|
dimension_names
|
Original contrast name, named event dimensions, and original labels.
TYPE:
|
coordinate_labels
|
Original contrast name, named event dimensions, and original labels.
TYPE:
|
max_working_elements
|
Upper bound on each temporary kernel tile, excluding input storage, output coordinates, and the shared bandwidth-reduction workspace.
TYPE:
|
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; |
num_samples
property
¶
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:
|
prior
|
Marginal KDE ordinates at the same original-coordinate null.
TYPE:
|
log_ratio
|
Posterior minus prior log density. This always describes the empirical density ratio, independently of any Bayesian interpretation.
TYPE:
|
assumptions
|
Caller declarations, retained without claiming mechanical verification.
TYPE:
|
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:
|
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:
|
bindings
|
Optional expression aliases mapped to original variable labels. This
permits labels such as
TYPE:
|
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
TYPE:
|
est_error
|
Mean and sample standard deviation, or median and normal-consistent
median absolute deviation when
TYPE:
|
probs
|
Requested type-7 quantile probabilities and values with a leading probability axis. Remaining axes are the original event coordinates.
TYPE:
|
quantiles
|
Requested type-7 quantile probabilities and values with a leading probability axis. Remaining axes are the original event coordinates.
TYPE:
|
null
|
Finite comparison value broadcast only across event coordinates.
TYPE:
|
below
|
Evidence for the strict regions
TYPE:
|
above
|
Evidence for the strict regions
TYPE:
|
equal_probability
|
Descriptive equality frequencies, without a point-null Bayes factor.
TYPE:
|
prior_equal_probability
|
Descriptive equality frequencies, without a point-null Bayes factor.
TYPE:
|
name
|
Original contrast name, named event axes, and their original labels.
TYPE:
|
dimension_names
|
Original contrast name, named event axes, and their original labels.
TYPE:
|
coordinate_labels
|
Original contrast name, named event axes, and their original labels.
TYPE:
|
sample_shape
|
Original chain and draw counts; prior counts may differ.
TYPE:
|
prior_sample_shape
|
Original chain and draw counts; prior counts may differ.
TYPE:
|
chain_labels
|
Original posterior sample-axis labels or their positional defaults.
TYPE:
|
draw_labels
|
Original posterior sample-axis labels or their positional defaults.
TYPE:
|
robust
|
Whether location and dispersion use median and scaled MAD.
TYPE:
|
kind
|
Caller-supplied provenance; no convergence diagnostics are inferred.
TYPE:
|
point_evidence
|
Optional marginal posterior/prior density comparison at the null, separate from strict-region evidence and descriptive equality frequency.
TYPE:
|
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:
|
log_odds
|
Posterior region frequency and its natural-log odds. Zero and unit frequencies give negative and positive infinity, without pseudocounts.
TYPE:
|
prior_probability
|
Corresponding frequencies and log odds from jointly aligned prior draws.
TYPE:
|
prior_log_odds
|
Corresponding frequencies and log odds from jointly aligned prior draws.
TYPE:
|
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:
|
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:
|
columns
|
Statistic labels, for instance
TYPE:
|
components
|
Labels of the third axis, empty for a two-way table.
TYPE:
|
values
|
Float64 statistics in row, column, and component order.
TYPE:
|
value
¶
Read one statistic by its labels.
| PARAMETER | DESCRIPTION |
|---|---|
row
|
Row label.
TYPE:
|
column
|
Statistic label.
TYPE:
|
component
|
Component label of a three-way table; None for a two-way table.
TYPE:
|
| 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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Rows indexed by |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If a component is required, not allowed, or unknown. |
Source code in src/quivers/diagnostics/posterior_tables.py
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:
|
elpd
|
ELPD estimate and its standard error over observations.
TYPE:
|
se_elpd
|
ELPD estimate and its standard error over observations.
TYPE:
|
p
|
Effective number of parameters and its standard error.
TYPE:
|
se_p
|
Effective number of parameters and its standard error.
TYPE:
|
pointwise_elpd
|
Float64 terms per scored unit. Subsampled estimates hold exact terms on the subsample and NaN elsewhere.
TYPE:
|
pointwise_p
|
Float64 terms per scored unit. Subsampled estimates hold exact terms on the subsample and NaN elsewhere.
TYPE:
|
pareto_k
|
Pareto shape diagnostic per unit for PSIS estimates (NaN where not computed), None for WAIC and k-fold.
TYPE:
|
num_samples
|
Pooled posterior draws behind the estimate.
TYPE:
|
good_k
|
Pareto shape threshold,
TYPE:
|
responses
|
Scored response names.
TYPE:
|
response_hash
|
Hash of the scored responses, checked before comparisons.
TYPE:
|
moment_matched
|
Units whose terms were improved by moment matching.
TYPE:
|
refitted
|
Units whose terms come from exact refits.
TYPE:
|
subsample
|
Units scored exactly by subsampled PSIS-LOO.
TYPE:
|
subsampling_se
|
Standard errors of the ELPD and of
TYPE:
|
subsampling_se_p
|
Standard errors of the ELPD and of
TYPE:
|
approximation
|
Approximate pointwise ELPD of every unit for subsampled PSIS-LOO.
TYPE:
|
approximation_method
|
TYPE:
|
folds
|
Zero-based fold of every observation for k-fold estimates.
TYPE:
|
joint
|
k-fold predictive unit:
TYPE:
|
num_observations
property
¶
Number of scored units.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Length of the pointwise terms. |
ic
property
¶
Deviance-scale criterion -2 * elpd (looic, waic, kfoldic).
| RETURNS | DESCRIPTION |
|---|---|
float
|
The information criterion. |
se_ic
property
¶
Standard error of the deviance-scale criterion.
| RETURNS | DESCRIPTION |
|---|---|
float
|
|
estimates
¶
estimates() -> SummaryTable
Return the loo package's estimates table.
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable
|
Rows |
Source code in src/quivers/diagnostics/elpd.py
bad_observations
¶
List units whose Pareto shape exceeds a threshold.
| PARAMETER | DESCRIPTION |
|---|---|
threshold
|
Shape threshold; None uses
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[int, ...]
|
Zero-based unit positions, as loo's |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the estimate has no Pareto diagnostics. |
Source code in src/quivers/diagnostics/elpd.py
to_arviz
¶
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
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 (
TYPE:
|
pareto_k
|
Function-specific Pareto shape per unit (and component).
TYPE:
|
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
TYPE:
|
pareto_k
|
Pareto shape diagnostic per unit [@vehtari2024psis].
TYPE:
|
r_eff
|
Relative efficiency used for the tail length.
TYPE:
|
good_k
|
Threshold
TYPE:
|
BridgeRelativeError
didactic-model
¶
Bases: ValueModel
Approximate error of one "normal" bridge estimate.
| PARAMETER | DESCRIPTION |
|---|---|
re2
|
Approximate relative mean-squared error of the marginal likelihood
estimate, :math:
TYPE:
|
cv
|
Coefficient of variation, the square root of
TYPE:
|
percentage
property
¶
Return the coefficient of variation as a percentage label.
| RETURNS | DESCRIPTION |
|---|---|
str
|
|
BridgeRepetitionSpread
didactic-model
¶
Bases: ValueModel
Spread of the log marginal likelihood over independent repetitions.
| PARAMETER | DESCRIPTION |
|---|---|
min
|
Smallest and largest log marginal likelihood.
TYPE:
|
max
|
Smallest and largest log marginal likelihood.
TYPE:
|
iqr
|
Interquartile range (R
TYPE:
|
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:
|
niter
|
Fixed-point iterations of each repetition, counting a restart's
iterations after the
TYPE:
|
method
|
Proposal used.
TYPE:
|
neff
|
Effective sample size of the iteration draws used in
TYPE:
|
q11
|
Log unnormalized posterior at the iteration draws
TYPE:
|
q12
|
Log proposal density at the iteration draws
TYPE:
|
q21
|
Log unnormalized posterior at each repetition's proposal draws
TYPE:
|
q22
|
Log proposal density at each repetition's proposal draws
TYPE:
|
log_det_warp
|
Log determinant of the warp's Cholesky factor; zero for
TYPE:
|
nonfinite_posterior
|
Iteration draws whose log posterior was
TYPE:
|
nonfinite_proposal
|
Proposal draws whose log posterior was
TYPE:
|
logml
property
¶
Return the log marginal likelihood (median over repetitions).
| RETURNS | DESCRIPTION |
|---|---|
float
|
The estimate, as |
repetitions
property
¶
Return the number of independent proposal draws.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Repetition count. |
error_measures
¶
error_measures() -> BridgeRelativeError | BridgeRepetitionSpread
Return the estimator's approximate error, as error_measures.
| RETURNS | DESCRIPTION |
|---|---|
BridgeRelativeError or BridgeRepetitionSpread
|
The relative mean-squared error of one |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
For one |
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
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:
|
null_mass |
The band's exact probability under uniform ranks,
TYPE:
|
lower_rank |
The smallest rank in the band.
TYPE:
|
upper_rank |
The largest rank in the band.
TYPE:
|
family_error |
The error rate shared by all statistics' intervals; each
interval has confidence
TYPE:
|
coverage |
Float64, shape
TYPE:
|
lower |
Float64, shape
TYPE:
|
upper |
Float64, shape
TYPE:
|
consistent |
Bool, shape
TYPE:
|
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
TYPE:
|
num_draws |
TYPE:
|
statistic_names |
The name of each column of
TYPE:
|
truths |
Float64, shape
TYPE:
|
thinning |
Int64, shape
TYPE:
|
retained |
Int64, shape
TYPE:
|
seed |
The seed that reproduces the run.
TYPE:
|
ess
¶
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 atproband1 - prob(probdefaults 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 theprobquantile;probis required.
| PARAMETER | DESCRIPTION |
|---|---|
draws
|
Draws laid out
TYPE:
|
method
|
Which effective sample size to compute.
TYPE:
|
prob
|
The tail probability for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Float64 tensor of shape |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
ValueError
|
If |
Source code in src/quivers/diagnostics/convergence.py
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);probis required.
| PARAMETER | DESCRIPTION |
|---|---|
draws
|
Draws laid out
TYPE:
|
method
|
Which summary's standard error to compute.
TYPE:
|
prob
|
The quantile's probability for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Float64 tensor of shape |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
ValueError
|
If |
Source code in src/quivers/diagnostics/convergence.py
rhat
¶
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
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Float64 tensor of shape |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
ValueError
|
If |
Source code in src/quivers/diagnostics/convergence.py
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
TYPE:
|
probs
|
Probabilities of the quantiles to report, each in
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, ConvergenceSummary]
|
One summary per site, in the order of |
| 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 |
Source code in src/quivers/diagnostics/convergence.py
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:
|
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:
|
groups
|
Indivisible units assigned wholly to one fold.
TYPE:
|
strata
|
Labels balanced across folds. Every indivisible group must have one stratum; small strata need not occur in every fold.
TYPE:
|
seed
|
Local random stream; the caller's RNG is preserved.
TYPE:
|
| 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
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | |
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:
|
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:
|
fold_ids
|
Nonempty unique subset of complete-plan folds, or all folds.
TYPE:
|
responses
|
Explicit joint response selection; required with multiple scored names.
TYPE:
|
joint
|
Sum row/response log likelihoods within a draw before log-mean-exp.
TYPE:
|
groups
|
Original row labels for joint group-within-fold prediction units.
TYPE:
|
save_fits
|
Retain actual callback results and their omitted-row metadata in plan.
TYPE:
|
| 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
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 | |
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.
TYPE:
|
observed_data
|
Site name to observed tensor (the original data used at
fit time). Becomes the
TYPE:
|
posterior_predictive
|
Site name to posterior-predictive draws of shape
TYPE:
|
log_likelihood
|
Site name to per-observation log-likelihood of shape
TYPE:
|
constant_data
|
Site name to fixed covariate tensor (e.g. design matrix).
Becomes the
TYPE:
|
coords
|
Coordinate values per named axis (e.g.
TYPE:
|
dims
|
Per-site axis names (e.g.
TYPE:
|
| 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
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 byto_datatreewith its chain and draw semantics; - a mapping of site name to tensor (SVI or Predictive draws),
converted by
to_datatree_from_sviwith a single pseudo-chain; - a tuple
(samples, log_densities), converted like the mapping form withsample_stats/lppopulated 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:
|
observed_data
|
Site name to observed tensor; becomes
TYPE:
|
posterior_predictive
|
Site name to posterior-predictive draws; becomes
TYPE:
|
log_likelihood
|
Site name to per-observation log-likelihood; becomes
TYPE:
|
constant_data
|
Site name to fixed covariate tensor; becomes
TYPE:
|
coords
|
Coordinate values per named axis, forwarded to ArviZ.
TYPE:
|
dims
|
Per-site axis names, forwarded to ArviZ.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataTree
|
The ArviZ DataTree of the fit. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
Source code in src/quivers/diagnostics/arviz_io.py
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 | |
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
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataTree
|
A DataTree with the |
Source code in src/quivers/diagnostics/arviz_io.py
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
TYPE:
|
log_densities
|
Per-draw log densities; becomes
TYPE:
|
observed_data
|
Site name to observed tensor; becomes
TYPE:
|
posterior_predictive
|
Site name to posterior-predictive draws of shape
TYPE:
|
log_likelihood
|
Site name to per-observation log-likelihood of shape
TYPE:
|
constant_data
|
Site name to fixed covariate tensor; becomes
TYPE:
|
coords
|
Coordinate values per named axis, forwarded to ArviZ.
TYPE:
|
dims
|
Per-site axis names, forwarded to ArviZ.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataTree
|
The ArviZ DataTree, with a chain dimension of size 1. |
Source code in src/quivers/diagnostics/arviz_io.py
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 | |
waic
¶
waic(log_likelihood: Tensor) -> WAICResult
Estimate WAIC from raw conditional log likelihoods.
| PARAMETER | DESCRIPTION |
|---|---|
log_likelihood
|
Finite real scores with shape
TYPE:
|
| 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
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:
|
observed
|
Responses shaped row x event axes. Their centered residual variance supplies the denominator's unexplained component.
TYPE:
|
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:
|
| 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
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
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:
|
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:
|
marginalize
|
Average reference-row predictions within each posterior draw. False conditions separately on each supplied row and never averages them.
TYPE:
|
weights
|
Optional finite nonnegative reference-population weights, normalized only for empirical averaging. These are not likelihood weights.
TYPE:
|
max_rows
|
Positive upper bound on points times reference rows, checked before Cartesian allocation. Larger requests require an explicit larger budget.
TYPE:
|
| 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
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 | |
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
TYPE:
|
at
|
Finite evaluation point, broadcasting only over event axes.
TYPE:
|
bandwidth
|
TYPE:
|
adjust
|
Positive finite multiplier applied to the selected bandwidth.
TYPE:
|
name
|
Original contrast name, retained without parsing.
TYPE:
|
dims
|
Event dimension names using the retained-analysis coordinate policy.
TYPE:
|
coords
|
Original labels of event dimensions.
TYPE:
|
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:
|
| 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
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:
|
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:
|
null
|
Finite scalar or event-shaped evaluation point.
TYPE:
|
bandwidth
|
Posterior bandwidth rule or positive absolute value.
TYPE:
|
prior_bandwidth
|
Prior bandwidth; None applies the same policy separately to each input. Automatic rules use each distribution's own count and scale.
TYPE:
|
adjust
|
Positive multiplier applied to both selected bandwidths.
TYPE:
|
assumptions
|
Explicit declarations enabling a point-null BF01 interpretation when both are true. These declarations cannot be verified from sample arrays.
TYPE:
|
name
|
Original derived-contrast label.
TYPE:
|
dims
|
Shared event dimensions and original labels.
TYPE:
|
coords
|
Shared event dimensions and original labels.
TYPE:
|
max_working_elements
|
Positive kernel-tile element bound, as for log_density_ordinate.
TYPE:
|
| 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
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 | |
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
TYPE:
|
null
|
Finite null value, scalar or broadcastable over event axes only.
TYPE:
|
probs
|
Quantile probabilities strictly between zero and one, in requested order.
TYPE:
|
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:
|
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:
|
point
|
Explicit marginal point-density request. Requires finite continuous floating posterior and prior draws; the two strict regions are unchanged.
TYPE:
|
name
|
Nonempty contrast name, retained without parsing.
TYPE:
|
kind
|
Explicit provenance of the supplied contrast draws.
TYPE:
|
dims
|
Named event axes, using the shared retained-analysis coordinate policy.
TYPE:
|
coords
|
Labels for event, chain, or draw axes; labels retain their original values.
TYPE:
|
| 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
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | |
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:
|
method
|
Model-weight estimator. Default "stacking" follows Yao, Vehtari, Simpson, and Gelman (2018) Yao et al. (2018).
TYPE:
|
var_name
|
Observed variable in the log-likelihood group; required when a fit carries multiple log-likelihood variables.
TYPE:
|
reference
|
Fit name used as the reference for ELPD differences. Default is the top-ranked model.
TYPE:
|
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:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
ArviZ ranking table with one row per model. |
Source code in src/quivers/diagnostics/comparison.py
loo
¶
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:
|
pointwise
|
Whether to include one elpd_i and pareto_k value per observation. None uses ArviZ's configured default.
TYPE:
|
var_name
|
Log-likelihood variable to evaluate. Required when the log-likelihood group contains multiple variables.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDData
|
ArviZ's canonical PSIS-LOO result. |
Source code in src/quivers/diagnostics/comparison.py
loo_pit
¶
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
TYPE:
|
observed_name
|
Name of the observed site, which must appear in those groups.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dataset
|
The LOO-PIT value at each observed data point, under the
variable |
Source code in src/quivers/diagnostics/predictive_checks.py
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
TYPE:
|
observed_name
|
Name of the observed site (must appear in both groups).
TYPE:
|
statistic
|
Either a key into
TYPE:
|
by
|
If given, computes the statistic per group along the named
dim (e.g.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Mapping[str, float or ndarray]
|
|
Source code in src/quivers/diagnostics/predictive_checks.py
km_data
¶
Return Kaplan-Meier curves of observed and replicated data (ppc_km_overlay).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Observed times.
TYPE:
|
yrep
|
Draws
TYPE:
|
status
|
Event indicator of each observed time (one event, zero right censored).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a status is not zero or one. |
Source code in src/quivers/diagnostics/_ppc_data.py
loo_pit_values
¶
Return LOO-PIT values from PSIS log weights (rstantools loo_pit).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Observed values.
TYPE:
|
yrep
|
Draws
TYPE:
|
log_weights
|
Normalized PSIS log weights
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
:math: |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the weights do not match the draws. |
Source code in src/quivers/diagnostics/_ppc_data.py
pit_ecdf_data
¶
Return PIT values' empirical CDF on a uniform grid (ppc_pit_ecdf).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Observed values.
TYPE:
|
yrep
|
Draws
TYPE:
|
K
|
Grid size;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
Source code in src/quivers/diagnostics/_ppc_data.py
pit_values
¶
Return posterior predictive PIT values, as bayesplot ppc_pit_ecdf.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Observed values.
TYPE:
|
yrep
|
Draws
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
The share of draws with :math: |
Source code in src/quivers/diagnostics/_ppc_data.py
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:
|
yrep
|
Draws
TYPE:
|
group
|
Group label per observation.
TYPE:
|
prob
|
Interval probability of the replicated counts.
TYPE:
|
freq
|
Counts; False gives proportions within each data set and group.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If values are not whole numbers. |
Source code in src/quivers/diagnostics/_ppc_data.py
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
TYPE:
|
yrep
|
Draws
TYPE:
|
group
|
Group label per observation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Replicated rows, replicate fastest, then the observed rows, with
|
Source code in src/quivers/diagnostics/_ppc_data.py
ppc_error_binned_data
¶
Return binned errors per draw (ppc_error_binned).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Observed values.
TYPE:
|
epred
|
Expected values
TYPE:
|
bins
|
Bins; bayesplot's default by sample size.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
Source code in src/quivers/diagnostics/_ppc_data.py
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:
|
yrep
|
Draws
TYPE:
|
group
|
Group label per observation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
Source code in src/quivers/diagnostics/_ppc_data.py
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
TYPE:
|
yrep
|
Draws
TYPE:
|
x
|
Horizontal coordinate; the observation index by default.
TYPE:
|
group
|
Group label per observation.
TYPE:
|
prob
|
Inner and outer interval probabilities.
TYPE:
|
prob_outer
|
Inner and outer interval probabilities.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the probabilities are outside (0, 1]. |
Source code in src/quivers/diagnostics/_ppc_data.py
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:
|
yrep
|
Draws
TYPE:
|
style
|
Rootogram style [@kleiber2016visualizing].
TYPE:
|
prob
|
Interval probability of the replicated square-root frequencies.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If values are not nonnegative whole numbers or the style is unknown. |
Source code in src/quivers/diagnostics/_ppc_data.py
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
TYPE:
|
yrep
|
Draws
TYPE:
|
group
|
Group label per observation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
Source code in src/quivers/diagnostics/_ppc_data.py
ppc_scatter_data
¶
Return observed values against each replicate (ppc_scatter_data).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Observed values.
TYPE:
|
yrep
|
Draws
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
Source code in src/quivers/diagnostics/_ppc_data.py
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
TYPE:
|
yrep
|
Draws
TYPE:
|
stat
|
One statistic, or two for
TYPE:
|
group
|
Group label per observation; statistics are computed within groups.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
|
Source code in src/quivers/diagnostics/_ppc_data.py
predictive_errors
¶
Return predictive errors y - yrep (rstantools predictive_error).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Observed values.
TYPE:
|
yrep
|
Draws
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Errors |
Source code in src/quivers/diagnostics/_ppc_data.py
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 |
prob
|
Central probability mass, 0.95 by default as in brms.
TYPE:
|
labels
|
Row labels of a positional tensor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable
|
Columns |
Source code in src/quivers/diagnostics/posterior_tables.py
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 |
probs
|
Quantile probabilities strictly between zero and one.
TYPE:
|
robust
|
Report the median and R's
TYPE:
|
labels
|
Row labels of a positional tensor; 0-based positions by default.
TYPE:
|
components
|
Labels of a positional tensor's component axis; 0-based by default.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable
|
Columns |
| 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
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
TYPE:
|
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
TYPE:
|
labels
|
Row labels; 0-based positions by default.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable
|
Columns |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If draws contain a value outside the given levels. |
Source code in src/quivers/diagnostics/posterior_tables.py
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
TYPE:
|
prob
|
Central probability mass, 0.9 by default as in brms.
TYPE:
|
labels
|
Row labels; 0-based positions by default.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable
|
Columns |
Source code in src/quivers/diagnostics/posterior_tables.py
ar_spectrum0
¶
Return the AR spectral density at frequency zero, as coda spectrum0.ar.
| PARAMETER | DESCRIPTION |
|---|---|
series
|
One real series of length at least two.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
|
| 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
bayes_factor_from_logml
¶
Return the Bayes factor of model 1 over model 2.
| PARAMETER | DESCRIPTION |
|---|---|
logml1
|
Log marginal likelihoods.
TYPE:
|
logml2
|
Log marginal likelihoods.
TYPE:
|
log
|
Return the log Bayes factor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
:math: |
Source code in src/quivers/diagnostics/bridge.py
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
TYPE:
|
chains
|
Unconstrained posterior draws
TYPE:
|
method
|
Proposal: a normal with the moments of the fitting half, or the standard normal after the warp-3 transformation.
TYPE:
|
repetitions
|
Independent proposal draws, each giving one estimate.
TYPE:
|
use_neff
|
Use the median coda effective size of the iteration draws in
TYPE:
|
maxiter
|
Iteration bound of the fixed-point scheme.
TYPE:
|
seed
|
Seed of the proposal draws.
TYPE:
|
| 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
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 | |
effective_size
¶
Return coda effectiveSize of an mcmc.list.
| PARAMETER | DESCRIPTION |
|---|---|
chains
|
One
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Per-parameter effective sizes summed over chains, each chain
contributing |
Source code in src/quivers/diagnostics/bridge.py
near_pd
¶
Return the nearest positive-definite matrix, as Matrix nearPD.
| PARAMETER | DESCRIPTION |
|---|---|
matrix
|
Square real matrix.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Higham's alternating projection with Dykstra's correction
( |
| 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
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:
|
prior_prob
|
Prior model probabilities in the order of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float]
|
:math: |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If fewer than two models are given, prior probabilities do not match
the models or do not sum to one (R |
Source code in src/quivers/diagnostics/bridge.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable
|
Rows ordered from best to worst; columns |
| 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
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 | |
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:
|
log_likelihood
|
The scores
TYPE:
|
criterion
|
Estimator label.
TYPE:
|
responses
|
Scored response names.
TYPE:
|
hashed
|
Response hash.
TYPE:
|
moment_matched
|
Units changed by moment matching or exact refits.
TYPE:
|
refitted
|
Units changed by moment matching or exact refits.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
The estimate with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the result has no pointwise terms. |
Source code in src/quivers/diagnostics/elpd.py
good_k
¶
Return the sample-size dependent Pareto shape threshold.
| PARAMETER | DESCRIPTION |
|---|---|
num_samples
|
Pooled draw count S.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
|
Source code in src/quivers/diagnostics/elpd.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float]
|
Normalized weights in input order. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If criteria differ. |
Source code in src/quivers/diagnostics/elpd.py
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:
|
lpd
|
Full-data log predictive density of the same units.
TYPE:
|
num_samples
|
Pooled draws of the full-data fit.
TYPE:
|
folds
|
Zero-based fold of every observation.
TYPE:
|
joint
|
Predictive unit.
TYPE:
|
responses
|
Scored response names.
TYPE:
|
hashed
|
Response hash.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
|
Source code in src/quivers/diagnostics/elpd.py
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
TYPE:
|
weights
|
Leave-one-out weights of the same units.
TYPE:
|
kind
|
Weighted statistic. The weighted variance divides by
TYPE:
|
probs
|
Probabilities for
TYPE:
|
labels
|
Unit and component labels; 0-based positions by default.
TYPE:
|
components
|
Unit and component labels; 0-based positions by default.
TYPE:
|
| 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
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 | |
loo_r2_draws
¶
Draw brms's leave-one-out R-squared by the Bayesian bootstrap.
| PARAMETER | DESCRIPTION |
|---|---|
observed
|
Observed responses
TYPE:
|
loo_mean
|
Leave-one-out expected responses
TYPE:
|
generator
|
Stream of the Dirichlet weights.
TYPE:
|
num_draws
|
Bootstrap draws, the posterior draw count S in brms.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If fewer than two units are given. |
Source code in src/quivers/diagnostics/elpd.py
pointwise_lpd
¶
Return the log pointwise predictive density over pooled draws.
| PARAMETER | DESCRIPTION |
|---|---|
log_likelihood
|
Scores
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Float64 |
Source code in src/quivers/diagnostics/elpd.py
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
TYPE:
|
r_eff
|
Relative efficiency of the draws, one for independent draws.
TYPE:
|
| 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
require_psis_draws
¶
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:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If fewer than 25 draws are pooled. |
Source code in src/quivers/diagnostics/elpd.py
require_scores
¶
require_scores(log_likelihood: Tensor, *, criterion: str) -> None
Refuse an importance-sampling criterion over missing pointwise scores.
| PARAMETER | DESCRIPTION |
|---|---|
log_likelihood
|
Scores
TYPE:
|
criterion
|
Criterion named in the error.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a score is missing ( |
Source code in src/quivers/diagnostics/elpd.py
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:
|
| 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
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:
|
method
|
Stacking of predictive distributions [@yao2018stacking] or pseudo-BMA weights.
TYPE:
|
bayesian_bootstrap
|
Regularize pseudo-BMA weights with the Bayesian bootstrap (loo's
TYPE:
|
seed
|
Seed of the Bayesian bootstrap.
TYPE:
|
| 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
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,
TYPE:
|
approximation
|
Approximate terms of every unit,
TYPE:
|
subsample
|
Zero-based subsample units, aligned with
TYPE:
|
lpd
|
Log predictive densities of the subsample,
TYPE:
|
pareto_k
|
Pareto shapes of the subsample,
TYPE:
|
num_samples
|
Pooled draw count.
TYPE:
|
responses
|
Scored response names.
TYPE:
|
hashed
|
Response hash.
TYPE:
|
method
|
Approximation behind
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
The subsampled estimate with total and subsampling-only standard
errors; |
| 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
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 | |
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
TYPE:
|
responses
|
Scored response names.
TYPE:
|
hashed
|
Response hash.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
|
Source code in src/quivers/diagnostics/elpd.py
weighted_quantile
¶
Interpolate quantiles of a weighted sample as loo's E_loo.
| PARAMETER | DESCRIPTION |
|---|---|
values
|
Draws
TYPE:
|
weights
|
Nonnegative weights
TYPE:
|
probs
|
Probabilities in the open unit interval.
TYPE:
|
| 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
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
- runs
modelforward at the one-row inputxand the hostdata, drawing every latent from its prior and every site inobserved_namesfrom the model given those latents; - calls
fit(observations, fit_seed)with the simulated observations merged withdata, and reads its posterior draws (seeSBCPosterior); - 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:
|
x
|
A one-row program input: one run, as MCMC and the guides take.
TYPE:
|
fit
|
The inference procedure:
TYPE:
|
observed_names
|
The sites treated as data.
TYPE:
|
num_simulations
|
Number of simulations.
TYPE:
|
seed
|
Seed of the whole procedure.
TYPE:
|
data
|
Host data the program reads by name (covariates), held fixed.
TYPE:
|
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,
TYPE:
|
thin
|
TYPE:
|
num_guide_draws
|
Draws taken from a fit that returns a
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SBCResult
|
The ranks and the bookkeeping that reproduces them. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |
Source code in src/quivers/diagnostics/calibration.py
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 | |
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
TYPE:
|
num_draws
|
TYPE:
|
mass
|
Requested central mass, in
TYPE:
|
family_error
|
Error rate shared by all statistics' intervals, in
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SBCCoverage
|
The band, its null mass, and each statistic's coverage and interval. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/diagnostics/calibration.py
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 | |
sbc_ranks
¶
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
TYPE:
|
draws
|
Posterior draws, shape
TYPE:
|
generator
|
Source of the tie-breaking draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Int64 ranks, shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/diagnostics/calibration.py
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
TYPE:
|
num_draws
|
TYPE:
|
num_reference
|
Monte Carlo draws of the null distribution.
TYPE:
|
seed
|
Seed of the reference draws, so the p-values are reproducible.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Float64 p-values, shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/diagnostics/calibration.py
__getattr__
¶
Bind an SBC or ArviZ-backed export on first access.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
The attribute requested.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
_LazyExport
|
The function, class, type alias, or statistic table the defining module binds under that name. |
| RAISES | DESCRIPTION |
|---|---|
AttributeError
|
If |
ModuleNotFoundError
|
If the |
Source code in src/quivers/diagnostics/__init__.py
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.