Skip to content

quivers.formulas fit entry point

fit (one-line fit) takes a formula, data, a family, and an inference configuration and returns a BayesianFit, which gives posterior summaries, predictive draws, and diagnostics. Posterior draws carry the uncertainty in the coefficients, and predictive draws add the variation of the response given those coefficients. formula_to_qvr emits the QVR source of a formula. get_prior returns the effective named priors, including autoscaled defaults, without running inference. Unknown or unused prior overrides raise ValueError before fitting. The three entry points also accept an authored QVR program and a mapping of formulas on its parameters. BayesianFit.update(data=None, **overrides) reuses a retained fitting recipe with the original raw dataframe and all canonical fit settings. It fits a fresh posterior, with isolated initial neural state and explicit clone/reference data ownership. Method changes clear inherited inactive budgets; explicit invalid overrides still fail. See updating and refitting for data ownership and adapters to the shared cross-validation runner. BayesianFit.refit_callback(method_factory=..., num_samples=...) gives that runner with fresh formula fits and raw held-out likelihoods. Fold coordinates address retained included rows; the adapter maps them to original rows and partitions retained neural inputs by the same positions. Its method factory owns fitting seeds and budgets, while prediction keywords retain the existing group-selection and new-level policies. See the formula partition example. sample_prior="yes" retains an independent prior stream without changing the fitted posterior; sample_prior="only" disables observation likelihoods during the selected inference method and retains priors and explicit score potentials. prior_draws and prior_view reuse the retained conditional laws, data-dependent priors, encodings, and existing prediction/likelihood methods. Independent samples have no MCMC convergence statistics. See prior-only fitting for seed and factor-conditioned sampling semantics. BayesianFit.evidence(sampler) applies the existing SMC driver to the retained program and training data, without recompilation or conversion of the fitted posterior. It returns SMCResult, including particles, the temperature ladder, and log_evidence. For instance:

import pandas as pd
from quivers.formulas import fit
from quivers.inference import SMC
from quivers.inference.mcmc import MetropolisKernel, RandomWalkProposal

fitted = fit(
    "y ~ 1", data=pd.DataFrame({"y": [0.2, 0.7, 1.1]}),
    fixed_parameters={"sigma": 1.0}, method="svi", num_steps=1, seed=7,
)
evidence = fitted.evidence(SMC(
    MetropolisKernel(RandomWalkProposal(0.5)), num_particles=128,
    num_mcmc_steps=2, num_pilot_steps=0, seed=11,
))
assert evidence.num_particles == 128

This is a separate inference run whose budget and seed belong to sampler. Its log normalizer is ordinary marginal data evidence when the retained prior and likelihood form a normalized sampling model. Non-unit response weights yield the powered target's log normalizer. SMC refuses an explicit prior potential with unknown mass, an opaque joint override that prevents role decomposition, and an active subsampling handler. fixed_parameters={"quantile": 0.9} performs asymmetric Laplace quantile regression at a specified quantile, and other auxiliary parameters can likewise be held fixed. All three entry points accept distributional={"sigma": "~ z"} to give an auxiliary parameter its own predictor; distributional regression describes coefficient names, priors, and group coding.

BayesianFit.draws preserves chain and draw axes. fixed_effects, random_effects, and coefficients expose population and group coefficients with retained labels. hypothesis("x - Intercept") evaluates a checked QVR contrast over the same population coefficients. parameter selects a distributional or nonlinear predictor, class_ selects an emitted parameter role, and scope="ranef" or "coef" with group retains the level axis of adjustments or combined coefficients. class_=None uses exact latent site names. prior=True evaluates the contrast on the corresponding joint prior stream, yielding region evidence in addition to posterior odds. It does not estimate point-null density evidence. See formula hypotheses and contrast summaries. An explicit point=PointNullSpec(...) with prior=True also returns point_evidence from those same joint streams. Its marginal density ratio, optional declared-assumption point Bayes factor, bandwidths, and numerical limits follow the shared density interface.

posterior_linpred, posterior_epred, and posterior_predict replay native fitted bindings on the training rows or on a given new_data frame. The first two expose predictors and response expectations; posterior_predict independently samples responses conditional on each posterior draw. Its tensor has shape (chain, draw, row) followed by any response event dimensions; categorical and ordinal responses use integer codes in category_labels order. posterior_thresholds additionally exposes effective ordinal cutpoints as (chain, draw, row, threshold), labeled by adjacent category pairs in threshold_labels. It excludes the proportional population predictor and discrimination. All four accept keyword-only new_data and predictor_data. New rows reuse fitted transforms, contrasts, and known group levels. Ordinary categorical predictor levels remain strict; allow_new_levels=True admits new or missing grouping identities. sample_new_levels selects per-draw donors ("uncertainty"), one donor index across draws ("old_levels"), or the fitted Normal/LKJ group law ("gaussian"). A grouped Cox baseline replays its Dirichlet profile law under this policy. Donors are joint across slopes, auxiliary predictors, and baseline profiles. For constrained cumulative category-specific new-group profiles or effects, explicit "feasible_uncertainty" and "feasible_gaussian" condition the joint proposal on requested-row ordering. They retain all posterior draws and refuse after 1,024 failed proposals. Fitted cutpoints are replayed without reconstruction from fresh rows or selected effects; crossing profiles fail with located diagnostics. re_formula=None retains fitted varying effects, "~0" sets them to zero, and a one-sided group formula selects fitted terms. Unsupported selectors fail explicitly. Response and likelihood-weight columns are unnecessary, but retained covariates, offsets, exposures, auxiliary predictors, and per-row trials must be given, together with retained measurement-error and truncation columns when those sampling-law roles use data columns. Censoring and training subset columns are unnecessary. Neural fits require explicit new predictor_data. Training predictions reuse the compiled program; new rows specialize one program per request. Both fill one preallocated output tensor across draws. The posterior workflow describes shapes, labels, link scales, and expectations. The new-row workflow gives an executable example and the retained evaluator's serialization boundary.

BayesianFit.bayes_r2 reuses these prediction bindings to report per-draw regression variance ratios on the response scale. method="model" uses average native conditional variance; method="residual" uses actual-minus-expected response variance. Auto uses model variances for ordinary Gaussian/Bernoulli responses and residual variances otherwise; explicit observations select the residual definition. New-data residual calculations evaluate the fitted response transform or accept observed directly. Censoring bounds cannot substitute for actual responses. Ordered categories use their retained integer scores, while unordered categories require a chosen metric. See regression variance ratios for the executable workflow and the pure diagnostic for scaling, event axes, and degenerate cases.

fit, formula_to_qvr, and get_prior accept weights="column" for observation-only likelihood weights. The column is retained on the parsed formula; posterior predictors use the unweighted response law at each draw. See likelihood weights.

Both reparameterize="centered" and "noncentered" support correlated blocks with mixed scalar, transition, and response-component widths. Coefficient labels and inspection methods retain their meanings across coordinates. Correlated centered blocks have a joint group_coefficients_<block> site; centered grouped threshold log slacks use cutpoint_log_spacing_value. These are natural-scale site names for initial_values; the corresponding noncentered sites contain innovations. Gaussian prediction prepares the requested group sites' upstream prior program once per request and replays their conditional law at each draw, without executing unrelated downstream response computations.

Nonlinear predictors

nonlinear maps parameter names to one-sided additive formulas or NonlinearExpression values. With the argument present, the main right side is a deterministic QVR expression; distributional expressions give other family outputs on their link scales. The graph is dependency-checked, retains each additive leaf's fitted design, and applies each output's inverse link once. Component mappings use explicit free-coordinate labels. The nonlinear workflow gives an executable fit and explains coefficient names and default priors.

NonlinearExpression didactic-model

NonlinearExpression(*, expression: str | dict[str | int, str] = field(opaque=True, extras=OPAQUE_BY_VALUE), syntax: Literal['qvr', 'r'] = 'qvr')

Bases: ValueModel

A deterministic QVR value expression, rather than an additive design.

PARAMETER DESCRIPTION
expression

Scalar expression or explicit component-label mapping using named nonlinear parameters and numeric data columns. Distributional expressions describe the family's link scale; inverse links are applied once, after evaluation. Intermediate nonlinear parameters have the identity link.

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

syntax

Language of the expression text. "r" reads an R expression over Stan's functions, as brms nlf() takes, with numeric data read as doubles.

TYPE: ('qvr', 'r') DEFAULT: "qvr"

ComponentExpression didactic-model

ComponentExpression(*, components: tuple[str, ...], values: tuple[LetExprNode, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

An explicitly labelled vector value whose coordinates keep nominal order.

PARAMETER DESCRIPTION
components

Authored coordinate labels, never inferred from extent equality.

TYPE: tuple[str, ...]

values

Scalar expressions aligned to those coordinate labels.

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

at

at(component: str) -> LetExprNode

Return the expression of one coordinate.

PARAMETER DESCRIPTION
component

Coordinate label.

TYPE: str

RETURNS DESCRIPTION
LetExprNode

Scalar expression of the coordinate.

RAISES DESCRIPTION
ValueError

If the value has no such coordinate.

Source code in src/quivers/formulas/_predictor_graph.py
def at(self, component: str) -> LetExprNode:
    """Return the expression of one coordinate.

    Parameters
    ----------
    component : str
        Coordinate label.

    Returns
    -------
    LetExprNode
        Scalar expression of the coordinate.

    Raises
    ------
    ValueError
        If the value has no such coordinate.
    """
    if component not in self.components:
        raise ValueError(
            f"the nonlinear vector {self.components} has no component {component!r}"
        )
    return self.values[self.components.index(component)]

PredictorGraph didactic-model

PredictorGraph(*, leaves: dict[str, Formula] = field(opaque=True, extras=OPAQUE_BY_VALUE), expressions: dict[str, LetExprNode | ComponentExpression] = field(opaque=True, extras=OPAQUE_BY_VALUE), roots: dict[str, LetExprNode | ComponentExpression] = field(opaque=True, extras=OPAQUE_BY_VALUE), inputs: dict[str, FixedColumn] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Retain additive parameter designs and a checked deterministic dependency DAG.

PARAMETER DESCRIPTION
leaves

Nonlinear parameters whose coefficients use ordinary formula emission.

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

expressions

Deterministic intermediate nodes in dependency order.

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

roots

Family link-scale outputs, keyed by distributional parameter.

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

inputs

Numeric raw columns with their exact fitted carriers and row axis.

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

Decoded response draws

posterior_response returns ResponseDraws after one posterior predictive replay. Its value tensor preserves the response's measurement coordinates; for a Wiener response, this is positive reaction time including nondecision delay, and decision records zero for the lower boundary and one for the upper boundary. decision_labels names those codes. posterior_predict retains the corresponding lossless signed response tensor.

PredictionOptions defines the shared keyword contract for these two prediction methods. ExpectationOptions additionally includes mc_samples for explicitly requested Monte Carlo expectations. posterior_choice_probs uses the same expectation keywords and returns the joint model's lower/upper choice probabilities; it does not estimate them by repeated response sampling.

ResponseDraws didactic-model

ResponseDraws(*, value: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), decision: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), decision_labels: tuple[str, ...] = ())

Bases: ValueModel

Posterior responses decoded into their original measurement coordinates.

PARAMETER DESCRIPTION
value

Response draws preserving chain, draw, row, and event dimensions. Wiener responses are positive reaction times, including nondecision delay.

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

decision

Joint binary decisions on the same sample axes, zero lower and one upper; None for a response without a decision modifier.

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

decision_labels

Semantic labels of the binary codes, or an empty tuple.

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

PredictionOptions

Bases: TypedDict

Optional prediction keywords shared by native and decoded response draws.

Each key follows BayesianFit.posterior_predict: retained predictor encodings, group policies, trial counts, draw count, and random seed. Omitted keys retain that method's defaults.

ExpectationOptions

Bases: PredictionOptions

Optional expectation keywords shared by response and decision means.

Prediction keys follow BayesianFit.posterior_epred. The additional mc_samples key requests Monte Carlo moments when no closed mean exists. Decision probabilities always use their closed joint-model probabilities.

Likelihoods and analysis

BayesianFit.log_likelihood(num_samples=100, seed=7) returns raw response log densities or recorded-event log probabilities on training rows, with chain and draw axes followed by the observation axis. Truncation normalizes the response law before the event is scored. These scores exclude fitting weights and priors. analysis retains the same posterior draws and scores for summaries, empirical WAIC, DataTree conversion, and PSIS-LOO. It samples a variational guide once per request and never treats its pseudo-chain as recorded MCMC output. The executable workflow and shared API describe score units, optional ArviZ dependencies, and the distinction between uncertainty and convergence.

Smooth contributions

conditional_smooths(fitted, term, new_data) returns one fitted s(), t2(), or approximate gp() term's posterior contribution to its linear predictor at explicit rows, as brms's conditional_smooths reports it. The structured predictor guide states the bases and their retained prediction state.

conditional_smooths

conditional_smooths(fitted: SingleFit, term: str, new_data: IntoDataFrame, *, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0, draws: Mapping[str, Tensor] | None = None, site_prefix: str = '') -> Tensor

Evaluate one smooth's posterior contribution to its linear predictor.

The contribution is the smooth's unpenalized columns times their population coefficients plus each penalized block times its scale and innovations, evaluated through the retained training basis, as brms's conditional_smooths reports. For an approximate gp() term it is the retained eigenfunction basis times sqrt(spd) * zgp of every sub-GP, which brms reports through conditional_effects. For an exact gp() term each draw's latent function is drawn at the rows' distinct inputs given its training values, as brms's .predictor_gp_new does, at O(u^3 + u^2 m + u m^2 + m^3) per draw for u training and m fresh inputs. Other terms, the intercept, and the inverse link are excluded. Costs O(draws times rows times basis width).

PARAMETER DESCRIPTION
fitted

Fitted formula model.

TYPE: BayesianFit

term

Smooth or GP term exactly as the fitted formula's evaluator names it, for instance "s(x)", "t2(x, z, k=4)", or "gp(x, k=10)".

TYPE: str

new_data

Rows holding the smooth's covariates and any by variable.

TYPE: IntoDataFrame

parameter

mu or a distributional or nonlinear parameter carrying the term.

TYPE: str DEFAULT: 'mu'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and for the latent function of an exact gp() term at the rows.

TYPE: int DEFAULT: 0

draws

Explicit constrained draws to read in place of the fit's own.

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

site_prefix

Namespace of that response's sites within draws.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
Tensor

Contributions with shape (chain, draw, rows), followed by the free coordinates of a vector-valued parameter.

RAISES DESCRIPTION
ValueError

If the fit is joint, the term is not a fitted smooth of the predictor, or the rows are invalid for its retained basis.

Source code in src/quivers/formulas/_smooth_effects.py
def conditional_smooths(
    fitted: SingleFit,
    term: str,
    new_data: IntoDataFrame,
    *,
    parameter: str = "mu",
    num_samples: int | None = None,
    seed: int = 0,
    draws: Mapping[str, torch.Tensor] | None = None,
    site_prefix: str = "",
) -> torch.Tensor:
    """Evaluate one smooth's posterior contribution to its linear predictor.

    The contribution is the smooth's unpenalized columns times their
    population coefficients plus each penalized block times its scale and
    innovations, evaluated through the retained training basis, as brms's
    ``conditional_smooths`` reports. For an approximate ``gp()`` term it is
    the retained eigenfunction basis times ``sqrt(spd) * zgp`` of every
    sub-GP, which brms reports through ``conditional_effects``. For an exact
    ``gp()`` term each draw's latent function is drawn at the rows' distinct
    inputs given its training values, as brms's ``.predictor_gp_new`` does,
    at O(u^3 + u^2 m + u m^2 + m^3) per draw for ``u`` training and ``m``
    fresh inputs. Other terms, the intercept, and the
    inverse link are excluded. Costs O(draws times rows times basis width).

    Parameters
    ----------
    fitted : BayesianFit
        Fitted formula model.
    term : str
        Smooth or GP term exactly as the fitted formula's evaluator names
        it, for instance ``"s(x)"``, ``"t2(x, z, k=4)"``, or
        ``"gp(x, k=10)"``.
    new_data : IntoDataFrame
        Rows holding the smooth's covariates and any ``by`` variable.
    parameter : str
        ``mu`` or a distributional or nonlinear parameter carrying the term.
    num_samples : int or None
        Draw count under the convention of ``draws``.
    seed : int
        Seed for variational draws and for the latent function of an exact
        ``gp()`` term at the rows.
    draws : Mapping[str, torch.Tensor] or None
        Explicit constrained draws to read in place of the fit's own.
    site_prefix : str
        Namespace of that response's sites within ``draws``.

    Returns
    -------
    torch.Tensor
        Contributions with shape ``(chain, draw, rows)``, followed by the free
        coordinates of a vector-valued parameter.

    Raises
    ------
    ValueError
        If the fit is joint, the term is not a fitted smooth of the
        predictor, or the rows are invalid for its retained basis.
    """
    if hasattr(fitted, "response_fits"):
        raise ValueError(
            "conditional_smooths evaluates the smooth of one response; for a "
            "joint fit call its conditional_smooths method with resp"
        )

    def effect_draws() -> Mapping[str, torch.Tensor]:
        return (
            fitted.draws(num_samples=num_samples, seed=seed) if draws is None else draws
        )

    return _smooth_contribution(
        fitted._predictor_readout,
        term,
        new_data,
        parameter=parameter,
        seed=seed,
        get_draws=effect_draws,
        site_prefix=site_prefix,
    )

Named initial values

fit(..., initial_values={...}) initializes latent sites by their generated QVR names, which are visible in formula_to_qvr output and get_prior results. Values use each site's natural scale; scalars broadcast and tensors must match the site's full declared shape. Unknown names, observed sites, Boolean or nonfinite values, incompatible shapes, and support boundaries are refused. The inference object detaches and copies the given values.

import pandas as pd

from quivers.formulas import fit

result = fit(
    "y ~ x",
    data=pd.DataFrame({"y": [0.1, 0.4, 0.8], "x": [-1.0, 0.0, 1.0]}),
    method="svi",
    num_steps=10,
    seed=2026,
    initial_values={"intercept": 0.4, "beta_x": 0.0, "sigma": 0.5},
)
assert set(result.draws(num_samples=2)) == {"intercept", "beta_x", "sigma"}

For method="svi", the default AutoNormalGuide maps these values into its initial unconstrained centers. A custom guide must accept initial_values when a nonempty mapping is passed. For "hmc" and "nuts", named values replace the corresponding coordinates after seeded initialization, as in the MCMC interface.

A shifted_lognormal fit with a regressed ndt, a log link, and an intercept initializes the population intercept to log(min(y) / 4) and the other population coefficients to zero. The implied population shift thus starts below every training response. Group effects retain the inference method's starting values. These are starting coefficients; the model's predictor and priors remain unchanged. Explicit initial_values override the automatic entries and can also set group sites. A custom SVI guide used with this automatic initialization must also accept the mapping.

Hazard rate and expected event time

For a cox fit, posterior_linpred(transform=True) returns the positive hazard multiplier. posterior_predict draws positive event times from the retained spline baseline and its explicit constant-hazard tail. posterior_epred(mc_samples=...) approximates expected event time using the shared finite-mean sampler; omitting the budget fails explicitly. The fitted knots and coefficient table are retained on new predictor rows. See the Cox example.

Trial counts

Trial-count families use binomial_trials for either one common count or a column name. Trial counts satisfy 0 <= n <= 2**53, including zero, which permits only a zero response. This family-specific bound preserves exact integer representation in native float64 arithmetic; Int itself remains signed 64-bit. The same metadata and validation apply to fitting and new-data prediction, including the zero-inflated binomial and beta-binomial variants. See the count-family example.

brms post-processing

BayesianFit and MultivariateFit carry brms's summary, residual, accessor, and leave-one-out methods: summary, fixef, ranef, coef, varcorr, vcov, variables, posterior_summary, posterior_interval, predict, fitted, residuals, predictive_error, predictive_interval, ndraws, nchains, niterations, nobs, ngrps, rhat, neff_ratio, nuts_params, log_posterior, loo, loo_moment_match, loo_subsample, waic, psis, loo_predict, loo_epred, loo_linpred, loo_predictive_interval, loo_r2, kfold, and add_criterion. The analysis guide states their brms counterparts and the deliberate differences.

FitSummary didactic-model

FitSummary(*, formula: str, family: str, nobs: int, ngrps: Mapping[str, int] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), algorithm: str, chains: int, iterations: int, warmup: int, total_ndraws: int, fixed: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), spec_pars: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), random: Mapping[str, SummaryTable] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), splines: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), rescor: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), other: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), divergences: int = 0)

Bases: ValueModel

brms's summary of a fitted model, section by section.

PARAMETER DESCRIPTION
formula

Authored formula text.

TYPE: str

family

Family description.

TYPE: str

nobs

Number of observations used in fitting.

TYPE: int

ngrps

Number of levels of each grouping factor.

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

algorithm

"sampling" for recorded chains, "meanfield" or the guide's name for variational fits, "prior" for prior draws.

TYPE: str

chains

Chains, retained draws per chain, and warmup iterations per chain.

TYPE: int

iterations

Chains, retained draws per chain, and warmup iterations per chain.

TYPE: int

warmup

Chains, retained draws per chain, and warmup iterations per chain.

TYPE: int

total_ndraws

Retained draws pooled over chains.

TYPE: int

fixed

Population coefficients, named without their b_ prefix.

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

spec_pars

Unregressed family parameters (sigma, shape, ...).

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

random

Per grouping factor, sd(<coef>) and cor(<coef>,<coef>) rows.

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

splines

Smoothing standard deviations of s() and t2() terms, sds(<label>_<penalty>).

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

rescor

Residual correlations of a joint fit, rescor(<a>,<b>).

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

other

Native QVR sites without a brms counterpart.

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

divergences

Divergent transitions after warmup, zero without recorded chains.

TYPE: int DEFAULT: 0

VarCorrBlock didactic-model

VarCorrBlock(*, labels: tuple[str, ...], sd: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), cor: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), cov: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), sd_draws: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), cor_draws: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), cov_draws: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Standard deviations, correlations and covariances of one block.

PARAMETER DESCRIPTION
sd

Summary of the standard deviations, one row per coefficient.

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

cor

Three-way summaries (coef, statistic, coef); None when the block has a single coefficient and no correlation.

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

cov

Three-way summaries (coef, statistic, coef); None when the block has a single coefficient and no correlation.

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

sd_draws

Draws (chain, draw, coef) of the standard deviations.

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

cor_draws

Draws (chain, draw, coef, coef).

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

cov_draws

Draws (chain, draw, coef, coef).

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

labels

Coefficient labels.

TYPE: tuple[str, ...]

KFoldResult didactic-model

KFoldResult(*, estimate: ELPDEstimate = field(opaque=True, extras=OPAQUE_BY_VALUE), cross_validation: CrossValidationResult = field(opaque=True, extras=OPAQUE_BY_IDENTITY), data: IntoDataFrame = field(opaque=True, extras=OPAQUE_BY_IDENTITY), positions: tuple[int, ...], fold_type: str, joint_fit: bool, resp: str | tuple[str, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A brms kfold result: the criterion, its refits and its partition.

PARAMETER DESCRIPTION
estimate

The k-fold criterion.

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

cross_validation

Held-out scores, the partition, and the refits when saved.

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

data

Original rows of the fitted model.

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

positions

Original row position of every partitioned unit.

TYPE: tuple[int, ...]

fold_type

random, group, stratified, grouped, loo or custom.

TYPE: str

joint_fit

Whether the refits are joint fits.

TYPE: bool

resp

Joint response selection of the scores.

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

KFoldPrediction didactic-model

KFoldPrediction(*, observed: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), predicted: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), positions: tuple[int, ...])

Bases: ValueModel

Held-out observations and predictions of k-fold refits, as kfold_predict.

PARAMETER DESCRIPTION
observed

Observed responses of the predicted units, in original row order.

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

predicted

Draws (chain, draw, unit[, event]) from each unit's own refit.

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

positions

Original row position of each predicted unit.

TYPE: tuple[int, ...]

SinglePredictionOptions

Bases: TypedDict

Prediction keywords forwarded to BayesianFit prediction methods.

Each key has the meaning of the keyword of the same name on BayesianFit.posterior_predict.

JointPredictionOptions

Bases: TypedDict

Prediction keywords forwarded to MultivariateFit prediction methods.

Each key has the meaning of the keyword of the same name on MultivariateFit.posterior_predict.

kfold_predict

kfold_predict(result: KFoldResult, *, method: str = 'posterior_predict', resp: str | None = None, num_samples: int | None = None, seed: int = 0) -> KFoldPrediction

Predict held-out rows from their own k-fold refits, as brms kfold_predict.

PARAMETER DESCRIPTION
result

A kfold result computed with save_fits=True.

TYPE: KFoldResult

method

posterior_predict (default), posterior_epred or posterior_linpred, or one of brms's aliases.

TYPE: str DEFAULT: 'posterior_predict'

resp

Response of a joint fit; None for a single response.

TYPE: str or None DEFAULT: None

num_samples

Draws per chain of each refit.

TYPE: int or None DEFAULT: None

seed

Prediction seed.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
KFoldPrediction

Observed responses and predictions of every held-out row, ordered by original row; new group levels are sampled from the fitted Gaussian group law, as brms.

RAISES DESCRIPTION
ValueError

If the refits were not saved or draw counts differ between folds.

Source code in src/quivers/formulas/_postprocess_methods.py
def kfold_predict(
    result: KFoldResult,
    *,
    method: str = "posterior_predict",
    resp: str | None = None,
    num_samples: int | None = None,
    seed: int = 0,
) -> KFoldPrediction:
    """Predict held-out rows from their own k-fold refits, as brms ``kfold_predict``.

    Parameters
    ----------
    result : KFoldResult
        A `kfold` result computed with ``save_fits=True``.
    method : str
        ``posterior_predict`` (default), ``posterior_epred`` or
        ``posterior_linpred``, or one of brms's aliases.
    resp : str or None
        Response of a joint fit; None for a single response.
    num_samples : int or None
        Draws per chain of each refit.
    seed : int
        Prediction seed.

    Returns
    -------
    KFoldPrediction
        Observed responses and predictions of every held-out row, ordered by
        original row; new group levels are sampled from the fitted Gaussian
        group law, as brms.

    Raises
    ------
    ValueError
        If the refits were not saved or draw counts differ between folds.
    """
    cv = result.cross_validation
    if not cv.fits:
        raise ValueError("kfold_predict requires kfold(save_fits=True)")
    canonical = prediction_method(method)
    observed: dict[int, torch.Tensor] = {}
    predicted: dict[int, torch.Tensor] = {}
    for fold, fitted in cv.fits.items():
        rows = cv.plan.split(fold).test
        positions = [result.positions[row] for row in rows]
        frame = nw.from_native(result.data, eager_only=True)[positions, :].to_native()
        options = {
            "new_data": frame,
            "allow_new_levels": True,
            "sample_new_levels": "gaussian",
            "num_samples": num_samples,
            "seed": seed,
        }
        if result.joint_fit:
            joint_fit = cast("MultivariateFit", fitted)
            name = resp if resp is not None else joint_fit.response_names[0]
            call = getattr(joint_fit, canonical)
            draws = call(resp=name, **options)[name]
            truth = evaluate_responses(joint_fit._response_data(name), frame)
        else:
            single = cast("BayesianFit", fitted)
            draws = getattr(single, canonical)(**options)
            truth = _responses(single, ExpectationOptions(new_data=frame))
        for index, row in enumerate(rows):
            predicted[row] = draws[:, :, index]
            observed[row] = truth[index]
    order = sorted(predicted)
    shapes = {tuple(predicted[row].shape[:2]) for row in order}
    if len(shapes) != 1:
        raise ValueError("refits have different draw counts; set num_samples")
    return KFoldPrediction(
        observed=torch.stack([observed[row] for row in order]),
        predicted=torch.stack([predicted[row] for row in order], dim=2),
        positions=tuple(result.positions[row] for row in order),
    )

loo_compare

loo_compare(models: Mapping[str, ModelInput], *, criterion: Literal['loo', 'waic', 'kfold'] = 'loo') -> SummaryTable

Compare models by a stored criterion, as brms loo_compare.

PARAMETER DESCRIPTION
models

Named fits holding the criterion from add_criterion, or estimates.

TYPE: Mapping[str, BayesianFit or MultivariateFit or ELPDEstimate]

criterion

Criterion to compare.

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

RETURNS DESCRIPTION
SummaryTable

The loo package's comparison table, best model first.

RAISES DESCRIPTION
ValueError

If a fit has no stored criterion, or the models score different data.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_compare(
    models: Mapping[str, ModelInput],
    *,
    criterion: Literal["loo", "waic", "kfold"] = "loo",
) -> SummaryTable:
    """Compare models by a stored criterion, as brms ``loo_compare``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit or ELPDEstimate]
        Named fits holding the criterion from `add_criterion`, or estimates.
    criterion : {"loo", "waic", "kfold"}
        Criterion to compare.

    Returns
    -------
    SummaryTable
        The loo package's comparison table, best model first.

    Raises
    ------
    ValueError
        If a fit has no stored criterion, or the models score different data.
    """
    return compare_estimates(
        {
            name: _estimate(model, criterion, compute=False)
            for name, model in models.items()
        }
    )

loo_model_weights

loo_model_weights(models: Mapping[str, ModelInput], *, method: Literal['stacking', 'pseudobma'] = 'stacking', bayesian_bootstrap: bool = True, seed: int = 0) -> dict[str, float]

Return stacking or pseudo-BMA weights, as brms loo_model_weights.

PARAMETER DESCRIPTION
models

Named fits or PSIS-LOO estimates; fits without a stored loo are evaluated with loo.

TYPE: Mapping[str, BayesianFit or MultivariateFit or ELPDEstimate]

method

Weighting method.

TYPE: ('stacking', 'pseudobma') DEFAULT: "stacking"

bayesian_bootstrap

Bayesian-bootstrap regularization of pseudo-BMA weights (loo's BB).

TYPE: bool DEFAULT: True

seed

Seed of the Bayesian bootstrap.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, float]

Weights summing to one.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_model_weights(
    models: Mapping[str, ModelInput],
    *,
    method: Literal["stacking", "pseudobma"] = "stacking",
    bayesian_bootstrap: bool = True,
    seed: int = 0,
) -> dict[str, float]:
    """Return stacking or pseudo-BMA weights, as brms ``loo_model_weights``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit or ELPDEstimate]
        Named fits or PSIS-LOO estimates; fits without a stored ``loo`` are
        evaluated with `loo`.
    method : {"stacking", "pseudobma"}
        Weighting method.
    bayesian_bootstrap : bool
        Bayesian-bootstrap regularization of pseudo-BMA weights (loo's ``BB``).
    seed : int
        Seed of the Bayesian bootstrap.

    Returns
    -------
    dict[str, float]
        Weights summing to one.
    """
    return stacking_weights(
        {name: _estimate(model, "loo", compute=True) for name, model in models.items()},
        method=method,
        bayesian_bootstrap=bayesian_bootstrap,
        seed=seed,
    )

model_weights

model_weights(models: Mapping[str, ModelInput], *, weights: Literal['stacking', 'pseudobma', 'loo', 'waic', 'kfold', 'bma'] = 'stacking', seed: int = 0) -> dict[str, float]

Return model weights, as brms model_weights.

PARAMETER DESCRIPTION
models

Named fits or estimates.

TYPE: Mapping[str, BayesianFit or MultivariateFit or ELPDEstimate]

weights

Stacking or pseudo-BMA weights of PSIS-LOO, or Akaike-type weights exp(-ic_diff / 2) of an information criterion. k-fold weights require stored kfold criteria. "bma" gives posterior model probabilities from bridge-sampled marginal likelihoods (post_prob).

TYPE: ('stacking', 'pseudobma', 'loo', 'waic', 'kfold', 'bma') DEFAULT: "stacking"

seed

Seed of the pseudo-BMA Bayesian bootstrap and of bridge sampling.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, float]

Weights summing to one.

RAISES DESCRIPTION
ValueError

If the weighting method is unknown.

Source code in src/quivers/formulas/_postprocess_methods.py
def model_weights(
    models: Mapping[str, ModelInput],
    *,
    weights: Literal[
        "stacking", "pseudobma", "loo", "waic", "kfold", "bma"
    ] = "stacking",
    seed: int = 0,
) -> dict[str, float]:
    """Return model weights, as brms ``model_weights``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit or ELPDEstimate]
        Named fits or estimates.
    weights : {"stacking", "pseudobma", "loo", "waic", "kfold", "bma"}
        Stacking or pseudo-BMA weights of PSIS-LOO, or Akaike-type weights
        ``exp(-ic_diff / 2)`` of an information criterion. k-fold weights
        require stored ``kfold`` criteria. ``"bma"`` gives posterior model
        probabilities from bridge-sampled marginal likelihoods (`post_prob`).
    seed : int
        Seed of the pseudo-BMA Bayesian bootstrap and of bridge sampling.

    Returns
    -------
    dict[str, float]
        Weights summing to one.

    Raises
    ------
    ValueError
        If the weighting method is unknown.
    """
    if weights in {"stacking", "pseudobma"}:
        return loo_model_weights(
            models, method=cast(Literal["stacking", "pseudobma"], weights), seed=seed
        )
    # Posterior model probabilities by bridge sampling.
    if weights == "bma":
        fits = {
            name: model
            for name, model in models.items()
            if not isinstance(model, ELPDEstimate)
        }
        if len(fits) != len(models):
            raise ValueError("bma weights require fits, not ELPD estimates")
        return post_prob(fits, seed=seed)
    if weights not in {"loo", "waic", "kfold"}:
        raise ValueError(
            "weights must be 'stacking', 'pseudobma', 'loo', 'waic', 'kfold' or 'bma'"
        )
    return information_weights(
        {
            name: _estimate(
                model, cast(Literal["loo", "waic", "kfold"], weights), compute=True
            )
            for name, model in models.items()
        }
    )

SinglePostprocess

Bases: _PostprocessCore

brms post-processing methods of a single-response BayesianFit.

variables

variables(*, num_samples: int | None = None, seed: int = 0) -> dict[str, Tensor]

Return draws under brms parameter names, as brms variables/as_draws.

Population coefficients are b_<coef> (b_<dpar>_<coef> for a distributional or nonlinear parameter), cumulative thresholds b_Intercept[k], unregressed family parameters by name (sigma), group standard deviations sd_<group>__<coef>, correlations cor_<group>__<a>__<b> and per-level coefficients r_<group>[<level>,<coef>]. Native sites without a brms counterpart keep their QVR names. The log density lp__ is returned by log_posterior.

PARAMETER DESCRIPTION
num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, Tensor]

brms-named draws on chain and draw axes.

Source code in src/quivers/formulas/_postprocess_methods.py
def variables(
    self, *, num_samples: int | None = None, seed: int = 0
) -> dict[str, torch.Tensor]:
    """Return draws under brms parameter names, as brms ``variables``/``as_draws``.

    Population coefficients are ``b_<coef>`` (``b_<dpar>_<coef>`` for a
    distributional or nonlinear parameter), cumulative thresholds
    ``b_Intercept[k]``, unregressed family parameters by name
    (``sigma``), group standard deviations ``sd_<group>__<coef>``,
    correlations ``cor_<group>__<a>__<b>`` and per-level coefficients
    ``r_<group>[<level>,<coef>]``. Native sites without a brms
    counterpart keep their QVR names. The log density ``lp__`` is
    returned by `log_posterior`.

    Parameters
    ----------
    num_samples : int or None
        Draws per chain under the convention of `draws`.
    seed : int
        Seed for variational draws.

    Returns
    -------
    dict[str, torch.Tensor]
        brms-named draws on chain and draw axes.
    """
    return self._pp_named(num_samples, seed)

nobs

nobs() -> int

Return the number of observations used in fitting, as brms nobs.

RETURNS DESCRIPTION
int

Fitted rows.

Source code in src/quivers/formulas/_postprocess_methods.py
def nobs(self) -> int:
    """Return the number of observations used in fitting, as brms ``nobs``.

    Returns
    -------
    int
        Fitted rows.
    """
    return self._pp_nobs(None)

predict

predict(*, summary: bool = True, robust: bool = False, probs: Sequence[float] = (0.025, 0.975), draw_ids: Sequence[int] | None = None, **options: Unpack[SinglePredictionOptions]) -> SummaryTable | Tensor

Summarize posterior predictive draws, as brms predict.

PARAMETER DESCRIPTION
summary

Summarize; False returns posterior_predict draws.

TYPE: bool DEFAULT: True

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

probs

Quantile probabilities.

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

draw_ids

0-based positions of the pooled draws to use (brms draw_ids minus one); None uses every draw.

TYPE: Sequence[int] or None DEFAULT: None

**options

posterior_predict keywords such as new_data.

TYPE: SinglePredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
SummaryTable or Tensor

Estimate, Est.Error and quantiles per row; for ordinal and categorical responses, category frequencies P(Y = <category>) labeled by the fitted categories.

Source code in src/quivers/formulas/_postprocess_methods.py
def predict(
    self,
    *,
    summary: bool = True,
    robust: bool = False,
    probs: Sequence[float] = (0.025, 0.975),
    draw_ids: Sequence[int] | None = None,
    **options: Unpack[SinglePredictionOptions],
) -> SummaryTable | torch.Tensor:
    """Summarize posterior predictive draws, as brms ``predict``.

    Parameters
    ----------
    summary : bool
        Summarize; False returns `posterior_predict` draws.
    robust : bool
        Median and MAD instead of mean and SD.
    probs : Sequence[float]
        Quantile probabilities.
    draw_ids : Sequence[int] or None
        0-based positions of the pooled draws to use (brms ``draw_ids``
        minus one); None uses every draw.
    **options : SinglePredictionOptions
        `posterior_predict` keywords such as ``new_data``.

    Returns
    -------
    SummaryTable or torch.Tensor
        ``Estimate``, ``Est.Error`` and quantiles per row; for ordinal
        and categorical responses, category frequencies
        ``P(Y = <category>)`` labeled by the fitted categories.
    """
    draws = self._pp_prediction("posterior_predict", options, draw_ids=draw_ids)
    if not summary:
        return draws
    return summarize_prediction(
        draws,
        categories=self._pp_fit().category_labels,
        discrete_table=self._pp_categorical(),
        probs=probs,
        robust=robust,
    )

fitted

fitted(*, scale: Literal['response', 'linear'] = 'response', parameter: str | None = None, summary: bool = True, robust: bool = False, probs: Sequence[float] = (0.025, 0.975), draw_ids: Sequence[int] | None = None, **options: Unpack[SinglePredictionOptions]) -> SummaryTable | Tensor

Summarize expected values or linear predictors, as brms fitted.

PARAMETER DESCRIPTION
scale

Expected responses (posterior_epred) or linear predictors (posterior_linpred).

TYPE: ('response', 'linear') DEFAULT: "response"

parameter

A distributional or nonlinear parameter (brms dpar/nlpar); on the response scale its inverse-link value is returned.

TYPE: str or None DEFAULT: None

summary

Summarize; False returns the draws.

TYPE: bool DEFAULT: True

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

probs

Quantile probabilities.

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

draw_ids

0-based pooled draw positions.

TYPE: Sequence[int] or None DEFAULT: None

**options

Prediction keywords such as new_data.

TYPE: SinglePredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
SummaryTable or Tensor

Per-row statistics; category probabilities of ordinal and categorical responses form a three-way table with a category axis.

RAISES DESCRIPTION
ValueError

If the scale is unknown.

Source code in src/quivers/formulas/_postprocess_methods.py
def fitted(
    self,
    *,
    scale: Literal["response", "linear"] = "response",
    parameter: str | None = None,
    summary: bool = True,
    robust: bool = False,
    probs: Sequence[float] = (0.025, 0.975),
    draw_ids: Sequence[int] | None = None,
    **options: Unpack[SinglePredictionOptions],
) -> SummaryTable | torch.Tensor:
    """Summarize expected values or linear predictors, as brms ``fitted``.

    Parameters
    ----------
    scale : {"response", "linear"}
        Expected responses (`posterior_epred`) or linear predictors
        (`posterior_linpred`).
    parameter : str or None
        A distributional or nonlinear parameter (brms ``dpar``/``nlpar``);
        on the response scale its inverse-link value is returned.
    summary : bool
        Summarize; False returns the draws.
    robust : bool
        Median and MAD instead of mean and SD.
    probs : Sequence[float]
        Quantile probabilities.
    draw_ids : Sequence[int] or None
        0-based pooled draw positions.
    **options : SinglePredictionOptions
        Prediction keywords such as ``new_data``.

    Returns
    -------
    SummaryTable or torch.Tensor
        Per-row statistics; category probabilities of ordinal and
        categorical responses form a three-way table with a category axis.

    Raises
    ------
    ValueError
        If the scale is unknown.
    """
    if scale not in {"response", "linear"}:
        raise ValueError("scale must be 'response' or 'linear'")
    fit = self._pp_fit()
    if parameter is None and scale == "response":
        draws = self._pp_prediction("posterior_epred", options, draw_ids=draw_ids)
        labels = fit.category_labels
    else:
        name = parameter or "mu"
        draws = self._pp_prediction(
            "posterior_linpred",
            options,
            draw_ids=draw_ids,
            parameter=name,
            transform=scale == "response",
        )
        labels = fit.predictor_labels(name)
    if not summary:
        return draws
    return summarize_prediction(
        draws, categories=labels, discrete_table=False, probs=probs, robust=robust
    )

predictive_error

predictive_error(*, method: str = 'posterior_predict', draw_ids: Sequence[int] | None = None, **options: Unpack[SinglePredictionOptions]) -> Tensor

Return draws of observed minus predicted responses, as brms predictive_error.

PARAMETER DESCRIPTION
method

posterior_predict (default), posterior_epred or posterior_linpred, or one of brms's aliases.

TYPE: str DEFAULT: 'posterior_predict'

draw_ids

0-based pooled draw positions.

TYPE: Sequence[int] or None DEFAULT: None

**options

Prediction keywords; new_data must hold the response.

TYPE: SinglePredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
Tensor

Float64 draws (chain, draw, row).

RAISES DESCRIPTION
ValueError

For ordinal or categorical responses, where errors are undefined.

Source code in src/quivers/formulas/_postprocess_methods.py
def predictive_error(
    self,
    *,
    method: str = "posterior_predict",
    draw_ids: Sequence[int] | None = None,
    **options: Unpack[SinglePredictionOptions],
) -> torch.Tensor:
    """Return draws of observed minus predicted responses, as brms ``predictive_error``.

    Parameters
    ----------
    method : str
        ``posterior_predict`` (default), ``posterior_epred`` or
        ``posterior_linpred``, or one of brms's aliases.
    draw_ids : Sequence[int] or None
        0-based pooled draw positions.
    **options : SinglePredictionOptions
        Prediction keywords; ``new_data`` must hold the response.

    Returns
    -------
    torch.Tensor
        Float64 draws ``(chain, draw, row)``.

    Raises
    ------
    ValueError
        For ordinal or categorical responses, where errors are undefined.
    """
    return self._pp_errors(method, draw_ids, options, pearson=False)

residuals

residuals(*, method: str = 'posterior_predict', type: Literal['ordinary', 'pearson'] = 'ordinary', summary: bool = True, robust: bool = False, probs: Sequence[float] = (0.025, 0.975), draw_ids: Sequence[int] | None = None, **options: Unpack[SinglePredictionOptions]) -> SummaryTable | Tensor

Summarize predictive errors, as brms residuals.

PARAMETER DESCRIPTION
method

Prediction method or alias behind the errors.

TYPE: str DEFAULT: 'posterior_predict'

type

y - yrep, or that divided by the predictive standard deviation of each row (the Est.Error of predict).

TYPE: ('ordinary', 'pearson') DEFAULT: "ordinary"

summary

Summarize; False returns the draws.

TYPE: bool DEFAULT: True

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

probs

Quantile probabilities.

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

draw_ids

0-based pooled draw positions.

TYPE: Sequence[int] or None DEFAULT: None

**options

Prediction keywords; new_data must hold the response.

TYPE: SinglePredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
SummaryTable or Tensor

Per-row statistics, or error draws.

RAISES DESCRIPTION
ValueError

If the type is unknown or the response is ordinal or categorical.

Source code in src/quivers/formulas/_postprocess_methods.py
def residuals(
    self,
    *,
    method: str = "posterior_predict",
    type: Literal["ordinary", "pearson"] = "ordinary",
    summary: bool = True,
    robust: bool = False,
    probs: Sequence[float] = (0.025, 0.975),
    draw_ids: Sequence[int] | None = None,
    **options: Unpack[SinglePredictionOptions],
) -> SummaryTable | torch.Tensor:
    """Summarize predictive errors, as brms ``residuals``.

    Parameters
    ----------
    method : str
        Prediction method or alias behind the errors.
    type : {"ordinary", "pearson"}
        ``y - yrep``, or that divided by the predictive standard
        deviation of each row (the ``Est.Error`` of `predict`).
    summary : bool
        Summarize; False returns the draws.
    robust : bool
        Median and MAD instead of mean and SD.
    probs : Sequence[float]
        Quantile probabilities.
    draw_ids : Sequence[int] or None
        0-based pooled draw positions.
    **options : SinglePredictionOptions
        Prediction keywords; ``new_data`` must hold the response.

    Returns
    -------
    SummaryTable or torch.Tensor
        Per-row statistics, or error draws.

    Raises
    ------
    ValueError
        If the type is unknown or the response is ordinal or categorical.
    """
    if type not in {"ordinary", "pearson"}:
        raise ValueError("type must be 'ordinary' or 'pearson'")
    draws = self._pp_errors(method, draw_ids, options, pearson=type == "pearson")
    if not summary:
        return draws
    return summary_table(draws, probs=probs, robust=robust)

predictive_interval

predictive_interval(*, prob: float = 0.9, **options: Unpack[SinglePredictionOptions]) -> SummaryTable

Compute central posterior predictive intervals, as brms predictive_interval.

PARAMETER DESCRIPTION
prob

Central mass, 0.9 as in brms.

TYPE: float DEFAULT: 0.9

**options

posterior_predict keywords.

TYPE: SinglePredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
SummaryTable

Lower and upper bounds per row.

Source code in src/quivers/formulas/_postprocess_methods.py
def predictive_interval(
    self, *, prob: float = 0.9, **options: Unpack[SinglePredictionOptions]
) -> SummaryTable:
    """Compute central posterior predictive intervals, as brms ``predictive_interval``.

    Parameters
    ----------
    prob : float
        Central mass, 0.9 as in brms.
    **options : SinglePredictionOptions
        `posterior_predict` keywords.

    Returns
    -------
    SummaryTable
        Lower and upper bounds per row.
    """
    return predictive_table(self._pp_fit().posterior_predict(**options), prob=prob)

loo

loo(*, moment_match: bool = False, reloo: bool = False, k_threshold: float = 0.7, moment_match_args: Mapping[str, int | bool] | None = None, method_factory: MethodFactory | None = None, use_stored: bool = True, num_samples: int | None = None, seed: int = 0) -> ELPDEstimate

Estimate PSIS-LOO, as brms loo.

PARAMETER DESCRIPTION
moment_match

Moment-match units with Pareto shape above k_threshold [@paananen2021implicitly].

TYPE: bool DEFAULT: False

reloo

Refit the model once per unit still above k_threshold.

TYPE: bool DEFAULT: False

k_threshold

Pareto shape threshold, 0.7 as in brms.

TYPE: float DEFAULT: 0.7

moment_match_args

max_iters (30), split (True) and cov (True).

TYPE: Mapping or None DEFAULT: None

method_factory

Fit settings of each exact refit; None keeps the original settings with the refit's own seed.

TYPE: MethodFactory or None DEFAULT: None

use_stored

Return a loo criterion stored by add_criterion when no correction is requested.

TYPE: bool DEFAULT: True

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and refits.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ELPDEstimate

PSIS-LOO estimate with Pareto diagnostics.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo(
    self,
    *,
    moment_match: bool = False,
    reloo: bool = False,
    k_threshold: float = 0.7,
    moment_match_args: Mapping[str, int | bool] | None = None,
    method_factory: MethodFactory | None = None,
    use_stored: bool = True,
    num_samples: int | None = None,
    seed: int = 0,
) -> ELPDEstimate:
    """Estimate PSIS-LOO, as brms ``loo``.

    Parameters
    ----------
    moment_match : bool
        Moment-match units with Pareto shape above ``k_threshold``
        [@paananen2021implicitly].
    reloo : bool
        Refit the model once per unit still above ``k_threshold``.
    k_threshold : float
        Pareto shape threshold, 0.7 as in brms.
    moment_match_args : Mapping or None
        ``max_iters`` (30), ``split`` (True) and ``cov`` (True).
    method_factory : MethodFactory or None
        Fit settings of each exact refit; None keeps the original
        settings with the refit's own seed.
    use_stored : bool
        Return a ``loo`` criterion stored by `add_criterion` when no
        correction is requested.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws and refits.

    Returns
    -------
    ELPDEstimate
        PSIS-LOO estimate with Pareto diagnostics.
    """
    if (
        use_stored
        and not (moment_match or reloo)
        and "loo" in self._pp_fit().criteria
    ):
        return cast(ELPDEstimate, self._pp_fit().criteria["loo"])
    return loo_estimate(
        self._pp_fit(),
        joint=False,
        resp=None,
        moment_match_options=(moment_match_args or {}) if moment_match else None,
        reloo_factory=(method_factory or keep_settings) if reloo else None,
        k_threshold=k_threshold,
        num_samples=num_samples,
        seed=seed,
    )

loo_moment_match

loo_moment_match(loo: ELPDEstimate | None = None, *, k_threshold: float = 0.7, max_iters: int = 30, split: bool = True, cov: bool = True, num_samples: int | None = None, seed: int = 0) -> ELPDEstimate

Moment-match problematic PSIS-LOO units, as brms loo_moment_match.

PARAMETER DESCRIPTION
loo

An estimate whose response hash must match this fit; None recomputes PSIS-LOO.

TYPE: ELPDEstimate or None DEFAULT: None

k_threshold

Units above this Pareto shape are moment matched.

TYPE: float DEFAULT: 0.7

max_iters

Maximum iterations per unit.

TYPE: int DEFAULT: 30

split

Split moment matching with multiple importance sampling.

TYPE: bool DEFAULT: True

cov

Also match covariances.

TYPE: bool DEFAULT: True

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ELPDEstimate

Updated estimate.

RAISES DESCRIPTION
ValueError

If loo scores different responses.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_moment_match(
    self,
    loo: ELPDEstimate | None = None,
    *,
    k_threshold: float = 0.7,
    max_iters: int = 30,
    split: bool = True,
    cov: bool = True,
    num_samples: int | None = None,
    seed: int = 0,
) -> ELPDEstimate:
    """Moment-match problematic PSIS-LOO units, as brms ``loo_moment_match``.

    Parameters
    ----------
    loo : ELPDEstimate or None
        An estimate whose response hash must match this fit; None
        recomputes PSIS-LOO.
    k_threshold : float
        Units above this Pareto shape are moment matched.
    max_iters : int
        Maximum iterations per unit.
    split : bool
        Split moment matching with multiple importance sampling.
    cov : bool
        Also match covariances.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    ELPDEstimate
        Updated estimate.

    Raises
    ------
    ValueError
        If ``loo`` scores different responses.
    """
    result = loo_estimate(
        self._pp_fit(),
        joint=False,
        resp=None,
        moment_match_options={"max_iters": max_iters, "split": split, "cov": cov},
        reloo_factory=None,
        k_threshold=k_threshold,
        num_samples=num_samples,
        seed=seed,
    )
    if loo is not None and loo.response_hash != result.response_hash:
        raise ValueError("response values used in loo and in this fit differ")
    return result

waic

waic(*, num_samples: int | None = None, seed: int = 0) -> ELPDEstimate

Estimate WAIC, as brms waic.

PARAMETER DESCRIPTION
num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ELPDEstimate

WAIC estimate.

Source code in src/quivers/formulas/_postprocess_methods.py
def waic(self, *, num_samples: int | None = None, seed: int = 0) -> ELPDEstimate:
    """Estimate WAIC, as brms ``waic``.

    Parameters
    ----------
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    ELPDEstimate
        WAIC estimate.
    """
    return waic_from_fit(
        self._pp_fit(), joint=False, resp=None, num_samples=num_samples, seed=seed
    )

psis

psis(*, num_samples: int | None = None, seed: int = 0) -> PSISWeights

Return PSIS leave-one-out weights, as brms psis.

PARAMETER DESCRIPTION
num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PSISWeights

Smoothed log weights and Pareto diagnostics.

Source code in src/quivers/formulas/_postprocess_methods.py
def psis(self, *, num_samples: int | None = None, seed: int = 0) -> PSISWeights:
    """Return PSIS leave-one-out weights, as brms ``psis``.

    Parameters
    ----------
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    PSISWeights
        Smoothed log weights and Pareto diagnostics.
    """
    scores = criterion_scores(
        self._pp_fit(), joint=False, resp=None, num_samples=num_samples, seed=seed
    )
    return psis_weights(
        scores.log_likelihood, r_eff=relative_efficiency(scores.analysis)
    )

loo_subsample

loo_subsample(*, observations: int | Sequence[int] = 400, approximation: Literal['plpd', 'lpd'] = 'plpd', num_samples: int | None = None, seed: int = 0) -> ELPDEstimate

Estimate PSIS-LOO from a row subsample, as brms loo_subsample.

PARAMETER DESCRIPTION
observations

Subsample size (400 as in loo) or explicit 0-based rows.

TYPE: int or Sequence[int] DEFAULT: 400

approximation

Approximation of every row's term: the log density at the posterior mean (default) or the log predictive density.

TYPE: ('plpd', 'lpd') DEFAULT: "plpd"

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed of the subsample and variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ELPDEstimate

Subsampled estimate with total and subsampling standard errors.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_subsample(
    self,
    *,
    observations: int | Sequence[int] = 400,
    approximation: Literal["plpd", "lpd"] = "plpd",
    num_samples: int | None = None,
    seed: int = 0,
) -> ELPDEstimate:
    """Estimate PSIS-LOO from a row subsample, as brms ``loo_subsample``.

    Parameters
    ----------
    observations : int or Sequence[int]
        Subsample size (400 as in loo) or explicit 0-based rows.
    approximation : {"plpd", "lpd"}
        Approximation of every row's term: the log density at the
        posterior mean (default) or the log predictive density.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed of the subsample and variational draws.

    Returns
    -------
    ELPDEstimate
        Subsampled estimate with total and subsampling standard errors.
    """
    return loo_subsample_estimate(
        self._pp_fit(),
        joint=False,
        resp=None,
        observations=observations,
        approximation=approximation,
        num_samples=num_samples,
        seed=seed,
    )

loo_predict

loo_predict(*, type: Literal['mean', 'var', 'quantile'] = 'mean', probs: Sequence[float] = (0.5,), num_samples: int | None = None, seed: int = 0) -> LooExpectation

Compute leave-one-out predictive statistics, as brms loo_predict.

PARAMETER DESCRIPTION
type

Weighted statistic of posterior_predict draws.

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

probs

Quantile probabilities.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and responses.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
LooExpectation

Statistics per training row with function-specific Pareto shapes.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_predict(
    self,
    *,
    type: Literal["mean", "var", "quantile"] = "mean",
    probs: Sequence[float] = (0.5,),
    num_samples: int | None = None,
    seed: int = 0,
) -> LooExpectation:
    """Compute leave-one-out predictive statistics, as brms ``loo_predict``.

    Parameters
    ----------
    type : {"mean", "var", "quantile"}
        Weighted statistic of `posterior_predict` draws.
    probs : Sequence[float]
        Quantile probabilities.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws and responses.

    Returns
    -------
    LooExpectation
        Statistics per training row with function-specific Pareto shapes.
    """
    return self._pp_loo_expectation(
        "posterior_predict",
        type=type,
        probs=probs,
        num_samples=num_samples,
        seed=seed,
    )

loo_epred

loo_epred(*, type: Literal['mean', 'var', 'quantile'] = 'mean', probs: Sequence[float] = (0.5,), num_samples: int | None = None, seed: int = 0) -> LooExpectation

Compute leave-one-out expected responses, as brms loo_epred.

PARAMETER DESCRIPTION
type

Weighted statistic of posterior_epred draws.

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

probs

Quantile probabilities.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
LooExpectation

Statistics per training row.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_epred(
    self,
    *,
    type: Literal["mean", "var", "quantile"] = "mean",
    probs: Sequence[float] = (0.5,),
    num_samples: int | None = None,
    seed: int = 0,
) -> LooExpectation:
    """Compute leave-one-out expected responses, as brms ``loo_epred``.

    Parameters
    ----------
    type : {"mean", "var", "quantile"}
        Weighted statistic of `posterior_epred` draws.
    probs : Sequence[float]
        Quantile probabilities.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    LooExpectation
        Statistics per training row.
    """
    return self._pp_loo_expectation(
        "posterior_epred",
        type=type,
        probs=probs,
        num_samples=num_samples,
        seed=seed,
    )

loo_linpred

loo_linpred(*, type: Literal['mean', 'var', 'quantile'] = 'mean', probs: Sequence[float] = (0.5,), num_samples: int | None = None, seed: int = 0) -> LooExpectation

Compute leave-one-out linear predictors, as brms loo_linpred.

PARAMETER DESCRIPTION
type

Weighted statistic of posterior_linpred draws.

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

probs

Quantile probabilities.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
LooExpectation

Statistics per training row.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_linpred(
    self,
    *,
    type: Literal["mean", "var", "quantile"] = "mean",
    probs: Sequence[float] = (0.5,),
    num_samples: int | None = None,
    seed: int = 0,
) -> LooExpectation:
    """Compute leave-one-out linear predictors, as brms ``loo_linpred``.

    Parameters
    ----------
    type : {"mean", "var", "quantile"}
        Weighted statistic of `posterior_linpred` draws.
    probs : Sequence[float]
        Quantile probabilities.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    LooExpectation
        Statistics per training row.
    """
    return self._pp_loo_expectation(
        "posterior_linpred",
        type=type,
        probs=probs,
        num_samples=num_samples,
        seed=seed,
    )

loo_predictive_interval

loo_predictive_interval(*, prob: float = 0.9, num_samples: int | None = None, seed: int = 0) -> LooExpectation

Compute leave-one-out predictive intervals, as brms loo_predictive_interval.

PARAMETER DESCRIPTION
prob

Central mass, 0.9 as in brms.

TYPE: float DEFAULT: 0.9

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and responses.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
LooExpectation

Weighted quantiles (1 - prob) / 2 and 1 - (1 - prob) / 2.

RAISES DESCRIPTION
ValueError

If the mass is not strictly inside (0, 1).

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_predictive_interval(
    self, *, prob: float = 0.9, num_samples: int | None = None, seed: int = 0
) -> LooExpectation:
    """Compute leave-one-out predictive intervals, as brms ``loo_predictive_interval``.

    Parameters
    ----------
    prob : float
        Central mass, 0.9 as in brms.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws and responses.

    Returns
    -------
    LooExpectation
        Weighted quantiles ``(1 - prob) / 2`` and ``1 - (1 - prob) / 2``.

    Raises
    ------
    ValueError
        If the mass is not strictly inside (0, 1).
    """
    if not 0 < prob < 1:
        raise ValueError("prob must lie strictly between zero and one")
    alpha = (1 - prob) / 2
    return self.loo_predict(
        type="quantile",
        probs=(alpha, 1 - alpha),
        num_samples=num_samples,
        seed=seed,
    )

loo_r2

loo_r2(*, summary: bool = True, robust: bool = False, probs: Sequence[float] = (0.025, 0.975), num_samples: int | None = None, seed: int = 0) -> SummaryTable | Tensor

Compute the leave-one-out R-squared, as brms loo_R2.

PARAMETER DESCRIPTION
summary

Summarize; False returns the bootstrap draws.

TYPE: bool DEFAULT: True

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

probs

Quantile probabilities.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed of the Dirichlet weights and variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
SummaryTable or Tensor

A R2 row, or S bootstrap draws.

RAISES DESCRIPTION
ValueError

For unordered categorical responses.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_r2(
    self,
    *,
    summary: bool = True,
    robust: bool = False,
    probs: Sequence[float] = (0.025, 0.975),
    num_samples: int | None = None,
    seed: int = 0,
) -> SummaryTable | torch.Tensor:
    """Compute the leave-one-out R-squared, as brms ``loo_R2``.

    Parameters
    ----------
    summary : bool
        Summarize; False returns the bootstrap draws.
    robust : bool
        Median and MAD instead of mean and SD.
    probs : Sequence[float]
        Quantile probabilities.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed of the Dirichlet weights and variational draws.

    Returns
    -------
    SummaryTable or torch.Tensor
        A ``R2`` row, or S bootstrap draws.

    Raises
    ------
    ValueError
        For unordered categorical responses.
    """
    fit = self._pp_fit()
    if fit.family.unordered_categories:
        raise ValueError("loo_R2 is not defined for unordered categorical models")
    if "loo_R2" in fit.criteria:
        values = cast(torch.Tensor, fit.criteria["loo_R2"])
    else:
        weights = self.psis(num_samples=num_samples, seed=seed)
        expected = fit.posterior_epred(num_samples=num_samples, seed=seed)
        if expected.ndim == 4:
            scores = torch.arange(expected.shape[-1], dtype=torch.float64)
            expected = (expected.to(torch.float64) * scores).sum(-1)
        loo_mean = loo_expectation(expected, weights, kind="mean").table.values[
            :, 0
        ]
        observed = _responses(fit, ExpectationOptions())
        values = loo_r2_draws(
            observed,
            loo_mean,
            torch.Generator().manual_seed(seed),
            expected.shape[0] * expected.shape[1],
        )
    if not summary:
        return values
    return summary_table({"R2": values.reshape(1, -1)}, probs=probs, robust=robust)

kfold

kfold(*, K: int = 10, Ksub: int | Sequence[int] | None = None, folds: Literal['random', 'stratified', 'grouped', 'loo'] | Sequence[int | str] | None = None, group: str | None = None, joint: Literal['obs', 'fold', 'group'] | bool = 'obs', save_fits: bool = False, method_factory: MethodFactory | None = None, num_samples: int | None = None, seed: int = 0, allow_new_levels: bool = True, sample_new_levels: NewLevelPolicy = 'gaussian') -> KFoldResult

Run k-fold cross-validation, as brms kfold.

PARAMETER DESCRIPTION
K

Number of folds.

TYPE: int DEFAULT: 10

Ksub

Number of randomly chosen folds, or explicit 0-based folds.

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

folds

None (random folds, or one fold per level of group), "loo" (one fold per row; with group, each fold omits the row's whole group), "stratified", "grouped", or one fold label per row.

TYPE: str or Sequence or None DEFAULT: None

group

Grouping column.

TYPE: str or None DEFAULT: None

joint

Predictive unit: rows, whole folds, or groups within folds.

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

save_fits

Retain the refits for kfold_predict.

TYPE: bool DEFAULT: False

method_factory

Fit settings per fold; None keeps the original settings with the fold's seed.

TYPE: MethodFactory or None DEFAULT: None

num_samples

Draws per chain of held-out scoring.

TYPE: int or None DEFAULT: None

seed

Partition and refit seed.

TYPE: int DEFAULT: 0

allow_new_levels

Score held-out rows with new group levels, True as in brms.

TYPE: bool DEFAULT: True

sample_new_levels

New-level policy, "gaussian" as in brms's k-fold.

TYPE: NewLevelPolicy DEFAULT: 'gaussian'

RETURNS DESCRIPTION
KFoldResult

The kfold criterion and the refits.

Source code in src/quivers/formulas/_postprocess_methods.py
def kfold(
    self,
    *,
    K: int = 10,
    Ksub: int | Sequence[int] | None = None,
    folds: Literal["random", "stratified", "grouped", "loo"]
    | Sequence[int | str]
    | None = None,
    group: str | None = None,
    joint: Literal["obs", "fold", "group"] | bool = "obs",
    save_fits: bool = False,
    method_factory: MethodFactory | None = None,
    num_samples: int | None = None,
    seed: int = 0,
    allow_new_levels: bool = True,
    sample_new_levels: NewLevelPolicy = "gaussian",
) -> KFoldResult:
    """Run k-fold cross-validation, as brms ``kfold``.

    Parameters
    ----------
    K : int
        Number of folds.
    Ksub : int or Sequence[int] or None
        Number of randomly chosen folds, or explicit 0-based folds.
    folds : str or Sequence or None
        None (random folds, or one fold per level of ``group``),
        ``"loo"`` (one fold per row; with ``group``, each fold omits the
        row's whole group), ``"stratified"``, ``"grouped"``, or one fold
        label per row.
    group : str or None
        Grouping column.
    joint : {"obs", "fold", "group"} or bool
        Predictive unit: rows, whole folds, or groups within folds.
    save_fits : bool
        Retain the refits for `kfold_predict`.
    method_factory : MethodFactory or None
        Fit settings per fold; None keeps the original settings with the
        fold's seed.
    num_samples : int or None
        Draws per chain of held-out scoring.
    seed : int
        Partition and refit seed.
    allow_new_levels : bool
        Score held-out rows with new group levels, True as in brms.
    sample_new_levels : NewLevelPolicy
        New-level policy, ``"gaussian"`` as in brms's k-fold.

    Returns
    -------
    KFoldResult
        The ``kfold`` criterion and the refits.
    """
    return kfold_from_fit(
        self._pp_fit(),
        joint=False,
        resp=None,
        K=K,
        Ksub=Ksub,
        folds=folds,
        group=group,
        joint_unit=joint,
        save_fits=save_fits,
        method_factory=method_factory or keep_settings,
        num_samples=num_samples,
        seed=seed,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
    )

add_criterion

add_criterion(criterion: str | Sequence[str], *, overwrite: bool = False, num_samples: int | None = None, seed: int = 0, kfold_options: Mapping[str, object] | None = None) -> SingleFit

Return the fit with criteria stored, as brms add_criterion.

PARAMETER DESCRIPTION
criterion

Any of loo, waic, kfold, loo_subsample, bayes_R2 and loo_R2.

TYPE: str or Sequence[str]

overwrite

Recompute criteria already stored.

TYPE: bool DEFAULT: False

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and resampling.

TYPE: int DEFAULT: 0

kfold_options

Keywords of kfold.

TYPE: Mapping or None DEFAULT: None

RETURNS DESCRIPTION
BayesianFit

A fit sharing this fit's model with the criteria stored; they persist through save_fit and load_fit.

RAISES DESCRIPTION
ValueError

If a criterion is unknown.

Source code in src/quivers/formulas/_postprocess_methods.py
def add_criterion(
    self,
    criterion: str | Sequence[str],
    *,
    overwrite: bool = False,
    num_samples: int | None = None,
    seed: int = 0,
    kfold_options: Mapping[str, object] | None = None,
) -> SingleFit:
    """Return the fit with criteria stored, as brms ``add_criterion``.

    Parameters
    ----------
    criterion : str or Sequence[str]
        Any of ``loo``, ``waic``, ``kfold``, ``loo_subsample``,
        ``bayes_R2`` and ``loo_R2``.
    overwrite : bool
        Recompute criteria already stored.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws and resampling.
    kfold_options : Mapping or None
        Keywords of `kfold`.

    Returns
    -------
    BayesianFit
        A fit sharing this fit's model with the criteria stored; they
        persist through `save_fit` and `load_fit`.

    Raises
    ------
    ValueError
        If a criterion is unknown.
    """
    names = [criterion] if isinstance(criterion, str) else list(criterion)
    stored = dict(self._pp_fit().criteria)
    for name in names:
        if name in stored and not overwrite:
            continue
        stored[name] = self._pp_compute_criterion(
            name, num_samples=num_samples, seed=seed, kfold_options=kfold_options
        )
    return self._pp_fit().with_(criteria=stored)

JointPostprocess

Bases: _PostprocessCore

brms post-processing methods of a joint MultivariateFit.

Per-response results are dictionaries keyed by response, where brms returns arrays with a response axis. Criteria score the units of MultivariateFit.log_likelihood: one row's joint event under residual correlation, or the per-row sum over the selected responses.

criterion

criterion(name: str, *, resp: ResponseSelection = None) -> ELPDEstimate | Tensor

Return a criterion stored by add_criterion.

PARAMETER DESCRIPTION
name

Criterion name.

TYPE: str

resp

Response selection. None prefers the whole-fit criterion if it is stored, then the most recently stored selection of this criterion.

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

RETURNS DESCRIPTION
ELPDEstimate or Tensor

The stored estimate or R-squared draws.

RAISES DESCRIPTION
KeyError

If the criterion is not stored for the selection.

Source code in src/quivers/formulas/_postprocess_methods.py
def criterion(
    self, name: str, *, resp: ResponseSelection = None
) -> ELPDEstimate | torch.Tensor:
    """Return a criterion stored by `add_criterion`.

    Parameters
    ----------
    name : str
        Criterion name.
    resp : str or Sequence[str] or None
        Response selection. None prefers the whole-fit criterion if it is
        stored, then the most recently stored selection of this criterion.

    Returns
    -------
    ELPDEstimate or torch.Tensor
        The stored estimate or R-squared draws.

    Raises
    ------
    KeyError
        If the criterion is not stored for the selection.
    """
    fit = self._pp_fit()
    if resp is None:
        stored = fit.criteria
        value = stored.get(name)
        if value is not None:
            return value
        for key in reversed(tuple(stored)):
            if key.startswith(f"{name}:"):
                return stored[key]
    else:
        value = self._stored_criterion(name, fit._selection(resp))
        if value is not None:
            return value
    raise KeyError(f"criterion {name!r} is not stored; call add_criterion first")

nobs

nobs(*, resp: str | None = None) -> int

Return the number of observations, as brms nobs.

PARAMETER DESCRIPTION
resp

One response, counting its included rows; None counts the rows of the data.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
int

Row count.

Source code in src/quivers/formulas/_postprocess_methods.py
def nobs(self, *, resp: str | None = None) -> int:
    """Return the number of observations, as brms ``nobs``.

    Parameters
    ----------
    resp : str or None
        One response, counting its included rows; None counts the rows of
        the data.

    Returns
    -------
    int
        Row count.
    """
    return self._pp_nobs(resp)

predict

predict(*, resp: ResponseSelection = None, summary: bool = True, robust: bool = False, probs: Sequence[float] = (0.025, 0.975), draw_ids: Sequence[int] | None = None, **options: Unpack[JointPredictionOptions]) -> dict[str, SummaryTable] | dict[str, Tensor]

Summarize joint posterior predictive draws, as brms predict.

PARAMETER DESCRIPTION
resp

Selected responses.

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

summary

Summarize; False returns the draws.

TYPE: bool DEFAULT: True

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

probs

Quantile probabilities.

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

draw_ids

0-based pooled draw positions.

TYPE: Sequence[int] or None DEFAULT: None

**options

MultivariateFit.posterior_predict keywords.

TYPE: JointPredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
dict

Per response, a summary table (category frequencies for ordinal and categorical responses), or the draws.

Source code in src/quivers/formulas/_postprocess_methods.py
def predict(
    self,
    *,
    resp: ResponseSelection = None,
    summary: bool = True,
    robust: bool = False,
    probs: Sequence[float] = (0.025, 0.975),
    draw_ids: Sequence[int] | None = None,
    **options: Unpack[JointPredictionOptions],
) -> dict[str, SummaryTable] | dict[str, torch.Tensor]:
    """Summarize joint posterior predictive draws, as brms ``predict``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    summary : bool
        Summarize; False returns the draws.
    robust : bool
        Median and MAD instead of mean and SD.
    probs : Sequence[float]
        Quantile probabilities.
    draw_ids : Sequence[int] or None
        0-based pooled draw positions.
    **options : JointPredictionOptions
        `MultivariateFit.posterior_predict` keywords.

    Returns
    -------
    dict
        Per response, a summary table (category frequencies for ordinal
        and categorical responses), or the draws.
    """
    draws = self._pp_prediction(
        "posterior_predict", resp, options, draw_ids=draw_ids
    )
    if not summary:
        return draws
    fit = self._pp_fit()
    return {
        name: summarize_prediction(
            value,
            categories=fit._predictor_readout(name).category_labels,
            discrete_table=self._pp_categorical(name),
            probs=probs,
            robust=robust,
        )
        for name, value in draws.items()
    }

fitted

fitted(*, resp: ResponseSelection = None, scale: Literal['response', 'linear'] = 'response', parameter: str | None = None, summary: bool = True, robust: bool = False, probs: Sequence[float] = (0.025, 0.975), draw_ids: Sequence[int] | None = None, **options: Unpack[JointPredictionOptions]) -> dict[str, SummaryTable] | dict[str, Tensor]

Summarize expected values or linear predictors, as brms fitted.

PARAMETER DESCRIPTION
resp

Selected responses.

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

scale

Expected responses or linear predictors.

TYPE: ('response', 'linear') DEFAULT: "response"

parameter

Distributional or nonlinear parameter of every selected response.

TYPE: str or None DEFAULT: None

summary

Summarize; False returns the draws.

TYPE: bool DEFAULT: True

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

probs

Quantile probabilities.

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

draw_ids

0-based pooled draw positions.

TYPE: Sequence[int] or None DEFAULT: None

**options

Prediction keywords.

TYPE: JointPredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
dict

Per response, a summary table or the draws.

RAISES DESCRIPTION
ValueError

If the scale is unknown.

Source code in src/quivers/formulas/_postprocess_methods.py
def fitted(
    self,
    *,
    resp: ResponseSelection = None,
    scale: Literal["response", "linear"] = "response",
    parameter: str | None = None,
    summary: bool = True,
    robust: bool = False,
    probs: Sequence[float] = (0.025, 0.975),
    draw_ids: Sequence[int] | None = None,
    **options: Unpack[JointPredictionOptions],
) -> dict[str, SummaryTable] | dict[str, torch.Tensor]:
    """Summarize expected values or linear predictors, as brms ``fitted``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    scale : {"response", "linear"}
        Expected responses or linear predictors.
    parameter : str or None
        Distributional or nonlinear parameter of every selected response.
    summary : bool
        Summarize; False returns the draws.
    robust : bool
        Median and MAD instead of mean and SD.
    probs : Sequence[float]
        Quantile probabilities.
    draw_ids : Sequence[int] or None
        0-based pooled draw positions.
    **options : JointPredictionOptions
        Prediction keywords.

    Returns
    -------
    dict
        Per response, a summary table or the draws.

    Raises
    ------
    ValueError
        If the scale is unknown.
    """
    if scale not in {"response", "linear"}:
        raise ValueError("scale must be 'response' or 'linear'")
    fit = self._pp_fit()
    if parameter is None and scale == "response":
        draws = self._pp_prediction(
            "posterior_epred", resp, options, draw_ids=draw_ids
        )
        labels = {
            name: fit._predictor_readout(name).category_labels for name in draws
        }
    else:
        name_ = parameter or "mu"
        draws = self._pp_prediction(
            "posterior_linpred",
            resp,
            options,
            draw_ids=draw_ids,
            parameter=name_,
            transform=scale == "response",
        )
        labels = {
            name: fit._predictor_readout(name).predictor_labels(name_)
            for name in draws
        }
    if not summary:
        return draws
    return {
        name: summarize_prediction(
            value,
            categories=labels[name],
            discrete_table=False,
            probs=probs,
            robust=robust,
        )
        for name, value in draws.items()
    }

predictive_error

predictive_error(*, resp: ResponseSelection = None, method: str = 'posterior_predict', draw_ids: Sequence[int] | None = None, **options: Unpack[JointPredictionOptions]) -> dict[str, Tensor]

Return draws of observed minus predicted responses, as brms predictive_error.

PARAMETER DESCRIPTION
resp

Selected responses.

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

method

Prediction method or alias.

TYPE: str DEFAULT: 'posterior_predict'

draw_ids

0-based pooled draw positions.

TYPE: Sequence[int] or None DEFAULT: None

**options

Prediction keywords; new_data must hold the responses.

TYPE: JointPredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
dict[str, Tensor]

Error draws keyed by response.

Source code in src/quivers/formulas/_postprocess_methods.py
def predictive_error(
    self,
    *,
    resp: ResponseSelection = None,
    method: str = "posterior_predict",
    draw_ids: Sequence[int] | None = None,
    **options: Unpack[JointPredictionOptions],
) -> dict[str, torch.Tensor]:
    """Return draws of observed minus predicted responses, as brms ``predictive_error``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    method : str
        Prediction method or alias.
    draw_ids : Sequence[int] or None
        0-based pooled draw positions.
    **options : JointPredictionOptions
        Prediction keywords; ``new_data`` must hold the responses.

    Returns
    -------
    dict[str, torch.Tensor]
        Error draws keyed by response.
    """
    return self._pp_errors(method, resp, draw_ids, options, pearson=False)

residuals

residuals(*, resp: ResponseSelection = None, method: str = 'posterior_predict', type: Literal['ordinary', 'pearson'] = 'ordinary', summary: bool = True, robust: bool = False, probs: Sequence[float] = (0.025, 0.975), draw_ids: Sequence[int] | None = None, **options: Unpack[JointPredictionOptions]) -> dict[str, SummaryTable] | dict[str, Tensor]

Summarize predictive errors per response, as brms residuals.

PARAMETER DESCRIPTION
resp

Selected responses.

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

method

Prediction method or alias.

TYPE: str DEFAULT: 'posterior_predict'

type

Residual type.

TYPE: ('ordinary', 'pearson') DEFAULT: "ordinary"

summary

Summarize; False returns the draws.

TYPE: bool DEFAULT: True

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

probs

Quantile probabilities.

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

draw_ids

0-based pooled draw positions.

TYPE: Sequence[int] or None DEFAULT: None

**options

Prediction keywords.

TYPE: JointPredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
dict

Per response, a summary table or error draws.

RAISES DESCRIPTION
ValueError

If the type is unknown.

Source code in src/quivers/formulas/_postprocess_methods.py
def residuals(
    self,
    *,
    resp: ResponseSelection = None,
    method: str = "posterior_predict",
    type: Literal["ordinary", "pearson"] = "ordinary",
    summary: bool = True,
    robust: bool = False,
    probs: Sequence[float] = (0.025, 0.975),
    draw_ids: Sequence[int] | None = None,
    **options: Unpack[JointPredictionOptions],
) -> dict[str, SummaryTable] | dict[str, torch.Tensor]:
    """Summarize predictive errors per response, as brms ``residuals``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    method : str
        Prediction method or alias.
    type : {"ordinary", "pearson"}
        Residual type.
    summary : bool
        Summarize; False returns the draws.
    robust : bool
        Median and MAD instead of mean and SD.
    probs : Sequence[float]
        Quantile probabilities.
    draw_ids : Sequence[int] or None
        0-based pooled draw positions.
    **options : JointPredictionOptions
        Prediction keywords.

    Returns
    -------
    dict
        Per response, a summary table or error draws.

    Raises
    ------
    ValueError
        If the type is unknown.
    """
    if type not in {"ordinary", "pearson"}:
        raise ValueError("type must be 'ordinary' or 'pearson'")
    draws = self._pp_errors(
        method, resp, draw_ids, options, pearson=type == "pearson"
    )
    if not summary:
        return draws
    return {
        name: summary_table(value, probs=probs, robust=robust)
        for name, value in draws.items()
    }

predictive_interval

predictive_interval(*, resp: ResponseSelection = None, prob: float = 0.9, **options: Unpack[JointPredictionOptions]) -> dict[str, SummaryTable]

Compute central predictive intervals per response, as brms predictive_interval.

PARAMETER DESCRIPTION
resp

Selected responses.

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

prob

Central mass, 0.9 as in brms.

TYPE: float DEFAULT: 0.9

**options

Prediction keywords.

TYPE: JointPredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
dict[str, SummaryTable]

Lower and upper bounds per row, keyed by response.

Source code in src/quivers/formulas/_postprocess_methods.py
def predictive_interval(
    self,
    *,
    resp: ResponseSelection = None,
    prob: float = 0.9,
    **options: Unpack[JointPredictionOptions],
) -> dict[str, SummaryTable]:
    """Compute central predictive intervals per response, as brms ``predictive_interval``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    prob : float
        Central mass, 0.9 as in brms.
    **options : JointPredictionOptions
        Prediction keywords.

    Returns
    -------
    dict[str, SummaryTable]
        Lower and upper bounds per row, keyed by response.
    """
    draws = self._pp_fit().posterior_predict(resp=resp, **options)
    return {
        name: predictive_table(value, prob=prob) for name, value in draws.items()
    }

loo

loo(*, resp: ResponseSelection = None, moment_match: bool = False, reloo: bool = False, k_threshold: float = 0.7, moment_match_args: Mapping[str, int | bool] | None = None, method_factory: MethodFactory | None = None, use_stored: bool = True, num_samples: int | None = None, seed: int = 0) -> ELPDEstimate

Estimate PSIS-LOO over joint units, as brms loo.

PARAMETER DESCRIPTION
resp

Scored responses, with the units of log_likelihood.

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

moment_match

Moment-match units above k_threshold.

TYPE: bool DEFAULT: False

reloo

Refit once per unit still above k_threshold.

TYPE: bool DEFAULT: False

k_threshold

Pareto shape threshold, 0.7 as in brms.

TYPE: float DEFAULT: 0.7

moment_match_args

max_iters, split and cov.

TYPE: Mapping or None DEFAULT: None

method_factory

Fit settings of each refit; None keeps the original settings.

TYPE: MethodFactory or None DEFAULT: None

use_stored

Return a stored loo criterion for the selected responses when no correction is requested.

TYPE: bool DEFAULT: True

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and refits.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ELPDEstimate

PSIS-LOO estimate.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo(
    self,
    *,
    resp: ResponseSelection = None,
    moment_match: bool = False,
    reloo: bool = False,
    k_threshold: float = 0.7,
    moment_match_args: Mapping[str, int | bool] | None = None,
    method_factory: MethodFactory | None = None,
    use_stored: bool = True,
    num_samples: int | None = None,
    seed: int = 0,
) -> ELPDEstimate:
    """Estimate PSIS-LOO over joint units, as brms ``loo``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Scored responses, with the units of `log_likelihood`.
    moment_match : bool
        Moment-match units above ``k_threshold``.
    reloo : bool
        Refit once per unit still above ``k_threshold``.
    k_threshold : float
        Pareto shape threshold, 0.7 as in brms.
    moment_match_args : Mapping or None
        ``max_iters``, ``split`` and ``cov``.
    method_factory : MethodFactory or None
        Fit settings of each refit; None keeps the original settings.
    use_stored : bool
        Return a stored ``loo`` criterion for the selected responses
        when no correction is requested.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws and refits.

    Returns
    -------
    ELPDEstimate
        PSIS-LOO estimate.
    """
    fit = self._pp_fit()
    if use_stored and not (moment_match or reloo):
        stored = self._stored_criterion("loo", fit._selection(resp))
        if isinstance(stored, ELPDEstimate):
            return stored
    return loo_estimate(
        fit,
        joint=True,
        resp=resp,
        moment_match_options=(moment_match_args or {}) if moment_match else None,
        reloo_factory=(method_factory or keep_settings) if reloo else None,
        k_threshold=k_threshold,
        num_samples=num_samples,
        seed=seed,
    )

loo_moment_match

loo_moment_match(loo: ELPDEstimate | None = None, *, resp: ResponseSelection = None, k_threshold: float = 0.7, max_iters: int = 30, split: bool = True, cov: bool = True, num_samples: int | None = None, seed: int = 0) -> ELPDEstimate

Moment-match problematic joint units, as brms loo_moment_match.

PARAMETER DESCRIPTION
loo

An estimate whose response hash must match; None recomputes.

TYPE: ELPDEstimate or None DEFAULT: None

resp

Scored responses.

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

k_threshold

Pareto shape threshold.

TYPE: float DEFAULT: 0.7

max_iters

Maximum iterations per unit.

TYPE: int DEFAULT: 30

split

Split moment matching.

TYPE: bool DEFAULT: True

cov

Also match covariances.

TYPE: bool DEFAULT: True

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ELPDEstimate

Updated estimate.

RAISES DESCRIPTION
ValueError

If loo scores different responses.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_moment_match(
    self,
    loo: ELPDEstimate | None = None,
    *,
    resp: ResponseSelection = None,
    k_threshold: float = 0.7,
    max_iters: int = 30,
    split: bool = True,
    cov: bool = True,
    num_samples: int | None = None,
    seed: int = 0,
) -> ELPDEstimate:
    """Moment-match problematic joint units, as brms ``loo_moment_match``.

    Parameters
    ----------
    loo : ELPDEstimate or None
        An estimate whose response hash must match; None recomputes.
    resp : str or Sequence[str] or None
        Scored responses.
    k_threshold : float
        Pareto shape threshold.
    max_iters : int
        Maximum iterations per unit.
    split : bool
        Split moment matching.
    cov : bool
        Also match covariances.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    ELPDEstimate
        Updated estimate.

    Raises
    ------
    ValueError
        If ``loo`` scores different responses.
    """
    result = loo_estimate(
        self._pp_fit(),
        joint=True,
        resp=resp,
        moment_match_options={"max_iters": max_iters, "split": split, "cov": cov},
        reloo_factory=None,
        k_threshold=k_threshold,
        num_samples=num_samples,
        seed=seed,
    )
    if loo is not None and loo.response_hash != result.response_hash:
        raise ValueError("response values used in loo and in this fit differ")
    return result

waic

waic(*, resp: ResponseSelection = None, num_samples: int | None = None, seed: int = 0) -> ELPDEstimate

Estimate WAIC over joint units, as brms waic.

PARAMETER DESCRIPTION
resp

Scored responses.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ELPDEstimate

WAIC estimate.

Source code in src/quivers/formulas/_postprocess_methods.py
def waic(
    self,
    *,
    resp: ResponseSelection = None,
    num_samples: int | None = None,
    seed: int = 0,
) -> ELPDEstimate:
    """Estimate WAIC over joint units, as brms ``waic``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Scored responses.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    ELPDEstimate
        WAIC estimate.
    """
    return waic_from_fit(
        self._pp_fit(), joint=True, resp=resp, num_samples=num_samples, seed=seed
    )

psis

psis(*, resp: ResponseSelection = None, num_samples: int | None = None, seed: int = 0) -> PSISWeights

Return PSIS leave-one-out weights of joint units, as brms psis.

PARAMETER DESCRIPTION
resp

Scored responses.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PSISWeights

Smoothed log weights and Pareto diagnostics.

Source code in src/quivers/formulas/_postprocess_methods.py
def psis(
    self,
    *,
    resp: ResponseSelection = None,
    num_samples: int | None = None,
    seed: int = 0,
) -> PSISWeights:
    """Return PSIS leave-one-out weights of joint units, as brms ``psis``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Scored responses.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    PSISWeights
        Smoothed log weights and Pareto diagnostics.
    """
    scores = criterion_scores(
        self._pp_fit(), joint=True, resp=resp, num_samples=num_samples, seed=seed
    )
    return psis_weights(
        scores.log_likelihood, r_eff=relative_efficiency(scores.analysis)
    )

loo_subsample

loo_subsample(*, resp: ResponseSelection = None, observations: int | Sequence[int] = 400, approximation: Literal['plpd', 'lpd'] = 'plpd', num_samples: int | None = None, seed: int = 0) -> ELPDEstimate

Estimate PSIS-LOO from a row subsample, as brms loo_subsample.

PARAMETER DESCRIPTION
resp

Scored responses.

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

observations

Subsample size or explicit 0-based rows.

TYPE: int or Sequence[int] DEFAULT: 400

approximation

Approximation of every row's term.

TYPE: ('plpd', 'lpd') DEFAULT: "plpd"

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed of the subsample and variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ELPDEstimate

Subsampled estimate.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_subsample(
    self,
    *,
    resp: ResponseSelection = None,
    observations: int | Sequence[int] = 400,
    approximation: Literal["plpd", "lpd"] = "plpd",
    num_samples: int | None = None,
    seed: int = 0,
) -> ELPDEstimate:
    """Estimate PSIS-LOO from a row subsample, as brms ``loo_subsample``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Scored responses.
    observations : int or Sequence[int]
        Subsample size or explicit 0-based rows.
    approximation : {"plpd", "lpd"}
        Approximation of every row's term.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed of the subsample and variational draws.

    Returns
    -------
    ELPDEstimate
        Subsampled estimate.
    """
    return loo_subsample_estimate(
        self._pp_fit(),
        joint=True,
        resp=resp,
        observations=observations,
        approximation=approximation,
        num_samples=num_samples,
        seed=seed,
    )

loo_predict

loo_predict(*, resp: ResponseSelection = None, type: Literal['mean', 'var', 'quantile'] = 'mean', probs: Sequence[float] = (0.5,), num_samples: int | None = None, seed: int = 0) -> dict[str, LooExpectation]

Compute leave-one-out predictive statistics, as brms loo_predict.

PARAMETER DESCRIPTION
resp

Selected responses.

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

type

Weighted statistic.

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

probs

Quantile probabilities.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and responses.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, LooExpectation]

Statistics per row, keyed by response.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_predict(
    self,
    *,
    resp: ResponseSelection = None,
    type: Literal["mean", "var", "quantile"] = "mean",
    probs: Sequence[float] = (0.5,),
    num_samples: int | None = None,
    seed: int = 0,
) -> dict[str, LooExpectation]:
    """Compute leave-one-out predictive statistics, as brms ``loo_predict``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    type : {"mean", "var", "quantile"}
        Weighted statistic.
    probs : Sequence[float]
        Quantile probabilities.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws and responses.

    Returns
    -------
    dict[str, LooExpectation]
        Statistics per row, keyed by response.
    """
    return self._pp_loo_expectation(
        "posterior_predict",
        resp,
        type=type,
        probs=probs,
        num_samples=num_samples,
        seed=seed,
    )

loo_epred

loo_epred(*, resp: ResponseSelection = None, type: Literal['mean', 'var', 'quantile'] = 'mean', probs: Sequence[float] = (0.5,), num_samples: int | None = None, seed: int = 0) -> dict[str, LooExpectation]

Compute leave-one-out expected responses, as brms loo_epred.

PARAMETER DESCRIPTION
resp

Selected responses.

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

type

Weighted statistic.

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

probs

Quantile probabilities.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, LooExpectation]

Statistics per row, keyed by response.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_epred(
    self,
    *,
    resp: ResponseSelection = None,
    type: Literal["mean", "var", "quantile"] = "mean",
    probs: Sequence[float] = (0.5,),
    num_samples: int | None = None,
    seed: int = 0,
) -> dict[str, LooExpectation]:
    """Compute leave-one-out expected responses, as brms ``loo_epred``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    type : {"mean", "var", "quantile"}
        Weighted statistic.
    probs : Sequence[float]
        Quantile probabilities.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    dict[str, LooExpectation]
        Statistics per row, keyed by response.
    """
    return self._pp_loo_expectation(
        "posterior_epred",
        resp,
        type=type,
        probs=probs,
        num_samples=num_samples,
        seed=seed,
    )

loo_linpred

loo_linpred(*, resp: ResponseSelection = None, type: Literal['mean', 'var', 'quantile'] = 'mean', probs: Sequence[float] = (0.5,), num_samples: int | None = None, seed: int = 0) -> dict[str, LooExpectation]

Compute leave-one-out linear predictors, as brms loo_linpred.

PARAMETER DESCRIPTION
resp

Selected responses.

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

type

Weighted statistic.

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

probs

Quantile probabilities.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, LooExpectation]

Statistics per row, keyed by response.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_linpred(
    self,
    *,
    resp: ResponseSelection = None,
    type: Literal["mean", "var", "quantile"] = "mean",
    probs: Sequence[float] = (0.5,),
    num_samples: int | None = None,
    seed: int = 0,
) -> dict[str, LooExpectation]:
    """Compute leave-one-out linear predictors, as brms ``loo_linpred``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    type : {"mean", "var", "quantile"}
        Weighted statistic.
    probs : Sequence[float]
        Quantile probabilities.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws.

    Returns
    -------
    dict[str, LooExpectation]
        Statistics per row, keyed by response.
    """
    return self._pp_loo_expectation(
        "posterior_linpred",
        resp,
        type=type,
        probs=probs,
        num_samples=num_samples,
        seed=seed,
    )

loo_predictive_interval

loo_predictive_interval(*, resp: ResponseSelection = None, prob: float = 0.9, num_samples: int | None = None, seed: int = 0) -> dict[str, LooExpectation]

Compute leave-one-out predictive intervals, as brms loo_predictive_interval.

PARAMETER DESCRIPTION
resp

Selected responses.

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

prob

Central mass.

TYPE: float DEFAULT: 0.9

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and responses.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, LooExpectation]

Weighted quantiles per row, keyed by response.

RAISES DESCRIPTION
ValueError

If the mass is not strictly inside (0, 1).

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_predictive_interval(
    self,
    *,
    resp: ResponseSelection = None,
    prob: float = 0.9,
    num_samples: int | None = None,
    seed: int = 0,
) -> dict[str, LooExpectation]:
    """Compute leave-one-out predictive intervals, as brms ``loo_predictive_interval``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    prob : float
        Central mass.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed for variational draws and responses.

    Returns
    -------
    dict[str, LooExpectation]
        Weighted quantiles per row, keyed by response.

    Raises
    ------
    ValueError
        If the mass is not strictly inside (0, 1).
    """
    if not 0 < prob < 1:
        raise ValueError("prob must lie strictly between zero and one")
    alpha = (1 - prob) / 2
    return self.loo_predict(
        resp=resp,
        type="quantile",
        probs=(alpha, 1 - alpha),
        num_samples=num_samples,
        seed=seed,
    )

bayes_r2

bayes_r2(*, resp: ResponseSelection = None, method: Literal['auto', 'model', 'residual'] = 'auto', observed: Mapping[str, Tensor] | None = None, mc_samples: int | None = None, **options: Unpack[JointPredictionOptions]) -> dict[str, Tensor]

Compute the Bayesian R-squared of each response, as brms bayes_R2.

Each response is read as the single-response fit reads it (BayesianFit.bayes_r2): the residual form divides the variance of the conditional means over the rows by itself plus the variance of the residuals [@gelman2019rsquared]; the model form uses the mean conditional variance of each row's law instead, under residual correlation the marginal law of the response's coordinate. An ordinal response is scored by its category codes.

PARAMETER DESCRIPTION
resp

Selected responses, or None for every response.

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

method

Requested form; auto is each response's own default.

TYPE: ('auto', 'model', 'residual') DEFAULT: "auto"

observed

Explicit observed responses by label, for the residual form.

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

mc_samples

Monte Carlo budget of conditional means without a closed form.

TYPE: int or None DEFAULT: None

**options

Prediction keywords of MultivariateFit.posterior_epred.

TYPE: Unpack[JointPredictionOptions] DEFAULT: {}

RETURNS DESCRIPTION
dict[str, Tensor]

R2<resp> mapped to ratios on (chain, draw) axes.

RAISES DESCRIPTION
ValueError

If a selected response is unordered categorical, has several columns, or is censored without explicit observations under the residual form.

Notes

Cost is one posterior replay per draw for the conditional means, and one more for the model form.

Source code in src/quivers/formulas/_postprocess_methods.py
def bayes_r2(
    self,
    *,
    resp: ResponseSelection = None,
    method: Literal["auto", "model", "residual"] = "auto",
    observed: Mapping[str, torch.Tensor] | None = None,
    mc_samples: int | None = None,
    **options: Unpack[JointPredictionOptions],
) -> dict[str, torch.Tensor]:
    """Compute the Bayesian R-squared of each response, as brms ``bayes_R2``.

    Each response is read as the single-response fit reads it
    (`BayesianFit.bayes_r2`): the residual form divides the variance of
    the conditional means over the rows by itself plus the variance of
    the residuals [@gelman2019rsquared]; the model form uses the mean
    conditional variance of each row's law instead, under residual
    correlation the marginal law of the response's coordinate. An
    ordinal response is scored by its category codes.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses, or None for every response.
    method : {"auto", "model", "residual"}
        Requested form; ``auto`` is each response's own default.
    observed : Mapping[str, torch.Tensor] or None
        Explicit observed responses by label, for the residual form.
    mc_samples : int or None
        Monte Carlo budget of conditional means without a closed form.
    **options
        Prediction keywords of `MultivariateFit.posterior_epred`.

    Returns
    -------
    dict[str, torch.Tensor]
        ``R2<resp>`` mapped to ratios on ``(chain, draw)`` axes.

    Raises
    ------
    ValueError
        If a selected response is unordered categorical, has several
        columns, or is censored without explicit observations under the
        residual form.

    Notes
    -----
    Cost is one posterior replay per draw for the conditional means, and
    one more for the model form.
    """
    fit = self._pp_fit()
    new_data = options.get("new_data")
    values: dict[str, torch.Tensor] = {}
    for name in fit._selection(resp):
        data = fit._response_data(name)
        readout = fit._response_readout(name)
        dependence = fit.emission.responses[name].lens._residual

        def expected(
            name: str = name, ordinal: bool = readout.ordinal
        ) -> torch.Tensor:
            means = fit.posterior_epred(
                resp=name, mc_samples=mc_samples, **options
            )[name]
            if not ordinal and means.ndim != 3:
                raise ValueError(
                    f"bayes_R2 is defined for one value per row; response {name!r} "
                    f"has conditional means of shape {tuple(means.shape[2:])}"
                )
            return means

        values[f"R2{name}"] = formula_r2(
            data,
            readout,
            dependence,
            method,
            None if observed is None else observed.get(name),
            new_data=new_data,
            mc_samples=mc_samples,
            recorded=lambda: evaluate_responses(data, new_data),
            expected=expected,
            laws=lambda name=name: fit._response_laws(name, options),
        )
    return values

loo_r2

loo_r2(*, resp: ResponseSelection = None, summary: bool = True, robust: bool = False, probs: Sequence[float] = (0.025, 0.975), num_samples: int | None = None, seed: int = 0) -> SummaryTable | dict[str, Tensor]

Compute leave-one-out R-squared per response, as brms loo_R2.

Each response uses its own pointwise log-likelihood, as brms does.

PARAMETER DESCRIPTION
resp

Selected responses.

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

summary

Summarize; False returns the bootstrap draws.

TYPE: bool DEFAULT: True

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

probs

Quantile probabilities.

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

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed of the Dirichlet weights and variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
SummaryTable or dict[str, Tensor]

Rows R2<resp>, or draws keyed by R2<resp>.

RAISES DESCRIPTION
ValueError

For unordered categorical responses.

Source code in src/quivers/formulas/_postprocess_methods.py
def loo_r2(
    self,
    *,
    resp: ResponseSelection = None,
    summary: bool = True,
    robust: bool = False,
    probs: Sequence[float] = (0.025, 0.975),
    num_samples: int | None = None,
    seed: int = 0,
) -> SummaryTable | dict[str, torch.Tensor]:
    """Compute leave-one-out R-squared per response, as brms ``loo_R2``.

    Each response uses its own pointwise log-likelihood, as brms does.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses.
    summary : bool
        Summarize; False returns the bootstrap draws.
    robust : bool
        Median and MAD instead of mean and SD.
    probs : Sequence[float]
        Quantile probabilities.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed of the Dirichlet weights and variational draws.

    Returns
    -------
    SummaryTable or dict[str, torch.Tensor]
        Rows ``R2<resp>``, or draws keyed by ``R2<resp>``.

    Raises
    ------
    ValueError
        For unordered categorical responses.
    """
    fit = self._pp_fit()
    values: dict[str, torch.Tensor] = {}
    for index, name in enumerate(fit._selection(resp)):
        if fit._response_readout(name).unordered:
            raise ValueError(
                "loo_R2 is not defined for unordered categorical models"
            )
        weights = self.psis(resp=name, num_samples=num_samples, seed=seed)
        expected = fit.posterior_epred(
            resp=name, num_samples=num_samples, seed=seed
        )[name]
        if expected.ndim == 4:
            scores = torch.arange(expected.shape[-1], dtype=torch.float64)
            expected = (expected.to(torch.float64) * scores).sum(-1)
        loo_mean = loo_expectation(expected, weights, kind="mean").table.values[
            :, 0
        ]
        values[f"R2{name}"] = loo_r2_draws(
            evaluate_responses(fit._response_data(name), None),
            loo_mean,
            torch.Generator().manual_seed(seed + index),
            expected.shape[0] * expected.shape[1],
        )
    if not summary:
        return values
    return summary_table(
        {name: value.reshape(1, -1) for name, value in values.items()},
        probs=probs,
        robust=robust,
    )

kfold

kfold(*, resp: ResponseSelection = None, K: int = 10, Ksub: int | Sequence[int] | None = None, folds: Literal['random', 'stratified', 'grouped', 'loo'] | Sequence[int | str] | None = None, group: str | None = None, joint: Literal['obs', 'fold', 'group'] | bool = 'obs', save_fits: bool = False, method_factory: MethodFactory | None = None, num_samples: int | None = None, seed: int = 0, allow_new_levels: bool = True, sample_new_levels: NewLevelPolicy = 'gaussian') -> KFoldResult

Run k-fold cross-validation of the joint model, as brms kfold.

PARAMETER DESCRIPTION
resp

Scored responses.

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

K

Number of folds.

TYPE: int DEFAULT: 10

Ksub

Number of random folds, or explicit 0-based folds.

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

folds

Fold type or labels, as BayesianFit.kfold.

TYPE: str or Sequence or None DEFAULT: None

group

Grouping column.

TYPE: str or None DEFAULT: None

joint

Predictive unit.

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

save_fits

Retain the refits.

TYPE: bool DEFAULT: False

method_factory

Fit settings per fold.

TYPE: MethodFactory or None DEFAULT: None

num_samples

Draws per chain of held-out scoring.

TYPE: int or None DEFAULT: None

seed

Partition and refit seed.

TYPE: int DEFAULT: 0

allow_new_levels

Score new group levels.

TYPE: bool DEFAULT: True

sample_new_levels

New-level policy.

TYPE: NewLevelPolicy DEFAULT: 'gaussian'

RETURNS DESCRIPTION
KFoldResult

The criterion and the refits.

Source code in src/quivers/formulas/_postprocess_methods.py
def kfold(
    self,
    *,
    resp: ResponseSelection = None,
    K: int = 10,
    Ksub: int | Sequence[int] | None = None,
    folds: Literal["random", "stratified", "grouped", "loo"]
    | Sequence[int | str]
    | None = None,
    group: str | None = None,
    joint: Literal["obs", "fold", "group"] | bool = "obs",
    save_fits: bool = False,
    method_factory: MethodFactory | None = None,
    num_samples: int | None = None,
    seed: int = 0,
    allow_new_levels: bool = True,
    sample_new_levels: NewLevelPolicy = "gaussian",
) -> KFoldResult:
    """Run k-fold cross-validation of the joint model, as brms ``kfold``.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Scored responses.
    K : int
        Number of folds.
    Ksub : int or Sequence[int] or None
        Number of random folds, or explicit 0-based folds.
    folds : str or Sequence or None
        Fold type or labels, as `BayesianFit.kfold`.
    group : str or None
        Grouping column.
    joint : {"obs", "fold", "group"} or bool
        Predictive unit.
    save_fits : bool
        Retain the refits.
    method_factory : MethodFactory or None
        Fit settings per fold.
    num_samples : int or None
        Draws per chain of held-out scoring.
    seed : int
        Partition and refit seed.
    allow_new_levels : bool
        Score new group levels.
    sample_new_levels : NewLevelPolicy
        New-level policy.

    Returns
    -------
    KFoldResult
        The criterion and the refits.
    """
    return kfold_from_fit(
        self._pp_fit(),
        joint=True,
        resp=resp,
        K=K,
        Ksub=Ksub,
        folds=folds,
        group=group,
        joint_unit=joint,
        save_fits=save_fits,
        method_factory=method_factory or keep_settings,
        num_samples=num_samples,
        seed=seed,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
    )

add_criterion

add_criterion(criterion: str | Sequence[str], *, resp: ResponseSelection = None, overwrite: bool = False, num_samples: int | None = None, seed: int = 0, kfold_options: Mapping[str, object] | None = None) -> JointFit

Return the joint fit with criteria stored, as brms add_criterion.

PARAMETER DESCRIPTION
criterion

Any of loo, waic, kfold, loo_subsample, bayes_R2 and loo_R2.

TYPE: str or Sequence[str]

resp

Responses the criterion scores, as brms's resp; None scores every response. At a row with an mi() response, the likelihood scores the recorded outcomes given the completed values.

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

overwrite

Recompute stored criteria.

TYPE: bool DEFAULT: False

num_samples

Draws per chain.

TYPE: int or None DEFAULT: None

seed

Seed.

TYPE: int DEFAULT: 0

kfold_options

Keywords of kfold.

TYPE: Mapping or None DEFAULT: None

RETURNS DESCRIPTION
MultivariateFit

A fit sharing this model with the criteria stored.

RAISES DESCRIPTION
ValueError

If a criterion is unknown.

Source code in src/quivers/formulas/_postprocess_methods.py
def add_criterion(
    self,
    criterion: str | Sequence[str],
    *,
    resp: ResponseSelection = None,
    overwrite: bool = False,
    num_samples: int | None = None,
    seed: int = 0,
    kfold_options: Mapping[str, object] | None = None,
) -> JointFit:
    """Return the joint fit with criteria stored, as brms ``add_criterion``.

    Parameters
    ----------
    criterion : str or Sequence[str]
        Any of ``loo``, ``waic``, ``kfold``, ``loo_subsample``,
        ``bayes_R2`` and ``loo_R2``.
    resp : str or Sequence[str] or None
        Responses the criterion scores, as brms's ``resp``; None scores
        every response. At a row with an ``mi()`` response, the likelihood
        scores the recorded outcomes given the completed values.
    overwrite : bool
        Recompute stored criteria.
    num_samples : int or None
        Draws per chain.
    seed : int
        Seed.
    kfold_options : Mapping or None
        Keywords of `kfold`.

    Returns
    -------
    MultivariateFit
        A fit sharing this model with the criteria stored.

    Raises
    ------
    ValueError
        If a criterion is unknown.
    """
    fit = self._pp_fit()
    names = [criterion] if isinstance(criterion, str) else list(criterion)
    stored = dict(fit.criteria)
    for name in names:
        options = dict(kfold_options or {}) if name == "kfold" else {}
        selected = fit._selection(
            cast(ResponseSelection, options.get("resp", resp))
        )
        key = self._criterion_key(name, selected)
        legacy = stored.get(name)
        if (
            isinstance(legacy, ELPDEstimate)
            and legacy.responses != fit.response_names
            and legacy.responses
            and set(legacy.responses) <= set(fit.response_names)
        ):
            stored.setdefault(self._criterion_key(name, legacy.responses), legacy)
            del stored[name]
        if key in stored and not overwrite:
            continue
        if name == "loo":
            stored[key] = self.loo(
                resp=resp, use_stored=False, num_samples=num_samples, seed=seed
            )
        elif name == "waic":
            stored[key] = self.waic(resp=resp, num_samples=num_samples, seed=seed)
        elif name == "loo_subsample":
            stored[key] = self.loo_subsample(
                resp=resp, num_samples=num_samples, seed=seed
            )
        elif name == "kfold":
            options.setdefault("resp", resp)
            options.setdefault("seed", seed)
            stored[key] = self.kfold(**cast(dict, options)).estimate
        elif name == "loo_R2":
            draws = cast(
                dict,
                self.loo_r2(
                    resp=resp, summary=False, num_samples=num_samples, seed=seed
                ),
            )
            stored[key] = torch.stack(list(draws.values()), dim=-1)
        elif name == "bayes_R2":
            ratios = self.bayes_r2(resp=resp, num_samples=num_samples, seed=seed)
            stored[key] = torch.stack(
                [value.flatten(0, 1) for value in ratios.values()], dim=-1
            )
        else:
            raise ValueError(
                f"unknown criterion {name!r}; expected loo, waic, kfold, "
                "loo_subsample, bayes_R2 or loo_R2"
            )
    return fit.with_(criteria=stored, response_fits=dict(fit.response_fits))

brms evidence, effects, and predictive checks

BayesianFit and MultivariateFit carry brms's marginal-likelihood, conditional-effects, predictive-check and MCMC-plot methods: bridge_sampler, bayes_factor, automatic conditional_effects, conditional_smooths, pp_check, mcmc_plot, plot, and pairs. The functions post_prob, posterior_average, pp_average, and make_conditions take several fits or a data frame. The analysis guide states their brms counterparts and the deliberate differences.

bridge_sampler

bridge_sampler(fit: Fit, *, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> BridgeResult

Estimate a fit's log marginal likelihood by bridge sampling.

PARAMETER DESCRIPTION
fit

Fit with posterior MCMC draws and proper priors.

TYPE: BayesianFit or MultivariateFit

method

Proposal of the bridgesampling package.

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

repetitions

Independent proposal draws.

TYPE: int DEFAULT: 1

use_neff

Use the effective size of the iteration draws.

TYPE: bool DEFAULT: True

maxiter

Iteration bound of the fixed-point scheme.

TYPE: int DEFAULT: 1000

seed

Seed of the proposal draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
BridgeResult

The estimate, with the retained log densities.

RAISES DESCRIPTION
ValueError

If the fit is refused by require_normalized or its draws are invalid for the estimator.

RuntimeError

If the scheme does not converge.

Notes

Cost is S / 2 (1 + R) program evaluations for S draws and R repetitions (twice that for "warp3"), each O(C) for one log-joint evaluation of the fit's program.

Source code in src/quivers/formulas/_evidence.py
def bridge_sampler(
    fit: Fit,
    *,
    method: BridgeMethod = "normal",
    repetitions: int = 1,
    use_neff: bool = True,
    maxiter: int = 1000,
    seed: int = 0,
) -> BridgeResult:
    """Estimate a fit's log marginal likelihood by bridge sampling.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fit with posterior MCMC draws and proper priors.
    method : {"normal", "warp3"}
        Proposal of the ``bridgesampling`` package.
    repetitions : int
        Independent proposal draws.
    use_neff : bool
        Use the effective size of the iteration draws.
    maxiter : int
        Iteration bound of the fixed-point scheme.
    seed : int
        Seed of the proposal draws.

    Returns
    -------
    BridgeResult
        The estimate, with the retained log densities.

    Raises
    ------
    ValueError
        If the fit is refused by `require_normalized` or its draws are
        invalid for the estimator.
    RuntimeError
        If the scheme does not converge.

    Notes
    -----
    Cost is ``S / 2 (1 + R)`` program evaluations for ``S`` draws and ``R``
    repetitions (twice that for ``"warp3"``), each O(C) for one log-joint
    evaluation of the fit's program.
    """
    require_normalized(fit, "bridge_sampler")
    upars, potential = log_posterior_function(fit)

    def log_posterior(points: np.ndarray) -> np.ndarray:
        """Evaluate the Jacobian-corrected log joint row-wise.

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

        Returns
        -------
        numpy.ndarray
            Log densities ``(N,)``, ``-inf`` outside the support.
        """
        values = torch.from_numpy(np.ascontiguousarray(points))
        with torch.no_grad():
            return np.array(
                [float(potential.log_density(row)) for row in values],
                dtype=np.float64,
            )

    return bridge_estimate(
        log_posterior,
        upars,
        method=method,
        repetitions=repetitions,
        use_neff=use_neff,
        maxiter=maxiter,
        seed=seed,
    )

bayes_factor

bayes_factor(x1: EvidenceInput, x2: EvidenceInput, *, log: bool = False, model_names: tuple[str, str] = ('x1', 'x2'), method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> BayesFactor

Return the Bayes factor of two models, as brms bayes_factor.

PARAMETER DESCRIPTION
x1

Numerator and denominator models, or their bridge estimates.

TYPE: BayesianFit or MultivariateFit or BridgeResult

x2

Numerator and denominator models, or their bridge estimates.

TYPE: BayesianFit or MultivariateFit or BridgeResult

log

Return the log Bayes factor.

TYPE: bool DEFAULT: False

model_names

Names of the two models.

TYPE: tuple[str, str] DEFAULT: ('x1', 'x2')

method

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

repetitions

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

use_neff

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

maxiter

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

seed

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

RETURNS DESCRIPTION
BayesFactor

:math:p(y \mid M_1) / p(y \mid M_2).

RAISES DESCRIPTION
ValueError

If the fits model different response data or are refused by bridge_sampler.

Source code in src/quivers/formulas/_evidence.py
def bayes_factor(
    x1: EvidenceInput,
    x2: EvidenceInput,
    *,
    log: bool = False,
    model_names: tuple[str, str] = ("x1", "x2"),
    method: BridgeMethod = "normal",
    repetitions: int = 1,
    use_neff: bool = True,
    maxiter: int = 1000,
    seed: int = 0,
) -> BayesFactor:
    """Return the Bayes factor of two models, as brms ``bayes_factor``.

    Parameters
    ----------
    x1, x2 : BayesianFit or MultivariateFit or BridgeResult
        Numerator and denominator models, or their bridge estimates.
    log : bool
        Return the log Bayes factor.
    model_names : tuple[str, str]
        Names of the two models.
    method, repetitions, use_neff, maxiter, seed
        `bridge_sampler` settings for fits.

    Returns
    -------
    BayesFactor
        :math:`p(y \\mid M_1) / p(y \\mid M_2)`.

    Raises
    ------
    ValueError
        If the fits model different response data or are refused by
        `bridge_sampler`.
    """
    match_responses((x1, x2))
    options = BridgeSettings(
        method=method,
        repetitions=repetitions,
        use_neff=use_neff,
        maxiter=maxiter,
        seed=seed,
    )
    value = bayes_factor_from_logml(_logml(x1, options), _logml(x2, options), log=log)
    return BayesFactor(
        bf=value, log=log, numerator=model_names[0], denominator=model_names[1]
    )

post_prob

post_prob(models: Mapping[str, EvidenceInput], *, prior_prob: Sequence[float] | None = None, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> dict[str, float]

Return posterior model probabilities, as brms post_prob.

PARAMETER DESCRIPTION
models

At least two named models of the same response data.

TYPE: Mapping[str, BayesianFit or MultivariateFit or BridgeResult]

prior_prob

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

TYPE: Sequence[float] or None DEFAULT: None

method

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

repetitions

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

use_neff

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

maxiter

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

seed

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

RETURNS DESCRIPTION
dict[str, float]

Posterior probabilities summing to one.

RAISES DESCRIPTION
ValueError

If fewer than two models are given, the fits model different data, or the prior probabilities are invalid.

Source code in src/quivers/formulas/_evidence.py
def post_prob(
    models: Mapping[str, EvidenceInput],
    *,
    prior_prob: Sequence[float] | None = None,
    method: BridgeMethod = "normal",
    repetitions: int = 1,
    use_neff: bool = True,
    maxiter: int = 1000,
    seed: int = 0,
) -> dict[str, float]:
    """Return posterior model probabilities, as brms ``post_prob``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit or BridgeResult]
        At least two named models of the same response data.
    prior_prob : Sequence[float] or None
        Prior model probabilities in the order of ``models``; uniform when None.
    method, repetitions, use_neff, maxiter, seed
        `bridge_sampler` settings for fits.

    Returns
    -------
    dict[str, float]
        Posterior probabilities summing to one.

    Raises
    ------
    ValueError
        If fewer than two models are given, the fits model different data,
        or the prior probabilities are invalid.
    """
    match_responses(tuple(models.values()))
    options = BridgeSettings(
        method=method,
        repetitions=repetitions,
        use_neff=use_neff,
        maxiter=maxiter,
        seed=seed,
    )
    return posterior_model_probabilities(
        {name: _logml(model, options) for name, model in models.items()},
        prior_prob=prior_prob,
    )

BayesFactor didactic-model

BayesFactor(*, bf: float, log: bool, numerator: str = 'x1', denominator: str = 'x2')

Bases: ValueModel

A Bayes factor of two models, as a bf_bridge object.

PARAMETER DESCRIPTION
bf

:math:p(y \mid M_1) / p(y \mid M_2), or its logarithm.

TYPE: float

log

Whether bf is on the log scale.

TYPE: bool

numerator

Names of the numerator and denominator models.

TYPE: str DEFAULT: 'x1'

denominator

Names of the numerator and denominator models.

TYPE: str DEFAULT: 'x1'

posterior_average

posterior_average(models: Mapping[str, Fit], *, variable: str | Sequence[str] | None = None, weights: WeightMethod | Sequence[float] = 'stacking', ndraws: int | None = None, missing: float | Mapping[str, float] | None = None, seed: int = 0) -> PosteriorAverage

Mix the posterior draws of several fits, as brms posterior_average.

PARAMETER DESCRIPTION
models

Named fits.

TYPE: Mapping[str, BayesianFit or MultivariateFit]

variable

brms variable names (see variables); None takes every variable common to all models (every variable of any model with missing).

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

weights

Weighting method of averaging_weights, or explicit weights.

TYPE: str or Sequence[float] DEFAULT: 'stacking'

ndraws

Total draws; the first model's draw count by default.

TYPE: int or None DEFAULT: None

missing

Value of a variable in models that lack it; None requires every variable in every model.

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

seed

Seed of the draw selection and of the weights.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PosteriorAverage

Pooled draws, weights and draw counts.

RAISES DESCRIPTION
ValueError

If a variable is absent from the required models, missing lacks a value for one, or the weights or draw counts are invalid.

Source code in src/quivers/formulas/_model_averaging.py
def posterior_average(
    models: Mapping[str, Fit],
    *,
    variable: str | Sequence[str] | None = None,
    weights: WeightMethod | Sequence[float] = "stacking",
    ndraws: int | None = None,
    missing: float | Mapping[str, float] | None = None,
    seed: int = 0,
) -> PosteriorAverage:
    """Mix the posterior draws of several fits, as brms ``posterior_average``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit]
        Named fits.
    variable : str or Sequence[str] or None
        brms variable names (see ``variables``); None takes every variable
        common to all models (every variable of any model with ``missing``).
    weights : str or Sequence[float]
        Weighting method of `averaging_weights`, or explicit weights.
    ndraws : int or None
        Total draws; the first model's draw count by default.
    missing : float or Mapping[str, float] or None
        Value of a variable in models that lack it; None requires every
        variable in every model.
    seed : int
        Seed of the draw selection and of the weights.

    Returns
    -------
    PosteriorAverage
        Pooled draws, weights and draw counts.

    Raises
    ------
    ValueError
        If a variable is absent from the required models, ``missing`` lacks
        a value for one, or the weights or draw counts are invalid.
    """
    named = {name: fit.variables() for name, fit in models.items()}
    every = list(dict.fromkeys(v for draws in named.values() for v in draws))
    if missing is None:
        common = [v for v in every if all(v in draws for draws in named.values())]
        requested = common if variable is None else _names(variable)
        absent = [v for v in requested if v not in common]
        if absent:
            raise ValueError(
                f"variables {absent} are not in all models; give missing= to fill them"
            )
        fill: dict[str, float] = {}
    else:
        requested = every if variable is None else _names(variable)
        unknown = [v for v in requested if v not in every]
        if unknown:
            raise ValueError(f"variables {unknown} are in none of the models")
        if isinstance(missing, Mapping):
            needed = {
                v for draws in named.values() for v in requested if v not in draws
            }
            lacking = sorted(needed - set(missing))
            if lacking:
                raise ValueError(f"missing has no value for variables {lacking}")
            fill = {k: float(v) for k, v in missing.items()}
        else:
            fill = {v: float(missing) for v in requested}
    normalized, counts = _allocation(models, weights, ndraws, seed)
    generator = torch.Generator().manual_seed(seed)
    parts: dict[str, list[torch.Tensor]] = {v: [] for v in requested}
    for name, fit in models.items():
        count = counts[name]
        if count == 0:
            continue
        draws = named[name]
        ids = torch.tensor(_draw_ids(fit.ndraws(), count, generator))
        for v in requested:
            if v in draws:
                pooled = draws[v].reshape(-1, *draws[v].shape[2:]).double()
                parts[v].append(pooled[ids])
            else:
                parts[v].append(torch.full((count,), fill[v], dtype=torch.float64))
    return PosteriorAverage(
        draws={v: torch.cat(p) for v, p in parts.items()},
        weights=normalized,
        ndraws=counts,
    )

pp_average

pp_average(models: Mapping[str, Fit], *, weights: WeightMethod | Sequence[float] = 'stacking', method: PredictionMethod = 'posterior_predict', ndraws: int | None = None, summary: bool = True, probs: Sequence[float] = (0.025, 0.975), robust: bool = False, resp: str | None = None, **options: Unpack[PredictionOptions]) -> PredictionAverage

Mix the predictions of several fits, as brms pp_average.

PARAMETER DESCRIPTION
models

Named fits of the same response data.

TYPE: Mapping[str, BayesianFit or MultivariateFit]

weights

Weighting method of averaging_weights, or explicit weights.

TYPE: str or Sequence[float] DEFAULT: 'stacking'

method

Prediction method.

TYPE: ('posterior_predict', 'posterior_epred', 'posterior_linpred') DEFAULT: "posterior_predict"

ndraws

Total draws; the first model's draw count by default.

TYPE: int or None DEFAULT: None

summary

Also summarize the pooled draws.

TYPE: bool DEFAULT: True

probs

Quantile probabilities of the summary.

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

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

resp

Response of joint fits; required when a joint fit has several.

TYPE: str or None DEFAULT: None

**options

Prediction keywords such as new_data and re_formula; seed also seeds the draw selection and the weights.

TYPE: PredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
PredictionAverage

Pooled draws, weights, draw counts and the optional summary.

RAISES DESCRIPTION
ValueError

If the fits model different responses, draw_ids or num_samples is given, a joint response is ambiguous, or the weights are invalid.

Source code in src/quivers/formulas/_model_averaging.py
def pp_average(
    models: Mapping[str, Fit],
    *,
    weights: WeightMethod | Sequence[float] = "stacking",
    method: PredictionMethod = "posterior_predict",
    ndraws: int | None = None,
    summary: bool = True,
    probs: Sequence[float] = (0.025, 0.975),
    robust: bool = False,
    resp: str | None = None,
    **options: Unpack[PredictionOptions],
) -> PredictionAverage:
    """Mix the predictions of several fits, as brms ``pp_average``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit]
        Named fits of the same response data.
    weights : str or Sequence[float]
        Weighting method of `averaging_weights`, or explicit weights.
    method : {"posterior_predict", "posterior_epred", "posterior_linpred"}
        Prediction method.
    ndraws : int or None
        Total draws; the first model's draw count by default.
    summary : bool
        Also summarize the pooled draws.
    probs : Sequence[float]
        Quantile probabilities of the summary.
    robust : bool
        Median and MAD instead of mean and SD.
    resp : str or None
        Response of joint fits; required when a joint fit has several.
    **options : PredictionOptions
        Prediction keywords such as ``new_data`` and ``re_formula``; ``seed``
        also seeds the draw selection and the weights.

    Returns
    -------
    PredictionAverage
        Pooled draws, weights, draw counts and the optional summary.

    Raises
    ------
    ValueError
        If the fits model different responses, ``draw_ids`` or ``num_samples``
        is given, a joint response is ambiguous, or the weights are invalid.
    """
    if "num_samples" in options:
        raise ValueError("pp_average chooses draws itself; give ndraws instead")
    if method not in {"posterior_predict", "posterior_epred", "posterior_linpred"}:
        raise ValueError(
            "method must be posterior_predict, posterior_epred, or posterior_linpred"
        )
    match_responses(tuple(models.values()))
    seed = options.get("seed", 0)
    normalized, counts = _allocation(models, weights, ndraws, seed)
    generator = torch.Generator().manual_seed(seed)
    parts: list[torch.Tensor] = []
    request = dict(options)
    for name, fit in models.items():
        count = counts[name]
        if count == 0:
            continue
        ids = _draw_ids(fit.ndraws(), count, generator)
        if hasattr(fit, "response_fits"):
            joint = cast("MultivariateFit", fit)
            selected = resp
            if selected is None:
                if len(joint.response_names) != 1:
                    raise ValueError(
                        "pp_average of a joint fit with several responses requires resp"
                    )
                selected = joint.response_names[0]
            values = joint._pp_prediction(
                method, selected, cast(JointPredictionOptions, request), draw_ids=ids
            )[selected]
        else:
            if resp is not None:
                raise ValueError("resp applies only to joint fits")
            values = cast("BayesianFit", fit)._pp_prediction(
                method, cast(SinglePredictionOptions, request), draw_ids=ids
            )
        parts.append(values.reshape(-1, *values.shape[2:]).double())
    pooled = torch.cat(parts)
    table = (
        summary_table(pooled.unsqueeze(0), probs=probs, robust=robust)
        if summary
        else None
    )
    return PredictionAverage(
        draws=pooled, weights=normalized, ndraws=counts, summary=table
    )

PosteriorAverage didactic-model

PosteriorAverage(*, draws: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), weights: dict[str, float], ndraws: dict[str, int])

Bases: ValueModel

Model-averaged posterior draws, as brms posterior_average.

PARAMETER DESCRIPTION
draws

Pooled draws (S,) of each brms-named variable, model by model.

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

weights

Normalized model weights.

TYPE: dict[str, float]

ndraws

Draws contributed by each model.

TYPE: dict[str, int]

to_frame

to_frame() -> DataFrame

Return the draws as brms's data frame, one column per variable.

RETURNS DESCRIPTION
DataFrame

One row per pooled draw.

Source code in src/quivers/formulas/_model_averaging.py
def to_frame(self) -> pd.DataFrame:
    """Return the draws as brms's data frame, one column per variable.

    Returns
    -------
    pandas.DataFrame
        One row per pooled draw.
    """
    return pd.DataFrame({name: value.numpy() for name, value in self.draws.items()})

PredictionAverage didactic-model

PredictionAverage(*, draws: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), weights: dict[str, float], ndraws: dict[str, int], summary: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Model-averaged predictions, as brms pp_average.

PARAMETER DESCRIPTION
draws

Pooled prediction draws (S, row[, event]), model by model.

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

weights

Normalized model weights.

TYPE: dict[str, float]

ndraws

Draws contributed by each model.

TYPE: dict[str, int]

summary

brms's summary of the pooled draws, when requested.

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

make_conditions

make_conditions(data: IntoDataFrame | Fit, variables: str | Sequence[str], **labels: str | int | bool) -> DataFrame

Build conditions from variables of the data, as brms make_conditions.

PARAMETER DESCRIPTION
data

A data frame, or a fit whose retained training data is used.

TYPE: IntoDataFrame or BayesianFit or MultivariateFit

variables

Variables to condition on.

TYPE: str or Sequence[str]

**labels

rows2labels options (digits, sep, incl_vars).

TYPE: str or int or bool DEFAULT: {}

RETURNS DESCRIPTION
DataFrame

Every combination of the levels of factor variables and of the mean and mean plus and minus one standard deviation of numeric variables, the last variable varying fastest, with cond__ labels.

RAISES DESCRIPTION
ValueError

If a variable is not a column of the data.

Source code in src/quivers/formulas/_brms_effects.py
def make_conditions(
    data: IntoDataFrame | Fit,
    variables: str | Sequence[str],
    **labels: str | int | bool,
) -> pd.DataFrame:
    """Build conditions from variables of the data, as brms ``make_conditions``.

    Parameters
    ----------
    data : IntoDataFrame or BayesianFit or MultivariateFit
        A data frame, or a fit whose retained training data is used.
    variables : str or Sequence[str]
        Variables to condition on.
    **labels : str or int or bool
        `rows2labels` options (``digits``, ``sep``, ``incl_vars``).

    Returns
    -------
    pandas.DataFrame
        Every combination of the levels of factor variables and of the mean
        and mean plus and minus one standard deviation of numeric variables,
        the last variable varying fastest, with ``cond__`` labels.

    Raises
    ------
    ValueError
        If a variable is not a column of the data.
    """
    if hasattr(data, "refit_recipe"):
        frame = model_frame(cast("Fit", data))
    else:
        frame = nw.from_native(cast(IntoDataFrame, data), eager_only=True).to_pandas()
    names = [variables] if isinstance(variables, str) else list(variables)
    missing = [v for v in names if v not in frame.columns]
    if missing:
        raise ValueError(f"make_conditions: variables {missing} are not in the data")
    values: dict[str, list[ConditionValue]] = {}
    for name in names:
        column = _col(frame, name)
        if _like_factor(column):
            values[name] = _levels(column)
        else:
            mean = _number(column.mean())
            sd = _number(column.std(ddof=1))
            values[name] = [mean - sd, mean, mean + sd]
    index = pd.MultiIndex.from_product([values[n] for n in names], names=names)
    out = index.to_frame(index=False)
    for name in names:
        if _like_factor(_col(frame, name)) and isinstance(
            _col(frame, name).dtype, pd.CategoricalDtype
        ):
            out[name] = pd.Categorical(
                out[name], categories=_col(frame, name).cat.categories
            )
    out["cond__"] = rows2labels(
        cast(pd.DataFrame, out[names]),
        digits=int(labels.get("digits", 2)),
        sep=str(labels.get("sep", " & ")),
        incl_vars=bool(labels.get("incl_vars", True)),
    )
    return out

BrmsConditionalEffects didactic-model

BrmsConditionalEffects(*, effects: tuple[EffectFrame, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), smooths_only: bool = False)

Bases: ValueModel

Conditional effects of one call, as a brms_conditional_effects list.

PARAMETER DESCRIPTION
effects

Effects in brms's order.

TYPE: tuple[EffectFrame, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

smooths_only

Whether the effects are smooth contributions (conditional_smooths).

TYPE: bool DEFAULT: False

names

names() -> tuple[str, ...]

Return the effect names in order.

RETURNS DESCRIPTION
tuple[str, ...]

brms's list names.

Source code in src/quivers/formulas/_brms_effects.py
def names(self) -> tuple[str, ...]:
    """Return the effect names in order.

    Returns
    -------
    tuple[str, ...]
        brms's list names.
    """
    return tuple(effect.name for effect in self.effects)

__getitem__

__getitem__(name: str) -> EffectFrame

Return one effect by name.

PARAMETER DESCRIPTION
name

brms's list name.

TYPE: str

RETURNS DESCRIPTION
EffectFrame

The effect.

RAISES DESCRIPTION
KeyError

If no effect has the name.

Source code in src/quivers/formulas/_brms_effects.py
def __getitem__(self, name: str) -> EffectFrame:
    """Return one effect by name.

    Parameters
    ----------
    name : str
        brms's list name.

    Returns
    -------
    EffectFrame
        The effect.

    Raises
    ------
    KeyError
        If no effect has the name.
    """
    for effect in self.effects:
        if effect.name == name:
            return effect
    raise KeyError(f"no effect {name!r}; effects are {list(self.names())}")

frames

frames() -> dict[str, DataFrame]

Return every effect's data frame by name.

RETURNS DESCRIPTION
dict[str, DataFrame]

brms's data frames.

Source code in src/quivers/formulas/_brms_effects.py
def frames(self) -> dict[str, pd.DataFrame]:
    """Return every effect's data frame by name.

    Returns
    -------
    dict[str, pandas.DataFrame]
        brms's data frames.
    """
    return {effect.name: effect.frame for effect in self.effects}

EffectFrame didactic-model

EffectFrame(*, name: str, effects: tuple[str, ...], response: str, frame: DataFrame = field(opaque=True, extras=OPAQUE_BY_IDENTITY), draws: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), surface: bool = False, categorical: bool = False, spaghetti: DataFrame | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), points: DataFrame | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

One conditional effect, as an element of brms_conditional_effects.

PARAMETER DESCRIPTION
name

brms's list name: the effects joined by :, prefixed by <resp>. for a joint fit.

TYPE: str

effects

Plotted variables in plotting order; cats__ for categories.

TYPE: tuple[str, ...]

response

Response, distributional parameter, or nonlinear parameter predicted.

TYPE: str

frame

Grid and condition columns, cond__, effect1__ (and effect2__, cats__), and estimate__, se__, lower__, upper__.

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

draws

Prediction draws (chain, draw, row), rows in frame order.

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

surface

Whether both effects are numeric and plotted as a surface.

TYPE: bool DEFAULT: False

categorical

Whether rows are per category.

TYPE: bool DEFAULT: False

spaghetti

One row per draw and grid row with estimate__ and sample__.

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

points

Observed data assigned to conditions, with resp__.

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

pp_check

pp_check(fit: Fit, type: str = 'dens_overlay', *, ndraws: int | None = None, prefix: Prefix = 'ppc', group: str | None = None, x: str | None = None, newdata: IntoDataFrame | None = None, resp: str | None = None, draw_ids: Sequence[int] | None = None, stat: StatisticSpec | None = None, prob: float = 0.5, prob_outer: float = 0.9, bins: int | None = None, freq: bool = True, style: Literal['standing', 'hanging', 'suspended'] = 'standing', seed: int = 0) -> PPCheck

Prepare a posterior or prior predictive check, as brms pp_check.

PARAMETER DESCRIPTION
fit

Fitted model; a prior view (prior_view) checks the prior predictive distribution.

TYPE: BayesianFit or MultivariateFit

type

bayesplot type without prefix (PPC_TYPES, or PPD_TYPES for prefix="ppd").

TYPE: str DEFAULT: 'dens_overlay'

ndraws

Random draws; every draw for summary types and ten otherwise.

TYPE: int or None DEFAULT: None

prefix

Compare with observed data, or show the predictive distribution only.

TYPE: ('ppc', 'ppd') DEFAULT: "ppc"

group

Grouping variable; required by *_grouped types.

TYPE: str or None DEFAULT: None

x

Covariate of intervals, ribbon and error_scatter_avg_vs_x.

TYPE: str or None DEFAULT: None

newdata

Rows to predict, holding the response for ppc types.

TYPE: IntoDataFrame or None DEFAULT: None

resp

Response of a joint fit; required when it has several.

TYPE: str or None DEFAULT: None

draw_ids

Explicit 0-based draws.

TYPE: Sequence[int] or None DEFAULT: None

stat

Test statistic; "mean" (("mean", "sd") for stat_2d) by default.

TYPE: str or Callable or tuple or None DEFAULT: None

prob

Interval probabilities of interval types; prob_outer is the interval of bars and rootogram.

TYPE: float DEFAULT: 0.5

prob_outer

Interval probabilities of interval types; prob_outer is the interval of bars and rootogram.

TYPE: float DEFAULT: 0.5

bins

Bins of error_binned.

TYPE: int or None DEFAULT: None

freq

Counts instead of proportions for bars.

TYPE: bool DEFAULT: True

style

Rootogram style.

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

seed

Seed of the draw selection and predictions.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PPCheck

The table behind the plot with the inputs it was computed from.

RAISES DESCRIPTION
ValueError

If the type is unknown for the prefix, a required group or x is missing or not a data variable, a joint response is ambiguous, or no uncensored response remains.

Notes

Cost is one prediction at S draws over N rows, plus one log-likelihood evaluation and PSIS smoothing, O(S N log S), for leave-one-out types.

Source code in src/quivers/formulas/_pp_check.py
def pp_check(
    fit: Fit,
    type: str = "dens_overlay",
    *,
    ndraws: int | None = None,
    prefix: Prefix = "ppc",
    group: str | None = None,
    x: str | None = None,
    newdata: IntoDataFrame | None = None,
    resp: str | None = None,
    draw_ids: Sequence[int] | None = None,
    stat: StatisticSpec | None = None,
    prob: float = 0.5,
    prob_outer: float = 0.9,
    bins: int | None = None,
    freq: bool = True,
    style: Literal["standing", "hanging", "suspended"] = "standing",
    seed: int = 0,
) -> PPCheck:
    """Prepare a posterior or prior predictive check, as brms ``pp_check``.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model; a prior view (``prior_view``) checks the prior
        predictive distribution.
    type : str
        bayesplot type without prefix (`PPC_TYPES`, or `PPD_TYPES` for
        ``prefix="ppd"``).
    ndraws : int or None
        Random draws; every draw for summary types and ten otherwise.
    prefix : {"ppc", "ppd"}
        Compare with observed data, or show the predictive distribution only.
    group : str or None
        Grouping variable; required by ``*_grouped`` types.
    x : str or None
        Covariate of ``intervals``, ``ribbon`` and ``error_scatter_avg_vs_x``.
    newdata : IntoDataFrame or None
        Rows to predict, holding the response for ``ppc`` types.
    resp : str or None
        Response of a joint fit; required when it has several.
    draw_ids : Sequence[int] or None
        Explicit 0-based draws.
    stat : str or Callable or tuple or None
        Test statistic; ``"mean"`` (``("mean", "sd")`` for ``stat_2d``) by
        default.
    prob, prob_outer : float
        Interval probabilities of interval types; ``prob_outer`` is the
        interval of ``bars`` and ``rootogram``.
    bins : int or None
        Bins of ``error_binned``.
    freq : bool
        Counts instead of proportions for ``bars``.
    style : {"standing", "hanging", "suspended"}
        Rootogram style.
    seed : int
        Seed of the draw selection and predictions.

    Returns
    -------
    PPCheck
        The table behind the plot with the inputs it was computed from.

    Raises
    ------
    ValueError
        If the type is unknown for the prefix, a required ``group`` or ``x``
        is missing or not a data variable, a joint response is ambiguous, or
        no uncensored response remains.

    Notes
    -----
    Cost is one prediction at ``S`` draws over ``N`` rows, plus one
    log-likelihood evaluation and PSIS smoothing, O(S N log S), for
    leave-one-out types.
    """
    if prefix not in ("ppc", "ppd"):
        raise ValueError("prefix must be 'ppc' or 'ppd'")
    valid = set(PPC_TYPES) if prefix == "ppc" else set(PPD_TYPES)
    if type not in valid:
        raise ValueError(
            f"type {type!r} is not a valid {prefix} type; valid types are "
            f"{', '.join(sorted(valid))}"
        )
    if _joint(fit):
        joint = cast("MultivariateFit", fit)
        if resp is None:
            if len(joint.response_names) != 1:
                raise ValueError(
                    "pp_check of a joint fit with several responses requires resp"
                )
            resp = joint.response_names[0]
        elif resp not in joint.response_names:
            raise ValueError(f"unknown response {resp!r}")
        formula = joint.emission.responses[resp].formula
        family = joint.prepared[resp].family
    else:
        if resp is not None:
            raise ValueError("resp applies only to joint fits")
        single = cast("BayesianFit", fit)
        formula, family = single.formula, single.family
    if family.vector_response:
        raise ValueError(
            "pp_check is not implemented for multicolumn response families"
        )
    rows = (
        model_frame(fit)
        if newdata is None
        else nw.from_native(newdata, eager_only=True).to_pandas()
    )
    grouped = type.endswith("_grouped")
    if grouped and group is None:
        raise ValueError(f"argument group is required for ppc type {type!r}")
    for name, value in (("group", group), ("x", x)):
        if value is not None and value not in rows.columns:
            raise ValueError(
                f"{name} variable {value!r} could not be found in the data"
            )
    if type == "error_scatter_avg_vs_x" and x is None:
        raise ValueError("error_scatter_avg_vs_x requires x")
    kind = PPC_TYPES[type]
    method: PredictionMethod = (
        "posterior_epred" if type == "error_binned" else "posterior_predict"
    )
    if type == "error_binned" and (
        family.ordinal is not None or response_category_labels(formula, family)
    ):
        raise ValueError("error_binned is not available for polytomous models")
    ids = _select_draws(fit, type, ndraws, draw_ids, seed)
    yrep = _predict(fit, resp, method, newdata, ids, seed)
    y = _observed(formula, family, newdata) if prefix == "ppc" else None
    n = yrep.shape[1]
    group_values = (
        None if group is None else np.asarray(rows[group].tolist(), dtype=object)
    )
    x_values = None if x is None else np.asarray(rows[x].tolist(), dtype=object)
    if group_values is not None and group_values.shape[0] != n:
        raise ValueError("group values do not align with the predicted rows")
    keep = np.ones(n, dtype=bool)
    if y is not None:
        keep &= ~torch.isnan(y).numpy()
    status_values = None
    codes = _status(formula, newdata)
    if codes is not None:
        if kind == "km":
            keep &= np.isin(codes, (0.0, 1.0))
            status_values = 1.0 - codes
        else:
            keep &= codes == 0.0
    elif kind == "km":
        status_values = np.ones(n)
    if not keep.any():
        raise ValueError("no valid responses found to include")
    yrep_np = yrep.numpy()[:, keep]
    y_np = None if y is None else y.numpy()[keep]
    g = None if group_values is None else group_values[keep]
    xv = None if x_values is None else x_values[keep]
    status_kept = None if status_values is None else status_values[keep]
    log_weights = log_lik = pit = None
    if kind in {"loo_pit", "loo_intervals"}:
        log_lik_full = _log_likelihood(fit, resp, ids, seed)
        log_lik = log_lik_full[:, keep]
        weights = psis_weights(torch.from_numpy(log_lik).unsqueeze(0), r_eff=1.0)
        log_weights = weights.log_weights.reshape(log_lik.shape).double().numpy()
    if kind == "long":
        frame = data_functions.ppc_data(y_np, yrep_np, group=g)
    elif kind == "stat":
        default: StatisticSpec = ("mean", "sd") if type == "stat_2d" else "mean"
        chosen = stat if stat is not None else default
        if type == "stat_2d" and not isinstance(chosen, tuple):
            raise ValueError("stat_2d requires two statistics")
        frame = data_functions.ppc_stat_data(y_np, yrep_np, stat=chosen, group=g)
    elif kind == "intervals":
        frame = data_functions.ppc_intervals_data(
            y_np,
            yrep_np,
            x=None if xv is None else xv.astype(np.float64),
            group=g,
            prob=prob,
            prob_outer=prob_outer,
        )
    else:
        assert y_np is not None
        if kind == "bars":
            frame = data_functions.ppc_bars_data(
                y_np, yrep_np, group=g, prob=prob_outer, freq=freq
            )
        elif kind == "error":
            frame = data_functions.ppc_error_data(y_np, yrep_np, group=g)
        elif kind == "error_avg":
            frame = data_functions.ppc_scatter_avg_data(
                y_np, y_np[None, :] - yrep_np, group=g
            )
        elif kind == "error_avg_x":
            assert xv is not None
            frame = data_functions.ppc_scatter_avg_data(
                xv.astype(np.float64), y_np[None, :] - yrep_np
            )
        elif kind == "error_binned":
            frame = data_functions.ppc_error_binned_data(y_np, yrep_np, bins=bins)
        elif kind == "scatter":
            frame = data_functions.ppc_scatter_data(y_np, yrep_np)
        elif kind == "scatter_avg":
            frame = data_functions.ppc_scatter_avg_data(y_np, yrep_np, group=g)
        elif kind == "rootogram":
            frame = data_functions.ppc_rootogram_data(
                y_np, yrep_np, style=style, prob=prob_outer
            )
        elif kind == "km":
            assert status_kept is not None
            frame = data_functions.km_data(y_np, yrep_np, status=status_kept)
        elif kind == "pit_ecdf":
            pit = data_functions.pit_values(y_np, yrep_np)
            frame = data_functions.pit_ecdf_data(y_np, yrep_np)
        elif kind == "loo_pit":
            assert log_weights is not None
            pit = data_functions.loo_pit_values(y_np, yrep_np, log_weights)
            frame = _loo_pit_frame(pit, qq=type == "loo_pit_qq")
        else:
            assert log_weights is not None and log_lik is not None
            frame = _loo_interval_frame(y_np, yrep_np, log_lik, prob, prob_outer)
    return PPCheck(
        type=type,
        prefix=prefix,
        data=frame,
        y=None if y_np is None else torch.from_numpy(y_np),
        yrep=torch.from_numpy(np.ascontiguousarray(yrep_np)),
        draw_ids=tuple(ids),
        group=None if g is None else tuple(g.tolist()),
        x=None if xv is None else tuple(xv.tolist()),
        status=None if status_kept is None else torch.from_numpy(status_kept),
        log_weights=None if log_weights is None else torch.from_numpy(log_weights),
        log_likelihood=None if log_lik is None else torch.from_numpy(log_lik),
        pit=None
        if pit is None
        else torch.from_numpy(np.asarray(pit, dtype=np.float64)),
    )

PPCheck didactic-model

PPCheck(*, type: str, prefix: Prefix, data: DataFrame = field(opaque=True, extras=OPAQUE_BY_IDENTITY), y: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), yrep: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), draw_ids: tuple[int, ...] = (), group: tuple[str | int | float | bool, ...] | None = None, x: tuple[str | int | float | bool, ...] | None = None, status: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), log_weights: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), log_likelihood: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), pit: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The data behind one predictive check, as brms pp_check prepares it.

PARAMETER DESCRIPTION
type

bayesplot type without its prefix.

TYPE: str

prefix

Posterior predictive check or predictive distribution.

TYPE: ('ppc', 'ppd') DEFAULT: "ppc"

data

bayesplot's table for the type (see the ppc_* functions of quivers.diagnostics).

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

y

Observed responses (N,); None for ppd types.

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

yrep

Predictive draws (S, N) (expected values for error_binned).

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

draw_ids

Pooled 0-based draws used.

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

group

Group label per observation.

TYPE: tuple or None DEFAULT: None

x

Covariate per observation.

TYPE: tuple or None DEFAULT: None

status

Event indicator of censored responses (km_overlay).

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

log_weights

Normalized PSIS log weights (S, N) of leave-one-out types.

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

log_likelihood

Pointwise log-likelihoods (S, N) of leave-one-out types.

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

pit

PIT or LOO-PIT values per observation.

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

to_datatree

to_datatree() -> DataTree

Return an ArviZ data tree of the check.

RETURNS DESCRIPTION
DataTree

posterior_predictive (one chain), observed_data for ppc types, log_likelihood for leave-one-out types, and constant_data with the event indicator of censored responses.

Source code in src/quivers/formulas/_pp_check.py
def to_datatree(self) -> xr.DataTree:
    """Return an ArviZ data tree of the check.

    Returns
    -------
    xarray.DataTree
        ``posterior_predictive`` (one chain), ``observed_data`` for
        ``ppc`` types, ``log_likelihood`` for leave-one-out types, and
        ``constant_data`` with the event indicator of censored responses.
    """
    draws = self.yrep.double().numpy()[None]
    groups: dict[str, xr.Dataset] = {
        "posterior_predictive": xr.Dataset(
            {"y": (("chain", "draw", "obs"), draws)},
            coords={"chain": [0], "draw": np.arange(draws.shape[1])},
        )
    }
    if self.y is not None:
        groups["observed_data"] = xr.Dataset(
            {"y": (("obs",), self.y.double().numpy())}
        )
    if self.log_likelihood is not None:
        groups["log_likelihood"] = xr.Dataset(
            {
                "y": (
                    ("chain", "draw", "obs"),
                    self.log_likelihood.double().numpy()[None],
                )
            },
            coords={"chain": [0], "draw": np.arange(draws.shape[1])},
        )
    if self.status is not None:
        # ArviZ's censored check reads 1 for a censored observation.
        groups["constant_data"] = xr.Dataset(
            {"y": (("obs",), 1.0 - self.status.double().numpy())}
        )
    return xr.DataTree.from_dict(groups)

plot

plot(*, backend: str, **kwargs: str | int | float | bool) -> PlotCollection

Draw the check with its ArviZ counterpart.

PARAMETER DESCRIPTION
backend

ArviZ plotting backend ("matplotlib", "bokeh", "plotly", or "none" to build the plot without drawing).

TYPE: str

**kwargs

Further keyword arguments of the ArviZ function.

TYPE: str or int or float or bool DEFAULT: {}

RETURNS DESCRIPTION
PlotCollection

The plot.

RAISES DESCRIPTION
ValueError

If ArviZ has no counterpart of the type; its data remain in data.

Source code in src/quivers/formulas/_pp_check.py
def plot(
    self, *, backend: str, **kwargs: str | int | float | bool
) -> azp.PlotCollection:
    """Draw the check with its ArviZ counterpart.

    Parameters
    ----------
    backend : str
        ArviZ plotting backend (``"matplotlib"``, ``"bokeh"``,
        ``"plotly"``, or ``"none"`` to build the plot without drawing).
    **kwargs : str or int or float or bool
        Further keyword arguments of the ArviZ function.

    Returns
    -------
    arviz_plots.PlotCollection
        The plot.

    Raises
    ------
    ValueError
        If ArviZ has no counterpart of the type; its data remain in `data`.
    """
    if self.type not in ARVIZ_PLOTS or (
        self.prefix == "ppd"
        and self.type not in {"dens", "dens_overlay", "hist", "ecdf_overlay"}
    ):
        raise ValueError(
            f"ArviZ has no counterpart of {self.prefix}_{self.type}; plot the "
            "table in PPCheck.data"
        )
    name, defaults = ARVIZ_PLOTS[self.type]
    options: dict[str, str | int | float | bool] = {**defaults, **kwargs}
    if self.prefix == "ppd":
        # The predictive distribution alone: ArviZ's marginal plot.
        name = "plot_dist"
        options.setdefault("group", "posterior_predictive")
    function = getattr(azp, name)
    return function(self.to_datatree(), backend=backend, **options)

mcmc_plot

mcmc_plot(fit: Fit, type: str = 'intervals', *, variable: str | Sequence[str] | None = None, regex: bool = False, backend: str, **kwargs: str | int | float | bool) -> PlotResult

Draw an MCMC diagnostic plot, as brms mcmc_plot.

PARAMETER DESCRIPTION
fit

Fitted model.

TYPE: BayesianFit or MultivariateFit

type

bayesplot mcmc_* type without prefix (MCMC_PLOTS).

TYPE: str DEFAULT: 'intervals'

variable

brms variable names or regular expressions; None for all.

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

regex

brms regex: search each expression anywhere in a name.

TYPE: bool DEFAULT: False

backend

ArviZ plotting backend ("matplotlib", "bokeh", "plotly", or "none" to build without drawing).

TYPE: str

**kwargs

Further ArviZ keyword arguments.

TYPE: str or int or float or bool DEFAULT: {}

RETURNS DESCRIPTION
PlotCollection or PlotMatrix

The plot.

RAISES DESCRIPTION
ValueError

If the type is unknown or has no ArviZ counterpart.

Source code in src/quivers/formulas/_mcmc_plot.py
def mcmc_plot(
    fit: Fit,
    type: str = "intervals",
    *,
    variable: str | Sequence[str] | None = None,
    regex: bool = False,
    backend: str,
    **kwargs: str | int | float | bool,
) -> PlotResult:
    """Draw an MCMC diagnostic plot, as brms ``mcmc_plot``.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model.
    type : str
        bayesplot ``mcmc_*`` type without prefix (`MCMC_PLOTS`).
    variable : str or Sequence[str] or None
        brms variable names or regular expressions; None for all.
    regex : bool
        brms ``regex``: search each expression anywhere in a name.
    backend : str
        ArviZ plotting backend (``"matplotlib"``, ``"bokeh"``, ``"plotly"``,
        or ``"none"`` to build without drawing).
    **kwargs : str or int or float or bool
        Further ArviZ keyword arguments.

    Returns
    -------
    arviz_plots.PlotCollection or arviz_plots.PlotMatrix
        The plot.

    Raises
    ------
    ValueError
        If the type is unknown or has no ArviZ counterpart.
    """
    if type in NOT_PROVIDED:
        raise ValueError(
            f"mcmc_plot type {type!r} is not provided: {NOT_PROVIDED[type]}"
        )
    if type not in MCMC_PLOTS:
        raise ValueError(
            f"unknown mcmc_plot type {type!r}; types are {', '.join(sorted(MCMC_PLOTS))}"
        )
    name, defaults = MCMC_PLOTS[type]
    options: dict[str, str | int | float | bool] = {**defaults, **kwargs}
    function = getattr(azp, name)
    tree = mcmc_datatree(fit, variable, regex=regex)
    return function(tree, backend=backend, **options)

_evidence

Marginal likelihoods, Bayes factors and posterior model probabilities of fits.

brms computes bridge_sampler, bayes_factor and post_prob by handing its Stan model to the R bridgesampling package [@gronau2020bridgesampling]. Here the same estimator (quivers.diagnostics.bridge.bridge_sampler) runs on a fit's retained MCMC draws, mapped to the sampler's unconstrained coordinates, with the fit's own Jacobian-corrected log joint (PotentialFn) as the log unnormalized posterior. Every density of a compiled formula program keeps its normalizing constant, so the requirement brms states as save_pars(all = TRUE) with a normalized Stan model holds by construction. What cannot hold is refused with a located error: improper priors, explicit score potentials of unknown mass, opaque joint overrides, discrete Gibbs sites, and draws that are not posterior MCMC draws.

EvidenceInput

EvidenceInput = Fit | BridgeResult

A fit, or a bridge-sampling estimate computed from one.

BayesFactor didactic-model

BayesFactor(*, bf: float, log: bool, numerator: str = 'x1', denominator: str = 'x2')

Bases: ValueModel

A Bayes factor of two models, as a bf_bridge object.

PARAMETER DESCRIPTION
bf

:math:p(y \mid M_1) / p(y \mid M_2), or its logarithm.

TYPE: float

log

Whether bf is on the log scale.

TYPE: bool

numerator

Names of the numerator and denominator models.

TYPE: str DEFAULT: 'x1'

denominator

Names of the numerator and denominator models.

TYPE: str DEFAULT: 'x1'

BridgeSettings didactic-model

BridgeSettings(*, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0)

Bases: ValueModel

bridge_sampler keywords applied to every fit of a comparison.

PARAMETER DESCRIPTION
method

Proposal of the bridgesampling package.

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

repetitions

Independent proposal draws.

TYPE: int DEFAULT: 1

use_neff

Use the effective size of the iteration draws.

TYPE: bool DEFAULT: True

maxiter

Iteration bound of the fixed-point scheme.

TYPE: int DEFAULT: 1000

seed

Seed of the proposal draws.

TYPE: int DEFAULT: 0

EvidenceMethods

Marginal-likelihood methods shared by BayesianFit and MultivariateFit.

bridge_sampler

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

Estimate the log marginal likelihood, as brms bridge_sampler.

PARAMETER DESCRIPTION
method

Proposal of the bridgesampling package.

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

repetitions

Independent proposal draws.

TYPE: int DEFAULT: 1

use_neff

Use the effective size of the iteration draws.

TYPE: bool DEFAULT: True

maxiter

Iteration bound of the fixed-point scheme.

TYPE: int DEFAULT: 1000

seed

Seed of the proposal draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
BridgeResult

The estimate.

RAISES DESCRIPTION
ValueError

If the fit has improper priors, unnormalized potentials, discrete latent sites, or no posterior MCMC draws.

RuntimeError

If the scheme does not converge.

Source code in src/quivers/formulas/_evidence.py
def bridge_sampler(
    self,
    *,
    method: BridgeMethod = "normal",
    repetitions: int = 1,
    use_neff: bool = True,
    maxiter: int = 1000,
    seed: int = 0,
) -> BridgeResult:
    """Estimate the log marginal likelihood, as brms ``bridge_sampler``.

    Parameters
    ----------
    method : {"normal", "warp3"}
        Proposal of the ``bridgesampling`` package.
    repetitions : int
        Independent proposal draws.
    use_neff : bool
        Use the effective size of the iteration draws.
    maxiter : int
        Iteration bound of the fixed-point scheme.
    seed : int
        Seed of the proposal draws.

    Returns
    -------
    BridgeResult
        The estimate.

    Raises
    ------
    ValueError
        If the fit has improper priors, unnormalized potentials, discrete
        latent sites, or no posterior MCMC draws.
    RuntimeError
        If the scheme does not converge.
    """
    return bridge_sampler(
        cast("Fit", self),
        method=method,
        repetitions=repetitions,
        use_neff=use_neff,
        maxiter=maxiter,
        seed=seed,
    )

bayes_factor

bayes_factor(other: EvidenceInput, *, log: bool = False, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> BayesFactor

Return the Bayes factor of this model over another.

PARAMETER DESCRIPTION
other

Denominator model or its estimate.

TYPE: BayesianFit or MultivariateFit or BridgeResult

log

Return the log Bayes factor.

TYPE: bool DEFAULT: False

method

bridge_sampler settings.

TYPE: BridgeMethod DEFAULT: 'normal'

repetitions

bridge_sampler settings.

TYPE: BridgeMethod DEFAULT: 'normal'

use_neff

bridge_sampler settings.

TYPE: BridgeMethod DEFAULT: 'normal'

maxiter

bridge_sampler settings.

TYPE: BridgeMethod DEFAULT: 'normal'

seed

bridge_sampler settings.

TYPE: BridgeMethod DEFAULT: 'normal'

RETURNS DESCRIPTION
BayesFactor

The Bayes factor.

RAISES DESCRIPTION
ValueError

If the models have different response data or a fit is refused.

Source code in src/quivers/formulas/_evidence.py
def bayes_factor(
    self,
    other: EvidenceInput,
    *,
    log: bool = False,
    method: BridgeMethod = "normal",
    repetitions: int = 1,
    use_neff: bool = True,
    maxiter: int = 1000,
    seed: int = 0,
) -> BayesFactor:
    """Return the Bayes factor of this model over another.

    Parameters
    ----------
    other : BayesianFit or MultivariateFit or BridgeResult
        Denominator model or its estimate.
    log : bool
        Return the log Bayes factor.
    method, repetitions, use_neff, maxiter, seed
        `bridge_sampler` settings.

    Returns
    -------
    BayesFactor
        The Bayes factor.

    Raises
    ------
    ValueError
        If the models have different response data or a fit is refused.
    """
    return bayes_factor(
        cast("Fit", self),
        other,
        log=log,
        method=method,
        repetitions=repetitions,
        use_neff=use_neff,
        maxiter=maxiter,
        seed=seed,
    )

require_normalized

require_normalized(fit: Fit, purpose: str) -> None

Refuse a fit whose log joint is not a normalized posterior kernel.

PARAMETER DESCRIPTION
fit

Fitted model.

TYPE: BayesianFit or MultivariateFit

purpose

Operation named in the error.

TYPE: str

RAISES DESCRIPTION
ValueError

If a prior is improper, the program carries an explicit score potential of unknown mass or an opaque joint override, or the posterior is not retained MCMC draws.

Source code in src/quivers/formulas/_evidence.py
def require_normalized(fit: Fit, purpose: str) -> None:
    """Refuse a fit whose log joint is not a normalized posterior kernel.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model.
    purpose : str
        Operation named in the error.

    Raises
    ------
    ValueError
        If a prior is improper, the program carries an explicit score
        potential of unknown mass or an opaque joint override, or the
        posterior is not retained MCMC draws.
    """
    fit._require_proper(purpose)
    if _has_custom_joint(fit.program):
        raise ValueError(
            f"{purpose} requires the canonical log joint; an overridden "
            "log_joint has no verifiable normalizing constant"
        )
    if _has_potential(project_prior_sites(fit.program)):
        raise ValueError(
            f"{purpose} requires a normalized prior, but the program carries an "
            "explicit score potential whose mass is unknown"
        )
    if not isinstance(fit.posterior, MCMCResult):
        raise ValueError(
            f"{purpose} requires posterior MCMC draws (method 'nuts' or 'hmc'); "
            "variational and prior draws are not draws of the posterior"
        )

log_posterior_function

log_posterior_function(fit: Fit) -> tuple[ndarray, PotentialFn]

Return a fit's unconstrained draws and its log-posterior potential.

PARAMETER DESCRIPTION
fit

Fit with retained MCMC draws.

TYPE: BayesianFit or MultivariateFit

RETURNS DESCRIPTION
tuple[ndarray, PotentialFn]

Float64 draws (chain, draw, D) in the sampler's flat layout, and the potential whose log_density is the Jacobian-corrected log joint.

RAISES DESCRIPTION
ValueError

If a retained draw is not a site of the latent registry (a discrete Gibbs site, for instance) or a registry site has no draws.

Source code in src/quivers/formulas/_evidence.py
def log_posterior_function(fit: Fit) -> tuple[np.ndarray, PotentialFn]:
    """Return a fit's unconstrained draws and its log-posterior potential.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fit with retained MCMC draws.

    Returns
    -------
    tuple[numpy.ndarray, PotentialFn]
        Float64 draws ``(chain, draw, D)`` in the sampler's flat layout, and
        the potential whose ``log_density`` is the Jacobian-corrected log joint.

    Raises
    ------
    ValueError
        If a retained draw is not a site of the latent registry (a discrete
        Gibbs site, for instance) or a registry site has no draws.
    """
    draws = fit.draws()
    registry, upars = unconstrained_draws(fit, draws)
    if set(draws) != set(registry.names):
        raise ValueError(
            "bridge sampling requires every latent site in the unconstrained "
            "registry; sites "
            f"{sorted(set(draws) ^ set(registry.names))} are discrete or "
            "outside it"
        )
    potential = PotentialFn(
        fit.program,
        registry,
        torch.zeros(1, 1, dtype=torch.long),
        dict(fit.observations),
    )
    return upars.numpy(), potential

bridge_sampler

bridge_sampler(fit: Fit, *, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> BridgeResult

Estimate a fit's log marginal likelihood by bridge sampling.

PARAMETER DESCRIPTION
fit

Fit with posterior MCMC draws and proper priors.

TYPE: BayesianFit or MultivariateFit

method

Proposal of the bridgesampling package.

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

repetitions

Independent proposal draws.

TYPE: int DEFAULT: 1

use_neff

Use the effective size of the iteration draws.

TYPE: bool DEFAULT: True

maxiter

Iteration bound of the fixed-point scheme.

TYPE: int DEFAULT: 1000

seed

Seed of the proposal draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
BridgeResult

The estimate, with the retained log densities.

RAISES DESCRIPTION
ValueError

If the fit is refused by require_normalized or its draws are invalid for the estimator.

RuntimeError

If the scheme does not converge.

Notes

Cost is S / 2 (1 + R) program evaluations for S draws and R repetitions (twice that for "warp3"), each O(C) for one log-joint evaluation of the fit's program.

Source code in src/quivers/formulas/_evidence.py
def bridge_sampler(
    fit: Fit,
    *,
    method: BridgeMethod = "normal",
    repetitions: int = 1,
    use_neff: bool = True,
    maxiter: int = 1000,
    seed: int = 0,
) -> BridgeResult:
    """Estimate a fit's log marginal likelihood by bridge sampling.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fit with posterior MCMC draws and proper priors.
    method : {"normal", "warp3"}
        Proposal of the ``bridgesampling`` package.
    repetitions : int
        Independent proposal draws.
    use_neff : bool
        Use the effective size of the iteration draws.
    maxiter : int
        Iteration bound of the fixed-point scheme.
    seed : int
        Seed of the proposal draws.

    Returns
    -------
    BridgeResult
        The estimate, with the retained log densities.

    Raises
    ------
    ValueError
        If the fit is refused by `require_normalized` or its draws are
        invalid for the estimator.
    RuntimeError
        If the scheme does not converge.

    Notes
    -----
    Cost is ``S / 2 (1 + R)`` program evaluations for ``S`` draws and ``R``
    repetitions (twice that for ``"warp3"``), each O(C) for one log-joint
    evaluation of the fit's program.
    """
    require_normalized(fit, "bridge_sampler")
    upars, potential = log_posterior_function(fit)

    def log_posterior(points: np.ndarray) -> np.ndarray:
        """Evaluate the Jacobian-corrected log joint row-wise.

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

        Returns
        -------
        numpy.ndarray
            Log densities ``(N,)``, ``-inf`` outside the support.
        """
        values = torch.from_numpy(np.ascontiguousarray(points))
        with torch.no_grad():
            return np.array(
                [float(potential.log_density(row)) for row in values],
                dtype=np.float64,
            )

    return bridge_estimate(
        log_posterior,
        upars,
        method=method,
        repetitions=repetitions,
        use_neff=use_neff,
        maxiter=maxiter,
        seed=seed,
    )

match_responses

match_responses(models: Sequence[EvidenceInput]) -> None

Require that fits model the same response data, as brms match_response.

PARAMETER DESCRIPTION
models

Compared models; stored estimates are not checked.

TYPE: Sequence[BayesianFit or MultivariateFit or BridgeResult]

RAISES DESCRIPTION
ValueError

If two fits score different observed responses.

Source code in src/quivers/formulas/_evidence.py
def match_responses(models: Sequence[EvidenceInput]) -> None:
    """Require that fits model the same response data, as brms ``match_response``.

    Parameters
    ----------
    models : Sequence[BayesianFit or MultivariateFit or BridgeResult]
        Compared models; stored estimates are not checked.

    Raises
    ------
    ValueError
        If two fits score different observed responses.
    """
    hashes = {h for h in map(_response_hash, models) if h is not None}
    if len(hashes) > 1:
        raise ValueError(
            "marginal likelihoods of models with different response data are "
            "not comparable"
        )

bayes_factor

bayes_factor(x1: EvidenceInput, x2: EvidenceInput, *, log: bool = False, model_names: tuple[str, str] = ('x1', 'x2'), method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> BayesFactor

Return the Bayes factor of two models, as brms bayes_factor.

PARAMETER DESCRIPTION
x1

Numerator and denominator models, or their bridge estimates.

TYPE: BayesianFit or MultivariateFit or BridgeResult

x2

Numerator and denominator models, or their bridge estimates.

TYPE: BayesianFit or MultivariateFit or BridgeResult

log

Return the log Bayes factor.

TYPE: bool DEFAULT: False

model_names

Names of the two models.

TYPE: tuple[str, str] DEFAULT: ('x1', 'x2')

method

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

repetitions

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

use_neff

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

maxiter

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

seed

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

RETURNS DESCRIPTION
BayesFactor

:math:p(y \mid M_1) / p(y \mid M_2).

RAISES DESCRIPTION
ValueError

If the fits model different response data or are refused by bridge_sampler.

Source code in src/quivers/formulas/_evidence.py
def bayes_factor(
    x1: EvidenceInput,
    x2: EvidenceInput,
    *,
    log: bool = False,
    model_names: tuple[str, str] = ("x1", "x2"),
    method: BridgeMethod = "normal",
    repetitions: int = 1,
    use_neff: bool = True,
    maxiter: int = 1000,
    seed: int = 0,
) -> BayesFactor:
    """Return the Bayes factor of two models, as brms ``bayes_factor``.

    Parameters
    ----------
    x1, x2 : BayesianFit or MultivariateFit or BridgeResult
        Numerator and denominator models, or their bridge estimates.
    log : bool
        Return the log Bayes factor.
    model_names : tuple[str, str]
        Names of the two models.
    method, repetitions, use_neff, maxiter, seed
        `bridge_sampler` settings for fits.

    Returns
    -------
    BayesFactor
        :math:`p(y \\mid M_1) / p(y \\mid M_2)`.

    Raises
    ------
    ValueError
        If the fits model different response data or are refused by
        `bridge_sampler`.
    """
    match_responses((x1, x2))
    options = BridgeSettings(
        method=method,
        repetitions=repetitions,
        use_neff=use_neff,
        maxiter=maxiter,
        seed=seed,
    )
    value = bayes_factor_from_logml(_logml(x1, options), _logml(x2, options), log=log)
    return BayesFactor(
        bf=value, log=log, numerator=model_names[0], denominator=model_names[1]
    )

post_prob

post_prob(models: Mapping[str, EvidenceInput], *, prior_prob: Sequence[float] | None = None, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> dict[str, float]

Return posterior model probabilities, as brms post_prob.

PARAMETER DESCRIPTION
models

At least two named models of the same response data.

TYPE: Mapping[str, BayesianFit or MultivariateFit or BridgeResult]

prior_prob

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

TYPE: Sequence[float] or None DEFAULT: None

method

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

repetitions

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

use_neff

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

maxiter

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

seed

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

RETURNS DESCRIPTION
dict[str, float]

Posterior probabilities summing to one.

RAISES DESCRIPTION
ValueError

If fewer than two models are given, the fits model different data, or the prior probabilities are invalid.

Source code in src/quivers/formulas/_evidence.py
def post_prob(
    models: Mapping[str, EvidenceInput],
    *,
    prior_prob: Sequence[float] | None = None,
    method: BridgeMethod = "normal",
    repetitions: int = 1,
    use_neff: bool = True,
    maxiter: int = 1000,
    seed: int = 0,
) -> dict[str, float]:
    """Return posterior model probabilities, as brms ``post_prob``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit or BridgeResult]
        At least two named models of the same response data.
    prior_prob : Sequence[float] or None
        Prior model probabilities in the order of ``models``; uniform when None.
    method, repetitions, use_neff, maxiter, seed
        `bridge_sampler` settings for fits.

    Returns
    -------
    dict[str, float]
        Posterior probabilities summing to one.

    Raises
    ------
    ValueError
        If fewer than two models are given, the fits model different data,
        or the prior probabilities are invalid.
    """
    match_responses(tuple(models.values()))
    options = BridgeSettings(
        method=method,
        repetitions=repetitions,
        use_neff=use_neff,
        maxiter=maxiter,
        seed=seed,
    )
    return posterior_model_probabilities(
        {name: _logml(model, options) for name, model in models.items()},
        prior_prob=prior_prob,
    )

_model_averaging

Posterior and posterior-predictive model averaging, as brms.

brms posterior_average and pp_average mix the draws of several fits in proportion to model weights: with weights :math:w_k and a draw budget :math:S, model :math:k contributes :math:S_k draws, the largest-remainder rounding of :math:w_k S, chosen at random without replacement. The pooled draws are draws of the mixture :math:\sum_k w_k p(\cdot \mid y, M_k) [@hoeting1999bayesian; @yao2018stacking]. Weights are stacking, pseudo-BMA or information-criterion weights (model_weights), Bayesian model averaging weights from bridge-sampled marginal likelihoods (post_prob), or explicit.

WeightMethod

WeightMethod = Literal['stacking', 'pseudobma', 'loo', 'waic', 'kfold', 'bma']

brms model_weights methods.

PosteriorAverage didactic-model

PosteriorAverage(*, draws: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), weights: dict[str, float], ndraws: dict[str, int])

Bases: ValueModel

Model-averaged posterior draws, as brms posterior_average.

PARAMETER DESCRIPTION
draws

Pooled draws (S,) of each brms-named variable, model by model.

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

weights

Normalized model weights.

TYPE: dict[str, float]

ndraws

Draws contributed by each model.

TYPE: dict[str, int]

to_frame

to_frame() -> DataFrame

Return the draws as brms's data frame, one column per variable.

RETURNS DESCRIPTION
DataFrame

One row per pooled draw.

Source code in src/quivers/formulas/_model_averaging.py
def to_frame(self) -> pd.DataFrame:
    """Return the draws as brms's data frame, one column per variable.

    Returns
    -------
    pandas.DataFrame
        One row per pooled draw.
    """
    return pd.DataFrame({name: value.numpy() for name, value in self.draws.items()})

PredictionAverage didactic-model

PredictionAverage(*, draws: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), weights: dict[str, float], ndraws: dict[str, int], summary: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Model-averaged predictions, as brms pp_average.

PARAMETER DESCRIPTION
draws

Pooled prediction draws (S, row[, event]), model by model.

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

weights

Normalized model weights.

TYPE: dict[str, float]

ndraws

Draws contributed by each model.

TYPE: dict[str, int]

summary

brms's summary of the pooled draws, when requested.

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

round_largest_remainder

round_largest_remainder(values: Sequence[float]) -> list[int]

Round to integers preserving the rounded total, as brms.

PARAMETER DESCRIPTION
values

Nonnegative reals.

TYPE: Sequence[float]

RETURNS DESCRIPTION
list[int]

Floors, with one added to the largest fractional parts until the total equals round(sum(values)).

Source code in src/quivers/formulas/_model_averaging.py
def round_largest_remainder(values: Sequence[float]) -> list[int]:
    """Round to integers preserving the rounded total, as brms.

    Parameters
    ----------
    values : Sequence[float]
        Nonnegative reals.

    Returns
    -------
    list[int]
        Floors, with one added to the largest fractional parts until the
        total equals ``round(sum(values))``.
    """
    total = round(sum(values))
    floors = [math.floor(v) for v in values]
    order = sorted(
        range(len(values)), key=lambda i: values[i] - floors[i], reverse=True
    )
    for i in order[: total - sum(floors)]:
        floors[i] += 1
    return floors

averaging_weights

averaging_weights(models: Mapping[str, Fit], weights: WeightMethod | Sequence[float], *, seed: int) -> dict[str, float]

Return normalized model weights, as brms validate_weights.

PARAMETER DESCRIPTION
models

Named fits.

TYPE: Mapping[str, BayesianFit or MultivariateFit]

weights

A model_weights method, "bma" for posterior model probabilities, or one nonnegative weight per model.

TYPE: str or Sequence[float]

seed

Seed of pseudo-BMA bootstrap weights and bridge-sampling proposals.

TYPE: int

RETURNS DESCRIPTION
dict[str, float]

Weights summing to one.

RAISES DESCRIPTION
ValueError

If explicit weights have the wrong length, are negative, or sum to zero, or the method is unknown.

Source code in src/quivers/formulas/_model_averaging.py
def averaging_weights(
    models: Mapping[str, Fit],
    weights: WeightMethod | Sequence[float],
    *,
    seed: int,
) -> dict[str, float]:
    """Return normalized model weights, as brms ``validate_weights``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit]
        Named fits.
    weights : str or Sequence[float]
        A `model_weights` method, ``"bma"`` for posterior model
        probabilities, or one nonnegative weight per model.
    seed : int
        Seed of pseudo-BMA bootstrap weights and bridge-sampling proposals.

    Returns
    -------
    dict[str, float]
        Weights summing to one.

    Raises
    ------
    ValueError
        If explicit weights have the wrong length, are negative, or sum to
        zero, or the method is unknown.
    """
    if isinstance(weights, str):
        return model_weights(models, weights=weights, seed=seed)
    values = [float(w) for w in weights]
    if len(values) != len(models):
        raise ValueError("numeric weights must have one value per model")
    if any(not math.isfinite(w) or w < 0 for w in values) or sum(values) <= 0:
        raise ValueError("numeric weights must be nonnegative with a positive sum")
    total = sum(values)
    return {name: w / total for name, w in zip(models, values, strict=True)}

posterior_average

posterior_average(models: Mapping[str, Fit], *, variable: str | Sequence[str] | None = None, weights: WeightMethod | Sequence[float] = 'stacking', ndraws: int | None = None, missing: float | Mapping[str, float] | None = None, seed: int = 0) -> PosteriorAverage

Mix the posterior draws of several fits, as brms posterior_average.

PARAMETER DESCRIPTION
models

Named fits.

TYPE: Mapping[str, BayesianFit or MultivariateFit]

variable

brms variable names (see variables); None takes every variable common to all models (every variable of any model with missing).

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

weights

Weighting method of averaging_weights, or explicit weights.

TYPE: str or Sequence[float] DEFAULT: 'stacking'

ndraws

Total draws; the first model's draw count by default.

TYPE: int or None DEFAULT: None

missing

Value of a variable in models that lack it; None requires every variable in every model.

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

seed

Seed of the draw selection and of the weights.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PosteriorAverage

Pooled draws, weights and draw counts.

RAISES DESCRIPTION
ValueError

If a variable is absent from the required models, missing lacks a value for one, or the weights or draw counts are invalid.

Source code in src/quivers/formulas/_model_averaging.py
def posterior_average(
    models: Mapping[str, Fit],
    *,
    variable: str | Sequence[str] | None = None,
    weights: WeightMethod | Sequence[float] = "stacking",
    ndraws: int | None = None,
    missing: float | Mapping[str, float] | None = None,
    seed: int = 0,
) -> PosteriorAverage:
    """Mix the posterior draws of several fits, as brms ``posterior_average``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit]
        Named fits.
    variable : str or Sequence[str] or None
        brms variable names (see ``variables``); None takes every variable
        common to all models (every variable of any model with ``missing``).
    weights : str or Sequence[float]
        Weighting method of `averaging_weights`, or explicit weights.
    ndraws : int or None
        Total draws; the first model's draw count by default.
    missing : float or Mapping[str, float] or None
        Value of a variable in models that lack it; None requires every
        variable in every model.
    seed : int
        Seed of the draw selection and of the weights.

    Returns
    -------
    PosteriorAverage
        Pooled draws, weights and draw counts.

    Raises
    ------
    ValueError
        If a variable is absent from the required models, ``missing`` lacks
        a value for one, or the weights or draw counts are invalid.
    """
    named = {name: fit.variables() for name, fit in models.items()}
    every = list(dict.fromkeys(v for draws in named.values() for v in draws))
    if missing is None:
        common = [v for v in every if all(v in draws for draws in named.values())]
        requested = common if variable is None else _names(variable)
        absent = [v for v in requested if v not in common]
        if absent:
            raise ValueError(
                f"variables {absent} are not in all models; give missing= to fill them"
            )
        fill: dict[str, float] = {}
    else:
        requested = every if variable is None else _names(variable)
        unknown = [v for v in requested if v not in every]
        if unknown:
            raise ValueError(f"variables {unknown} are in none of the models")
        if isinstance(missing, Mapping):
            needed = {
                v for draws in named.values() for v in requested if v not in draws
            }
            lacking = sorted(needed - set(missing))
            if lacking:
                raise ValueError(f"missing has no value for variables {lacking}")
            fill = {k: float(v) for k, v in missing.items()}
        else:
            fill = {v: float(missing) for v in requested}
    normalized, counts = _allocation(models, weights, ndraws, seed)
    generator = torch.Generator().manual_seed(seed)
    parts: dict[str, list[torch.Tensor]] = {v: [] for v in requested}
    for name, fit in models.items():
        count = counts[name]
        if count == 0:
            continue
        draws = named[name]
        ids = torch.tensor(_draw_ids(fit.ndraws(), count, generator))
        for v in requested:
            if v in draws:
                pooled = draws[v].reshape(-1, *draws[v].shape[2:]).double()
                parts[v].append(pooled[ids])
            else:
                parts[v].append(torch.full((count,), fill[v], dtype=torch.float64))
    return PosteriorAverage(
        draws={v: torch.cat(p) for v, p in parts.items()},
        weights=normalized,
        ndraws=counts,
    )

pp_average

pp_average(models: Mapping[str, Fit], *, weights: WeightMethod | Sequence[float] = 'stacking', method: PredictionMethod = 'posterior_predict', ndraws: int | None = None, summary: bool = True, probs: Sequence[float] = (0.025, 0.975), robust: bool = False, resp: str | None = None, **options: Unpack[PredictionOptions]) -> PredictionAverage

Mix the predictions of several fits, as brms pp_average.

PARAMETER DESCRIPTION
models

Named fits of the same response data.

TYPE: Mapping[str, BayesianFit or MultivariateFit]

weights

Weighting method of averaging_weights, or explicit weights.

TYPE: str or Sequence[float] DEFAULT: 'stacking'

method

Prediction method.

TYPE: ('posterior_predict', 'posterior_epred', 'posterior_linpred') DEFAULT: "posterior_predict"

ndraws

Total draws; the first model's draw count by default.

TYPE: int or None DEFAULT: None

summary

Also summarize the pooled draws.

TYPE: bool DEFAULT: True

probs

Quantile probabilities of the summary.

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

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

resp

Response of joint fits; required when a joint fit has several.

TYPE: str or None DEFAULT: None

**options

Prediction keywords such as new_data and re_formula; seed also seeds the draw selection and the weights.

TYPE: PredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
PredictionAverage

Pooled draws, weights, draw counts and the optional summary.

RAISES DESCRIPTION
ValueError

If the fits model different responses, draw_ids or num_samples is given, a joint response is ambiguous, or the weights are invalid.

Source code in src/quivers/formulas/_model_averaging.py
def pp_average(
    models: Mapping[str, Fit],
    *,
    weights: WeightMethod | Sequence[float] = "stacking",
    method: PredictionMethod = "posterior_predict",
    ndraws: int | None = None,
    summary: bool = True,
    probs: Sequence[float] = (0.025, 0.975),
    robust: bool = False,
    resp: str | None = None,
    **options: Unpack[PredictionOptions],
) -> PredictionAverage:
    """Mix the predictions of several fits, as brms ``pp_average``.

    Parameters
    ----------
    models : Mapping[str, BayesianFit or MultivariateFit]
        Named fits of the same response data.
    weights : str or Sequence[float]
        Weighting method of `averaging_weights`, or explicit weights.
    method : {"posterior_predict", "posterior_epred", "posterior_linpred"}
        Prediction method.
    ndraws : int or None
        Total draws; the first model's draw count by default.
    summary : bool
        Also summarize the pooled draws.
    probs : Sequence[float]
        Quantile probabilities of the summary.
    robust : bool
        Median and MAD instead of mean and SD.
    resp : str or None
        Response of joint fits; required when a joint fit has several.
    **options : PredictionOptions
        Prediction keywords such as ``new_data`` and ``re_formula``; ``seed``
        also seeds the draw selection and the weights.

    Returns
    -------
    PredictionAverage
        Pooled draws, weights, draw counts and the optional summary.

    Raises
    ------
    ValueError
        If the fits model different responses, ``draw_ids`` or ``num_samples``
        is given, a joint response is ambiguous, or the weights are invalid.
    """
    if "num_samples" in options:
        raise ValueError("pp_average chooses draws itself; give ndraws instead")
    if method not in {"posterior_predict", "posterior_epred", "posterior_linpred"}:
        raise ValueError(
            "method must be posterior_predict, posterior_epred, or posterior_linpred"
        )
    match_responses(tuple(models.values()))
    seed = options.get("seed", 0)
    normalized, counts = _allocation(models, weights, ndraws, seed)
    generator = torch.Generator().manual_seed(seed)
    parts: list[torch.Tensor] = []
    request = dict(options)
    for name, fit in models.items():
        count = counts[name]
        if count == 0:
            continue
        ids = _draw_ids(fit.ndraws(), count, generator)
        if hasattr(fit, "response_fits"):
            joint = cast("MultivariateFit", fit)
            selected = resp
            if selected is None:
                if len(joint.response_names) != 1:
                    raise ValueError(
                        "pp_average of a joint fit with several responses requires resp"
                    )
                selected = joint.response_names[0]
            values = joint._pp_prediction(
                method, selected, cast(JointPredictionOptions, request), draw_ids=ids
            )[selected]
        else:
            if resp is not None:
                raise ValueError("resp applies only to joint fits")
            values = cast("BayesianFit", fit)._pp_prediction(
                method, cast(SinglePredictionOptions, request), draw_ids=ids
            )
        parts.append(values.reshape(-1, *values.shape[2:]).double())
    pooled = torch.cat(parts)
    table = (
        summary_table(pooled.unsqueeze(0), probs=probs, robust=robust)
        if summary
        else None
    )
    return PredictionAverage(
        draws=pooled, weights=normalized, ndraws=counts, summary=table
    )

_brms_effects

Automatic conditional effects and smooths, as brms conditional_effects.

brms conditional_effects [@burkner2017brms] chooses its effects from the model: every population-level predictor variable and every pair of variables that appear together in one term, across all predicted parameters, with the variables of special terms (mo, me, mi, s, t2, gp) crossed with each other. For each effect it builds a grid over the effect's variables (resolution equally spaced values over the observed range of a numeric variable, the levels of a factor, the mean and the mean plus and minus one standard deviation of a numeric second variable), holds every other variable at a condition (the mean of a numeric variable, the rounded median of an integer variable, the reference level of a factor, one for trial counts, and no group level), predicts the grid, and summarizes the draws of each row. This module reproduces those choices from the fit's retained training data and its fitted term structure, and predicts through the fit's own prediction methods. Results are labeled data frames with brms's columns (effect1__, effect2__, cond__, estimate__, se__, lower__, upper__), with the draws retained for paired contrasts.

EffectMethod

EffectMethod = Literal['epred', 'linpred', 'predict', 'posterior_epred', 'posterior_linpred', 'posterior_predict']

Prediction method of conditional_effects: short or brms names.

ConditionValue

ConditionValue = str | int | float | bool | None

A scalar condition or grid value.

IntCondition

IntCondition = Sequence[ConditionValue] | Mapping[str, ConditionValue] | Callable[[Series], Sequence[ConditionValue]]

int_conditions entry: values, labeled values, or a function of the data.

EffectFrame didactic-model

EffectFrame(*, name: str, effects: tuple[str, ...], response: str, frame: DataFrame = field(opaque=True, extras=OPAQUE_BY_IDENTITY), draws: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), surface: bool = False, categorical: bool = False, spaghetti: DataFrame | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), points: DataFrame | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

One conditional effect, as an element of brms_conditional_effects.

PARAMETER DESCRIPTION
name

brms's list name: the effects joined by :, prefixed by <resp>. for a joint fit.

TYPE: str

effects

Plotted variables in plotting order; cats__ for categories.

TYPE: tuple[str, ...]

response

Response, distributional parameter, or nonlinear parameter predicted.

TYPE: str

frame

Grid and condition columns, cond__, effect1__ (and effect2__, cats__), and estimate__, se__, lower__, upper__.

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

draws

Prediction draws (chain, draw, row), rows in frame order.

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

surface

Whether both effects are numeric and plotted as a surface.

TYPE: bool DEFAULT: False

categorical

Whether rows are per category.

TYPE: bool DEFAULT: False

spaghetti

One row per draw and grid row with estimate__ and sample__.

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

points

Observed data assigned to conditions, with resp__.

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

BrmsConditionalEffects didactic-model

BrmsConditionalEffects(*, effects: tuple[EffectFrame, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), smooths_only: bool = False)

Bases: ValueModel

Conditional effects of one call, as a brms_conditional_effects list.

PARAMETER DESCRIPTION
effects

Effects in brms's order.

TYPE: tuple[EffectFrame, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

smooths_only

Whether the effects are smooth contributions (conditional_smooths).

TYPE: bool DEFAULT: False

names

names() -> tuple[str, ...]

Return the effect names in order.

RETURNS DESCRIPTION
tuple[str, ...]

brms's list names.

Source code in src/quivers/formulas/_brms_effects.py
def names(self) -> tuple[str, ...]:
    """Return the effect names in order.

    Returns
    -------
    tuple[str, ...]
        brms's list names.
    """
    return tuple(effect.name for effect in self.effects)

__getitem__

__getitem__(name: str) -> EffectFrame

Return one effect by name.

PARAMETER DESCRIPTION
name

brms's list name.

TYPE: str

RETURNS DESCRIPTION
EffectFrame

The effect.

RAISES DESCRIPTION
KeyError

If no effect has the name.

Source code in src/quivers/formulas/_brms_effects.py
def __getitem__(self, name: str) -> EffectFrame:
    """Return one effect by name.

    Parameters
    ----------
    name : str
        brms's list name.

    Returns
    -------
    EffectFrame
        The effect.

    Raises
    ------
    KeyError
        If no effect has the name.
    """
    for effect in self.effects:
        if effect.name == name:
            return effect
    raise KeyError(f"no effect {name!r}; effects are {list(self.names())}")

frames

frames() -> dict[str, DataFrame]

Return every effect's data frame by name.

RETURNS DESCRIPTION
dict[str, DataFrame]

brms's data frames.

Source code in src/quivers/formulas/_brms_effects.py
def frames(self) -> dict[str, pd.DataFrame]:
    """Return every effect's data frame by name.

    Returns
    -------
    dict[str, pandas.DataFrame]
        brms's data frames.
    """
    return {effect.name: effect.frame for effect in self.effects}

ConditionalEffectsOptions

Bases: ExpectationOptions

Keywords of the fits' conditional_effects methods.

Prediction keys follow BayesianFit.posterior_epred and apply to explicit prediction grids. The remaining keys are brms conditional_effects arguments of automatic effects (see brms_conditional_effects).

JointConditionalEffectsOptions

Bases: TypedDict

Keywords of MultivariateFit.conditional_effects.

re_formula, allow_new_levels, sample_new_levels, num_samples and seed follow MultivariateFit.posterior_predict and apply to explicit grids; the remaining keys are brms conditional_effects arguments of automatic effects.

model_frame

model_frame(fit: Fit) -> DataFrame

Return the fitted rows of the retained training data, as model.frame.

PARAMETER DESCRIPTION
fit

Fitted model with a refit recipe.

TYPE: BayesianFit or MultivariateFit

RETURNS DESCRIPTION
DataFrame

The included rows of a single-response fit, or every row of a joint fit, with a fresh default index.

RAISES DESCRIPTION
ValueError

If the fit retains no training data (a restored artifact).

Source code in src/quivers/formulas/_brms_effects.py
def model_frame(fit: Fit) -> pd.DataFrame:
    """Return the fitted rows of the retained training data, as ``model.frame``.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model with a refit recipe.

    Returns
    -------
    pandas.DataFrame
        The included rows of a single-response fit, or every row of a joint
        fit, with a fresh default index.

    Raises
    ------
    ValueError
        If the fit retains no training data (a restored artifact).
    """
    recipe = fit.refit_recipe
    if recipe is None:
        raise ValueError(
            "automatic conditional effects require the retained training data; "
            "pass an explicit prediction_grid for a restored fit"
        )
    frame = nw.from_native(recipe.data, eager_only=True).to_pandas()
    if not _joint(fit):
        frame = frame.iloc[list(cast("BayesianFit", fit).included_rows)]
    return frame.reset_index(drop=True)

model_variables

model_variables(readouts: Mapping[str, PredictorReadout], data: DataFrame) -> list[str]

Return the data variables of the formulas, in order of appearance.

PARAMETER DESCRIPTION
readouts

Response readouts.

TYPE: Mapping[str, PredictorReadout]

data

Model frame.

TYPE: DataFrame

RETURNS DESCRIPTION
list[str]

Responses, predictors, group variables and addition-term variables.

Source code in src/quivers/formulas/_brms_effects.py
def model_variables(
    readouts: Mapping[str, PredictorReadout], data: pd.DataFrame
) -> list[str]:
    """Return the data variables of the formulas, in order of appearance.

    Parameters
    ----------
    readouts : Mapping[str, PredictorReadout]
        Response readouts.
    data : pandas.DataFrame
        Model frame.

    Returns
    -------
    list[str]
        Responses, predictors, group variables and addition-term variables.
    """
    found: list[str] = []
    for readout in readouts.values():
        for text in _formula_texts(readout):
            for match in _IDENTIFIER.finditer(text):
                token = match.group(0)
                if token in data.columns and token not in found:
                    found.append(token)
    return found

rows2labels

rows2labels(frame: DataFrame, *, digits: int = 2, sep: str = ' & ', incl_vars: bool = True) -> list[str]

Label condition rows, as brms rows2labels.

PARAMETER DESCRIPTION
frame

Condition rows.

TYPE: DataFrame

digits

Decimal places of numeric values.

TYPE: int DEFAULT: 2

sep

Separator between variables.

TYPE: str DEFAULT: ' & '

incl_vars

Prefix each value with <name> =.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
list[str]

One label per row.

Source code in src/quivers/formulas/_brms_effects.py
def rows2labels(
    frame: pd.DataFrame, *, digits: int = 2, sep: str = " & ", incl_vars: bool = True
) -> list[str]:
    """Label condition rows, as brms ``rows2labels``.

    Parameters
    ----------
    frame : pandas.DataFrame
        Condition rows.
    digits : int
        Decimal places of numeric values.
    sep : str
        Separator between variables.
    incl_vars : bool
        Prefix each value with ``<name> = ``.

    Returns
    -------
    list[str]
        One label per row.
    """
    parts: list[list[str]] = []
    for name in frame.columns:
        column = _col(frame, name)
        numeric = not _like_factor(column)
        texts = [
            _r_text(_r_round(v, digits) if numeric and v is not None else v)
            for v in column.tolist()
        ]
        parts.append([f"{name} = {t}" if incl_vars else t for t in texts])
    return [sep.join(row) for row in zip(*parts, strict=True)]

make_conditions

make_conditions(data: IntoDataFrame | Fit, variables: str | Sequence[str], **labels: str | int | bool) -> DataFrame

Build conditions from variables of the data, as brms make_conditions.

PARAMETER DESCRIPTION
data

A data frame, or a fit whose retained training data is used.

TYPE: IntoDataFrame or BayesianFit or MultivariateFit

variables

Variables to condition on.

TYPE: str or Sequence[str]

**labels

rows2labels options (digits, sep, incl_vars).

TYPE: str or int or bool DEFAULT: {}

RETURNS DESCRIPTION
DataFrame

Every combination of the levels of factor variables and of the mean and mean plus and minus one standard deviation of numeric variables, the last variable varying fastest, with cond__ labels.

RAISES DESCRIPTION
ValueError

If a variable is not a column of the data.

Source code in src/quivers/formulas/_brms_effects.py
def make_conditions(
    data: IntoDataFrame | Fit,
    variables: str | Sequence[str],
    **labels: str | int | bool,
) -> pd.DataFrame:
    """Build conditions from variables of the data, as brms ``make_conditions``.

    Parameters
    ----------
    data : IntoDataFrame or BayesianFit or MultivariateFit
        A data frame, or a fit whose retained training data is used.
    variables : str or Sequence[str]
        Variables to condition on.
    **labels : str or int or bool
        `rows2labels` options (``digits``, ``sep``, ``incl_vars``).

    Returns
    -------
    pandas.DataFrame
        Every combination of the levels of factor variables and of the mean
        and mean plus and minus one standard deviation of numeric variables,
        the last variable varying fastest, with ``cond__`` labels.

    Raises
    ------
    ValueError
        If a variable is not a column of the data.
    """
    if hasattr(data, "refit_recipe"):
        frame = model_frame(cast("Fit", data))
    else:
        frame = nw.from_native(cast(IntoDataFrame, data), eager_only=True).to_pandas()
    names = [variables] if isinstance(variables, str) else list(variables)
    missing = [v for v in names if v not in frame.columns]
    if missing:
        raise ValueError(f"make_conditions: variables {missing} are not in the data")
    values: dict[str, list[ConditionValue]] = {}
    for name in names:
        column = _col(frame, name)
        if _like_factor(column):
            values[name] = _levels(column)
        else:
            mean = _number(column.mean())
            sd = _number(column.std(ddof=1))
            values[name] = [mean - sd, mean, mean + sd]
    index = pd.MultiIndex.from_product([values[n] for n in names], names=names)
    out = index.to_frame(index=False)
    for name in names:
        if _like_factor(_col(frame, name)) and isinstance(
            _col(frame, name).dtype, pd.CategoricalDtype
        ):
            out[name] = pd.Categorical(
                out[name], categories=_col(frame, name).cat.categories
            )
    out["cond__"] = rows2labels(
        cast(pd.DataFrame, out[names]),
        digits=int(labels.get("digits", 2)),
        sep=str(labels.get("sep", " & ")),
        incl_vars=bool(labels.get("incl_vars", True)),
    )
    return out

prepare_conditions

prepare_conditions(context: _Context, readouts: Mapping[str, PredictorReadout], conditions: IntoDataFrame | Mapping[str, Sequence[ConditionValue]] | None) -> tuple[DataFrame, list[str]]

Complete conditions with brms's defaults, as prepare_conditions.

PARAMETER DESCRIPTION
context

Model frame and variable classes.

TYPE: _Context

readouts

Response readouts.

TYPE: Mapping[str, PredictorReadout]

conditions

User conditions, one row per condition, optionally with cond__.

TYPE: IntoDataFrame or Mapping or None

RETURNS DESCRIPTION
tuple[DataFrame, list[str]]

Completed conditions (without cond__) and their labels.

RAISES DESCRIPTION
ValueError

If the conditions are empty or their labels repeat.

Source code in src/quivers/formulas/_brms_effects.py
def prepare_conditions(
    context: _Context,
    readouts: Mapping[str, PredictorReadout],
    conditions: IntoDataFrame | Mapping[str, Sequence[ConditionValue]] | None,
) -> tuple[pd.DataFrame, list[str]]:
    """Complete conditions with brms's defaults, as ``prepare_conditions``.

    Parameters
    ----------
    context : _Context
        Model frame and variable classes.
    readouts : Mapping[str, PredictorReadout]
        Response readouts.
    conditions : IntoDataFrame or Mapping or None
        User conditions, one row per condition, optionally with ``cond__``.

    Returns
    -------
    tuple[pandas.DataFrame, list[str]]
        Completed conditions (without ``cond__``) and their labels.

    Raises
    ------
    ValueError
        If the conditions are empty or their labels repeat.
    """
    data = context.data
    required = [v for v in context.variables]
    if conditions is None:
        frame = pd.DataFrame({v: [None] for v in required})
        labels = ["1"]
    else:
        frame = (
            pd.DataFrame(dict(conditions))
            if isinstance(conditions, Mapping)
            else nw.from_native(conditions, eager_only=True).to_pandas()
        )
        if not len(frame):
            raise ValueError("conditions must have at least one row")
        frame = frame.drop_duplicates()
        if "cond__" in frame.columns:
            labels = [str(v) for v in frame["cond__"].tolist()]
            frame = frame.drop(columns="cond__")
        else:
            labels = [str(i + 1) for i in frame.index.tolist()]
        if len(set(labels)) != len(labels):
            raise ValueError("condition labels must be unique")
        frame = frame.reset_index(drop=True)
        required = [v for v in required if v not in frame.columns]
    trial_vars = [v for readout in readouts.values() for v in _trial_variables(readout)]
    for v in trial_vars:
        if v not in frame.columns or _col(frame, v).isna().all():
            frame[v] = 1
            if v in required:
                required.remove(v)
    for v in required:
        if v in context.group_vars:
            if v not in frame.columns:
                frame[v] = None
            continue
        column = _col(data, v)
        if _like_factor(column):
            value: ConditionValue = _levels(column)[0]
        elif v in context.int_vars:
            value = float(round(_number(column.median())))
        else:
            value = _number(column.mean())
        frame[v] = [value] * len(frame)
    return frame, labels

prepare_cond_data

prepare_cond_data(context: _Context, effects: tuple[str, ...], conditions: DataFrame, labels: list[str], *, int_conditions: Mapping[str, IntCondition], surface: bool, resolution: int, reorder: bool) -> tuple[DataFrame, tuple[str, ...], tuple[str, ...], list[str] | None]

Build one effect's prediction grid, as brms prepare_cond_data.

PARAMETER DESCRIPTION
context

Model frame and variable classes.

TYPE: _Context

effects

One or two variables.

TYPE: tuple[str, ...]

conditions

Completed conditions.

TYPE: DataFrame

labels

Condition labels.

TYPE: list[str]

int_conditions

Values of chosen effect variables.

TYPE: Mapping

surface

Grid a numeric second variable over its range.

TYPE: bool

resolution

Numeric grid size.

TYPE: int

reorder

Put numeric effects first (default effects only).

TYPE: bool

RETURNS DESCRIPTION
tuple[DataFrame, tuple[str, ...], tuple[str, ...], list[str] or None]

Grid rows replicated per condition with cond__, the effects and their types ("numeric"/"factor") in plotting order, and the labels of the second effect's int_conditions.

Source code in src/quivers/formulas/_brms_effects.py
def prepare_cond_data(
    context: _Context,
    effects: tuple[str, ...],
    conditions: pd.DataFrame,
    labels: list[str],
    *,
    int_conditions: Mapping[str, IntCondition],
    surface: bool,
    resolution: int,
    reorder: bool,
) -> tuple[pd.DataFrame, tuple[str, ...], tuple[str, ...], list[str] | None]:
    """Build one effect's prediction grid, as brms ``prepare_cond_data``.

    Parameters
    ----------
    context : _Context
        Model frame and variable classes.
    effects : tuple[str, ...]
        One or two variables.
    conditions : pandas.DataFrame
        Completed conditions.
    labels : list[str]
        Condition labels.
    int_conditions : Mapping
        Values of chosen effect variables.
    surface : bool
        Grid a numeric second variable over its range.
    resolution : int
        Numeric grid size.
    reorder : bool
        Put numeric effects first (default effects only).

    Returns
    -------
    tuple[pandas.DataFrame, tuple[str, ...], tuple[str, ...], list[str] or None]
        Grid rows replicated per condition with ``cond__``, the effects and
        their types (``"numeric"``/``"factor"``) in plotting order, and the
        labels of the second effect's ``int_conditions``.
    """
    data = context.data
    types = tuple(
        "factor"
        if _like_factor(_col(data, e)) or e in context.group_vars
        else "numeric"
        for e in effects
    )
    if reorder and len(effects) == 2 and types == ("factor", "numeric"):
        effects, types = effects[::-1], types[::-1]
    values: list[list[ConditionValue] | list[float]] = []
    levels: list[list[ConditionValue] | None] = []
    second_labels: list[str] | None = None
    for position, (effect, kind) in enumerate(zip(effects, types, strict=True)):
        column = _col(data, effect)
        factor_levels = _levels(column) if kind == "factor" else None
        if effect in int_conditions:
            chosen, names = _int_condition(int_conditions[effect], column)
            if position == 1:
                second_labels = names
        elif kind == "factor":
            chosen = list(cast(list[ConditionValue], factor_levels))
        elif position == 0 or surface:
            chosen = list(_numeric_grid(column, effect in context.int_vars, resolution))
        elif effect in context.int_vars:
            median = _number(column.median())
            mad = 1.4826 * _number((column - median).abs().median())
            chosen = [float(round(median + k * mad)) for k in (-1, 0, 1)]
        else:
            mean, sd = _number(column.mean()), _number(column.std(ddof=1))
            chosen = [mean - sd, mean, mean + sd]
        values.append(chosen)
        levels.append(factor_levels)
    if len(effects) == 2:
        rows = [(a, b) for b in values[1] for a in values[0]]
    else:
        rows = [(a,) for a in values[0]]
    unique_rows = list(dict.fromkeys(rows))
    unique_rows.sort(
        key=lambda row: tuple(_sort_key(v, levels[i]) for i, v in enumerate(row))
    )
    grid = pd.DataFrame(unique_rows, columns=list(effects))
    blocks = []
    cond_vars = [c for c in conditions.columns if c not in effects]
    for j, label in enumerate(labels):
        block = grid.copy()
        for v in cond_vars:
            block[v] = [conditions[v].iloc[j]] * len(block)
        block["cond__"] = label
        blocks.append(block)
    frame = pd.concat(blocks, ignore_index=True)
    frame["cond__"] = pd.Categorical(frame["cond__"], categories=list(labels))
    return frame, effects, types, second_labels

exclude_too_far

exclude_too_far(g1: ndarray, g2: ndarray, d1: ndarray, d2: ndarray, dist: float) -> ndarray

Flag grid points far from the data, as mgcv exclude.too.far.

PARAMETER DESCRIPTION
g1

Grid coordinates.

TYPE: ndarray

g2

Grid coordinates.

TYPE: ndarray

d1

Data coordinates.

TYPE: ndarray

d2

Data coordinates.

TYPE: ndarray

dist

Distance threshold on the grid's unit square.

TYPE: float

RETURNS DESCRIPTION
ndarray

True where the nearest data point is farther than dist after both axes are scaled by the grid's range. Costs O(n m) for n grid and m data points.

Source code in src/quivers/formulas/_brms_effects.py
def exclude_too_far(
    g1: np.ndarray, g2: np.ndarray, d1: np.ndarray, d2: np.ndarray, dist: float
) -> np.ndarray:
    """Flag grid points far from the data, as mgcv ``exclude.too.far``.

    Parameters
    ----------
    g1, g2 : numpy.ndarray
        Grid coordinates.
    d1, d2 : numpy.ndarray
        Data coordinates.
    dist : float
        Distance threshold on the grid's unit square.

    Returns
    -------
    numpy.ndarray
        True where the nearest data point is farther than ``dist`` after
        both axes are scaled by the grid's range. Costs O(n m) for n grid
        and m data points.
    """

    def scale(grid: np.ndarray, data: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        low = grid.min()
        span = (grid - low).max()
        return (grid - low) / span, (data - low) / span

    a1, b1 = scale(np.asarray(g1, float), np.asarray(d1, float))
    a2, b2 = scale(np.asarray(g2, float), np.asarray(d2, float))
    nearest = np.full(a1.shape[0], np.inf)
    for start in range(0, a1.shape[0], 4096):
        stop = start + 4096
        squared = (a1[start:stop, None] - b1[None, :]) ** 2 + (
            a2[start:stop, None] - b2[None, :]
        ) ** 2
        nearest[start:stop] = np.sqrt(squared.min(axis=1))
    return nearest > dist

brms_conditional_effects

brms_conditional_effects(fit: Fit, effects: str | Sequence[str] | None = None, *, conditions: IntoDataFrame | Mapping[str, Sequence[ConditionValue]] | None = None, int_conditions: Mapping[str, IntCondition] | None = None, re_formula: str | None = '~0', prob: float = 0.95, robust: bool = True, method: PredictionMethod = 'posterior_epred', spaghetti: bool = False, surface: bool = False, categorical: bool = False, ordinal: bool = False, resolution: int = 100, select_points: float = 0.0, too_far: float = 0.0, resp: str | Sequence[str] | None = None, dpar: str | None = None, nlpar: str | None = None, ndraws: int | None = None, draw_ids: Sequence[int] | None = None, seed: int = 0, mc_samples: int | None = None) -> BrmsConditionalEffects

Compute brms's automatic conditional effects of a fit.

PARAMETER DESCRIPTION
fit

Fitted model with retained training data.

TYPE: BayesianFit or MultivariateFit

effects

Effects such as "x" or "x:z"; None selects brms's defaults.

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

conditions

Rows of values of other variables, each one condition, optionally labeled by cond__ (see make_conditions).

TYPE: IntoDataFrame or Mapping or None DEFAULT: None

int_conditions

Values (a sequence, a labeled mapping, or a function of the data) of effect variables, replacing brms's default grid values.

TYPE: Mapping or None DEFAULT: None

re_formula

Varying effects included: "~0" (brms's NA) none, None all.

TYPE: str or None DEFAULT: '~0'

prob

Interval probability.

TYPE: float DEFAULT: 0.95

robust

Median and MAD (brms's default) instead of mean and SD.

TYPE: bool DEFAULT: True

method

Prediction method.

TYPE: ('posterior_epred', 'posterior_linpred', 'posterior_predict') DEFAULT: "posterior_epred"

spaghetti

Also return per-draw lines of numeric first effects.

TYPE: bool DEFAULT: False

surface

Grid a numeric second effect over its range.

TYPE: bool DEFAULT: False

categorical

Per-category probabilities of categorical and ordinal models.

TYPE: bool DEFAULT: False

ordinal

brms's deprecated alias of categorical.

TYPE: bool DEFAULT: False

resolution

Numeric grid size.

TYPE: int DEFAULT: 100

select_points

Unit-scaled distance for assigning data points to numeric conditions.

TYPE: float DEFAULT: 0.0

too_far

Drop surface grid points farther than this from the data.

TYPE: float DEFAULT: 0.0

resp

Responses of a joint fit.

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

dpar

Distributional or nonlinear parameter to predict instead of the mean.

TYPE: str or None DEFAULT: None

nlpar

Distributional or nonlinear parameter to predict instead of the mean.

TYPE: str or None DEFAULT: None

ndraws

Random subset of draws.

TYPE: int or None DEFAULT: None

draw_ids

Explicit 0-based draws.

TYPE: Sequence[int] or None DEFAULT: None

seed

Seed of draw selection and predictions.

TYPE: int DEFAULT: 0

mc_samples

Monte Carlo budget of a conditional mean without a closed form (posterior_epred of a single-response fit only).

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
BrmsConditionalEffects

One EffectFrame per effect (per response for joint fits).

RAISES DESCRIPTION
ValueError

If arguments are invalid, effects are invalid for the model, the fit retains no data, or a categorical model is summarized without categorical=True.

Notes

Each effect costs one prediction over G C rows for G grid points and C conditions, O(S G C) for S draws beyond the model's own per-row prediction cost.

Source code in src/quivers/formulas/_brms_effects.py
def brms_conditional_effects(
    fit: Fit,
    effects: str | Sequence[str] | None = None,
    *,
    conditions: IntoDataFrame | Mapping[str, Sequence[ConditionValue]] | None = None,
    int_conditions: Mapping[str, IntCondition] | None = None,
    re_formula: str | None = "~0",
    prob: float = 0.95,
    robust: bool = True,
    method: PredictionMethod = "posterior_epred",
    spaghetti: bool = False,
    surface: bool = False,
    categorical: bool = False,
    ordinal: bool = False,
    resolution: int = 100,
    select_points: float = 0.0,
    too_far: float = 0.0,
    resp: str | Sequence[str] | None = None,
    dpar: str | None = None,
    nlpar: str | None = None,
    ndraws: int | None = None,
    draw_ids: Sequence[int] | None = None,
    seed: int = 0,
    mc_samples: int | None = None,
) -> BrmsConditionalEffects:
    """Compute brms's automatic conditional effects of a fit.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model with retained training data.
    effects : str or Sequence[str] or None
        Effects such as ``"x"`` or ``"x:z"``; None selects brms's defaults.
    conditions : IntoDataFrame or Mapping or None
        Rows of values of other variables, each one condition, optionally
        labeled by ``cond__`` (see `make_conditions`).
    int_conditions : Mapping or None
        Values (a sequence, a labeled mapping, or a function of the data) of
        effect variables, replacing brms's default grid values.
    re_formula : str or None
        Varying effects included: ``"~0"`` (brms's ``NA``) none, None all.
    prob : float
        Interval probability.
    robust : bool
        Median and MAD (brms's default) instead of mean and SD.
    method : {"posterior_epred", "posterior_linpred", "posterior_predict"}
        Prediction method.
    spaghetti : bool
        Also return per-draw lines of numeric first effects.
    surface : bool
        Grid a numeric second effect over its range.
    categorical : bool
        Per-category probabilities of categorical and ordinal models.
    ordinal : bool
        brms's deprecated alias of ``categorical``.
    resolution : int
        Numeric grid size.
    select_points : float
        Unit-scaled distance for assigning data points to numeric conditions.
    too_far : float
        Drop surface grid points farther than this from the data.
    resp : str or Sequence[str] or None
        Responses of a joint fit.
    dpar, nlpar : str or None
        Distributional or nonlinear parameter to predict instead of the mean.
    ndraws : int or None
        Random subset of draws.
    draw_ids : Sequence[int] or None
        Explicit 0-based draws.
    seed : int
        Seed of draw selection and predictions.
    mc_samples : int or None
        Monte Carlo budget of a conditional mean without a closed form
        (``posterior_epred`` of a single-response fit only).

    Returns
    -------
    BrmsConditionalEffects
        One `EffectFrame` per effect (per response for joint fits).

    Raises
    ------
    ValueError
        If arguments are invalid, effects are invalid for the model, the fit
        retains no data, or a categorical model is summarized without
        ``categorical=True``.

    Notes
    -----
    Each effect costs one prediction over ``G C`` rows for ``G`` grid points
    and ``C`` conditions, O(S G C) for S draws beyond the model's own
    per-row prediction cost.
    """
    if not 0.0 <= prob <= 1.0:
        raise ValueError("prob must be in [0, 1]")
    if method not in {"posterior_epred", "posterior_linpred", "posterior_predict"}:
        raise ValueError(
            "method must be posterior_epred, posterior_linpred, or posterior_predict"
        )
    if (
        isinstance(resolution, bool)
        or not isinstance(resolution, int)
        or resolution < 1
    ):
        raise ValueError("resolution must be a positive integer")
    if categorical and ordinal:
        raise ValueError("use categorical instead of ordinal")
    per_category = categorical or ordinal
    if spaghetti and surface:
        raise ValueError("spaghetti and surface cannot be combined")
    probs = ((1.0 - prob) / 2.0, 1.0 - (1.0 - prob) / 2.0)
    # Effects and conditions come from every response; resp selects predictions.
    every = _readouts(fit, None)
    readouts = _readouts(fit, resp)
    data = model_frame(fit)
    variables = model_variables(every, data)
    context = _Context(
        data=data,
        variables=tuple(variables),
        group_vars=tuple(sorted(_group_variables(every, data))),
        int_vars=tuple(sorted(_integer_variables(every))),
    )
    available: list[tuple[str, ...]] = []
    for readout in every.values():
        for effect in _parameter_effects(readout):
            if effect not in available:
                available.append(effect)
    combined = list(dict.fromkeys(v for e in available for v in e))
    combined += [g for g in context.group_vars if g not in combined]
    chosen, defaults = _requested_effects(effects, available, combined)
    if per_category:
        chosen = [e for e in chosen if len(e) == 1]
    if not chosen:
        raise ValueError("no valid effects detected")
    filled, labels = prepare_conditions(context, every, conditions)
    resolved_int = dict(int_conditions or {})
    selected = _draw_ids(fit, ndraws, draw_ids, seed)
    out: list[EffectFrame] = []
    # brms loops effects, then responses (conditional_effects.mvbrmsterms).
    for effect in chosen:
        for response, readout in readouts.items():
            family = readout.family
            is_categorical = family.response is not None
            is_ordinal = family.response_ordinal() is not None
            frame, ordered, types, second_labels = prepare_cond_data(
                context,
                effect,
                filled,
                labels,
                int_conditions=resolved_int,
                surface=surface,
                resolution=resolution,
                reorder=defaults,
            )
            is_surface = (
                surface and len(ordered) == 2 and types == ("numeric", "numeric")
            )
            if is_surface and too_far > 0:
                far = exclude_too_far(
                    _col(frame, ordered[0]).to_numpy(float),
                    _col(frame, ordered[1]).to_numpy(float),
                    _col(data, ordered[0]).to_numpy(float),
                    _col(data, ordered[1]).to_numpy(float),
                    too_far,
                )
                frame = frame.loc[~far].reset_index(drop=True)
            draws = _predict(
                fit,
                response,
                frame,
                method=method,
                dpar=dpar,
                nlpar=nlpar,
                re_formula=re_formula,
                draw_ids=selected,
                seed=seed,
                mc_samples=mc_samples,
            ).double()
            names = list(ordered)
            categories: tuple[int | str, ...] = ()
            if per_category:
                if method != "posterior_epred":
                    raise ValueError("categorical requires method='posterior_epred'")
                if not (is_categorical or is_ordinal):
                    raise ValueError(
                        "categorical applies only to categorical or ordinal models"
                    )
                categories = readout.category_labels
                frame = pd.concat([frame] * len(categories), ignore_index=True)
                frame["cats__"] = pd.Categorical(
                    np.repeat(
                        [str(c) for c in categories], len(frame) // len(categories)
                    ),
                    categories=[str(c) for c in categories],
                )
                draws = draws.movedim(-1, 2).reshape(*draws.shape[:2], -1)
                names = [names[0], "cats__"]
                types = (types[0], "factor")
            elif dpar is None and nlpar is None:
                if is_categorical:
                    raise ValueError(
                        "set categorical=True for the effects of a categorical model"
                    )
                if is_ordinal and method == "posterior_epred":
                    # brms: equidistant category scores 1..K.
                    scores = torch.arange(1, draws.shape[-1] + 1, dtype=draws.dtype)
                    draws = (draws * scores).sum(-1)
            if draws.ndim != 3:
                raise ValueError(
                    "conditional effects require one prediction per grid row; "
                    "select a scalar parameter"
                )
            for i, name in enumerate(names, start=1):
                frame[f"effect{i}__"] = _effect_column(frame, name)
            if len(names) == 2 and types[1] == "numeric" and not surface:
                frame["effect2__"] = _second_effect_labels(
                    _col(frame, names[1]), second_labels
                )
            spag = (
                _spaghetti(frame, draws, tuple(names))
                if spaghetti and types[0] == "numeric"
                else None
            )
            stats = _summary(draws, probs, robust)
            frame["estimate__"] = stats[:, 0]
            frame["se__"] = stats[:, 1]
            frame["lower__"] = stats[:, 2]
            frame["upper__"] = stats[:, 3]
            observed = readout.formula.response_name if not response else response
            response_values = (
                _col(data, observed)
                if observed in data.columns
                else pd.Series(
                    np.asarray(readout.formula.response_values).reshape(len(data), -1)[
                        :, 0
                    ]
                )
            )
            points = _points(
                context,
                response_values,
                tuple(names),
                filled,
                labels,
                select_points=select_points,
                binary=family.native.support == "boolean",
            )
            prefix = f"{response}.{response}_" if response else ""
            out.append(
                EffectFrame(
                    name=prefix + ":".join(names),
                    effects=tuple(names),
                    response=dpar
                    or nlpar
                    or readout.formula.formula.split("~", 1)[0].strip(),
                    frame=frame,
                    draws=draws,
                    surface=is_surface,
                    categorical=per_category,
                    spaghetti=spag,
                    points=points,
                )
            )
    return BrmsConditionalEffects(effects=tuple(out))

brms_conditional_smooths

brms_conditional_smooths(fit: Fit, smooths: str | Sequence[str] | None = None, *, resp: str | Sequence[str] | None = None, int_conditions: Mapping[str, IntCondition] | None = None, prob: float = 0.95, spaghetti: bool = False, surface: bool = True, resolution: int = 100, too_far: float = 0.0, ndraws: int | None = None, draw_ids: Sequence[int] | None = None, seed: int = 0) -> BrmsConditionalEffects

Compute every smooth's contribution on a grid, as brms conditional_smooths.

PARAMETER DESCRIPTION
fit

Fitted model with s() or t2() terms and retained data.

TYPE: BayesianFit or MultivariateFit

smooths

Smooth term labels (white space ignored); None for all.

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

resp

Responses of a joint fit whose smooths are evaluated; None for all.

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

int_conditions

Values of covariates or by variables.

TYPE: Mapping or None DEFAULT: None

prob

Interval probability.

TYPE: float DEFAULT: 0.95

spaghetti

Also return per-draw curves of one-dimensional smooths.

TYPE: bool DEFAULT: False

surface

Grid a numeric second covariate over its range (brms's default).

TYPE: bool DEFAULT: True

resolution

Grid size per numeric covariate.

TYPE: int DEFAULT: 100

too_far

Drop surface grid points farther than this from the data.

TYPE: float DEFAULT: 0.0

ndraws

Random subset of draws.

TYPE: int or None DEFAULT: None

draw_ids

Explicit 0-based draws.

TYPE: Sequence[int] or None DEFAULT: None

seed

Seed of draw selection.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
BrmsConditionalEffects

One EffectFrame named <parameter>: <term> per smooth (<parameter>_<resp>: <term> in a joint fit, as brms), with robust summaries (median and MAD) as brms computes them.

RAISES DESCRIPTION
ValueError

If the fit has no matching smooth term or the arguments are invalid.

Notes

Each smooth costs one evaluation of its contribution over the grid, O(S G B) for S draws, G grid points and basis width B.

Source code in src/quivers/formulas/_brms_effects.py
def brms_conditional_smooths(
    fit: Fit,
    smooths: str | Sequence[str] | None = None,
    *,
    resp: str | Sequence[str] | None = None,
    int_conditions: Mapping[str, IntCondition] | None = None,
    prob: float = 0.95,
    spaghetti: bool = False,
    surface: bool = True,
    resolution: int = 100,
    too_far: float = 0.0,
    ndraws: int | None = None,
    draw_ids: Sequence[int] | None = None,
    seed: int = 0,
) -> BrmsConditionalEffects:
    """Compute every smooth's contribution on a grid, as brms ``conditional_smooths``.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model with ``s()`` or ``t2()`` terms and retained data.
    smooths : str or Sequence[str] or None
        Smooth term labels (white space ignored); None for all.
    resp : str or Sequence[str] or None
        Responses of a joint fit whose smooths are evaluated; None for all.
    int_conditions : Mapping or None
        Values of covariates or ``by`` variables.
    prob : float
        Interval probability.
    spaghetti : bool
        Also return per-draw curves of one-dimensional smooths.
    surface : bool
        Grid a numeric second covariate over its range (brms's default).
    resolution : int
        Grid size per numeric covariate.
    too_far : float
        Drop surface grid points farther than this from the data.
    ndraws : int or None
        Random subset of draws.
    draw_ids : Sequence[int] or None
        Explicit 0-based draws.
    seed : int
        Seed of draw selection.

    Returns
    -------
    BrmsConditionalEffects
        One `EffectFrame` named ``<parameter>: <term>`` per smooth
        (``<parameter>_<resp>: <term>`` in a joint fit, as brms), with
        robust summaries (median and MAD) as brms computes them.

    Raises
    ------
    ValueError
        If the fit has no matching smooth term or the arguments are invalid.

    Notes
    -----
    Each smooth costs one evaluation of its contribution over the grid,
    O(S G B) for S draws, G grid points and basis width B.
    """
    if not 0.0 <= prob <= 1.0:
        raise ValueError("prob must be in [0, 1]")
    if (
        isinstance(resolution, bool)
        or not isinstance(resolution, int)
        or resolution < 1
    ):
        raise ValueError("resolution must be a positive integer")
    probs = ((1.0 - prob) / 2.0, 1.0 - (1.0 - prob) / 2.0)
    wanted = (
        None
        if smooths is None
        else {
            re.sub(r"\s", "", s)
            for s in ([smooths] if isinstance(smooths, str) else smooths)
        }
    )
    data = model_frame(fit)
    readouts = _readouts(fit, resp)
    context = _Context(
        data=data,
        variables=tuple(model_variables(readouts, data)),
        group_vars=tuple(sorted(_group_variables(readouts, data))),
        int_vars=tuple(sorted(_integer_variables(readouts))),
    )
    filled, _ = prepare_conditions(context, readouts, None)
    resolved_int = dict(int_conditions or {})
    selected = _draw_ids(fit, ndraws, draw_ids, seed)
    replayed = fit if selected is None else fit._pp_view(selected, seed)
    # A response of a joint fit reads the joint draws under its namespace.
    joint_draws = (
        cast("MultivariateFit", replayed).draws(seed=seed) if _joint(fit) else None
    )

    def effect_draws() -> Mapping[str, torch.Tensor]:
        if joint_draws is not None:
            return joint_draws
        return cast("BayesianFit", replayed).draws(seed=seed)

    out: list[EffectFrame] = []
    for response, readout in readouts.items():
        if readout.designs is None:
            continue
        site_prefix = (
            cast("MultivariateFit", fit).emission.responses[response].prefix
            if joint_draws is not None
            else ""
        )
        prefixes = {
            name: prefix
            for name, prefix, _ in predictor_items(
                readout.formula, readout.distributional, readout.predictor_graph
            )
        }
        for parameter, design in readout.designs.items():
            if design.common is None:
                continue
            kinds = _effect_kinds(readout, prefixes[parameter])
            for label, term in design.common.terms.items():
                if kinds.get(label) != "sm":
                    continue
                compact = re.sub(r"\s", "", label)
                if wanted is not None and compact not in wanted:
                    continue
                sources = design_variables(term)
                byvars = list(sources.by)
                covars = [v for v in sources.names if v not in byvars]
                if len(covars) > 2:
                    byvars = covars[2:] + byvars
                    covars = covars[:2]
                elif len(covars) == 1 and byvars:
                    covars = covars + byvars[:1]
                    byvars = byvars[1:]
                grid_values: list[list[ConditionValue] | list[float]] = []
                numeric = []
                for position, cv in enumerate(covars):
                    column = _col(data, cv)
                    is_numeric = not _like_factor(column)
                    numeric.append(is_numeric)
                    if cv in resolved_int:
                        grid_values.append(_int_condition(resolved_int[cv], column)[0])
                    elif is_numeric:
                        if not surface and position == 1:
                            mean, sd = (
                                _number(column.mean()),
                                _number(column.std(ddof=1)),
                            )
                            grid_values.append([mean - sd, mean, mean + sd])
                        else:
                            grid_values.append(
                                list(_numeric_grid(column, False, resolution))
                            )
                    else:
                        grid_values.append(_levels(column))
                for cv in byvars:
                    column = _col(data, cv)
                    if cv in resolved_int:
                        grid_values.append(_int_condition(resolved_int[cv], column)[0])
                    elif not _like_factor(column):
                        mean, sd = _number(column.mean()), _number(column.std(ddof=1))
                        grid_values.append([mean - sd, mean, mean + sd])
                    else:
                        grid_values.append(_levels(column))
                variables = covars + byvars
                index = pd.MultiIndex.from_product(
                    grid_values[::-1], names=variables[::-1]
                )
                grid = cast(pd.DataFrame, index.to_frame(index=False)[variables])
                show_surface = surface and len(covars) == 2 and all(numeric)
                if show_surface and too_far > 0:
                    far = exclude_too_far(
                        _col(grid, covars[0]).to_numpy(float),
                        _col(grid, covars[1]).to_numpy(float),
                        _col(data, covars[0]).to_numpy(float),
                        _col(data, covars[1]).to_numpy(float),
                        too_far,
                    )
                    grid = grid.loc[~far].reset_index(drop=True)
                newdata = grid.copy()
                for v in filled.columns:
                    if v not in newdata.columns:
                        newdata[v] = [filled[v].iloc[0]] * len(newdata)
                eta = _smooth_contribution(
                    readout,
                    label,
                    newdata,
                    parameter=parameter,
                    seed=seed,
                    get_draws=effect_draws,
                    site_prefix=site_prefix,
                )
                output = next(
                    term.output
                    for item in readout.predictors
                    if item.parameter == parameter
                    for term in item.terms
                    if any(
                        source.label == label and source.kind == "sm"
                        for source in term.effects()
                    )
                )
                # A vector of smooths has one effect per coordinate.
                parameters, effects = (parameter,), (eta,)
                if output is not None:
                    effects = eta.unbind(-1)
                    parameters = output.parameters or tuple(
                        f"{parameter}[{index + 1}]" for index in range(output.size)
                    )
                for coordinate, values in zip(parameters, effects, strict=True):
                    name = f"{coordinate}_{response}" if response else coordinate
                    frame = cast(pd.DataFrame, grid[variables]).copy()
                    plotted = covars[:2]
                    for i, covariate in enumerate(plotted, start=1):
                        frame[f"effect{i}__"] = _col(frame, covariate).to_numpy()
                    if len(numeric) == 2 and numeric[1] and not surface:
                        frame["effect2__"] = _second_effect_labels(
                            _col(frame, plotted[1]), None
                        )
                    frame["cond__"] = (
                        pd.Categorical(rows2labels(cast(pd.DataFrame, frame[byvars])))
                        if byvars
                        else pd.Categorical(["1"] * len(frame))
                    )
                    spag = (
                        _spaghetti(frame, values, tuple(plotted))
                        if spaghetti and not show_surface and numeric[0]
                        else None
                    )
                    stats = _summary(values.double(), probs, True)
                    frame["estimate__"] = stats[:, 0]
                    frame["se__"] = stats[:, 1]
                    frame["lower__"] = stats[:, 2]
                    frame["upper__"] = stats[:, 3]
                    points = cast(pd.DataFrame, data[variables]).copy()
                    for i, covariate in enumerate(covars, start=1):
                        points[f"effect{i}__"] = points[covariate].to_numpy()
                    out.append(
                        EffectFrame(
                            name=f"{name}: {compact}",
                            effects=tuple(plotted),
                            response=f"{name}: {compact}",
                            frame=frame,
                            draws=values.double(),
                            surface=show_surface,
                            spaghetti=spag,
                            points=points,
                        )
                    )
    if not out:
        raise ValueError("no valid smooth terms found in the model")
    return BrmsConditionalEffects(effects=tuple(out), smooths_only=True)

joint_grid_options

Return the prediction keywords of an explicit joint-grid request.

PARAMETER DESCRIPTION
options

Method keywords.

TYPE: JointConditionalEffectsOptions

RETURNS DESCRIPTION
JointPredictionOptions

The prediction keywords.

RAISES DESCRIPTION
ValueError

If a brms automatic-effects keyword is given with an explicit grid.

Source code in src/quivers/formulas/_brms_effects.py
def joint_grid_options(
    options: JointConditionalEffectsOptions,
) -> JointPredictionOptions:
    """Return the prediction keywords of an explicit joint-grid request.

    Parameters
    ----------
    options : JointConditionalEffectsOptions
        Method keywords.

    Returns
    -------
    JointPredictionOptions
        The prediction keywords.

    Raises
    ------
    ValueError
        If a brms automatic-effects keyword is given with an explicit grid.
    """
    extra = sorted(_AUTOMATIC_KEYS & set(options))
    if extra:
        raise ValueError(
            f"{extra} apply to automatic conditional effects, not to an explicit grid"
        )
    return cast(JointPredictionOptions, options)

grid_options

Return the prediction keywords of an explicit-grid request.

PARAMETER DESCRIPTION
options

Method keywords.

TYPE: ConditionalEffectsOptions

RETURNS DESCRIPTION
ExpectationOptions

The same keywords.

RAISES DESCRIPTION
ValueError

If a brms automatic-effects keyword is given with an explicit grid.

Source code in src/quivers/formulas/_brms_effects.py
def grid_options(options: ConditionalEffectsOptions) -> ExpectationOptions:
    """Return the prediction keywords of an explicit-grid request.

    Parameters
    ----------
    options : ConditionalEffectsOptions
        Method keywords.

    Returns
    -------
    ExpectationOptions
        The same keywords.

    Raises
    ------
    ValueError
        If a brms automatic-effects keyword is given with an explicit grid.
    """
    extra = sorted(_AUTOMATIC_KEYS & set(options))
    if extra:
        raise ValueError(
            f"{extra} apply to automatic conditional effects, not to an explicit grid"
        )
    return cast(ExpectationOptions, options)

automatic_conditional_effects

automatic_conditional_effects(fit: Fit, effects: str | Sequence[str] | None, *, method: str, parameter: str, transform: bool, resp: str | Sequence[str] | None, options: ConditionalEffectsOptions | JointConditionalEffectsOptions) -> BrmsConditionalEffects

Dispatch a fit's conditional_effects call without a grid.

PARAMETER DESCRIPTION
fit

Fitted model.

TYPE: BayesianFit or MultivariateFit

effects

brms effects.

TYPE: str or Sequence[str] or None

method

epred/linpred/predict or brms's function names.

TYPE: str

parameter

mu or a distributional parameter (brms dpar).

TYPE: str

transform

Must be False; brms applies no inverse link to posterior_linpred.

TYPE: bool

resp

Joint responses.

TYPE: str or Sequence[str] or None

options

brms arguments and re_formula and seed.

TYPE: ConditionalEffectsOptions or JointConditionalEffectsOptions

RETURNS DESCRIPTION
BrmsConditionalEffects

The effects.

RAISES DESCRIPTION
ValueError

If the method is unknown, or a keyword applies only to explicit grids.

Source code in src/quivers/formulas/_brms_effects.py
def automatic_conditional_effects(
    fit: Fit,
    effects: str | Sequence[str] | None,
    *,
    method: str,
    parameter: str,
    transform: bool,
    resp: str | Sequence[str] | None,
    options: ConditionalEffectsOptions | JointConditionalEffectsOptions,
) -> BrmsConditionalEffects:
    """Dispatch a fit's ``conditional_effects`` call without a grid.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model.
    effects : str or Sequence[str] or None
        brms ``effects``.
    method : str
        ``epred``/``linpred``/``predict`` or brms's function names.
    parameter : str
        ``mu`` or a distributional parameter (brms ``dpar``).
    transform : bool
        Must be False; brms applies no inverse link to ``posterior_linpred``.
    resp : str or Sequence[str] or None
        Joint responses.
    options : ConditionalEffectsOptions or JointConditionalEffectsOptions
        brms arguments and ``re_formula`` and ``seed``.

    Returns
    -------
    BrmsConditionalEffects
        The effects.

    Raises
    ------
    ValueError
        If the method is unknown, or a keyword applies only to explicit grids.
    """
    if method not in _METHODS:
        raise ValueError(
            "method must be epred, linpred, predict, posterior_epred, "
            "posterior_linpred, or posterior_predict"
        )
    unsupported = sorted(
        set(options) - _AUTOMATIC_KEYS - {"re_formula", "seed", "mc_samples"}
    )
    if unsupported or transform:
        raise ValueError(
            f"{unsupported or ['transform']} apply only to explicit prediction grids; "
            "automatic effects choose rows and draws themselves (use ndraws)"
        )
    dpar = options.get("dpar")
    if parameter != "mu":
        if dpar is not None and dpar != parameter:
            raise ValueError("give the parameter once, as parameter or dpar")
        dpar = parameter
    return brms_conditional_effects(
        fit,
        effects,
        conditions=options.get("conditions"),
        int_conditions=options.get("int_conditions"),
        re_formula=options.get("re_formula", "~0"),
        prob=options.get("prob", 0.95),
        robust=options.get("robust", True),
        method=_METHODS[method],
        spaghetti=options.get("spaghetti", False),
        surface=options.get("surface", False),
        categorical=options.get("categorical", False),
        ordinal=options.get("ordinal", False),
        resolution=options.get("resolution", 100),
        select_points=options.get("select_points", 0.0),
        too_far=options.get("too_far", 0.0),
        resp=resp,
        dpar=dpar,
        nlpar=options.get("nlpar"),
        ndraws=options.get("ndraws"),
        draw_ids=options.get("draw_ids"),
        seed=options.get("seed", 0),
        mc_samples=options.get("mc_samples"),
    )

_pp_check

Posterior and prior predictive checks of fits, as brms pp_check.

brms pp_check draws replicated data, selects observed responses and covariates, and hands them to a bayesplot ppc_* or ppd_* function. pp_check here performs the same preparation through the fit's own prediction methods and returns the data behind the requested plot (the ppc_* functions of quivers.diagnostics) as a PPCheck, which keeps the observed values, the replicated draws, and (for leave-one-out types) the PSIS log weights. Where ArviZ implements a counterpart plot, PPCheck.plot draws it from PPCheck.to_datatree with the backend the caller names.

Prefix

Prefix = Literal['ppc', 'ppd']

Posterior predictive check (ppc) or predictive distribution (ppd).

StatisticSpec

StatisticSpec = Statistic | tuple[Statistic, Statistic]

One statistic, or two for stat_2d.

PPCheck didactic-model

PPCheck(*, type: str, prefix: Prefix, data: DataFrame = field(opaque=True, extras=OPAQUE_BY_IDENTITY), y: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), yrep: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), draw_ids: tuple[int, ...] = (), group: tuple[str | int | float | bool, ...] | None = None, x: tuple[str | int | float | bool, ...] | None = None, status: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), log_weights: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), log_likelihood: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), pit: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The data behind one predictive check, as brms pp_check prepares it.

PARAMETER DESCRIPTION
type

bayesplot type without its prefix.

TYPE: str

prefix

Posterior predictive check or predictive distribution.

TYPE: ('ppc', 'ppd') DEFAULT: "ppc"

data

bayesplot's table for the type (see the ppc_* functions of quivers.diagnostics).

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

y

Observed responses (N,); None for ppd types.

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

yrep

Predictive draws (S, N) (expected values for error_binned).

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

draw_ids

Pooled 0-based draws used.

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

group

Group label per observation.

TYPE: tuple or None DEFAULT: None

x

Covariate per observation.

TYPE: tuple or None DEFAULT: None

status

Event indicator of censored responses (km_overlay).

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

log_weights

Normalized PSIS log weights (S, N) of leave-one-out types.

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

log_likelihood

Pointwise log-likelihoods (S, N) of leave-one-out types.

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

pit

PIT or LOO-PIT values per observation.

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

to_datatree

to_datatree() -> DataTree

Return an ArviZ data tree of the check.

RETURNS DESCRIPTION
DataTree

posterior_predictive (one chain), observed_data for ppc types, log_likelihood for leave-one-out types, and constant_data with the event indicator of censored responses.

Source code in src/quivers/formulas/_pp_check.py
def to_datatree(self) -> xr.DataTree:
    """Return an ArviZ data tree of the check.

    Returns
    -------
    xarray.DataTree
        ``posterior_predictive`` (one chain), ``observed_data`` for
        ``ppc`` types, ``log_likelihood`` for leave-one-out types, and
        ``constant_data`` with the event indicator of censored responses.
    """
    draws = self.yrep.double().numpy()[None]
    groups: dict[str, xr.Dataset] = {
        "posterior_predictive": xr.Dataset(
            {"y": (("chain", "draw", "obs"), draws)},
            coords={"chain": [0], "draw": np.arange(draws.shape[1])},
        )
    }
    if self.y is not None:
        groups["observed_data"] = xr.Dataset(
            {"y": (("obs",), self.y.double().numpy())}
        )
    if self.log_likelihood is not None:
        groups["log_likelihood"] = xr.Dataset(
            {
                "y": (
                    ("chain", "draw", "obs"),
                    self.log_likelihood.double().numpy()[None],
                )
            },
            coords={"chain": [0], "draw": np.arange(draws.shape[1])},
        )
    if self.status is not None:
        # ArviZ's censored check reads 1 for a censored observation.
        groups["constant_data"] = xr.Dataset(
            {"y": (("obs",), 1.0 - self.status.double().numpy())}
        )
    return xr.DataTree.from_dict(groups)

plot

plot(*, backend: str, **kwargs: str | int | float | bool) -> PlotCollection

Draw the check with its ArviZ counterpart.

PARAMETER DESCRIPTION
backend

ArviZ plotting backend ("matplotlib", "bokeh", "plotly", or "none" to build the plot without drawing).

TYPE: str

**kwargs

Further keyword arguments of the ArviZ function.

TYPE: str or int or float or bool DEFAULT: {}

RETURNS DESCRIPTION
PlotCollection

The plot.

RAISES DESCRIPTION
ValueError

If ArviZ has no counterpart of the type; its data remain in data.

Source code in src/quivers/formulas/_pp_check.py
def plot(
    self, *, backend: str, **kwargs: str | int | float | bool
) -> azp.PlotCollection:
    """Draw the check with its ArviZ counterpart.

    Parameters
    ----------
    backend : str
        ArviZ plotting backend (``"matplotlib"``, ``"bokeh"``,
        ``"plotly"``, or ``"none"`` to build the plot without drawing).
    **kwargs : str or int or float or bool
        Further keyword arguments of the ArviZ function.

    Returns
    -------
    arviz_plots.PlotCollection
        The plot.

    Raises
    ------
    ValueError
        If ArviZ has no counterpart of the type; its data remain in `data`.
    """
    if self.type not in ARVIZ_PLOTS or (
        self.prefix == "ppd"
        and self.type not in {"dens", "dens_overlay", "hist", "ecdf_overlay"}
    ):
        raise ValueError(
            f"ArviZ has no counterpart of {self.prefix}_{self.type}; plot the "
            "table in PPCheck.data"
        )
    name, defaults = ARVIZ_PLOTS[self.type]
    options: dict[str, str | int | float | bool] = {**defaults, **kwargs}
    if self.prefix == "ppd":
        # The predictive distribution alone: ArviZ's marginal plot.
        name = "plot_dist"
        options.setdefault("group", "posterior_predictive")
    function = getattr(azp, name)
    return function(self.to_datatree(), backend=backend, **options)

pp_check

pp_check(fit: Fit, type: str = 'dens_overlay', *, ndraws: int | None = None, prefix: Prefix = 'ppc', group: str | None = None, x: str | None = None, newdata: IntoDataFrame | None = None, resp: str | None = None, draw_ids: Sequence[int] | None = None, stat: StatisticSpec | None = None, prob: float = 0.5, prob_outer: float = 0.9, bins: int | None = None, freq: bool = True, style: Literal['standing', 'hanging', 'suspended'] = 'standing', seed: int = 0) -> PPCheck

Prepare a posterior or prior predictive check, as brms pp_check.

PARAMETER DESCRIPTION
fit

Fitted model; a prior view (prior_view) checks the prior predictive distribution.

TYPE: BayesianFit or MultivariateFit

type

bayesplot type without prefix (PPC_TYPES, or PPD_TYPES for prefix="ppd").

TYPE: str DEFAULT: 'dens_overlay'

ndraws

Random draws; every draw for summary types and ten otherwise.

TYPE: int or None DEFAULT: None

prefix

Compare with observed data, or show the predictive distribution only.

TYPE: ('ppc', 'ppd') DEFAULT: "ppc"

group

Grouping variable; required by *_grouped types.

TYPE: str or None DEFAULT: None

x

Covariate of intervals, ribbon and error_scatter_avg_vs_x.

TYPE: str or None DEFAULT: None

newdata

Rows to predict, holding the response for ppc types.

TYPE: IntoDataFrame or None DEFAULT: None

resp

Response of a joint fit; required when it has several.

TYPE: str or None DEFAULT: None

draw_ids

Explicit 0-based draws.

TYPE: Sequence[int] or None DEFAULT: None

stat

Test statistic; "mean" (("mean", "sd") for stat_2d) by default.

TYPE: str or Callable or tuple or None DEFAULT: None

prob

Interval probabilities of interval types; prob_outer is the interval of bars and rootogram.

TYPE: float DEFAULT: 0.5

prob_outer

Interval probabilities of interval types; prob_outer is the interval of bars and rootogram.

TYPE: float DEFAULT: 0.5

bins

Bins of error_binned.

TYPE: int or None DEFAULT: None

freq

Counts instead of proportions for bars.

TYPE: bool DEFAULT: True

style

Rootogram style.

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

seed

Seed of the draw selection and predictions.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PPCheck

The table behind the plot with the inputs it was computed from.

RAISES DESCRIPTION
ValueError

If the type is unknown for the prefix, a required group or x is missing or not a data variable, a joint response is ambiguous, or no uncensored response remains.

Notes

Cost is one prediction at S draws over N rows, plus one log-likelihood evaluation and PSIS smoothing, O(S N log S), for leave-one-out types.

Source code in src/quivers/formulas/_pp_check.py
def pp_check(
    fit: Fit,
    type: str = "dens_overlay",
    *,
    ndraws: int | None = None,
    prefix: Prefix = "ppc",
    group: str | None = None,
    x: str | None = None,
    newdata: IntoDataFrame | None = None,
    resp: str | None = None,
    draw_ids: Sequence[int] | None = None,
    stat: StatisticSpec | None = None,
    prob: float = 0.5,
    prob_outer: float = 0.9,
    bins: int | None = None,
    freq: bool = True,
    style: Literal["standing", "hanging", "suspended"] = "standing",
    seed: int = 0,
) -> PPCheck:
    """Prepare a posterior or prior predictive check, as brms ``pp_check``.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model; a prior view (``prior_view``) checks the prior
        predictive distribution.
    type : str
        bayesplot type without prefix (`PPC_TYPES`, or `PPD_TYPES` for
        ``prefix="ppd"``).
    ndraws : int or None
        Random draws; every draw for summary types and ten otherwise.
    prefix : {"ppc", "ppd"}
        Compare with observed data, or show the predictive distribution only.
    group : str or None
        Grouping variable; required by ``*_grouped`` types.
    x : str or None
        Covariate of ``intervals``, ``ribbon`` and ``error_scatter_avg_vs_x``.
    newdata : IntoDataFrame or None
        Rows to predict, holding the response for ``ppc`` types.
    resp : str or None
        Response of a joint fit; required when it has several.
    draw_ids : Sequence[int] or None
        Explicit 0-based draws.
    stat : str or Callable or tuple or None
        Test statistic; ``"mean"`` (``("mean", "sd")`` for ``stat_2d``) by
        default.
    prob, prob_outer : float
        Interval probabilities of interval types; ``prob_outer`` is the
        interval of ``bars`` and ``rootogram``.
    bins : int or None
        Bins of ``error_binned``.
    freq : bool
        Counts instead of proportions for ``bars``.
    style : {"standing", "hanging", "suspended"}
        Rootogram style.
    seed : int
        Seed of the draw selection and predictions.

    Returns
    -------
    PPCheck
        The table behind the plot with the inputs it was computed from.

    Raises
    ------
    ValueError
        If the type is unknown for the prefix, a required ``group`` or ``x``
        is missing or not a data variable, a joint response is ambiguous, or
        no uncensored response remains.

    Notes
    -----
    Cost is one prediction at ``S`` draws over ``N`` rows, plus one
    log-likelihood evaluation and PSIS smoothing, O(S N log S), for
    leave-one-out types.
    """
    if prefix not in ("ppc", "ppd"):
        raise ValueError("prefix must be 'ppc' or 'ppd'")
    valid = set(PPC_TYPES) if prefix == "ppc" else set(PPD_TYPES)
    if type not in valid:
        raise ValueError(
            f"type {type!r} is not a valid {prefix} type; valid types are "
            f"{', '.join(sorted(valid))}"
        )
    if _joint(fit):
        joint = cast("MultivariateFit", fit)
        if resp is None:
            if len(joint.response_names) != 1:
                raise ValueError(
                    "pp_check of a joint fit with several responses requires resp"
                )
            resp = joint.response_names[0]
        elif resp not in joint.response_names:
            raise ValueError(f"unknown response {resp!r}")
        formula = joint.emission.responses[resp].formula
        family = joint.prepared[resp].family
    else:
        if resp is not None:
            raise ValueError("resp applies only to joint fits")
        single = cast("BayesianFit", fit)
        formula, family = single.formula, single.family
    if family.vector_response:
        raise ValueError(
            "pp_check is not implemented for multicolumn response families"
        )
    rows = (
        model_frame(fit)
        if newdata is None
        else nw.from_native(newdata, eager_only=True).to_pandas()
    )
    grouped = type.endswith("_grouped")
    if grouped and group is None:
        raise ValueError(f"argument group is required for ppc type {type!r}")
    for name, value in (("group", group), ("x", x)):
        if value is not None and value not in rows.columns:
            raise ValueError(
                f"{name} variable {value!r} could not be found in the data"
            )
    if type == "error_scatter_avg_vs_x" and x is None:
        raise ValueError("error_scatter_avg_vs_x requires x")
    kind = PPC_TYPES[type]
    method: PredictionMethod = (
        "posterior_epred" if type == "error_binned" else "posterior_predict"
    )
    if type == "error_binned" and (
        family.ordinal is not None or response_category_labels(formula, family)
    ):
        raise ValueError("error_binned is not available for polytomous models")
    ids = _select_draws(fit, type, ndraws, draw_ids, seed)
    yrep = _predict(fit, resp, method, newdata, ids, seed)
    y = _observed(formula, family, newdata) if prefix == "ppc" else None
    n = yrep.shape[1]
    group_values = (
        None if group is None else np.asarray(rows[group].tolist(), dtype=object)
    )
    x_values = None if x is None else np.asarray(rows[x].tolist(), dtype=object)
    if group_values is not None and group_values.shape[0] != n:
        raise ValueError("group values do not align with the predicted rows")
    keep = np.ones(n, dtype=bool)
    if y is not None:
        keep &= ~torch.isnan(y).numpy()
    status_values = None
    codes = _status(formula, newdata)
    if codes is not None:
        if kind == "km":
            keep &= np.isin(codes, (0.0, 1.0))
            status_values = 1.0 - codes
        else:
            keep &= codes == 0.0
    elif kind == "km":
        status_values = np.ones(n)
    if not keep.any():
        raise ValueError("no valid responses found to include")
    yrep_np = yrep.numpy()[:, keep]
    y_np = None if y is None else y.numpy()[keep]
    g = None if group_values is None else group_values[keep]
    xv = None if x_values is None else x_values[keep]
    status_kept = None if status_values is None else status_values[keep]
    log_weights = log_lik = pit = None
    if kind in {"loo_pit", "loo_intervals"}:
        log_lik_full = _log_likelihood(fit, resp, ids, seed)
        log_lik = log_lik_full[:, keep]
        weights = psis_weights(torch.from_numpy(log_lik).unsqueeze(0), r_eff=1.0)
        log_weights = weights.log_weights.reshape(log_lik.shape).double().numpy()
    if kind == "long":
        frame = data_functions.ppc_data(y_np, yrep_np, group=g)
    elif kind == "stat":
        default: StatisticSpec = ("mean", "sd") if type == "stat_2d" else "mean"
        chosen = stat if stat is not None else default
        if type == "stat_2d" and not isinstance(chosen, tuple):
            raise ValueError("stat_2d requires two statistics")
        frame = data_functions.ppc_stat_data(y_np, yrep_np, stat=chosen, group=g)
    elif kind == "intervals":
        frame = data_functions.ppc_intervals_data(
            y_np,
            yrep_np,
            x=None if xv is None else xv.astype(np.float64),
            group=g,
            prob=prob,
            prob_outer=prob_outer,
        )
    else:
        assert y_np is not None
        if kind == "bars":
            frame = data_functions.ppc_bars_data(
                y_np, yrep_np, group=g, prob=prob_outer, freq=freq
            )
        elif kind == "error":
            frame = data_functions.ppc_error_data(y_np, yrep_np, group=g)
        elif kind == "error_avg":
            frame = data_functions.ppc_scatter_avg_data(
                y_np, y_np[None, :] - yrep_np, group=g
            )
        elif kind == "error_avg_x":
            assert xv is not None
            frame = data_functions.ppc_scatter_avg_data(
                xv.astype(np.float64), y_np[None, :] - yrep_np
            )
        elif kind == "error_binned":
            frame = data_functions.ppc_error_binned_data(y_np, yrep_np, bins=bins)
        elif kind == "scatter":
            frame = data_functions.ppc_scatter_data(y_np, yrep_np)
        elif kind == "scatter_avg":
            frame = data_functions.ppc_scatter_avg_data(y_np, yrep_np, group=g)
        elif kind == "rootogram":
            frame = data_functions.ppc_rootogram_data(
                y_np, yrep_np, style=style, prob=prob_outer
            )
        elif kind == "km":
            assert status_kept is not None
            frame = data_functions.km_data(y_np, yrep_np, status=status_kept)
        elif kind == "pit_ecdf":
            pit = data_functions.pit_values(y_np, yrep_np)
            frame = data_functions.pit_ecdf_data(y_np, yrep_np)
        elif kind == "loo_pit":
            assert log_weights is not None
            pit = data_functions.loo_pit_values(y_np, yrep_np, log_weights)
            frame = _loo_pit_frame(pit, qq=type == "loo_pit_qq")
        else:
            assert log_weights is not None and log_lik is not None
            frame = _loo_interval_frame(y_np, yrep_np, log_lik, prob, prob_outer)
    return PPCheck(
        type=type,
        prefix=prefix,
        data=frame,
        y=None if y_np is None else torch.from_numpy(y_np),
        yrep=torch.from_numpy(np.ascontiguousarray(yrep_np)),
        draw_ids=tuple(ids),
        group=None if g is None else tuple(g.tolist()),
        x=None if xv is None else tuple(xv.tolist()),
        status=None if status_kept is None else torch.from_numpy(status_kept),
        log_weights=None if log_weights is None else torch.from_numpy(log_weights),
        log_likelihood=None if log_lik is None else torch.from_numpy(log_lik),
        pit=None
        if pit is None
        else torch.from_numpy(np.asarray(pit, dtype=np.float64)),
    )

_mcmc_plot

brms mcmc_plot, plot and pairs through ArviZ.

brms draws MCMC diagnostics with bayesplot's mcmc_* functions on its brms-named draws. Here each bayesplot type maps onto the ArviZ plot that shows the same quantity, drawn from a data tree of the fit's brms-named draws (variables) and sampler statistics. Types without an ArviZ counterpart are refused with the reason.

PlotResult

PlotResult = PlotCollection | PlotMatrix

An ArviZ plot.

mcmc_datatree

mcmc_datatree(fit: Fit, variable: str | Sequence[str] | None = None, *, regex: bool = False) -> DataTree

Return an ArviZ data tree of brms-named draws and sampler statistics.

PARAMETER DESCRIPTION
fit

Fitted model.

TYPE: BayesianFit or MultivariateFit

variable

brms variable names, or regular expressions matched against them; None for every variable.

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

regex

brms regex: with True each entry of variable is a regular expression searched for anywhere in a name, as R's grepl does (variable="^b_", regex=True). With False an entry selects the name it equals or matches in full.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DataTree

posterior with one scalar variable per brms name (brackets replaced by dots) and sample_stats with energy and diverging of NUTS chains.

RAISES DESCRIPTION
ValueError

If no variable matches.

Source code in src/quivers/formulas/_mcmc_plot.py
def mcmc_datatree(
    fit: Fit, variable: str | Sequence[str] | None = None, *, regex: bool = False
) -> xr.DataTree:
    """Return an ArviZ data tree of brms-named draws and sampler statistics.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model.
    variable : str or Sequence[str] or None
        brms variable names, or regular expressions matched against them;
        None for every variable.
    regex : bool
        brms ``regex``: with True each entry of ``variable`` is a regular
        expression searched for anywhere in a name, as R's ``grepl`` does
        (``variable="^b_", regex=True``). With False an entry selects the
        name it equals or matches in full.

    Returns
    -------
    xarray.DataTree
        ``posterior`` with one scalar variable per brms name (brackets
        replaced by dots) and ``sample_stats`` with ``energy`` and
        ``diverging`` of NUTS chains.

    Raises
    ------
    ValueError
        If no variable matches.
    """
    named = fit.variables()
    if variable is None:
        chosen = list(named)
    else:
        patterns = [variable] if isinstance(variable, str) else list(variable)
        chosen = [
            n
            for n in named
            if any(
                re.search(p, n) is not None
                if regex
                else n == p or re.fullmatch(p, n) is not None
                for p in patterns
            )
        ]
    if not chosen:
        raise ValueError(f"no variable matches {variable!r}")
    posterior = xr.Dataset(
        {
            _safe(n): (
                ("chain", "draw"),
                named[n].double().numpy().reshape(named[n].shape[:2]),
            )
            for n in chosen
            if named[n].ndim == 2
        },
        coords={
            "chain": np.arange(named[chosen[0]].shape[0]),
            "draw": np.arange(named[chosen[0]].shape[1]),
        },
    )
    groups = {"posterior": posterior}
    result = fit.posterior
    if isinstance(result, MCMCResult):
        stats = {
            _ARVIZ_SAMPLE_STATS[key]: (("chain", "draw"), value.double().numpy())
            for key, value in result.sample_stats.items()
            if key in _ARVIZ_SAMPLE_STATS and value.ndim == 2
        }
        if stats:
            groups["sample_stats"] = xr.Dataset(stats, coords=posterior.coords)
    return xr.DataTree.from_dict(groups)

mcmc_plot

mcmc_plot(fit: Fit, type: str = 'intervals', *, variable: str | Sequence[str] | None = None, regex: bool = False, backend: str, **kwargs: str | int | float | bool) -> PlotResult

Draw an MCMC diagnostic plot, as brms mcmc_plot.

PARAMETER DESCRIPTION
fit

Fitted model.

TYPE: BayesianFit or MultivariateFit

type

bayesplot mcmc_* type without prefix (MCMC_PLOTS).

TYPE: str DEFAULT: 'intervals'

variable

brms variable names or regular expressions; None for all.

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

regex

brms regex: search each expression anywhere in a name.

TYPE: bool DEFAULT: False

backend

ArviZ plotting backend ("matplotlib", "bokeh", "plotly", or "none" to build without drawing).

TYPE: str

**kwargs

Further ArviZ keyword arguments.

TYPE: str or int or float or bool DEFAULT: {}

RETURNS DESCRIPTION
PlotCollection or PlotMatrix

The plot.

RAISES DESCRIPTION
ValueError

If the type is unknown or has no ArviZ counterpart.

Source code in src/quivers/formulas/_mcmc_plot.py
def mcmc_plot(
    fit: Fit,
    type: str = "intervals",
    *,
    variable: str | Sequence[str] | None = None,
    regex: bool = False,
    backend: str,
    **kwargs: str | int | float | bool,
) -> PlotResult:
    """Draw an MCMC diagnostic plot, as brms ``mcmc_plot``.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted model.
    type : str
        bayesplot ``mcmc_*`` type without prefix (`MCMC_PLOTS`).
    variable : str or Sequence[str] or None
        brms variable names or regular expressions; None for all.
    regex : bool
        brms ``regex``: search each expression anywhere in a name.
    backend : str
        ArviZ plotting backend (``"matplotlib"``, ``"bokeh"``, ``"plotly"``,
        or ``"none"`` to build without drawing).
    **kwargs : str or int or float or bool
        Further ArviZ keyword arguments.

    Returns
    -------
    arviz_plots.PlotCollection or arviz_plots.PlotMatrix
        The plot.

    Raises
    ------
    ValueError
        If the type is unknown or has no ArviZ counterpart.
    """
    if type in NOT_PROVIDED:
        raise ValueError(
            f"mcmc_plot type {type!r} is not provided: {NOT_PROVIDED[type]}"
        )
    if type not in MCMC_PLOTS:
        raise ValueError(
            f"unknown mcmc_plot type {type!r}; types are {', '.join(sorted(MCMC_PLOTS))}"
        )
    name, defaults = MCMC_PLOTS[type]
    options: dict[str, str | int | float | bool] = {**defaults, **kwargs}
    function = getattr(azp, name)
    tree = mcmc_datatree(fit, variable, regex=regex)
    return function(tree, backend=backend, **options)

EvidenceEffectsMethods

Bases: EvidenceMethods

brms evidence, effects and predictive-check methods of formula fits.

prior_draws

prior_draws(*, num_samples: int = 100, seed: int = 0, method: Literal['ancestral'] | MCMC = 'ancestral') -> PriorDraws | MCMCResult

Draw conditional priors using the fitted model's retained designs.

PARAMETER DESCRIPTION
num_samples

Positive number of independent ancestral draws.

TYPE: int DEFAULT: 100

seed

Isolated CPU seed.

TYPE: int DEFAULT: 0

method

Independent conditional sampling, or a configured driver for global score potentials. The driver controls its own budgets.

TYPE: 'ancestral' DEFAULT: "ancestral"

RETURNS DESCRIPTION
PriorDraws or MCMCResult

Constrained prior draws with independent or chain provenance.

RAISES DESCRIPTION
ValueError

If a fitted site has an improper prior.

Source code in src/quivers/formulas/_evidence_effects.py
def prior_draws(
    self,
    *,
    num_samples: int = 100,
    seed: int = 0,
    method: Literal["ancestral"] | MCMC = "ancestral",
) -> PriorDraws | MCMCResult:
    """Draw conditional priors using the fitted model's retained designs.

    Parameters
    ----------
    num_samples : int
        Positive number of independent ancestral draws.
    seed : int
        Isolated CPU seed.
    method : {"ancestral"} or MCMC
        Independent conditional sampling, or a configured driver for
        global score potentials. The driver controls its own budgets.

    Returns
    -------
    PriorDraws or MCMCResult
        Constrained prior draws with independent or chain provenance.

    Raises
    ------
    ValueError
        If a fitted site has an improper prior.
    """
    fit = cast("BayesianFit | MultivariateFit", self)
    self._require_proper("prior_draws")
    return prior_draws(
        fit.program,
        torch.zeros(1, 1),
        fit.observations,
        num_samples=num_samples,
        seed=seed,
        method=method,
    )

conditional_smooths

conditional_smooths(smooths: str | Sequence[str] | None = None, *, resp: str | Sequence[str] | None = None, int_conditions: Mapping[str, IntCondition] | None = None, prob: float = 0.95, spaghetti: bool = False, surface: bool = True, resolution: int = 100, too_far: float = 0.0, ndraws: int | None = None, draw_ids: Sequence[int] | None = None, seed: int = 0) -> BrmsConditionalEffects

Compute every smooth's contribution on a grid, as brms conditional_smooths.

PARAMETER DESCRIPTION
smooths

Smooth term labels; None for every s() and t2() term.

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

resp

Responses of a joint fit, as brms's resp; None for all. Must be None for a single-response fit.

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

int_conditions

Values of covariates or by variables.

TYPE: Mapping or None DEFAULT: None

prob

Interval probability.

TYPE: float DEFAULT: 0.95

spaghetti

Also return per-draw curves.

TYPE: bool DEFAULT: False

surface

Grid a numeric second covariate over its range.

TYPE: bool DEFAULT: True

resolution

Grid size per numeric covariate.

TYPE: int DEFAULT: 100

too_far

Drop surface points farther than this from the data.

TYPE: float DEFAULT: 0.0

ndraws

Random subset of draws.

TYPE: int or None DEFAULT: None

draw_ids

Explicit 0-based draws.

TYPE: Sequence[int] or None DEFAULT: None

seed

Seed of draw selection.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
BrmsConditionalEffects

One frame per smooth term.

RAISES DESCRIPTION
ValueError

If the fit has no matching smooth term, or resp is given for a single-response fit.

Source code in src/quivers/formulas/_evidence_effects.py
def conditional_smooths(
    self,
    smooths: str | Sequence[str] | None = None,
    *,
    resp: str | Sequence[str] | None = None,
    int_conditions: Mapping[str, IntCondition] | None = None,
    prob: float = 0.95,
    spaghetti: bool = False,
    surface: bool = True,
    resolution: int = 100,
    too_far: float = 0.0,
    ndraws: int | None = None,
    draw_ids: Sequence[int] | None = None,
    seed: int = 0,
) -> BrmsConditionalEffects:
    """Compute every smooth's contribution on a grid, as brms ``conditional_smooths``.

    Parameters
    ----------
    smooths : str or Sequence[str] or None
        Smooth term labels; None for every ``s()`` and ``t2()`` term.
    resp : str or Sequence[str] or None
        Responses of a joint fit, as brms's ``resp``; None for all. Must
        be None for a single-response fit.
    int_conditions : Mapping or None
        Values of covariates or ``by`` variables.
    prob : float
        Interval probability.
    spaghetti : bool
        Also return per-draw curves.
    surface : bool
        Grid a numeric second covariate over its range.
    resolution : int
        Grid size per numeric covariate.
    too_far : float
        Drop surface points farther than this from the data.
    ndraws : int or None
        Random subset of draws.
    draw_ids : Sequence[int] or None
        Explicit 0-based draws.
    seed : int
        Seed of draw selection.

    Returns
    -------
    BrmsConditionalEffects
        One frame per smooth term.

    Raises
    ------
    ValueError
        If the fit has no matching smooth term, or ``resp`` is given for
        a single-response fit.
    """
    return brms_conditional_smooths(
        cast("BayesianFit | MultivariateFit", self),
        smooths,
        resp=resp,
        int_conditions=int_conditions,
        prob=prob,
        spaghetti=spaghetti,
        surface=surface,
        resolution=resolution,
        too_far=too_far,
        ndraws=ndraws,
        draw_ids=draw_ids,
        seed=seed,
    )

pp_check

pp_check(type: str = 'dens_overlay', *, ndraws: int | None = None, prefix: Prefix = 'ppc', group: str | None = None, x: str | None = None, newdata: IntoDataFrame | None = None, resp: str | None = None, draw_ids: Sequence[int] | None = None, stat: StatisticSpec | None = None, prob: float = 0.5, prob_outer: float = 0.9, bins: int | None = None, freq: bool = True, style: Literal['standing', 'hanging', 'suspended'] = 'standing', seed: int = 0) -> PPCheck

Prepare a predictive check, as brms pp_check.

PARAMETER DESCRIPTION
type

bayesplot type without prefix.

TYPE: str DEFAULT: 'dens_overlay'

ndraws

Random draws; brms's default by type.

TYPE: int or None DEFAULT: None

prefix

Compare with observed data, or show the predictive distribution.

TYPE: ('ppc', 'ppd') DEFAULT: "ppc"

group

Grouping variable and covariate.

TYPE: str or None DEFAULT: None

x

Grouping variable and covariate.

TYPE: str or None DEFAULT: None

newdata

Prediction rows.

TYPE: IntoDataFrame or None DEFAULT: None

resp

Joint response.

TYPE: str or None DEFAULT: None

draw_ids

Explicit 0-based draws.

TYPE: Sequence[int] or None DEFAULT: None

stat

Test statistic(s).

TYPE: str or Callable or tuple or None DEFAULT: None

prob

Interval probabilities.

TYPE: float DEFAULT: 0.5

prob_outer

Interval probabilities.

TYPE: float DEFAULT: 0.5

bins

Bins of error_binned.

TYPE: int or None DEFAULT: None

freq

Counts instead of proportions for bars.

TYPE: bool DEFAULT: True

style

Rootogram style.

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

seed

Seed of draw selection and predictions.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PPCheck

The data behind the plot.

RAISES DESCRIPTION
ValueError

If the type or its required arguments are invalid.

Source code in src/quivers/formulas/_evidence_effects.py
def pp_check(
    self,
    type: str = "dens_overlay",
    *,
    ndraws: int | None = None,
    prefix: Prefix = "ppc",
    group: str | None = None,
    x: str | None = None,
    newdata: IntoDataFrame | None = None,
    resp: str | None = None,
    draw_ids: Sequence[int] | None = None,
    stat: StatisticSpec | None = None,
    prob: float = 0.5,
    prob_outer: float = 0.9,
    bins: int | None = None,
    freq: bool = True,
    style: Literal["standing", "hanging", "suspended"] = "standing",
    seed: int = 0,
) -> PPCheck:
    """Prepare a predictive check, as brms ``pp_check``.

    Parameters
    ----------
    type : str
        bayesplot type without prefix.
    ndraws : int or None
        Random draws; brms's default by type.
    prefix : {"ppc", "ppd"}
        Compare with observed data, or show the predictive distribution.
    group, x : str or None
        Grouping variable and covariate.
    newdata : IntoDataFrame or None
        Prediction rows.
    resp : str or None
        Joint response.
    draw_ids : Sequence[int] or None
        Explicit 0-based draws.
    stat : str or Callable or tuple or None
        Test statistic(s).
    prob, prob_outer : float
        Interval probabilities.
    bins : int or None
        Bins of ``error_binned``.
    freq : bool
        Counts instead of proportions for ``bars``.
    style : {"standing", "hanging", "suspended"}
        Rootogram style.
    seed : int
        Seed of draw selection and predictions.

    Returns
    -------
    PPCheck
        The data behind the plot.

    Raises
    ------
    ValueError
        If the type or its required arguments are invalid.
    """
    return pp_check(
        cast("BayesianFit | MultivariateFit", self),
        type,
        ndraws=ndraws,
        prefix=prefix,
        group=group,
        x=x,
        newdata=newdata,
        resp=resp,
        draw_ids=draw_ids,
        stat=stat,
        prob=prob,
        prob_outer=prob_outer,
        bins=bins,
        freq=freq,
        style=style,
        seed=seed,
    )

mcmc_plot

mcmc_plot(type: str = 'intervals', *, variable: str | Sequence[str] | None = None, regex: bool = False, backend: str, **kwargs: str | int | float | bool) -> PlotResult

Draw an MCMC diagnostic with ArviZ, as brms mcmc_plot.

PARAMETER DESCRIPTION
type

bayesplot mcmc_* type without prefix.

TYPE: str DEFAULT: 'intervals'

variable

brms variable names or regular expressions.

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

regex

brms regex: search each expression anywhere in a name, so variable="^b_", regex=True selects the population effects.

TYPE: bool DEFAULT: False

backend

ArviZ backend.

TYPE: str

**kwargs

ArviZ keyword arguments.

TYPE: str or int or float or bool DEFAULT: {}

RETURNS DESCRIPTION
PlotCollection or PlotMatrix

The plot.

RAISES DESCRIPTION
ValueError

If the type is unknown or has no ArviZ counterpart.

Source code in src/quivers/formulas/_evidence_effects.py
def mcmc_plot(
    self,
    type: str = "intervals",
    *,
    variable: str | Sequence[str] | None = None,
    regex: bool = False,
    backend: str,
    **kwargs: str | int | float | bool,
) -> PlotResult:
    """Draw an MCMC diagnostic with ArviZ, as brms ``mcmc_plot``.

    Parameters
    ----------
    type : str
        bayesplot ``mcmc_*`` type without prefix.
    variable : str or Sequence[str] or None
        brms variable names or regular expressions.
    regex : bool
        brms ``regex``: search each expression anywhere in a name, so
        ``variable="^b_", regex=True`` selects the population effects.
    backend : str
        ArviZ backend.
    **kwargs : str or int or float or bool
        ArviZ keyword arguments.

    Returns
    -------
    arviz_plots.PlotCollection or arviz_plots.PlotMatrix
        The plot.

    Raises
    ------
    ValueError
        If the type is unknown or has no ArviZ counterpart.
    """
    return mcmc_plot(
        cast("BayesianFit | MultivariateFit", self),
        type,
        variable=variable,
        regex=regex,
        backend=backend,
        **kwargs,
    )

plot

plot(*, variable: str | Sequence[str] | None = None, regex: bool = False, backend: str, **kwargs: str | int | float | bool) -> PlotResult

Draw marginal densities and trace plots, as brms plot.

PARAMETER DESCRIPTION
variable

brms variable names or regular expressions.

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

regex

brms regex: search each expression anywhere in a name, so variable="^b_", regex=True selects the population effects.

TYPE: bool DEFAULT: False

backend

ArviZ backend.

TYPE: str

**kwargs

ArviZ keyword arguments.

TYPE: str or int or float or bool DEFAULT: {}

RETURNS DESCRIPTION
PlotCollection

ArviZ plot_trace_dist.

Source code in src/quivers/formulas/_evidence_effects.py
def plot(
    self,
    *,
    variable: str | Sequence[str] | None = None,
    regex: bool = False,
    backend: str,
    **kwargs: str | int | float | bool,
) -> PlotResult:
    """Draw marginal densities and trace plots, as brms ``plot``.

    Parameters
    ----------
    variable : str or Sequence[str] or None
        brms variable names or regular expressions.
    regex : bool
        brms ``regex``: search each expression anywhere in a name, so
        ``variable="^b_", regex=True`` selects the population effects.
    backend : str
        ArviZ backend.
    **kwargs : str or int or float or bool
        ArviZ keyword arguments.

    Returns
    -------
    arviz_plots.PlotCollection
        ArviZ ``plot_trace_dist``.
    """
    return self.mcmc_plot(
        "combo", variable=variable, regex=regex, backend=backend, **kwargs
    )

pairs

pairs(*, variable: str | Sequence[str] | None = None, regex: bool = False, backend: str, **kwargs: str | int | float | bool) -> PlotResult

Draw pairwise scatter plots of draws, as brms pairs.

PARAMETER DESCRIPTION
variable

brms variable names or regular expressions.

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

regex

brms regex: search each expression anywhere in a name, so variable="^b_", regex=True selects the population effects.

TYPE: bool DEFAULT: False

backend

ArviZ backend.

TYPE: str

**kwargs

ArviZ keyword arguments.

TYPE: str or int or float or bool DEFAULT: {}

RETURNS DESCRIPTION
PlotMatrix

ArviZ plot_pair.

Source code in src/quivers/formulas/_evidence_effects.py
def pairs(
    self,
    *,
    variable: str | Sequence[str] | None = None,
    regex: bool = False,
    backend: str,
    **kwargs: str | int | float | bool,
) -> PlotResult:
    """Draw pairwise scatter plots of draws, as brms ``pairs``.

    Parameters
    ----------
    variable : str or Sequence[str] or None
        brms variable names or regular expressions.
    regex : bool
        brms ``regex``: search each expression anywhere in a name, so
        ``variable="^b_", regex=True`` selects the population effects.
    backend : str
        ArviZ backend.
    **kwargs : str or int or float or bool
        ArviZ keyword arguments.

    Returns
    -------
    arviz_plots.PlotMatrix
        ArviZ ``plot_pair``.
    """
    return self.mcmc_plot(
        "pairs", variable=variable, regex=regex, backend=backend, **kwargs
    )

_fit

User-facing fit entry point and the BayesianFit result wrapper.

The compilation path is fully AST-driven: the formula lens emits a quivers.dsl.ast_nodes.Module, the existing quivers.dsl.compiler.Compiler consumes it directly (no source-string round-trip), and inference runs on the resulting quivers.continuous.programs.MonadicProgram. Source text is generated only when the user requests it via formula_to_qvr or BayesianFit.dump_qvr, in which case quivers.dsl.emit.module_to_source walks the same AST to produce canonical .qvr source.

BayesianFit didactic-model

BayesianFit(*, program: MonadicProgram = field(opaque=True, extras=OPAQUE_BY_IDENTITY), posterior: MCMCResult | PriorDraws | Guide = field(opaque=True, extras=OPAQUE_BY_IDENTITY), observations: Mapping[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), sample_prior: PriorMode = 'no', prior: PriorDraws | MCMCResult | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), losses: tuple[float, ...] = (), reparameterize: Literal['centered', 'noncentered'] = 'noncentered', fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: dict[str, GroupCovariance] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), priors: PriorSet = field(default_factory=PriorSet, opaque=True, extras=OPAQUE_BY_VALUE), criteria: Mapping[str, ELPDEstimate | Tensor] = field(default=NO_CRITERIA, opaque=True, extras=OPAQUE_BY_IDENTITY), formula: Formula = field(opaque=True, extras=OPAQUE_BY_VALUE), family: Family = field(opaque=True, extras=OPAQUE_BY_VALUE), residual: ResidualLaw | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor: Module | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), predictor_data: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), predictor_name: str | None = None, fixed_parameters: dict[str, float] = field(default_factory=dict), distributional: Mapping[str, Formula] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), predictor_graph: PredictorGraph | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), prediction_plan: FormulaPredictionPlan | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), refit_recipe: RefitRecipe[IntoDataFrame, Mapping[str, object], BayesianFit] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none')

Bases: SinglePostprocess, EvidenceEffectsMethods, FormulaFit

A fitted Bayesian regression: the compiled program, the parsed formula, the family, the user-supplied data, and the posterior samples.

PARAMETER DESCRIPTION
formula

Parsed formula IR.

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

family

Response family used at compile time.

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

residual

Residual law of the response: natural residuals correlated across rows by an autocorrelation term; None for independent rows.

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

program

The compiled program.

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

posterior

quivers.inference.MCMCResult from NUTS / HMC, or a quivers.inference.guides.base.Guide from SVI. A prior view instead retains independently generated PriorDraws.

TYPE: MCMCResult or PriorDraws or Guide DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

sample_prior

Ordinary fitting, additionally retained independent priors, or observation-free inference with explicit score potentials retained.

TYPE: ('no', 'yes', 'only') DEFAULT: "no"

prior

Independent prior samples, or explicitly factor-conditioned chains.

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

losses

Finite optimization losses for SVI; empty for recorded MCMC chains.

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

observations

Inference-time observations dict (response + per-column covariates + per-group plate indices).

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

group_covariances

Known labeled covariance between grouping levels, including any explicitly supplied future labels. Coefficient correlations remain separate.

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

fixed_parameters

Auxiliary parameters bound to constants rather than sampled or regressed.

TYPE: dict[str, float] DEFAULT: field(default_factory=dict)

distributional

Evaluated auxiliary-parameter design matrices, retained so source inspection emits the fitted model without re-evaluating transforms.

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

predictor_graph

Named nonlinear designs, typed expressions, and numeric input contracts.

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

refit_recipe

Retained original data and canonical fitting configuration, held by identity. Clone ownership is the default; explicit reference ownership observes mutations.

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

prediction_plan

Live fitted evaluators for new-data prediction. The versioned runtime plan is held by identity and explicitly refuses durable serialization.

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

criteria

Criteria stored by add_criterion: ELPD estimates, or R-squared draws.

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

default_priors

Default prior policy the model was compiled with.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

center

brms intercept centering option.

TYPE: bool or None DEFAULT: None

decomp

brms population-coefficient decomposition.

TYPE: ('none', 'QR') DEFAULT: "none"

Notes

Fits compare by value over the formula, family, and settings, and by identity over the live objects: the program, the posterior, the observations mapping, the predictor, its data, the prediction plan, and the refit recipe. Two fits are thus equal exactly when they share those objects and agree on everything else.

qvr_source property

qvr_source: str

Lazily emit the AST-equivalent .qvr source for display.

RETURNS DESCRIPTION
str

Canonical source emitted from the retained formula AST.

included_rows property

included_rows: tuple[int, ...]

Positions of the input data rows the model was fitted to.

Rows excluded by subset or by a missing value in any model variable are absent. Pointwise likelihoods and predictions on the training rows follow this order.

RETURNS DESCRIPTION
tuple[int, ...]

Zero-based positions in the data passed to fit.

category_labels property

category_labels: tuple[int | str, ...]

Response-category labels in posterior probability-array order.

RETURNS DESCRIPTION
tuple[int or str, ...]

Factor levels, the integer values 1..K of an ordinal response coded as brms codes it, or the codes 0..K-1; empty for other families. Predicted categories are positions in this tuple. Categorical coefficient arrays omit the first category.

threshold_labels property

threshold_labels: tuple[tuple[int | str, int | str], ...]

Adjacent category pairs identifying the ordinal transition axis.

RETURNS DESCRIPTION
tuple of pair of int

Adjacent category labels, excluding the structural-zero boundary in a hurdle cumulative model; empty for nonordinal families.

group_levels property

group_levels: dict[str, tuple[str, ...]]

Retained group labels in each coefficient array's level-axis order.

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

Group names and the ordered labels used in coefficient arrays.

coefficient_labels property

coefficient_labels: tuple[int | str, ...]

Label free component coefficients in their retained coordinate order.

RETURNS DESCRIPTION
tuple[int | str, ...]

Nonreference component labels, or all labels without a reference.

update

update(data: IntoDataFrame | None = None, **overrides: object) -> BayesianFit

Fit retained or replacement rows through the original fitting recipe.

PARAMETER DESCRIPTION
data

Original-frame snapshot by default, or replacement unprepared rows.

TYPE: IntoDataFrame or None DEFAULT: None

**overrides

Explicit overrides of the canonical fit arguments, including formula, family, priors, inference method, budgets, or random seed. Changing methods resets inactive budgets unless explicitly overridden.

TYPE: object DEFAULT: {}

RETURNS DESCRIPTION
BayesianFit

A fresh fitted result; the retained posterior and predictor are unchanged.

RAISES DESCRIPTION
(ValueError, TypeError)

If no recipe was retained or an override fails canonical fit validation.

Source code in src/quivers/formulas/_fit.py
def update(
    self, data: IntoDataFrame | None = None, **overrides: object
) -> BayesianFit:
    """Fit retained or replacement rows through the original fitting recipe.

    Parameters
    ----------
    data : IntoDataFrame or None
        Original-frame snapshot by default, or replacement unprepared rows.
    **overrides : object
        Explicit overrides of the canonical fit arguments, including formula,
        family, priors, inference method, budgets, or random seed. Changing
        methods resets inactive budgets unless explicitly overridden.

    Returns
    -------
    BayesianFit
        A fresh fitted result; the retained posterior and predictor are unchanged.

    Raises
    ------
    ValueError, TypeError
        If no recipe was retained or an override fails canonical fit validation.
    """
    from quivers.formulas._refit import update_fit

    return update_fit(self.refit_recipe, data, overrides)

refit_callback

refit_callback(*, method_factory: Callable[[Mapping[str, object], int], Mapping[str, object]], partition: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame] | None = None, num_samples: int | None = None, **prediction: object) -> Callable[[FoldSplit], FoldPrediction]

Adapt retained included rows and neural inputs to explicit refits.

PARAMETER DESCRIPTION
method_factory

Fold-specific canonical fit settings and seed. Retained row attachments are partitioned automatically and cannot be replaced.

TYPE: Callable[[Mapping[str, object], int], Mapping[str, object]]

partition

Optional nonmutating original-frame row selection. By default, Narwhals preserves the dataframe backend and authored columns.

TYPE: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame] or None DEFAULT: None

num_samples

Per-chain draw budget for raw held-out likelihood scoring.

TYPE: int or None DEFAULT: None

**prediction

Existing log_likelihood options, including re_formula and explicit new-group policies. The adapter owns rows, neural inputs, and seeds.

TYPE: object DEFAULT: {}

RETURNS DESCRIPTION
Callable[[FoldSplit], FoldPrediction]

Callback for cross_validate. Fold indices address fitted included rows; subset positions map them to the original raw frame once. Neural predictor_data follows the same train/test selection.

RAISES DESCRIPTION
(ValueError, TypeError)

If retained rows or attachments do not align, a partition has the wrong included-row count, or options fail canonical validation.

Source code in src/quivers/formulas/_fit.py
def refit_callback(
    self,
    *,
    method_factory: Callable[[Mapping[str, object], int], Mapping[str, object]],
    partition: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame]
    | None = None,
    num_samples: int | None = None,
    **prediction: object,
) -> Callable[[FoldSplit], FoldPrediction]:
    """Adapt retained included rows and neural inputs to explicit refits.

    Parameters
    ----------
    method_factory : Callable[[Mapping[str, object], int], Mapping[str, object]]
        Fold-specific canonical fit settings and seed. Retained row
        attachments are partitioned automatically and cannot be replaced.
    partition : Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame] or None
        Optional nonmutating original-frame row selection. By default,
        Narwhals preserves the dataframe backend and authored columns.
    num_samples : int or None
        Per-chain draw budget for raw held-out likelihood scoring.
    **prediction : object
        Existing log_likelihood options, including re_formula and explicit
        new-group policies. The adapter owns rows, neural inputs, and seeds.

    Returns
    -------
    Callable[[FoldSplit], FoldPrediction]
        Callback for cross_validate. Fold indices address fitted included
        rows; subset positions map them to the original raw frame once.
        Neural predictor_data follows the same train/test selection.

    Raises
    ------
    ValueError, TypeError
        If retained rows or attachments do not align, a partition has the
        wrong included-row count, or options fail canonical validation.
    """
    from quivers.formulas._cross_validation import formula_refitter

    return formula_refitter(
        self,
        method_factory=method_factory,
        partition=partition,
        num_samples=num_samples,
        prediction=prediction,
    )

evidence

evidence(sampler: SMC) -> SMCResult

Estimate the retained formula target's normalizing constant with SMC.

PARAMETER DESCRIPTION
sampler

Configured likelihood-tempered driver, including its particle budget, rejuvenation kernel, and random stream.

TYPE: SMC

RETURNS DESCRIPTION
SMCResult

Independent particles and the estimated log normalizing constant. Ordinary data evidence requires a normalized prior and likelihood; response weights define a powered target's normalizer instead.

RAISES DESCRIPTION
ValueError

If SMC cannot partition the target, normalize its prior, or use an exact likelihood without observation subsampling.

RuntimeError

If no temperature step meets the driver's ESS requirement.

Notes

The compiled program, retained designs, fixed parameters, and observed tensors are reused without recompilation. The fitted posterior is neither sampled nor modified. Seeded drivers restore the caller's RNG.

Source code in src/quivers/formulas/_fit.py
def evidence(self, sampler: SMC) -> SMCResult:
    """Estimate the retained formula target's normalizing constant with SMC.

    Parameters
    ----------
    sampler : SMC
        Configured likelihood-tempered driver, including its particle
        budget, rejuvenation kernel, and random stream.

    Returns
    -------
    SMCResult
        Independent particles and the estimated log normalizing constant.
        Ordinary data evidence requires a normalized prior and likelihood;
        response weights define a powered target's normalizer instead.

    Raises
    ------
    ValueError
        If SMC cannot partition the target, normalize its prior, or use
        an exact likelihood without observation subsampling.
    RuntimeError
        If no temperature step meets the driver's ESS requirement.

    Notes
    -----
    The compiled program, retained designs, fixed parameters, and observed
    tensors are reused without recompilation. The fitted posterior is
    neither sampled nor modified. Seeded drivers restore the caller's RNG.
    """
    # An improper flat prior has no normalizing constant.
    self._require_proper("SMC evidence")
    return sampler.run(self.program, torch.zeros(1, 1), dict(self.observations))

prior_summary

prior_summary() -> PriorTable

Tabulate the effective prior of every parameter, as brms prior_summary.

RETURNS DESCRIPTION
PriorTable

brms's columns, with source user for rules given to fit.

RAISES DESCRIPTION
ValueError

If the fit retains no emission.

Source code in src/quivers/formulas/_fit.py
def prior_summary(self) -> PriorTable:
    """Tabulate the effective prior of every parameter, as brms ``prior_summary``.

    Returns
    -------
    PriorTable
        brms's columns, with ``source`` ``user`` for rules given to `fit`.

    Raises
    ------
    ValueError
        If the fit retains no emission.
    """
    plan = self.prediction_plan
    if plan is None:
        raise ValueError("prior_summary requires the fit's retained emission")
    return prior_table(
        plan.module,
        plan.prior_targets,
        user_selection(self.priors, plan.prior_targets),
        policy=self.default_priors,
    )

conditional_effects

conditional_effects(grid: PredictionGrid, *, method: EffectMethod = ..., parameter: str = ..., transform: bool = ..., **options: Unpack[ConditionalEffectsOptions]) -> ConditionalEffects
conditional_effects(grid: str | Sequence[str] | None = ..., *, method: EffectMethod = ..., parameter: str = ..., transform: bool = ..., **options: Unpack[ConditionalEffectsOptions]) -> BrmsConditionalEffects
conditional_effects(grid: PredictionGrid | str | Sequence[str] | None = None, *, method: EffectMethod = 'epred', parameter: str = 'mu', transform: bool = False, **options: Unpack[ConditionalEffectsOptions]) -> ConditionalEffects | BrmsConditionalEffects

Predict one joint grid and retain conditional or empirical effects.

Without a grid, or with brms effects such as "x" or "x:z", this computes brms's automatic conditional effects (quivers.formulas._brms_effects.brms_conditional_effects): default effects and conditions, grids, and labeled summary frames.

PARAMETER DESCRIPTION
grid

Explicit effect coordinates and conditioning/reference rows, constructed with quivers.diagnostics.prediction_grid; or brms effects (None for brms's default effects).

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

method

epred, linpred, predict, or brms's names posterior_epred, posterior_linpred, posterior_predict. Expectations average response laws, not sampled replications.

TYPE: str DEFAULT: 'epred'

parameter

Predictor selected only for linpred; other methods require mu.

TYPE: str DEFAULT: 'mu'

transform

Apply the inverse link only for linpred.

TYPE: bool DEFAULT: False

**options

Existing prediction keywords, including varying-effect selectors, new-level policies, trial/neural inputs, draw budget, and seed. The grid supplies new_data; mc_samples applies only to epred. Without a grid, brms's conditional_effects arguments (conditions, int_conditions, re_formula defaulting to "~0", prob, robust, spaghetti, surface, categorical, ordinal, resolution, select_points, too_far, dpar, nlpar, ndraws, draw_ids, seed).

TYPE: ConditionalEffectsOptions DEFAULT: {}

RETURNS DESCRIPTION
ConditionalEffects or BrmsConditionalEffects

Joint chain/draw/point/condition/event predictions, with reference rows averaged within each draw only for empirical grids. Retained draws support paired contrasts, covariance, and common summaries. Without a grid, brms's labeled effect frames.

RAISES DESCRIPTION
(ValueError, TypeError)

If the method/options or grid are invalid, or the existing fitted prediction contract rejects a predictor, group, or response law.

Source code in src/quivers/formulas/_fit.py
def conditional_effects(
    self,
    grid: PredictionGrid | str | Sequence[str] | None = None,
    *,
    method: EffectMethod = "epred",
    parameter: str = "mu",
    transform: bool = False,
    **options: Unpack[ConditionalEffectsOptions],
) -> ConditionalEffects | BrmsConditionalEffects:
    """Predict one joint grid and retain conditional or empirical effects.

    Without a grid, or with brms ``effects`` such as ``"x"`` or
    ``"x:z"``, this computes brms's automatic conditional effects
    (`quivers.formulas._brms_effects.brms_conditional_effects`): default
    effects and conditions, grids, and labeled summary frames.

    Parameters
    ----------
    grid : PredictionGrid or str or Sequence[str] or None
        Explicit effect coordinates and conditioning/reference rows,
        constructed with `quivers.diagnostics.prediction_grid`; or brms
        ``effects`` (None for brms's default effects).
    method : str
        ``epred``, ``linpred``, ``predict``, or brms's names
        ``posterior_epred``, ``posterior_linpred``, ``posterior_predict``.
        Expectations average response laws, not sampled replications.
    parameter : str
        Predictor selected only for linpred; other methods require mu.
    transform : bool
        Apply the inverse link only for linpred.
    **options : ConditionalEffectsOptions
        Existing prediction keywords, including varying-effect selectors,
        new-level policies, trial/neural inputs, draw budget, and seed.
        The grid supplies new_data; mc_samples applies only to epred.
        Without a grid, brms's ``conditional_effects`` arguments
        (``conditions``, ``int_conditions``, ``re_formula`` defaulting to
        ``"~0"``, ``prob``, ``robust``, ``spaghetti``, ``surface``,
        ``categorical``, ``ordinal``, ``resolution``, ``select_points``,
        ``too_far``, ``dpar``, ``nlpar``, ``ndraws``, ``draw_ids``, ``seed``).

    Returns
    -------
    ConditionalEffects or BrmsConditionalEffects
        Joint chain/draw/point/condition/event predictions, with reference
        rows averaged within each draw only for empirical grids. Retained
        draws support paired contrasts, covariance, and common summaries.
        Without a grid, brms's labeled effect frames.

    Raises
    ------
    ValueError, TypeError
        If the method/options or grid are invalid, or the existing fitted
        prediction contract rejects a predictor, group, or response law.
    """
    # brms automatic conditional effects.
    if not isinstance(grid, PredictionGrid):
        return automatic_conditional_effects(
            self,
            grid,
            method=method,
            parameter=parameter,
            transform=transform,
            resp=None,
            options=options,
        )
    expectation = grid_options(options)
    short = method.removeprefix("posterior_")
    if "new_data" in options:
        raise ValueError("conditional_effects takes new_data from its grid")
    if short not in {"epred", "linpred", "predict"}:
        raise ValueError("method must be epred, linpred, or predict")
    method = cast(Literal["epred", "linpred", "predict"], short)
    if method != "linpred" and (parameter != "mu" or transform):
        raise ValueError("parameter and transform apply only to linpred effects")
    if method != "epred" and "mc_samples" in options:
        raise ValueError("mc_samples applies only to epred effects")
    request = expectation.copy()
    request["new_data"] = grid.to_frame()
    if method == "epred":
        predictions = self.posterior_epred(**request)
    else:
        # The guard above excludes the sole expectation-only key.
        prediction_options = cast(PredictionOptions, request)
        if method == "linpred":
            predictions = self.posterior_linpred(
                parameter=parameter,
                transform=transform,
                **prediction_options,
            )
        else:
            predictions = self.posterior_predict(**prediction_options)
    return grid.result(
        predictions,
        kind=draw_provenance(self.posterior),
        method=method,
        labels=self.predictor_labels(parameter)
        if method == "linpred"
        else self.category_labels,
    )

prior_view

prior_view(*, num_samples: int | None = None, seed: int = 0, method: Literal['ancestral'] | MCMC = 'ancestral') -> BayesianFit

Reuse prediction, likelihood, and analysis methods with prior draws.

PARAMETER DESCRIPTION
num_samples

Fresh independent draw count. None reuses retained prior samples, or draws 100 if none were retained.

TYPE: int or None DEFAULT: None

seed

Isolated CPU seed for fresh ancestral draws.

TYPE: int DEFAULT: 0

method

Conditional sampling or explicitly factor-conditioned inference.

TYPE: 'ancestral' DEFAULT: "ancestral"

RETURNS DESCRIPTION
BayesianFit

A new view sharing the fitted model, encodings, and data.

Source code in src/quivers/formulas/_fit.py
def prior_view(
    self,
    *,
    num_samples: int | None = None,
    seed: int = 0,
    method: Literal["ancestral"] | MCMC = "ancestral",
) -> BayesianFit:
    """Reuse prediction, likelihood, and analysis methods with prior draws.

    Parameters
    ----------
    num_samples : int or None
        Fresh independent draw count. None reuses retained prior samples,
        or draws 100 if none were retained.
    seed : int
        Isolated CPU seed for fresh ancestral draws.
    method : {"ancestral"} or MCMC
        Conditional sampling or explicitly factor-conditioned inference.

    Returns
    -------
    BayesianFit
        A new view sharing the fitted model, encodings, and data.
    """
    prior = (
        self.prior
        if self.prior is not None and num_samples is None and method == "ancestral"
        else self.prior_draws(
            num_samples=100 if num_samples is None else num_samples,
            seed=seed,
            method=method,
        )
    )
    return self.with_(posterior=prior, prior=prior, sample_prior="only", losses=())

dump_qvr

dump_qvr(path: str | Path) -> Path

Write the AST-equivalent .qvr source to path and return the resulting Path.

PARAMETER DESCRIPTION
path

Destination for canonical QVR source.

TYPE: str or Path

RETURNS DESCRIPTION
Path

Written source path.

Source code in src/quivers/formulas/_fit.py
def dump_qvr(self, path: str | Path) -> Path:
    """Write the AST-equivalent ``.qvr`` source to ``path`` and
    return the resulting `Path`.

    Parameters
    ----------
    path : str or Path
        Destination for canonical QVR source.

    Returns
    -------
    Path
        Written source path.
    """
    out = Path(path)
    out.write_text(self.qvr_source)
    return out

fixed_effects

fixed_effects(*, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, Tensor]

Extract the population coefficients of one predictor.

PARAMETER DESCRIPTION
parameter

mu or a distributionally regressed auxiliary parameter.

TYPE: str DEFAULT: 'mu'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, Tensor]

Original column labels and coefficient arrays, shape (chain, draw) or (chain, draw, K-1) for categorical reference-category coefficients.

Source code in src/quivers/formulas/_fit.py
def fixed_effects(
    self, *, parameter: str = "mu", num_samples: int | None = None, seed: int = 0
) -> dict[str, torch.Tensor]:
    """Extract the population coefficients of one predictor.

    Parameters
    ----------
    parameter : str
        ``mu`` or a distributionally regressed auxiliary parameter.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws, restored on exit.

    Returns
    -------
    dict[str, torch.Tensor]
        Original column labels and coefficient arrays, shape
        ``(chain, draw)`` or ``(chain, draw, K-1)`` for categorical
        reference-category coefficients.
    """
    _, prefix = self._formula_predictor(parameter)
    draws = self.draws(num_samples=num_samples, seed=seed)
    return {
        name: self._at_parameter(parameter, values)
        for name, values in self._fixed_effects(draws, prefix).items()
    }

random_effects

random_effects(*, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, dict[str, Tensor]]

Extract native group adjustments, including correlations and scales.

PARAMETER DESCRIPTION
parameter

mu or a distributionally regressed auxiliary parameter.

TYPE: str DEFAULT: 'mu'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, dict[str, Tensor]]

Group name, then original coefficient label, mapped to arrays (chain, draw, level) or (chain, draw, level, K-1). Level order follows group_levels; categorical coefficients follow category_labels[1:].

Source code in src/quivers/formulas/_fit.py
def random_effects(
    self, *, parameter: str = "mu", num_samples: int | None = None, seed: int = 0
) -> dict[str, dict[str, torch.Tensor]]:
    """Extract native group adjustments, including correlations and scales.

    Parameters
    ----------
    parameter : str
        ``mu`` or a distributionally regressed auxiliary parameter.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws, restored on exit.

    Returns
    -------
    dict[str, dict[str, torch.Tensor]]
        Group name, then original coefficient label, mapped to arrays
        ``(chain, draw, level)`` or ``(chain, draw, level, K-1)``.
        Level order follows `group_levels`; categorical coefficients
        follow ``category_labels[1:]``.
    """

    predictor, prefix = self._formula_predictor(parameter)
    shape = draw_count(self.posterior, num_samples)
    if not predictor.random_terms:
        return {}
    draws = self.draws(num_samples=num_samples, seed=seed)
    return {
        group: {
            name: self._at_parameter(parameter, values)
            for name, values in coefficients.items()
        }
        for group, coefficients in self._random_effects(
            draws, shape, predictor, prefix
        ).items()
    }

coefficients

coefficients(*, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, dict[str, Tensor]]

Combine population coefficients and group adjustments by level.

PARAMETER DESCRIPTION
parameter

mu or a distributionally regressed auxiliary parameter.

TYPE: str DEFAULT: 'mu'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, dict[str, Tensor]]

Arrays with the structure of random_effects, now including population coefficients. A group-only slope has population coefficient zero; fixed-only coefficients repeat over levels.

Source code in src/quivers/formulas/_fit.py
def coefficients(
    self, *, parameter: str = "mu", num_samples: int | None = None, seed: int = 0
) -> dict[str, dict[str, torch.Tensor]]:
    """Combine population coefficients and group adjustments by level.

    Parameters
    ----------
    parameter : str
        ``mu`` or a distributionally regressed auxiliary parameter.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws, restored on exit.

    Returns
    -------
    dict[str, dict[str, torch.Tensor]]
        Arrays with the structure of `random_effects`, now including
        population coefficients. A group-only slope has population
        coefficient zero; fixed-only coefficients repeat over levels.
    """

    predictor, prefix = self._formula_predictor(parameter)
    shape = draw_count(self.posterior, num_samples)
    if not predictor.random_terms:
        return {}
    draws = self.draws(num_samples=num_samples, seed=seed)
    fixed = self._fixed_effects(draws, prefix)
    varying = self._random_effects(draws, shape, predictor, prefix)
    for group, coefficients in varying.items():
        for name, coefficient in fixed.items():
            population = coefficient.unsqueeze(2)
            coefficients[name] = (
                coefficients[name] + population
                if name in coefficients
                else population.expand(
                    *population.shape[:2],
                    len(predictor.group_levels[group]),
                    *population.shape[3:],
                )
            )
    return {
        group: {
            name: self._at_parameter(parameter, values)
            for name, values in coefficients.items()
        }
        for group, coefficients in varying.items()
    }

posterior_thresholds

posterior_thresholds(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0) -> Tensor

Replay complete ordinal threshold profiles at each requested row.

PARAMETER DESCRIPTION
new_data

Fresh predictors evaluated with fitted encodings, or training rows.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Explicit neural input for fresh prediction rows when required.

TYPE: Tensor or None DEFAULT: None

re_formula

Varying-effect selector, with the same meaning as posterior_epred.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen grouping identities under the selected policy.

TYPE: bool DEFAULT: False

sample_new_levels

Joint donor or Gaussian policy. Explicit feasible_ policies condition new category-specific effects on ordered row support.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for separate posterior and group-effect random streams.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Tensor

Effective thresholds with shape (chain, draw, row, threshold) and axis labels threshold_labels. They include centered group shapes, selected varying location/slope shifts, and category-specific shifts. The proportional population predictor, its offsets, neural contribution, and discrimination are excluded. With threshold groups (thres(n, gr)) a row holds its group's thresholds and NaN at the positions its group lacks. Cumulative profiles are strictly ordered at every row.

RAISES DESCRIPTION
ValueError

If the family is not ordinal or a requested profile crosses.

Source code in src/quivers/formulas/_fit.py
def posterior_thresholds(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
) -> torch.Tensor:
    """Replay complete ordinal threshold profiles at each requested row.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Fresh predictors evaluated with fitted encodings, or training rows.
    predictor_data : torch.Tensor or None
        Explicit neural input for fresh prediction rows when required.
    re_formula : str or None
        Varying-effect selector, with the same meaning as `posterior_epred`.
    allow_new_levels : bool
        Permit unseen grouping identities under the selected policy.
    sample_new_levels : str
        Joint donor or Gaussian policy. Explicit ``feasible_`` policies
        condition new category-specific effects on ordered row support.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for separate posterior and group-effect random streams.

    Returns
    -------
    torch.Tensor
        Effective thresholds with shape ``(chain, draw, row, threshold)``
        and axis labels `threshold_labels`. They include centered group
        shapes, selected varying location/slope shifts, and category-specific
        shifts. The proportional population predictor, its offsets, neural
        contribution, and discrimination are excluded. With threshold
        groups (``thres(n, gr)``) a row holds its group's thresholds and
        NaN at the positions its group lacks. Cumulative profiles
        are strictly ordered at every row.

    Raises
    ------
    ValueError
        If the family is not ordinal or a requested profile crosses.
    """
    from quivers.formulas._prediction import prepare_prediction

    if self.family.ordinal is None:
        raise ValueError("posterior_thresholds requires an ordinal response family")
    context = prepare_prediction(
        self,
        new_data,
        predictor_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
    )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    width = len(self.threshold_labels)
    plan = self.prediction_plan
    shifts = tuple(
        contribution.name
        for predictor in (plan.predictors if plan is not None else ())
        if not predictor.prefix
        for term in predictor.part(None)
        for contribution in term.contributions()
        if contribution.varying
    )

    def values():
        """Yield retained row values through the shared posterior replay.

        Yields
        ------
        torch.Tensor
            One checked row/event value per retained chain and draw.
        """
        for recorded in replay(self, draws, shape, context=context):
            if width == 0:
                yield torch.empty(context.rows, 0)
                continue
            cuts = row_binding(
                recorded.sites[
                    "row_cutpoints"
                    if self.thresholds_by
                    or self.formula.modifiers.threshold_groups is not None
                    else "cutpoints"
                ].value,
                context.rows,
                width,
            )
            threshold_groups = self.formula.modifiers.threshold_groups
            if threshold_groups is not None:
                # brms thres(n, gr): a row has only its group's thresholds.
                cuts = absent_thresholds(
                    cuts,
                    threshold_groups,
                    context.observations[threshold_groups.column.qvr_name],
                )
            if "eta_nonbaseline" in recorded.sites:
                cuts = cuts - row_binding(
                    recorded.sites["eta_nonbaseline"].value, context.rows, width
                )
            for name in shifts:
                cuts = cuts - row_binding(
                    recorded.sites[name].value, context.rows
                ).unsqueeze(-1)
            yield cuts

    return collect_draws(values(), shape)

posterior_linpred

posterior_linpred(*, parameter: str = 'mu', transform: bool = False, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> Tensor

Replay a fitted linear predictor on training or fresh predictor rows.

PARAMETER DESCRIPTION
parameter

mu or an auxiliary parameter of the family. An auxiliary parameter without a formula is constant over the rows: its draws are repeated for every row on the parameter's own scale whatever transform is, as brms does.

TYPE: str DEFAULT: 'mu'

transform

Return the native inverse-link binding instead of its linear predictor. For binomial data this is a probability, not a count. Ordinal probabilities are supplied by posterior_epred.

TYPE: bool DEFAULT: False

new_data

Fresh predictor rows evaluated with fitted transforms, contrasts, and known group levels. None reuses the retained training rows. Response and likelihood-weight columns are not required.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Explicit input for a neural predictor on new rows. Required for neural fits with new_data; otherwise must be None.

TYPE: Tensor or None DEFAULT: None

trials

Response trial count or column for prediction rows. Vector count fits infer training totals; fresh rows require explicit totals unless a retained trial column supplies them. Linear predictors do not require totals.

TYPE: int or str or None DEFAULT: None

re_formula

None includes all fitted varying effects; "~0" excludes them; a one-sided group formula selects fitted slopes. This sets excluded contributions to zero; it does not marginalize them.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen or missing grouping identities in new_data. Repeated missing values share one new identity per group. Ordinary categorical predictors still require fitted levels.

TYPE: bool DEFAULT: False

sample_new_levels

For each new identity, uncertainty chooses one fitted donor jointly across slopes per posterior draw; old_levels retains one donor across all chains and draws; gaussian samples the fitted conditional zero-mean group law. Existing groups retain their posterior effects. Group and response noise use distinct random streams, and the caller's CPU RNG is restored. Explicit feasible_uncertainty and feasible_gaussian policies condition joint new-group proposals on cumulative row-order support; at most 1024 attempts are made per posterior draw, with an error on failure. Fitted draws and cutpoints are retained.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

incl_autocor

Include an autocorrelation term (brms incl_autocor). False treats rows as independent with the fitted residual scale.

TYPE: bool DEFAULT: True

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Shape (chain, draw, row) or (chain, draw, row, category) for categorical logits/probabilities, including reference zero.

RAISES DESCRIPTION
ValueError

If a parameter has no fitted predictor or an ordinal inverse link is requested without its thresholds.

Source code in src/quivers/formulas/_fit.py
def posterior_linpred(
    self,
    *,
    parameter: str = "mu",
    transform: bool = False,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    trials: int | str | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
    incl_autocor: bool = True,
    data2: Mapping[str, AutocorMatrix] | None = None,
) -> torch.Tensor:
    """Replay a fitted linear predictor on training or fresh predictor rows.

    Parameters
    ----------
    parameter : str
        ``mu`` or an auxiliary parameter of the family. An auxiliary
        parameter without a formula is constant over the rows: its
        draws are repeated for every row on the parameter's own scale
        whatever ``transform`` is, as brms does.
    transform : bool
        Return the native inverse-link binding instead of its linear
        predictor. For binomial data this is a probability, not a count.
        Ordinal probabilities are supplied by `posterior_epred`.
    new_data : IntoDataFrame or None
        Fresh predictor rows evaluated with fitted transforms, contrasts,
        and known group levels. None reuses the retained training rows.
        Response and likelihood-weight columns are not required.
    predictor_data : torch.Tensor or None
        Explicit input for a neural predictor on new rows. Required for
        neural fits with new_data; otherwise must be None.
    trials : int or str or None
        Response trial count or column for prediction rows. Vector count
        fits infer training totals; fresh rows require explicit totals
        unless a retained trial column supplies them. Linear predictors
        do not require totals.
    re_formula : str or None
        None includes all fitted varying effects; ``"~0"`` excludes
        them; a one-sided group formula selects fitted slopes. This
        sets excluded contributions to zero; it does not marginalize them.
    allow_new_levels : bool
        Permit unseen or missing grouping identities in new_data.
        Repeated missing values share one new identity per group.
        Ordinary categorical predictors still require fitted levels.
    sample_new_levels : str
        For each new identity, uncertainty chooses one fitted donor
        jointly across slopes per posterior draw; old_levels retains
        one donor across all chains and draws; gaussian samples the
        fitted conditional zero-mean group law. Existing groups retain
        their posterior effects. Group and response noise use distinct
        random streams, and the caller's CPU RNG is restored. Explicit
        feasible_uncertainty and feasible_gaussian policies condition joint
        new-group proposals on cumulative row-order support; at most 1024
        attempts are made per posterior draw, with an error on failure.
        Fitted draws and cutpoints are retained.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws, restored on exit.
    incl_autocor : bool
        Include an autocorrelation term (brms ``incl_autocor``). False
        treats rows as independent with the fitted residual scale.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).

    Returns
    -------
    torch.Tensor
        Shape ``(chain, draw, row)`` or ``(chain, draw, row, category)``
        for categorical logits/probabilities, including reference zero.

    Raises
    ------
    ValueError
        If a parameter has no fitted predictor or an ordinal inverse
        link is requested without its thresholds.
    """
    from quivers.formulas._prediction import prepare_prediction

    readout = self._predictor_readout
    binding = readout._linpred_binding(parameter, transform)
    constant = readout._constant_parameter(parameter)
    context = prepare_prediction(
        self,
        new_data,
        predictor_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        trials=trials,
        require_trials=False,
        incl_autocor=incl_autocor,
        data2=data2,
        retain_law=False,
    )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    rows = context.rows

    def values():
        """Yield retained row values through the shared posterior replay.

        Yields
        ------
        torch.Tensor
            One checked row/event value per retained chain and draw.
        """
        for recorded in replay(self, draws, shape, context=context):
            if constant:
                fixed = recorded.sites[parameter].value
                if fixed.numel() != 1:
                    raise ValueError(
                        f"parameter {parameter!r} has no fitted predictor "
                        "and is not one scalar per draw"
                    )
                yield fixed.reshape(()).expand(rows)
                continue

            yield binding.read(
                readout._row_reader(
                    parameter, binding, recorded, lambda name: name
                ),
                rows,
            )

    return collect_draws(values(), shape)

posterior_epred

posterior_epred(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, mc_samples: int | None = None, component: Literal['response', 'decision'] = 'response', seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> Tensor

Evaluate native expected responses on training or fresh rows.

PARAMETER DESCRIPTION
new_data

Fresh predictor rows using fitted encodings and known levels, or None for training rows. No response or weight column is needed.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Explicit neural input for new_data, required for neural fits.

TYPE: Tensor or None DEFAULT: None

trials

Response trial count or column for prediction rows. Vector count fits infer training totals; fresh rows require explicit totals unless a retained trial column supplies them. Linear predictors do not require totals.

TYPE: int or str or None DEFAULT: None

re_formula

None includes all fitted varying effects; "~0" excludes them; a one-sided group formula selects fitted slopes. This sets excluded contributions to zero; it does not marginalize them.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen or missing grouping identities in new_data. Repeated missing values share one new identity per group. Ordinary categorical predictors still require fitted levels.

TYPE: bool DEFAULT: False

sample_new_levels

For each new identity, uncertainty chooses one fitted donor jointly across slopes per posterior draw; old_levels retains one donor across all chains and draws; gaussian samples the fitted conditional zero-mean group law. Existing groups retain their posterior effects. Group and response noise use distinct random streams, and the caller's CPU RNG is restored. Explicit feasible_uncertainty and feasible_gaussian policies condition joint new-group proposals on cumulative row-order support; at most 1024 attempts are made per posterior draw, with an error on failure. Fitted draws and cutpoints are retained.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

mc_samples

Explicit Monte Carlo budget for bounded or certified finite-mean response laws without a closed mean. Sampling uses chunks of at most 64; None requires an analytic expectation. Logistic-normal and Cox response means require a budget.

TYPE: int or None DEFAULT: None

component

Wiener response means are positive reaction times, including delay. Decision returns lower/upper probabilities for a decision response.

TYPE: ('response', 'decision') DEFAULT: "response"

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

incl_autocor

Include an autocorrelation term (brms incl_autocor). False treats rows as independent with the fitted residual scale.

TYPE: bool DEFAULT: True

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Native response means, shape (chain, draw, row). Binomial results are expected counts; mixtures include their weights; asymmetric Laplace results are means, not modeled quantiles. Ordinal and categorical responses instead return probabilities, (chain, draw, row, category), in category_labels order. Decision probabilities use a final axis ordered lower, upper.

RAISES DESCRIPTION
ValueError

If a draw has an undefined or nonfinite response mean.

TypeError

If the native family exposes no expectation, or a circular response would require a specified angular convention.

Source code in src/quivers/formulas/_fit.py
def posterior_epred(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    trials: int | str | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    mc_samples: int | None = None,
    component: Literal["response", "decision"] = "response",
    seed: int = 0,
    incl_autocor: bool = True,
    data2: Mapping[str, AutocorMatrix] | None = None,
) -> torch.Tensor:
    """Evaluate native expected responses on training or fresh rows.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Fresh predictor rows using fitted encodings and known levels,
        or None for training rows. No response or weight column is needed.
    predictor_data : torch.Tensor or None
        Explicit neural input for new_data, required for neural fits.
    trials : int or str or None
        Response trial count or column for prediction rows. Vector count
        fits infer training totals; fresh rows require explicit totals
        unless a retained trial column supplies them. Linear predictors
        do not require totals.
    re_formula : str or None
        None includes all fitted varying effects; ``"~0"`` excludes
        them; a one-sided group formula selects fitted slopes. This
        sets excluded contributions to zero; it does not marginalize them.
    allow_new_levels : bool
        Permit unseen or missing grouping identities in new_data.
        Repeated missing values share one new identity per group.
        Ordinary categorical predictors still require fitted levels.
    sample_new_levels : str
        For each new identity, uncertainty chooses one fitted donor
        jointly across slopes per posterior draw; old_levels retains
        one donor across all chains and draws; gaussian samples the
        fitted conditional zero-mean group law. Existing groups retain
        their posterior effects. Group and response noise use distinct
        random streams, and the caller's CPU RNG is restored. Explicit
        feasible_uncertainty and feasible_gaussian policies condition joint
        new-group proposals on cumulative row-order support; at most 1024
        attempts are made per posterior draw, with an error on failure.
        Fitted draws and cutpoints are retained.
    num_samples : int or None
        Draw count under the convention of `draws`.
    mc_samples : int or None
        Explicit Monte Carlo budget for bounded or certified finite-mean
        response laws without a closed mean. Sampling uses chunks of at most
        64; None requires an analytic expectation. Logistic-normal and Cox
        response means require a budget.
    component : {"response", "decision"}
        Wiener response means are positive reaction times, including delay.
        Decision returns lower/upper probabilities for a decision response.
    seed : int
        Seed for variational draws, restored on exit.
    incl_autocor : bool
        Include an autocorrelation term (brms ``incl_autocor``). False
        treats rows as independent with the fitted residual scale.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).

    Returns
    -------
    torch.Tensor
        Native response means, shape ``(chain, draw, row)``. Binomial
        results are expected counts; mixtures include their weights;
        asymmetric Laplace results are means, not modeled quantiles.
        Ordinal and categorical responses instead return probabilities,
        ``(chain, draw, row, category)``, in `category_labels` order.
        Decision probabilities use a final axis ordered lower, upper.

    Raises
    ------
    ValueError
        If a draw has an undefined or nonfinite response mean.
    TypeError
        If the native family exposes no expectation, or a circular
        response would require a specified angular convention.
    """
    from quivers.formulas._prediction import prepare_prediction

    if component not in {"response", "decision"}:
        raise ValueError("expected response component must be response or decision")
    data = self._response_data
    if component == "decision" and data.modifiers.decision is None:
        raise ValueError(
            "decision probabilities require a decision response modifier"
        )
    readout = self._response_readout
    if readout.circular:
        raise TypeError(
            "a circular response expectation requires an angular convention"
        )
    context = prepare_prediction(
        self,
        new_data,
        predictor_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        trials=trials,
        incl_autocor=incl_autocor,
        data2=data2,
    )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    rows = context.rows
    response = _qvr_name(data.name)
    categories = 2 if component == "decision" else readout.categories

    def values():
        """Yield retained row values through the shared posterior replay.

        Yields
        ------
        torch.Tensor
            One checked row/event value per retained chain and draw.

        Raises
        ------
        TypeError
            If the selected response has no requested native operation.
        """
        for recorded in replay(self, draws, shape, context=context):
            distribution = response_distribution(recorded, response)
            value = expected_response(
                distribution,
                readout,
                decision=component == "decision",
                mc_samples=mc_samples,
            )
            yield row_binding(value, rows, data.layout.event_shape or categories)

    with response_rng(seed + 2, (*draws.values(), *context.observations.values())):
        try:
            return collect_draws(values(), shape)
        except TypeError as error:
            if self.family.baseline is not None:
                # brms: "Cannot compute expected values of the posterior
                # predictive distribution for family 'cox'."
                error.add_note(
                    "brms refuses posterior_epred for family "
                    f"{self.family.name!r} as well: "
                    "the baseline hazard is a spline on the observed time "
                    "range, which fixes no mean survival time. Use "
                    "posterior_linpred for the log hazard ratio."
                )
            raise

bayes_r2

bayes_r2(*, method: Literal['auto', 'model', 'residual'] = 'auto', observed: Tensor | None = None, **options: Unpack[ExpectationOptions]) -> Tensor

Compute per-draw explained variance on the response scale.

PARAMETER DESCRIPTION
method

Model-variance ratios use native conditional means and variances; residual ratios use actual minus expected responses. Auto selects model variances for ordinary Gaussian and Bernoulli responses, and residual variances otherwise. Explicit observations select residual variances under auto.

TYPE: ('auto', 'model', 'residual') DEFAULT: "auto"

observed

Explicit actual responses on row/event axes for the residual method. Otherwise use retained training responses or evaluate their fitted transform in new_data. Censoring bounds cannot stand in for actual responses.

TYPE: Tensor or None DEFAULT: None

**options

Shared posterior expectation options, including new_data, group policies, trials, draw counts, and seed. Model variances require analytic native moments; mc_samples applies to residual means.

TYPE: Unpack[ExpectationOptions] DEFAULT: {}

RETURNS DESCRIPTION
Tensor

Ratios on chain, draw, and event axes. Ordinal residual ratios use ordered integer scores. Unordered categories require a separately specified response metric. Zero total variance is NaN.

Source code in src/quivers/formulas/_fit.py
def bayes_r2(
    self,
    *,
    method: Literal["auto", "model", "residual"] = "auto",
    observed: torch.Tensor | None = None,
    **options: Unpack[ExpectationOptions],
) -> torch.Tensor:
    """Compute per-draw explained variance on the response scale.

    Parameters
    ----------
    method : {"auto", "model", "residual"}
        Model-variance ratios use native conditional means and variances;
        residual ratios use actual minus expected responses. Auto selects
        model variances for ordinary Gaussian and Bernoulli responses,
        and residual variances otherwise. Explicit observations select
        residual variances under auto.
    observed : torch.Tensor or None
        Explicit actual responses on row/event axes for the residual
        method. Otherwise use retained training responses or evaluate
        their fitted transform in new_data. Censoring bounds cannot stand
        in for actual responses.
    **options
        Shared posterior expectation options, including new_data, group
        policies, trials, draw counts, and seed. Model variances require
        analytic native moments; mc_samples applies to residual means.

    Returns
    -------
    torch.Tensor
        Ratios on chain, draw, and event axes. Ordinal residual ratios
        use ordered integer scores. Unordered categories require a
        separately specified response metric. Zero total variance is NaN.
    """

    def laws() -> tuple[Generator[Distribution, None, None], tuple[int, int], int]:
        context = prepare_prediction(
            self,
            options.get("new_data"),
            options.get("predictor_data"),
            re_formula=options.get("re_formula"),
            allow_new_levels=options.get("allow_new_levels", False),
            sample_new_levels=options.get("sample_new_levels", "uncertainty"),
            seed=options.get("seed", 0),
            trials=options.get("trials"),
        )
        shape = draw_count(self.posterior, options.get("num_samples"))
        draws = self.draws(
            num_samples=options.get("num_samples"), seed=options.get("seed", 0)
        )
        response = _qvr_name(self.formula.response_name)
        return (
            (
                response_distribution(recorded, response)
                for recorded in replay(self, draws, shape, context=context)
            ),
            shape,
            context.rows,
        )

    return formula_r2(
        self._response_data,
        self._response_readout,
        self.residual,
        method,
        observed,
        new_data=options.get("new_data"),
        mc_samples=options.get("mc_samples"),
        recorded=lambda: _responses(self, options),
        expected=lambda: self.posterior_epred(**options),
        laws=laws,
    )

posterior_choice_probs

posterior_choice_probs(**options: Unpack[ExpectationOptions]) -> Tensor

Return joint-model lower/upper decision probabilities.

PARAMETER DESCRIPTION
**options

Shared posterior expectation options, including new_data, varying effect selection, draw count, and seed.

TYPE: Unpack[ExpectationOptions] DEFAULT: {}

RETURNS DESCRIPTION
Tensor

Probabilities shaped chain x draw x row x (lower, upper).

Source code in src/quivers/formulas/_fit.py
def posterior_choice_probs(
    self, **options: Unpack[ExpectationOptions]
) -> torch.Tensor:
    """Return joint-model lower/upper decision probabilities.

    Parameters
    ----------
    **options
        Shared posterior expectation options, including new_data, varying
        effect selection, draw count, and seed.

    Returns
    -------
    torch.Tensor
        Probabilities shaped chain x draw x row x (lower, upper).
    """
    return self.posterior_epred(component="decision", **options)

pp_mixture

pp_mixture(*, new_data: IntoDataFrame | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', log: bool = False, num_samples: int | None = None, seed: int = 0) -> Tensor

Posterior probabilities of mixture component membership, brms pp_mixture.

P(K = k | y_i) = theta_k p_k(y_i) / sum_j theta_j p_j(y_i) at each posterior draw, scoring censored rows by their recorded event. Cost: O(S n K) for S draws, n rows and K components.

PARAMETER DESCRIPTION
new_data

Rows with recorded responses and any censoring columns; None scores the training rows.

TYPE: IntoDataFrame or None DEFAULT: None

re_formula

Varying-effect selector, as for prediction.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen grouping levels in new_data.

TYPE: bool DEFAULT: False

sample_new_levels

Policy for unseen grouping levels.

TYPE: str DEFAULT: 'uncertainty'

log

Return log probabilities.

TYPE: bool DEFAULT: False

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and new-level policies.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Tensor

Shape (chain, draw, row, component).

RAISES DESCRIPTION
ValueError

If the fit is not a mixture model.

Source code in src/quivers/formulas/_fit.py
def pp_mixture(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    log: bool = False,
    num_samples: int | None = None,
    seed: int = 0,
) -> torch.Tensor:
    """Posterior probabilities of mixture component membership, brms ``pp_mixture``.

    ``P(K = k | y_i) = theta_k p_k(y_i) / sum_j theta_j p_j(y_i)`` at each
    posterior draw, scoring censored rows by their recorded event. Cost:
    O(S n K) for S draws, n rows and K components.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Rows with recorded responses and any censoring columns; None
        scores the training rows.
    re_formula : str or None
        Varying-effect selector, as for prediction.
    allow_new_levels : bool
        Permit unseen grouping levels in ``new_data``.
    sample_new_levels : str
        Policy for unseen grouping levels.
    log : bool
        Return log probabilities.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws and new-level policies.

    Returns
    -------
    torch.Tensor
        Shape ``(chain, draw, row, component)``.

    Raises
    ------
    ValueError
        If the fit is not a mixture model.
    """
    return pp_mixture(
        self,
        new_data=new_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        log=log,
        num_samples=num_samples,
        seed=seed,
    )

posterior_response

posterior_response(**options: Unpack[PredictionOptions]) -> ResponseDraws

Draw responses in original measurement coordinates in one replay.

PARAMETER DESCRIPTION
**options

Shared posterior_predict options, including new_data, varying effect selection, draw count, and seed.

TYPE: Unpack[PredictionOptions] DEFAULT: {}

RETURNS DESCRIPTION
ResponseDraws

Positive reaction time and its joint binary decision for Wiener; ordinary response values with no decision for other families.

Source code in src/quivers/formulas/_fit.py
def posterior_response(self, **options: Unpack[PredictionOptions]) -> ResponseDraws:
    """Draw responses in original measurement coordinates in one replay.

    Parameters
    ----------
    **options
        Shared posterior_predict options, including new_data, varying
        effect selection, draw count, and seed.

    Returns
    -------
    ResponseDraws
        Positive reaction time and its joint binary decision for Wiener;
        ordinary response values with no decision for other families.
    """
    from quivers.formulas._response_modifiers import decode_response_draws

    return decode_response_draws(self.formula, self.posterior_predict(**options))

hypothesis

hypothesis(expression: str | ContrastExpression | Sequence[str] | Mapping[str, str], *, class_: str | None = 'b', parameter: str = 'mu', group: str | None = None, scope: Literal['standard', 'ranef', 'coef'] = 'standard', prior: bool = False, num_samples: int | None = None, num_prior_samples: int | None = None, seed: int = 0, null: float | int | Tensor = 0.0, probs: Sequence[float] = (0.025, 0.975), robust: bool = False, point: PointNullSpec | None = None, name: str = 'contrast', alpha: float = 0.05) -> HypothesisSummary | HypothesisTable

Test a brms hypothesis string, or evaluate a checked contrast.

A string of the form "left (= | < | >) right", or several such strings, is a brms hypothesis: every name is prefixed with the class ("x > 0" tests b_x, and with class_="sd" and group="g" the name Intercept is sd_g__Intercept), the sides are R expressions (^, exp), and the result is brms's table. class_=None reads names as variables reports them.

PARAMETER DESCRIPTION
expression

brms hypothesis strings (a mapping names them), or a QVR value expression over authored labels, with optional aliases.

TYPE: str or ContrastExpression or Sequence[str] or Mapping[str, str]

class_

Parameter role such as b, Intercept, sd, cor, or an auxiliary name. The b role includes population intercepts. None selects exact constrained latent site names.

TYPE: str or None DEFAULT: 'b'

parameter

Distributional or nonlinear predictor for b, Intercept, and sd.

TYPE: str DEFAULT: 'mu'

group

Grouping factor for scale/correlation filtering or per-level scopes.

TYPE: str or None DEFAULT: None

scope

Named parameters, per-level random adjustments, or per-level population plus random coefficients. The latter two require b/group.

TYPE: ('standard', 'ranef', 'coef') DEFAULT: "standard"

prior

Also evaluate the same contrast on the corresponding joint prior stream, yielding prior-corrected region evidence.

TYPE: bool DEFAULT: False

num_samples

Posterior and prior counts. None follows retained-draw conventions; retained prior samples are reused when available.

TYPE: int or None DEFAULT: None

num_prior_samples

Posterior and prior counts. None follows retained-draw conventions; retained prior samples are reused when available.

TYPE: int or None DEFAULT: None

seed

Isolated seed for guide or fresh prior draws.

TYPE: int DEFAULT: 0

null

Finite comparison value on event axes only.

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

probs

Quantile probabilities, in requested order.

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

robust

Return median/scaled MAD rather than mean/sample SD.

TYPE: bool DEFAULT: False

point

Optional marginal point-density comparison using these same joint contrast streams. Requires prior=True and a checked Real result.

TYPE: PointNullSpec or None DEFAULT: None

name

Output contrast label.

TYPE: str DEFAULT: 'contrast'

alpha

brms alpha of a hypothesis string: the interval is alpha to 1 - alpha for a one-sided hypothesis and alpha / 2 to 1 - alpha / 2 for a two-sided one.

TYPE: float DEFAULT: 0.05

RETURNS DESCRIPTION
HypothesisSummary or HypothesisTable

For a brms hypothesis string, brms's table (Estimate, Est.Error, CI.Lower, CI.Upper, Evid.Ratio, Post.Prob, Star); its evidence ratio of a point hypothesis needs prior draws (sample_prior or prior=True). For a contrast expression, chain/draw/event-aware uncertainty and strict-region evidence. Posterior odds and prior-corrected region Bayes factors are distinct; equality frequencies do not estimate a point-null Bayes factor. Optional point_evidence uses the shared density estimator and retains its bandwidth and explicit assumption declarations.

RAISES DESCRIPTION
ValueError

If a hypothesis string is malformed or names a parameter that is not in the model (the message lists the class's parameters), or the contrast selectors match nothing.

Source code in src/quivers/formulas/_fit.py
def hypothesis(
    self,
    expression: str | ContrastExpression | Sequence[str] | Mapping[str, str],
    *,
    class_: str | None = "b",
    parameter: str = "mu",
    group: str | None = None,
    scope: Literal["standard", "ranef", "coef"] = "standard",
    prior: bool = False,
    num_samples: int | None = None,
    num_prior_samples: int | None = None,
    seed: int = 0,
    null: float | int | torch.Tensor = 0.0,
    probs: Sequence[float] = (0.025, 0.975),
    robust: bool = False,
    point: PointNullSpec | None = None,
    name: str = "contrast",
    alpha: float = 0.05,
) -> HypothesisSummary | HypothesisTable:
    """Test a brms hypothesis string, or evaluate a checked contrast.

    A string of the form ``"left (= | < | >) right"``, or several such
    strings, is a brms hypothesis: every name is prefixed with the
    class (``"x > 0"`` tests ``b_x``, and with ``class_="sd"`` and
    ``group="g"`` the name ``Intercept`` is ``sd_g__Intercept``), the
    sides are R expressions (``^``, ``exp``), and the result is brms's
    table. ``class_=None`` reads names as `variables` reports them.

    Parameters
    ----------
    expression : str or ContrastExpression or Sequence[str] or Mapping[str, str]
        brms hypothesis strings (a mapping names them), or a QVR value
        expression over authored labels, with optional aliases.
    class_ : str or None
        Parameter role such as b, Intercept, sd, cor, or an auxiliary name.
        The b role includes population intercepts. None selects exact
        constrained latent site names.
    parameter : str
        Distributional or nonlinear predictor for b, Intercept, and sd.
    group : str or None
        Grouping factor for scale/correlation filtering or per-level scopes.
    scope : {"standard", "ranef", "coef"}
        Named parameters, per-level random adjustments, or per-level
        population plus random coefficients. The latter two require b/group.
    prior : bool
        Also evaluate the same contrast on the corresponding joint prior
        stream, yielding prior-corrected region evidence.
    num_samples, num_prior_samples : int or None
        Posterior and prior counts. None follows retained-draw conventions;
        retained prior samples are reused when available.
    seed : int
        Isolated seed for guide or fresh prior draws.
    null : float, int, or torch.Tensor
        Finite comparison value on event axes only.
    probs : Sequence[float]
        Quantile probabilities, in requested order.
    robust : bool
        Return median/scaled MAD rather than mean/sample SD.
    point : PointNullSpec or None
        Optional marginal point-density comparison using these same joint
        contrast streams. Requires prior=True and a checked Real result.
    name : str
        Output contrast label.
    alpha : float
        brms ``alpha`` of a hypothesis string: the interval is
        ``alpha`` to ``1 - alpha`` for a one-sided hypothesis and
        ``alpha / 2`` to ``1 - alpha / 2`` for a two-sided one.

    Returns
    -------
    HypothesisSummary or HypothesisTable
        For a brms hypothesis string, brms's table (``Estimate``,
        ``Est.Error``, ``CI.Lower``, ``CI.Upper``, ``Evid.Ratio``,
        ``Post.Prob``, ``Star``); its evidence ratio of a point
        hypothesis needs prior draws (``sample_prior`` or
        ``prior=True``). For a contrast expression,
        chain/draw/event-aware uncertainty and strict-region evidence.
        Posterior odds and prior-corrected region Bayes factors are distinct;
        equality frequencies do not estimate a point-null Bayes factor.
        Optional point_evidence uses the shared density estimator and retains
        its bandwidth and explicit assumption declarations.

    Raises
    ------
    ValueError
        If a hypothesis string is malformed or names a parameter that
        is not in the model (the message lists the class's parameters),
        or the contrast selectors match nothing.
    """
    from quivers.formulas._hypothesis import _formula_hypothesis

    if is_brms_hypothesis(expression):
        return fit_hypothesis(
            self,
            cast("HypothesisInput", expression),
            class_=class_,
            group=group,
            scope=scope,
            alpha=alpha,
            robust=robust,
            prior=prior,
            num_samples=num_samples,
            num_prior_samples=num_prior_samples,
            seed=seed,
        )
    return _formula_hypothesis(
        self,
        expression,
        class_=class_,
        parameter=parameter,
        group=group,
        scope=scope,
        prior=prior,
        num_samples=num_samples,
        num_prior_samples=num_prior_samples,
        seed=seed,
        null=null,
        probs=probs,
        robust=robust,
        point=point,
        name=name,
    )

analysis

analysis(*, num_samples: int | None = None, seed: int = 0) -> PosteriorAnalysis

Prepare reusable posterior summaries and predictive comparisons.

PARAMETER DESCRIPTION
num_samples

Maximum MCMC draws per chain or fresh variational draw count.

TYPE: int or None DEFAULT: None

seed

Variational seed; the caller's CPU RNG is preserved.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PosteriorAnalysis

Retained draws, raw training-row likelihoods, response data, and actual sampler statistics. Later analysis reuses these tensors.

Source code in src/quivers/formulas/_fit.py
def analysis(
    self, *, num_samples: int | None = None, seed: int = 0
) -> PosteriorAnalysis:
    """Prepare reusable posterior summaries and predictive comparisons.

    Parameters
    ----------
    num_samples : int or None
        Maximum MCMC draws per chain or fresh variational draw count.
    seed : int
        Variational seed; the caller's CPU RNG is preserved.

    Returns
    -------
    quivers.diagnostics.PosteriorAnalysis
        Retained draws, raw training-row likelihoods, response data,
        and actual sampler statistics. Later analysis reuses these tensors.
    """
    from quivers.diagnostics.posterior import PosteriorAnalysis, _sample_stats

    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    response = _qvr_name(self.formula.response_name)
    plan = self.prediction_plan
    missing = plan.missing if plan is not None else None
    values = self.formula
    if missing is not None and missing.recorded is not None:
        values = values.with_(response_values=self._response_data.values)
    return PosteriorAnalysis(
        samples=draws,
        log_likelihood=self._response_scores(draws, shape, missing=missing),
        observed_data={response: response_tensor(values, self.family)},
        sample_stats=_sample_stats(self.posterior, shape[1]),
        kind=draw_provenance(self.posterior),
    )

log_likelihood

log_likelihood(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> dict[str, Tensor]

Evaluate raw response log likelihoods on fitted or recorded fresh rows.

PARAMETER DESCRIPTION
new_data

Fresh predictors, outcomes, and authored observation-event columns. None scores the fitted rows. Fitting weight columns are not required.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Neural inputs aligned with fresh rows before any subset selection.

TYPE: Tensor or None DEFAULT: None

trials

Existing count-trial override. Fresh vector counts otherwise infer their totals from their recorded components.

TYPE: int or str or None DEFAULT: None

re_formula

Existing varying-effect selector; ~0 excludes varying effects.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit fresh grouping identities under the selected prediction policy.

TYPE: bool DEFAULT: False

sample_new_levels

Existing joint donor or conditional Gaussian group-effect policy.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Maximum retained draws per chain, or fresh variational draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws; the caller's CPU RNG is preserved.

TYPE: int DEFAULT: 0

incl_autocor

Include an autocorrelation term (brms incl_autocor). False treats rows as independent with the fitted residual scale.

TYPE: bool DEFAULT: True

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

RETURNS DESCRIPTION
dict[str, Tensor]

Response name to raw scores with shape (chain, draw, row). Likelihood weights are excluded and event coordinates are reduced. Rows without a recorded mi() outcome score zero.

RAISES DESCRIPTION
TypeError

If a hidden response needs a marginal-likelihood observer.

Source code in src/quivers/formulas/_fit.py
def log_likelihood(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    trials: int | str | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
    incl_autocor: bool = True,
    data2: Mapping[str, AutocorMatrix] | None = None,
) -> dict[str, torch.Tensor]:
    """Evaluate raw response log likelihoods on fitted or recorded fresh rows.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Fresh predictors, outcomes, and authored observation-event columns.
        None scores the fitted rows. Fitting weight columns are not required.
    predictor_data : torch.Tensor or None
        Neural inputs aligned with fresh rows before any subset selection.
    trials : int or str or None
        Existing count-trial override. Fresh vector counts otherwise infer
        their totals from their recorded components.
    re_formula : str or None
        Existing varying-effect selector; ``~0`` excludes varying effects.
    allow_new_levels : bool
        Permit fresh grouping identities under the selected prediction policy.
    sample_new_levels : str
        Existing joint donor or conditional Gaussian group-effect policy.
    num_samples : int or None
        Maximum retained draws per chain, or fresh variational draws.
    seed : int
        Seed for variational draws; the caller's CPU RNG is preserved.
    incl_autocor : bool
        Include an autocorrelation term (brms ``incl_autocor``). False
        treats rows as independent with the fitted residual scale.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).

    Returns
    -------
    dict[str, torch.Tensor]
        Response name to raw scores with shape ``(chain, draw, row)``.
        Likelihood weights are excluded and event coordinates are reduced.
        Rows without a recorded ``mi()`` outcome score zero.

    Raises
    ------
    TypeError
        If a hidden response needs a marginal-likelihood observer.
    """

    if new_data is not None:
        from quivers.formulas._likelihood import prepare_likelihood

        context = prepare_likelihood(
            self,
            new_data,
            predictor_data,
            trials=trials,
            re_formula=re_formula,
            allow_new_levels=allow_new_levels,
            sample_new_levels=sample_new_levels,
            seed=seed,
            incl_autocor=incl_autocor,
            data2=data2,
        )
    else:
        from quivers.formulas._prediction import prepare_prediction

        if trials is not None:
            if self.family.trials_parameter is None:
                raise ValueError(
                    "trial overrides require a count family with a trial parameter"
                )
            _response_trials(
                self.formula,
                self._response_data.training_data,
                trials,
                caller="log_likelihood",
            )
        context = prepare_prediction(
            self,
            None,
            predictor_data,
            trials=trials,
            re_formula=re_formula,
            allow_new_levels=allow_new_levels,
            sample_new_levels=sample_new_levels,
            seed=seed,
            incl_autocor=incl_autocor,
            data2=data2,
            retain_law=False,
        )
        if trials is not None:
            name = response_input_name(self.formula)
            context = context.with_(
                observations=dict(context.observations)
                | {
                    name: self.observations[name],
                }
            )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    plan = self.prediction_plan
    missing = plan.missing if plan is not None and new_data is None else None
    return self._response_scores(draws, shape, context=context, missing=missing)

posterior_predict

posterior_predict(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> Tensor

Sample native response distributions on training or fresh rows.

PARAMETER DESCRIPTION
new_data

Fresh predictor rows using fitted encodings and known levels, or None for training rows. No response or weight column is needed.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Explicit neural input for new_data, required for neural fits.

TYPE: Tensor or None DEFAULT: None

trials

Response trial count or column for prediction rows. Vector count fits infer training totals; fresh rows require explicit totals unless a retained trial column supplies them. Linear predictors do not require totals.

TYPE: int or str or None DEFAULT: None

re_formula

None includes all fitted varying effects; "~0" excludes them; a one-sided group formula selects fitted slopes. This sets excluded contributions to zero; it does not marginalize them.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen or missing grouping identities in new_data. Repeated missing values share one new identity per group. Ordinary categorical predictors still require fitted levels.

TYPE: bool DEFAULT: False

sample_new_levels

For each new identity, uncertainty chooses one fitted donor jointly across slopes per posterior draw; old_levels retains one donor across all chains and draws; gaussian samples the fitted conditional zero-mean group law. Existing groups retain their posterior effects. Group and response noise use distinct random streams, and the caller's CPU RNG is restored. Explicit feasible_uncertainty and feasible_gaussian policies condition joint new-group proposals on cumulative row-order support; at most 1024 attempts are made per posterior draw, with an error on failure. Fitted draws and cutpoints are retained.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Maximum draws per MCMC chain, or fresh guide draws, following draws. Each posterior draw supplies one response per row.

TYPE: int or None DEFAULT: None

seed

Seed for separate latent and response random streams. The caller's CPU RNG state is restored on return or failure.

TYPE: int DEFAULT: 0

incl_autocor

Include an autocorrelation term (brms incl_autocor). False treats rows as independent with the fitted residual scale.

TYPE: bool DEFAULT: True

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Predictive responses, shape (chain, draw, row, *event). Categorical and ordinal responses contain integer codes in category_labels; binomial responses contain counts. Likelihood weights do not alter the response sampling law at a fixed posterior draw. Wiener draws retain their joint signed representation: positive upper-boundary and negative lower-boundary reaction times. Use posterior_response for positive times and their joint decisions.

RAISES DESCRIPTION
ValueError

If the requested count or retained posterior layout is invalid.

TypeError

If the response has no native sampling operation.

Source code in src/quivers/formulas/_fit.py
def posterior_predict(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    trials: int | str | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
    incl_autocor: bool = True,
    data2: Mapping[str, AutocorMatrix] | None = None,
) -> torch.Tensor:
    """Sample native response distributions on training or fresh rows.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Fresh predictor rows using fitted encodings and known levels,
        or None for training rows. No response or weight column is needed.
    predictor_data : torch.Tensor or None
        Explicit neural input for new_data, required for neural fits.
    trials : int or str or None
        Response trial count or column for prediction rows. Vector count
        fits infer training totals; fresh rows require explicit totals
        unless a retained trial column supplies them. Linear predictors
        do not require totals.
    re_formula : str or None
        None includes all fitted varying effects; ``"~0"`` excludes
        them; a one-sided group formula selects fitted slopes. This
        sets excluded contributions to zero; it does not marginalize them.
    allow_new_levels : bool
        Permit unseen or missing grouping identities in new_data.
        Repeated missing values share one new identity per group.
        Ordinary categorical predictors still require fitted levels.
    sample_new_levels : str
        For each new identity, uncertainty chooses one fitted donor
        jointly across slopes per posterior draw; old_levels retains
        one donor across all chains and draws; gaussian samples the
        fitted conditional zero-mean group law. Existing groups retain
        their posterior effects. Group and response noise use distinct
        random streams, and the caller's CPU RNG is restored. Explicit
        feasible_uncertainty and feasible_gaussian policies condition joint
        new-group proposals on cumulative row-order support; at most 1024
        attempts are made per posterior draw, with an error on failure.
        Fitted draws and cutpoints are retained.
    num_samples : int or None
        Maximum draws per MCMC chain, or fresh guide draws, following
        `draws`. Each posterior draw supplies one response per row.
    seed : int
        Seed for separate latent and response random streams. The
        caller's CPU RNG state is restored on return or failure.
    incl_autocor : bool
        Include an autocorrelation term (brms ``incl_autocor``). False
        treats rows as independent with the fitted residual scale.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).

    Returns
    -------
    torch.Tensor
        Predictive responses, shape ``(chain, draw, row, *event)``. Categorical
        and ordinal responses contain integer codes in `category_labels`;
        binomial responses contain counts. Likelihood weights do not
        alter the response sampling law at a fixed posterior draw.
        Wiener draws retain their joint signed representation: positive
        upper-boundary and negative lower-boundary reaction times. Use
        `posterior_response` for positive times and their joint decisions.

    Raises
    ------
    ValueError
        If the requested count or retained posterior layout is invalid.
    TypeError
        If the response has no native sampling operation.
    """
    from quivers.formulas._prediction import prepare_prediction
    from quivers.inference._response import response_sample

    context = prepare_prediction(
        self,
        new_data,
        predictor_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        trials=trials,
        incl_autocor=incl_autocor,
        data2=data2,
    )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    rows = context.rows
    response = _qvr_name(self.formula.response_name)

    def values():
        """Yield retained row values through the shared posterior replay.

        Yields
        ------
        torch.Tensor
            One checked row/event value per retained chain and draw.

        Raises
        ------
        TypeError
            If the selected response has no requested native operation.
        """
        for recorded in replay(self, draws, shape, context=context):
            yield row_binding(
                response_sample(recorded, response),
                rows,
                self.formula.response_layout.event_shape,
            )

    # Guide sampling uses its own seed and restores the caller's RNG.
    # A distinct stream avoids coupling response noise to guide noise.
    with (
        response_rng(seed + 1, (*draws.values(), *context.observations.values())),
        torch.no_grad(),
    ):
        return collect_draws(values(), shape)

predictor_labels

predictor_labels(parameter: str = 'mu') -> tuple[int | str, ...]

Label the last axis returned by posterior_linpred for one graph output.

PARAMETER DESCRIPTION
parameter

Family parameter or named nonlinear intermediate.

TYPE: str DEFAULT: 'mu'

RETURNS DESCRIPTION
tuple[int or str, ...]

Output coordinate order; empty for scalar-row values. Family coordinates use fitted response order, with the ALR reference omitted. Intermediate vectors retain authored label order.

RAISES DESCRIPTION
ValueError

If the parameter has no retained predictor or graph binding.

Source code in src/quivers/formulas/_fit.py
def predictor_labels(self, parameter: str = "mu") -> tuple[int | str, ...]:
    """Label the last axis returned by posterior_linpred for one graph output.

    Parameters
    ----------
    parameter : str
        Family parameter or named nonlinear intermediate.

    Returns
    -------
    tuple[int or str, ...]
        Output coordinate order; empty for scalar-row values. Family
        coordinates use fitted response order, with the ALR reference
        omitted. Intermediate vectors retain authored label order.

    Raises
    ------
    ValueError
        If the parameter has no retained predictor or graph binding.
    """
    return self._predictor_readout.predictor_labels(parameter)

fit

fit(formula: MultivariateFormula, *, data: IntoDataFrame, **options: Unpack[JointFitOptions]) -> MultivariateFit
fit(formula: str | ResponseModel, *, data: IntoDataFrame, **options: Unpack[FormulaFitOptions]) -> BayesianFit
fit(formula: None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str], response: str, entry: str | None = None, static: Mapping[str, int] | None = None, **options: Unpack[FormulaFitOptions]) -> BayesianFit
fit(formula: str | ResponseModel | MultivariateFormula | None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str] | None = None, entry: str | None = None, static: Mapping[str, int] | None = None, parameters: Mapping[str, str | NonlinearExpression] | None = None, response: str | None = None, family: str | Family = 'gaussian', weights: str | None = None, decision: str | None = None, data2: Mapping[str, AutocorMatrix] | None = None, distributional: Mapping[str, str | NonlinearExpression] | None = None, nonlinear: Mapping[str, str | NonlinearExpression] | None = None, fixed_parameters: Mapping[str, float] | None = None, method: FitMethod = 'nuts', num_warmup: int | None = None, num_samples: int | None = None, num_chains: int | None = None, num_steps: int | None = None, learning_rate: float = 0.01, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, priors: PriorInput | None = None, guide: type | None = None, initial_values: Mapping[str, Tensor | float] | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor: Module | None = None, predictor_data: Tensor | None = None, seed: int = 0, sample_prior: PriorMode = 'no', num_prior_samples: int = 100, prior_seed: int | None = None, snapshot_policy: SnapshotPolicy = 'clone', default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: Sequence[str] = (), control: SamplerControl | Mapping[str, float | int | str] | None = None, thin: int = 1, init: InitSpec | None = None, init_r: float = 2.0, algorithm: Algorithm | None = None, file: str | Path | None = None, file_refit: FileRefit = 'never', pathfinder: PathfinderOptions | Mapping[str, float | int | bool] | None = None, cores: int = 1, knots: Knots | None = None, drop_unused_levels: bool = True) -> BayesianFit | MultivariateFit

Compile a brms-style formula, fit it, and return the result.

See quivers.formulas for surface details. This entry point composes formula_from_data, FormulaToQVRModule, Compiler, and the inference layer in one call.

family="categorical" uses the sorted distinct integer labels or the declared factor levels and takes the first category as the default reference. An attached categorical predictor may return (N, K-1) reference logits or (N, K) full logits. For family="mixture", mixture_components selects any finite component count of at least two; the likelihood integrates assignments exactly.

PARAMETER DESCRIPTION
formula

brms/lme4-style response formula, or a joint formula built with bf (bf("mvbind(y1, y2) ~ x") or bf(...) + bf(...)), which returns a MultivariateFit. Response-level keywords then belong to each bf call. A single-response bf("y ~ x", "sigma ~ z") is fitted as the string formula with the response keywords it carries; a keyword given both there and here with different values raises. None for a program, given by program=.

TYPE: str or ResponseModel or MultivariateFormula or None DEFAULT: None

data

Pandas, Polars, or another Narwhals-compatible dataframe.

TYPE: IntoDataFrame

program

QVR source, or a source file path and a program name. With source text alone, the one program or the one exported program is selected. The program's observation of response is the likelihood, and its domain is the rows of the data. Every sample site and input that parameters names is replaced by a regression on the link scale its support requires; every other site keeps the program's own law. Data the program reads at each row are data columns of the same name; data on another axis and scalars come from data2.

TYPE: str or tuple[str or Path, str] or None DEFAULT: None

entry

The program name when it is given separately from the source text.

TYPE: str or None DEFAULT: None

static

Finite extents of the program, by binder name.

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

parameters

Formulas of the program's parameters, as {"noise": "~ 1 + (1 | g)"}. A NonlinearExpression gives a link-scale expression and can read additional parameter formulas in the mapping. Priors of the program's parameter formulas use dpar=<parameter>.

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

response

The site the program observes, a data column.

TYPE: str or None DEFAULT: None

family

Registered response family or a family value. Family.with_links selects location or auxiliary inverse links.

TYPE: str or Family DEFAULT: 'gaussian'

weights

Numeric column of finite nonnegative likelihood weights. Values multiply each response's log density, retain their original scale, and do not weight priors or posterior predictions.

TYPE: str or None DEFAULT: None

decision

Wiener boundary-choice column: numeric zero/lower or one/upper, or the labels lower and upper. Equivalent to response-side dec(column).

TYPE: str or None DEFAULT: None

nonlinear

Named additive parameter designs or deterministic QVR expressions. Supplying this mapping interprets the response RHS as a value expression. Defaults retain the same proper coefficient priors as ordinary QVR formulas; get_prior reports their exact site names.

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

data2

Named matrices referenced by autocorrelation terms, as in brms: the spatial weights of sar(M) and the fixed covariance of fcor(M), each over the included response rows. A group-level gr(g, cov = M) reads a labeled DataFrame covariance between the levels of g, and s(g, bs = "mrf", xt = list(penalty = M)) a penalty or neighbourhood matrix over them.

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

distributional

Auxiliary-parameter formulas, for instance {"sigma": "~ z + (1 | g)"}. The optional left-hand side must match the parameter name. Coefficient prior overrides use names such as dpar_sigma_intercept and dpar_sigma_beta_z.

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

fixed_parameters

Auxiliary parameters held constant on their natural scale, for instance {"quantile": 0.9}. A fixed parameter has no latent site or prior.

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

method

Inference algorithm.

TYPE: ('nuts', 'hmc', 'svi', 'fixed_param', 'pathfinder') DEFAULT: "nuts"

num_warmup

MCMC warmup iterations per chain (NUTS and HMC only); 500 when omitted.

TYPE: int or None DEFAULT: None

num_samples

MCMC draws kept per chain after warmup (NUTS and HMC only); 1000 when omitted.

TYPE: int or None DEFAULT: None

num_chains

MCMC chains (NUTS and HMC only), or Pathfinder paths as brms's chains; 4 when omitted.

TYPE: int or None DEFAULT: None

num_steps

SVI optimization steps (SVI only); 1000 when omitted.

TYPE: int or None DEFAULT: None

learning_rate

The Adam learning rate of the SVI optimizer (SVI only).

TYPE: float DEFAULT: 0.01

fixed_prior

Prior of every fixed-effect coefficient.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

random_scale_prior

Prior of every random-effect standard deviation.

TYPE: str DEFAULT: 'HalfNormal(1.0)'

correlation_prior

Default prior for correlated group blocks, in LKJ Cholesky form. Explicit shared IDs join coefficients across distributional formulas.

TYPE: str DEFAULT: 'LKJCholesky(1.0)'

group_covariances

Known covariance between labeled levels, keyed by grouping factor. The same declaration serves compilation, inspection, and prediction.

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

priors

Named overrides or typed selectors, including sampled shrinkage hierarchies. Unknown, unused, or ambiguous rules raise ValueError.

TYPE: PriorInput or None DEFAULT: None

guide

The SVI guide class; AutoNormalGuide when omitted.

TYPE: type or None DEFAULT: None

initial_values

Natural-scale starting values keyed by latent site, including coefficient names. Scalars broadcast to a site's declared shape. Values must lie strictly inside the prior support. MCMC applies these after its seeded initial strategy; SVI passes them to the guide constructor. A custom guide must accept this keyword when values are supplied. For a regressed shifted-lognormal or Wiener ndt with the log link and an intercept, default coefficient centers put the shift below the minimum observed response; explicit values override those centers. An unregressed learned Wiener delay starts at one quarter of the minimum reaction time, before explicit overrides.

TYPE: Mapping[str, Tensor or float] or None DEFAULT: None

reparameterize

Parameterization of the random effects.

TYPE: ('centered', 'noncentered') DEFAULT: "centered"

binomial_trials

Trials per row for binomial or beta-binomial responses: a constant or a column.

TYPE: int or str DEFAULT: None

thresholds_by

Column grouping the cutpoints of an ordinal family.

TYPE: str or None DEFAULT: None

mixture_components

Number of Gaussian components for the mixture family.

TYPE: int DEFAULT: 2

predictor

Optional differentiable contribution on the linear-predictor scale.

TYPE: Module or None DEFAULT: None

predictor_data

Input passed to predictor on each SVI step.

TYPE: Tensor or None DEFAULT: None

seed

Seed for compilation and inference. The caller's CPU random state is restored on return or failure.

TYPE: int DEFAULT: 0

sample_prior

Fit the posterior, additionally retain independent prior draws, or disable observation likelihoods during inference. Priors, their data dependencies, support constraints, and explicit potentials remain.

TYPE: ('no', 'yes', 'only') DEFAULT: "no"

num_prior_samples

Positive independent draw budget for mode "yes".

TYPE: int DEFAULT: 100

prior_seed

Isolated prior stream. None uses seed + 1 modulo 2**64. Retaining prior draws does not change fitted posterior draws or losses.

TYPE: int or None DEFAULT: None

snapshot_policy

Retain one independent original-data snapshot for update/refit by default. Reference mode shares caller data explicitly. Predictor initial states are copied before each refit, so fits do not share trained mutable parameters.

TYPE: ('clone', 'reference') DEFAULT: "clone"

default_priors

Default prior policy: the proper, autoscaled quivers defaults, or brms::default_prior (flat b; Student-t intercept, sd and sigma priors scaled by the response). Explicit priors win either way.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

center

brms bf(center = ): sample the intercept of the column-centered design and report b_Intercept = Intercept_c - mean(X) b. None centers under the brms policy only.

TYPE: bool or None DEFAULT: None

decomp

brms bf(decomp = "QR"): sample the location coefficients in scaled QR coordinates; class b priors act on those coordinates.

TYPE: ('none', 'QR') DEFAULT: "none"

cmc

brms cmc: with False, a formula without intercept keeps treatment coding (no cell-mean coding of its first factor).

TYPE: bool DEFAULT: True

sparse

brms sparse: the same model with centering disabled, as brms disables it for sparse designs; incompatible with decomp="QR".

TYPE: bool DEFAULT: False

unused

brms unused: further columns kept with the model rows, so rows missing them are excluded as for model variables.

TYPE: Sequence[str] DEFAULT: ()

control

brms control: adapt_delta (NUTS target acceptance), max_treedepth, initial stepsize, and metric (diag_e, dense_e, unit_e). MCMC only.

TYPE: SamplerControl or Mapping or None DEFAULT: None

thin

Keep every thin-th post-warmup transition; num_samples stays the retained draw count per chain. MCMC only.

TYPE: int DEFAULT: 1

init

brms init: "random" draws unconstrained starts uniformly from (-init_r, init_r), 0 or "0" starts at zero, a mapping gives named natural-scale starts, a list gives one mapping per chain, and a function of the one-based chain index returns one. None keeps the driver's seeded jitter. Formula starts and initial_values apply under every choice.

TYPE: str or float or Mapping or Sequence or Callable or None DEFAULT: None

init_r

Half-width of init = "random".

TYPE: float DEFAULT: 2.0

algorithm

brms algorithm: NUTS, SVI with a mean-field, full-rank, or Laplace guide, the fixed-parameter sampler, which keeps every draw at the initial values, or multi-path Pathfinder with num_chains paths.

TYPE: ('sampling', 'meanfield', 'fullrank', 'laplace', 'fixed_param', 'pathfinder') DEFAULT: "sampling"

file

brms file: load the fit saved there, or fit and save it there.

TYPE: str or Path or None DEFAULT: None

file_refit

brms file_refit: reuse a saved fit, always refit, or refit when the formula, data, priors, or settings differ from the saved recipe.

TYPE: ('never', 'always', 'on_change') DEFAULT: "never"

pathfinder

cmdstanr pathfinder arguments for algorithm="pathfinder" (draws, single_path_draws, history_size, max_lbfgs_iters, num_elbo_draws, psis_resample, calculate_lp, save_single_paths, init_alpha and the tol_* tolerances), which brms passes through its ....

TYPE: PathfinderOptions or Mapping or None DEFAULT: None

cores

brms cores: run the MCMC chains in up to this many worker processes. Each worker rebuilds the fit from the retained arguments and data and runs its share of the chains; the draws equal those of the serial run with the same seed. Every argument must be picklable.

TYPE: int DEFAULT: 1

knots

brms knots: knot values keyed by smooth covariate, passed to the cr, cs, cc, ps and bs constructors of s() as mgcv's smoothCon(knots = ) does.

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

drop_unused_levels

brms drop_unused_levels: with False, factor levels that no row uses keep their population columns (of zeros) and grouping-factor levels their group effects, as brms keeps them.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
BayesianFit or MultivariateFit

Parsed formula, compiled program, fitted posterior, and observations; a MultivariateFit for a joint formula.

RAISES DESCRIPTION
ValueError

If the family is unknown, a predictor and its data are not given together, a trainable predictor is used without SVI, or a count is given to a method it does not apply to (num_steps to NUTS or HMC; num_warmup, num_samples, or num_chains to SVI).

Source code in src/quivers/formulas/_fit.py
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
def fit(
    formula: str | ResponseModel | MultivariateFormula | None = None,
    *,
    data: IntoDataFrame,
    program: str | tuple[str | Path, str] | None = None,
    entry: str | None = None,
    static: Mapping[str, int] | None = None,
    parameters: Mapping[str, str | NonlinearExpression] | None = None,
    response: str | None = None,
    family: str | Family = "gaussian",
    weights: str | None = None,
    decision: str | None = None,
    data2: Mapping[str, AutocorMatrix] | None = None,
    distributional: Mapping[str, str | NonlinearExpression] | None = None,
    nonlinear: Mapping[str, str | NonlinearExpression] | None = None,
    fixed_parameters: Mapping[str, float] | None = None,
    method: FitMethod = "nuts",
    num_warmup: int | None = None,
    num_samples: int | None = None,
    num_chains: int | None = None,
    num_steps: int | None = None,
    learning_rate: float = 1e-2,
    fixed_prior: str = "Normal(0.0, 5.0)",
    random_scale_prior: str = "HalfNormal(1.0)",
    correlation_prior: str = "LKJCholesky(1.0)",
    group_covariances: Mapping[str, GroupCovariance] | None = None,
    priors: PriorInput | None = None,
    guide: type | None = None,
    initial_values: Mapping[str, torch.Tensor | float] | None = None,
    reparameterize: Literal["centered", "noncentered"] = "noncentered",
    binomial_trials: int | str | None = None,
    thresholds_by: str | None = None,
    mixture_components: int = 2,
    predictor: nn.Module | None = None,
    predictor_data: torch.Tensor | None = None,
    seed: int = 0,
    sample_prior: PriorMode = "no",
    num_prior_samples: int = 100,
    prior_seed: int | None = None,
    snapshot_policy: SnapshotPolicy = "clone",
    default_priors: DefaultPriorPolicy = "quivers",
    center: bool | None = None,
    decomp: Literal["none", "QR"] = "none",
    cmc: bool = True,
    sparse: bool = False,
    unused: Sequence[str] = (),
    control: SamplerControl | Mapping[str, float | int | str] | None = None,
    thin: int = 1,
    init: InitSpec | None = None,
    init_r: float = 2.0,
    algorithm: Algorithm | None = None,
    file: str | Path | None = None,
    file_refit: FileRefit = "never",
    pathfinder: PathfinderOptions | Mapping[str, float | int | bool] | None = None,
    cores: int = 1,
    knots: Knots | None = None,
    drop_unused_levels: bool = True,
) -> BayesianFit | _joint_fit.MultivariateFit:
    """Compile a brms-style formula, fit it, and return the result.

    See [`quivers.formulas`][quivers.formulas] for surface details.  This entry
    point composes `formula_from_data`, `FormulaToQVRModule`,
    `Compiler`, and the inference layer in one call.

    ``family="categorical"`` uses the sorted distinct integer labels or the
    declared factor levels and takes the first category as the default
    reference. An attached categorical predictor may return
    ``(N, K-1)`` reference logits or ``(N, K)`` full logits. For
    ``family="mixture"``, ``mixture_components`` selects any finite component
    count of at least two; the likelihood integrates assignments exactly.

    Parameters
    ----------
    formula : str or ResponseModel or MultivariateFormula or None
        brms/lme4-style response formula, or a joint formula built with
        `bf` (``bf("mvbind(y1, y2) ~ x")`` or ``bf(...) + bf(...)``), which
        returns a `MultivariateFit`. Response-level keywords then belong
        to each `bf` call. A single-response ``bf("y ~ x", "sigma ~ z")``
        is fitted as the string formula with the response keywords it
        carries; a keyword given both there and here with different values
        raises. None for a program, given by ``program=``.
    data : IntoDataFrame
        Pandas, Polars, or another Narwhals-compatible dataframe.
    program : str or tuple[str or Path, str] or None
        QVR source, or a source file path and a program name. With source
        text alone, the one program or the one exported program is selected.
        The program's observation of ``response`` is the likelihood, and its
        domain is the rows of the data. Every sample site and input that ``parameters``
        names is replaced by a regression on the link scale its support
        requires; every other site keeps the program's own law. Data the
        program reads at each row are data columns of the same name; data on
        another axis and scalars come from ``data2``.
    entry : str or None
        The program name when it is given separately from the source text.
    static : Mapping[str, int] or None
        Finite extents of the program, by binder name.
    parameters : Mapping[str, str or NonlinearExpression] or None
        Formulas of the program's parameters, as ``{"noise": "~ 1 + (1 | g)"}``.
        A `NonlinearExpression` gives a link-scale expression and can read
        additional parameter formulas in the mapping. Priors of the program's
        parameter formulas use ``dpar=<parameter>``.
    response : str or None
        The site the program observes, a data column.
    family : str or Family
        Registered response family or a family value. ``Family.with_links``
        selects location or auxiliary inverse links.
    weights : str or None
        Numeric column of finite nonnegative likelihood weights. Values
        multiply each response's log density, retain their original scale,
        and do not weight priors or posterior predictions.
    decision : str or None
        Wiener boundary-choice column: numeric zero/lower or one/upper, or
        the labels lower and upper. Equivalent to response-side dec(column).
    nonlinear : Mapping[str, str or NonlinearExpression] or None
        Named additive parameter designs or deterministic QVR expressions.
        Supplying this mapping interprets the response RHS as a value
        expression. Defaults retain the same proper coefficient priors as
        ordinary QVR formulas; get_prior reports their exact site names.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Named matrices referenced by autocorrelation terms, as in brms:
        the spatial weights of ``sar(M)`` and the fixed covariance of
        ``fcor(M)``, each over the included response rows. A group-level
        ``gr(g, cov = M)`` reads a labeled ``DataFrame`` covariance between
        the levels of ``g``, and ``s(g, bs = "mrf", xt = list(penalty = M))``
        a penalty or neighbourhood matrix over them.
    distributional : Mapping[str, str or NonlinearExpression] or None
        Auxiliary-parameter formulas, for instance
        ``{"sigma": "~ z + (1 | g)"}``. The optional left-hand side must
        match the parameter name. Coefficient prior overrides use names
        such as ``dpar_sigma_intercept`` and ``dpar_sigma_beta_z``.
    fixed_parameters : Mapping[str, float] or None
        Auxiliary parameters held constant on their natural scale, for instance
        ``{"quantile": 0.9}``. A fixed parameter has no latent site or prior.
    method : {"nuts", "hmc", "svi", "fixed_param", "pathfinder"}
        Inference algorithm.
    num_warmup : int or None
        MCMC warmup iterations per chain (NUTS and HMC only); 500 when
        omitted.
    num_samples : int or None
        MCMC draws kept per chain after warmup (NUTS and HMC only); 1000
        when omitted.
    num_chains : int or None
        MCMC chains (NUTS and HMC only), or Pathfinder paths as brms's
        ``chains``; 4 when omitted.
    num_steps : int or None
        SVI optimization steps (SVI only); 1000 when omitted.
    learning_rate : float
        The Adam learning rate of the SVI optimizer (SVI only).
    fixed_prior : str
        Prior of every fixed-effect coefficient.
    random_scale_prior : str
        Prior of every random-effect standard deviation.
    correlation_prior : str
        Default prior for correlated group blocks, in LKJ Cholesky form.
        Explicit shared IDs join coefficients across distributional formulas.
    group_covariances : Mapping[str, GroupCovariance] or None
        Known covariance between labeled levels, keyed by grouping factor.
        The same declaration serves compilation, inspection, and prediction.
    priors : PriorInput or None
        Named overrides or typed selectors, including sampled shrinkage
        hierarchies. Unknown, unused, or ambiguous rules raise ValueError.
    guide : type or None
        The SVI guide class; `AutoNormalGuide` when omitted.
    initial_values : Mapping[str, torch.Tensor or float] or None
        Natural-scale starting values keyed by latent site, including
        coefficient names. Scalars broadcast to a site's declared shape.
        Values must lie strictly inside the prior support. MCMC applies
        these after its seeded initial strategy; SVI passes them to the
        guide constructor. A custom guide must accept this keyword when
        values are supplied. For a regressed shifted-lognormal or Wiener ``ndt``
        with the log link and an intercept, default coefficient centers put the shift below
        the minimum observed response; explicit values override those centers.
        An unregressed learned Wiener delay starts at one quarter of the
        minimum reaction time, before explicit overrides.
    reparameterize : {"centered", "noncentered"}
        Parameterization of the random effects.
    binomial_trials : int or str
        Trials per row for binomial or beta-binomial responses: a constant or a column.
    thresholds_by : str or None
        Column grouping the cutpoints of an ordinal family.
    mixture_components : int
        Number of Gaussian components for the mixture family.
    predictor : nn.Module or None
        Optional differentiable contribution on the linear-predictor scale.
    predictor_data : torch.Tensor or None
        Input passed to ``predictor`` on each SVI step.
    seed : int
        Seed for compilation and inference. The caller's CPU random state
        is restored on return or failure.
    sample_prior : {"no", "yes", "only"}
        Fit the posterior, additionally retain independent prior draws, or
        disable observation likelihoods during inference. Priors, their data
        dependencies, support constraints, and explicit potentials remain.
    num_prior_samples : int
        Positive independent draw budget for mode "yes".
    prior_seed : int or None
        Isolated prior stream. None uses seed + 1 modulo 2**64. Retaining
        prior draws does not change fitted posterior draws or losses.

    snapshot_policy : {"clone", "reference"}
        Retain one independent original-data snapshot for update/refit by default.
        Reference mode shares caller data explicitly. Predictor initial states are
        copied before each refit, so fits do not share trained mutable parameters.
    default_priors : {"quivers", "brms"}
        Default prior policy: the proper, autoscaled quivers defaults, or
        ``brms::default_prior`` (flat ``b``; Student-t intercept, ``sd`` and
        ``sigma`` priors scaled by the response). Explicit priors win either way.
    center : bool or None
        brms ``bf(center = )``: sample the intercept of the column-centered
        design and report ``b_Intercept = Intercept_c - mean(X) b``. None
        centers under the brms policy only.
    decomp : {"none", "QR"}
        brms ``bf(decomp = "QR")``: sample the location coefficients in scaled
        QR coordinates; class ``b`` priors act on those coordinates.
    cmc : bool
        brms ``cmc``: with False, a formula without intercept keeps treatment
        coding (no cell-mean coding of its first factor).
    sparse : bool
        brms ``sparse``: the same model with centering disabled, as brms
        disables it for sparse designs; incompatible with ``decomp="QR"``.
    unused : Sequence[str]
        brms ``unused``: further columns kept with the model rows, so rows
        missing them are excluded as for model variables.
    control : SamplerControl or Mapping or None
        brms ``control``: ``adapt_delta`` (NUTS target acceptance),
        ``max_treedepth``, initial ``stepsize``, and ``metric`` (``diag_e``,
        ``dense_e``, ``unit_e``). MCMC only.
    thin : int
        Keep every ``thin``-th post-warmup transition; ``num_samples`` stays
        the retained draw count per chain. MCMC only.
    init : str or float or Mapping or Sequence or Callable or None
        brms ``init``: ``"random"`` draws unconstrained starts uniformly from
        ``(-init_r, init_r)``, ``0`` or ``"0"`` starts at zero, a mapping
        gives named natural-scale starts, a list gives one mapping per chain,
        and a function of the one-based chain index returns one. None keeps
        the driver's seeded jitter. Formula starts and ``initial_values``
        apply under every choice.
    init_r : float
        Half-width of ``init = "random"``.
    algorithm : {"sampling", "meanfield", "fullrank", "laplace", "fixed_param", "pathfinder"} or None
        brms ``algorithm``: NUTS, SVI with a mean-field, full-rank, or Laplace
        guide, the fixed-parameter sampler, which keeps every draw at the
        initial values, or multi-path Pathfinder with ``num_chains`` paths.
    file : str or Path or None
        brms ``file``: load the fit saved there, or fit and save it there.
    file_refit : {"never", "always", "on_change"}
        brms ``file_refit``: reuse a saved fit, always refit, or refit when the
        formula, data, priors, or settings differ from the saved recipe.
    pathfinder : PathfinderOptions or Mapping or None
        cmdstanr ``pathfinder`` arguments for ``algorithm="pathfinder"``
        (``draws``, ``single_path_draws``, ``history_size``,
        ``max_lbfgs_iters``, ``num_elbo_draws``, ``psis_resample``,
        ``calculate_lp``, ``save_single_paths``, ``init_alpha`` and the
        ``tol_*`` tolerances), which brms passes through its ``...``.
    cores : int
        brms ``cores``: run the MCMC chains in up to this many worker
        processes. Each worker rebuilds the fit from the retained arguments
        and data and runs its share of the chains; the draws equal those of
        the serial run with the same seed. Every argument must be picklable.
    knots : Mapping[str, Sequence[float]] or None
        brms ``knots``: knot values keyed by smooth covariate, passed to the
        ``cr``, ``cs``, ``cc``, ``ps`` and ``bs`` constructors of ``s()`` as
        mgcv's ``smoothCon(knots = )`` does.
    drop_unused_levels : bool
        brms ``drop_unused_levels``: with False, factor levels that no row
        uses keep their population columns (of zeros) and grouping-factor
        levels their group effects, as brms keeps them.

    Returns
    -------
    BayesianFit or MultivariateFit
        Parsed formula, compiled program, fitted posterior, and observations;
        a `MultivariateFit` for a joint formula.

    Raises
    ------
    ValueError
        If the family is unknown, a predictor and its data are not given
        together, a trainable predictor is used without SVI, or a count
        is given to a method it does not apply to (``num_steps`` to NUTS
        or HMC; ``num_warmup``, ``num_samples``, or ``num_chains`` to
        SVI).
    """
    from quivers.formulas._refit import capture_recipe

    # A single-response bf carries the response keywords of this call.
    if isinstance(formula, ResponseModel):
        authored = single_response(
            formula,
            family=family,
            distributional=distributional,
            nonlinear=nonlinear,
            fixed_parameters=fixed_parameters,
            weights=weights,
            decision=decision,
            binomial_trials=binomial_trials,
            thresholds_by=thresholds_by,
            mixture_components=mixture_components,
            center=center,
            decomp=decomp,
            cmc=cmc,
            sparse=sparse,
            unused=unused,
            caller="fit",
        )
        formula, family = authored["formula"], authored["family"]
        distributional = authored["distributional"]
        nonlinear = authored["nonlinear"]
        fixed_parameters = authored["fixed_parameters"]
        weights, decision = authored["weights"], authored["decision"]
        binomial_trials = authored["binomial_trials"]
        thresholds_by = authored["thresholds_by"]
        mixture_components = authored["mixture_components"]
        center, decomp = authored["center"], authored["decomp"]
        cmc, sparse = authored["cmc"], authored["sparse"]
        unused = authored["unused"]
    # An existing artifact with file_refit="never" needs no program file.
    if file is not None and file_refit == "never" and Path(file).exists():
        return cast(
            "BayesianFit | _joint_fit.MultivariateFit", artifact_store.load_fit(file)
        )
    if program is not None:
        program, entry = program_source(program, entry)
    # brms file / file_refit: reuse or refresh a fit in the artifact store.
    if file is not None:
        arguments = {
            name: value
            for name, value in locals().items()
            if name in _FIT_ARGUMENTS and name not in {"file", "file_refit"}
        }
        if not needs_refit(Path(file), file_refit, arguments):
            return cast(
                "BayesianFit | _joint_fit.MultivariateFit",
                artifact_store.load_fit(file),
            )
        result = fit(**arguments)
        artifact_store.save_fit(result, file)
        return result
    # brms algorithm selects the method and guide.
    method, guide = resolve_algorithm(algorithm, method, guide)
    controls = InferenceControls(
        control=sampler_control(control),
        thin=thin,
        init=init,
        init_r=init_r,
        pathfinder=pathfinder_options(pathfinder),
    )
    refit_recipe = capture_recipe(
        fit, data=data, arguments=locals(), snapshot_policy=snapshot_policy
    )
    # brms cores: workers rebuild the fit from the recipe.
    if checked_cores(cores) != 1:
        controls = controls.with_(
            cores=cores,
            chain_worker=FormulaChainWorker(
                arguments=dict(refit_recipe.method), data=refit_recipe._data
            ),
        )
    from quivers.modeling.refit import _snapshot

    preparation_data = (
        refit_recipe._data if snapshot_policy == "clone" else _snapshot(data)
    )
    with torch.random.fork_rng(devices=[]):
        torch.random.set_rng_state(torch.Generator().manual_seed(seed).get_state())
        # Joint (multivariate) formulas share the recipe and inference seam.
        if isinstance(formula, MultivariateFormula):
            return _joint_fit.fit_entry(
                formula, preparation_data, refit_recipe.method, refit_recipe
            )
        formula, family, distributional = program_arguments(
            formula,
            program=program,
            entry=entry,
            static=static,
            parameters=parameters,
            response=response,
            family=family,
            distributional=distributional,
            nonlinear=nonlinear,
            fixed_parameters=fixed_parameters,
            caller="fit",
        )
        _refuse_joint_syntax(formula, "fit")
        if method == "svi":
            given = [
                name
                for name, value in (
                    ("num_warmup", num_warmup),
                    ("num_samples", num_samples),
                    ("num_chains", num_chains),
                )
                if value is not None
            ]
            if given:
                raise ValueError(
                    f"fit: {', '.join(given)} count MCMC iterations, and "
                    "method='svi' runs none; give the optimization steps as "
                    "num_steps"
                )
        elif method != "pathfinder" and num_steps is not None:
            raise ValueError(
                f"fit: num_steps counts SVI optimization steps, and method={method!r} "
                "runs MCMC; give num_warmup, num_samples, and num_chains"
            )
        predictor_name = "neural_eta" if predictor is not None else None
        prepared = _prepare_formula(
            formula,
            data=preparation_data,
            family=family,
            weights=weights,
            decision=decision,
            data2=data2,
            distributional=distributional,
            nonlinear=nonlinear,
            fixed_parameters=fixed_parameters,
            fixed_prior=fixed_prior,
            random_scale_prior=random_scale_prior,
            correlation_prior=correlation_prior,
            group_covariances=group_covariances,
            priors=priors,
            reparameterize=reparameterize,
            binomial_trials=binomial_trials,
            thresholds_by=thresholds_by,
            mixture_components=mixture_components,
            predictor_name=predictor_name,
            caller="fit",
            allow_missing=True,
            default_priors=default_priors,
            center=center,
            decomp=decomp,
            cmc=cmc,
            sparse=sparse,
            unused=unused,
            knots=knots,
            drop_unused_levels=drop_unused_levels,
        )
        native = _prepare_fit(
            prepared,
            predictor=predictor,
            predictor_data=predictor_data,
            method=method,
            preparation_data=preparation_data,
        )
        # brms refuses prior sampling with improper flat priors.
        if sample_prior != "no":
            require_proper(native.module, f"sample_prior={sample_prior!r}")
        result = _run_inference(
            native.program,
            native.observations,
            method=method,
            num_steps=num_steps,
            num_warmup=num_warmup,
            num_samples=num_samples,
            num_chains=num_chains,
            learning_rate=learning_rate,
            seed=seed,
            guide=guide,
            sample_prior=sample_prior,
            num_prior_samples=num_prior_samples,
            prior_seed=prior_seed,
            predictor=native.predictor,
            predictor_data=native.predictor_data,
            predictor_name=native.predictor_name,
            predictor_categories=native.predictor_categories,
            predictor_reference=native.predictor_reference,
            initial_values=_initial_values(prepared, fixed_parameters, initial_values),
            controls=controls,
        )
        return _assemble_fit(
            native,
            result,
            refit_recipe=refit_recipe,
            reparameterize=reparameterize,
            thresholds_by=thresholds_by,
            mixture_components=mixture_components,
            fixed_prior=fixed_prior,
            random_scale_prior=random_scale_prior,
            correlation_prior=correlation_prior,
            group_covariances=group_covariances,
            priors=priors,
            fixed_parameters=fixed_parameters,
            default_priors=default_priors,
            center=center,
            decomp=decomp,
            cmc=cmc,
            sparse=sparse,
            unused=unused,
        )

formula_to_qvr

formula_to_qvr(formula: str | ResponseModel | MultivariateFormula | None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str] | None = None, entry: str | None = None, static: Mapping[str, int] | None = None, parameters: Mapping[str, str | NonlinearExpression] | None = None, response: str | None = None, family: str | Family = 'gaussian', weights: str | None = None, decision: str | None = None, data2: Mapping[str, AutocorMatrix] | None = None, distributional: Mapping[str, str | NonlinearExpression] | None = None, nonlinear: Mapping[str, str | NonlinearExpression] | None = None, fixed_parameters: Mapping[str, float] | None = None, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, priors: PriorInput | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor_name: str | None = None, default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: Sequence[str] = (), path: str | Path | None = None, knots: Knots | None = None, drop_unused_levels: bool = True) -> str

Emit .qvr source for a brms-style formula without fitting.

Builds the formula AST → QVR Module via FormulaToQVRModule, then serialises the module via quivers.dsl.emit.module_to_source. Optionally writes the result to path. mixture_components selects any integer component count of at least two for family="mixture". distributional maps auxiliary names to formulas, for instance {"sigma": "~ z"}; the corresponding linked predictors are emitted in the same QVR program as the location formula. fixed_parameters instead binds auxiliary parameters to constants on their natural scale. weights="column" retains nonnegative likelihood weights and emits them only on the response observation; priors and predictions are unweighted. decision="column" or rt | dec(column) ~ predictors retains a Wiener boundary choice alongside positive reaction times. Emitted source visibly adapts raw times and Boolean choices to a lossless signed response.

PARAMETER DESCRIPTION
formula

Authored formula over original dataframe rows, a single-response bf carrying its response keywords, or a joint formula whose one composed program is emitted; None for a program.

TYPE: str or ResponseModel or MultivariateFormula or None DEFAULT: None

data

Original training columns, including response modifiers.

TYPE: IntoDataFrame

program

QVR source, or a source file path and a program name, as in fit.

TYPE: str or tuple[str or Path, str] or None DEFAULT: None

entry

The program name when it is given separately from the source text.

TYPE: str or None DEFAULT: None

static

Finite extents of the program, by binder name.

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

parameters

Formulas of the program's parameters, by name.

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

response

The site the program observes.

TYPE: str or None DEFAULT: None

family

Checked response law and retained link, threshold, and event choices.

TYPE: str or Family DEFAULT: 'gaussian'

weights

Optional existing response-role columns.

TYPE: str or None DEFAULT: None

decision

Optional existing response-role columns.

TYPE: str or None DEFAULT: None

data2

Named matrices referenced by autocorrelation terms, as in brms: the spatial weights of sar(M) and the fixed covariance of fcor(M), each over the included response rows. A group-level gr(g, cov = M) reads a labeled DataFrame covariance between the levels of g.

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

distributional

Auxiliary designs and checked derived predictor graph.

TYPE: Mapping or None DEFAULT: None

nonlinear

Auxiliary designs and checked derived predictor graph.

TYPE: Mapping or None DEFAULT: None

fixed_parameters

Bound auxiliary constants.

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

fixed_prior

Defaults consumed by the existing typed prior catalog.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

random_scale_prior

Defaults consumed by the existing typed prior catalog.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

correlation_prior

Defaults consumed by the existing typed prior catalog.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

group_covariances

Known group covariance structures.

TYPE: Mapping or None DEFAULT: None

priors

Typed selectors or existing exact-name overrides.

TYPE: PriorInput or None DEFAULT: None

reparameterize

Shared group coordinate policy.

TYPE: ('centered', 'noncentered') DEFAULT: "centered"

binomial_trials

Finite-trial count or retained column.

TYPE: int or str or None DEFAULT: None

thresholds_by

Group with an identified full threshold profile.

TYPE: str or None DEFAULT: None

mixture_components

Finite-mixture component count.

TYPE: int DEFAULT: 2

predictor_name

Checked external neural binding.

TYPE: str or None DEFAULT: None

default_priors

Default prior policy: the proper, autoscaled quivers defaults, or brms::default_prior (flat b; Student-t intercept, sd and sigma priors scaled by the response). Explicit priors win either way.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

center

brms bf(center = ): sample the intercept of the column-centered design and report b_Intercept = Intercept_c - mean(X) b. None centers under the brms policy only.

TYPE: bool or None DEFAULT: None

decomp

brms bf(decomp = "QR"): sample the location coefficients in scaled QR coordinates; class b priors act on those coordinates.

TYPE: ('none', 'QR') DEFAULT: "none"

cmc

brms cmc: with False, a formula without intercept keeps treatment coding (no cell-mean coding of its first factor).

TYPE: bool DEFAULT: True

sparse

brms sparse: the same model with centering disabled, as brms disables it for sparse designs; incompatible with decomp="QR".

TYPE: bool DEFAULT: False

unused

brms unused: further columns kept with the model rows, so rows missing them are excluded as for model variables.

TYPE: Sequence[str] DEFAULT: ()

knots

brms knots: knot values keyed by smooth covariate, passed to the cr, cs, cc, ps and bs constructors of s() as mgcv's smoothCon(knots = ) does.

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

drop_unused_levels

brms drop_unused_levels: with False, factor levels that no row uses keep their population columns (of zeros) and grouping-factor levels their group effects, as brms keeps them.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
str

Canonical checked source, without fitting a posterior.

Source code in src/quivers/formulas/_fit.py
def formula_to_qvr(
    formula: str | ResponseModel | MultivariateFormula | None = None,
    *,
    data: IntoDataFrame,
    program: str | tuple[str | Path, str] | None = None,
    entry: str | None = None,
    static: Mapping[str, int] | None = None,
    parameters: Mapping[str, str | NonlinearExpression] | None = None,
    response: str | None = None,
    family: str | Family = "gaussian",
    weights: str | None = None,
    decision: str | None = None,
    data2: Mapping[str, AutocorMatrix] | None = None,
    distributional: Mapping[str, str | NonlinearExpression] | None = None,
    nonlinear: Mapping[str, str | NonlinearExpression] | None = None,
    fixed_parameters: Mapping[str, float] | None = None,
    fixed_prior: str = "Normal(0.0, 5.0)",
    random_scale_prior: str = "HalfNormal(1.0)",
    correlation_prior: str = "LKJCholesky(1.0)",
    group_covariances: Mapping[str, GroupCovariance] | None = None,
    priors: PriorInput | None = None,
    reparameterize: Literal["centered", "noncentered"] = "noncentered",
    binomial_trials: int | str | None = None,
    thresholds_by: str | None = None,
    mixture_components: int = 2,
    predictor_name: str | None = None,
    default_priors: DefaultPriorPolicy = "quivers",
    center: bool | None = None,
    decomp: Literal["none", "QR"] = "none",
    cmc: bool = True,
    sparse: bool = False,
    unused: Sequence[str] = (),
    path: str | Path | None = None,
    knots: Knots | None = None,
    drop_unused_levels: bool = True,
) -> str:
    """Emit ``.qvr`` source for a brms-style formula without fitting.

    Builds the formula AST → QVR Module via `FormulaToQVRModule`,
    then serialises the module via [`quivers.dsl.emit.module_to_source`][quivers.dsl.emit.module_to_source].
    Optionally writes the result to ``path``. ``mixture_components`` selects
    any integer component count of at least two for ``family="mixture"``.
    ``distributional`` maps auxiliary names to formulas, for instance
    ``{"sigma": "~ z"}``; the corresponding linked predictors are emitted
    in the same QVR program as the location formula. ``fixed_parameters``
    instead binds auxiliary parameters to constants on their natural scale.
    ``weights="column"`` retains nonnegative likelihood weights and emits
    them only on the response observation; priors and predictions are unweighted.
    ``decision="column"`` or ``rt | dec(column) ~ predictors`` retains a Wiener
    boundary choice alongside positive reaction times. Emitted source visibly
    adapts raw times and Boolean choices to a lossless signed response.

    Parameters
    ----------
    formula : str or ResponseModel or MultivariateFormula or None
        Authored formula over original dataframe rows, a single-response
        `bf` carrying its response keywords, or a joint formula whose one
        composed program is emitted; None for a program.
    data : IntoDataFrame
        Original training columns, including response modifiers.
    program : str or tuple[str or Path, str] or None
        QVR source, or a source file path and a program name, as in `fit`.
    entry : str or None
        The program name when it is given separately from the source text.
    static : Mapping[str, int] or None
        Finite extents of the program, by binder name.
    parameters : Mapping[str, str or NonlinearExpression] or None
        Formulas of the program's parameters, by name.
    response : str or None
        The site the program observes.
    family : str or Family
        Checked response law and retained link, threshold, and event choices.
    weights, decision : str or None
        Optional existing response-role columns.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Named matrices referenced by autocorrelation terms, as in brms:
        the spatial weights of ``sar(M)`` and the fixed covariance of
        ``fcor(M)``, each over the included response rows. A group-level
        ``gr(g, cov = M)`` reads a labeled ``DataFrame`` covariance between
        the levels of ``g``.
    distributional, nonlinear : Mapping or None
        Auxiliary designs and checked derived predictor graph.
    fixed_parameters : Mapping[str, float] or None
        Bound auxiliary constants.
    fixed_prior, random_scale_prior, correlation_prior : str
        Defaults consumed by the existing typed prior catalog.
    group_covariances : Mapping or None
        Known group covariance structures.
    priors : PriorInput or None
        Typed selectors or existing exact-name overrides.
    reparameterize : {"centered", "noncentered"}
        Shared group coordinate policy.
    binomial_trials : int or str or None
        Finite-trial count or retained column.
    thresholds_by : str or None
        Group with an identified full threshold profile.
    mixture_components : int
        Finite-mixture component count.
    predictor_name : str or None
        Checked external neural binding.

    default_priors : {"quivers", "brms"}
        Default prior policy: the proper, autoscaled quivers defaults, or
        ``brms::default_prior`` (flat ``b``; Student-t intercept, ``sd`` and
        ``sigma`` priors scaled by the response). Explicit priors win either way.
    center : bool or None
        brms ``bf(center = )``: sample the intercept of the column-centered
        design and report ``b_Intercept = Intercept_c - mean(X) b``. None
        centers under the brms policy only.
    decomp : {"none", "QR"}
        brms ``bf(decomp = "QR")``: sample the location coefficients in scaled
        QR coordinates; class ``b`` priors act on those coordinates.
    cmc : bool
        brms ``cmc``: with False, a formula without intercept keeps treatment
        coding (no cell-mean coding of its first factor).
    sparse : bool
        brms ``sparse``: the same model with centering disabled, as brms
        disables it for sparse designs; incompatible with ``decomp="QR"``.
    unused : Sequence[str]
        brms ``unused``: further columns kept with the model rows, so rows
        missing them are excluded as for model variables.
    knots : Mapping[str, Sequence[float]] or None
        brms ``knots``: knot values keyed by smooth covariate, passed to the
        ``cr``, ``cs``, ``cc``, ``ps`` and ``bs`` constructors of ``s()`` as
        mgcv's ``smoothCon(knots = )`` does.
    drop_unused_levels : bool
        brms ``drop_unused_levels``: with False, factor levels that no row
        uses keep their population columns (of zeros) and grouping-factor
        levels their group effects, as brms keeps them.
    Returns
    -------
    str
        Canonical checked source, without fitting a posterior.
    """
    # Joint (multivariate) formulas emit one composed program.
    if isinstance(formula, MultivariateFormula):
        with formula_data_options(knots, drop_unused_levels):
            module, _ = _joint_fit.joint_module(
                formula.with_default_priors(default_priors),
                data,
                fixed_prior=fixed_prior,
                random_scale_prior=random_scale_prior,
                correlation_prior=correlation_prior,
                group_covariances=group_covariances,
                priors=priors,
                reparameterize=reparameterize,
                data2=data2,
            )
        source = module_to_source(module)
        if path is not None:
            Path(path).write_text(source)
        return source
    formula, family, distributional = program_arguments(
        formula,
        program=program,
        entry=entry,
        static=static,
        parameters=parameters,
        response=response,
        family=family,
        distributional=distributional,
        nonlinear=nonlinear,
        fixed_parameters=fixed_parameters,
        caller="formula_to_qvr",
    )
    _refuse_joint_syntax(formula, "formula_to_qvr")
    prepared = _prepare_formula_entry(
        formula,
        data=data,
        family=family,
        weights=weights,
        decision=decision,
        data2=data2,
        distributional=distributional,
        nonlinear=nonlinear,
        fixed_parameters=fixed_parameters,
        fixed_prior=fixed_prior,
        random_scale_prior=random_scale_prior,
        correlation_prior=correlation_prior,
        group_covariances=group_covariances,
        priors=priors,
        reparameterize=reparameterize,
        binomial_trials=binomial_trials,
        thresholds_by=thresholds_by,
        mixture_components=mixture_components,
        predictor_name=predictor_name,
        default_priors=default_priors,
        center=center,
        decomp=decomp,
        cmc=cmc,
        sparse=sparse,
        unused=unused,
        knots=knots,
        drop_unused_levels=drop_unused_levels,
    )
    if prepared.missing is None:
        module, _ = prepared.lens.forward(prepared.formula)
    else:
        module = prepared.missing.emission.module
    source = module_to_source(module)
    if path is not None:
        Path(path).write_text(source)
    return source

get_prior

get_prior(formula: str | ResponseModel | MultivariateFormula | None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str] | None = None, entry: str | None = None, static: Mapping[str, int] | None = None, parameters: Mapping[str, str | NonlinearExpression] | None = None, response: str | None = None, family: str | Family = 'gaussian', weights: str | None = None, decision: str | None = None, data2: Mapping[str, AutocorMatrix] | None = None, distributional: Mapping[str, str | NonlinearExpression] | None = None, nonlinear: Mapping[str, str | NonlinearExpression] | None = None, fixed_parameters: Mapping[str, float] | None = None, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, priors: PriorInput | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor_name: str | None = None, default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: Sequence[str] = (), knots: Knots | None = None, drop_unused_levels: bool = True) -> dict[str, str]

Return effective named priors without running inference.

The arguments match formula_to_qvr, except for its output path. Priors reflect evaluated design columns, selected links, distributional formulas, group correlations, and explicit overrides. Default coefficient scales include column autoscaling; explicit overrides are emitted as given.

PARAMETER DESCRIPTION
formula

Response formula in brms/lme4 notation, a single-response bf carrying its response keywords, or a joint formula whose namespaced sites (response_<resp>__..., rescor) are listed; None for a program.

TYPE: str or ResponseModel or MultivariateFormula or None DEFAULT: None

data

Rows used to evaluate design matrices and autoscale default priors.

TYPE: IntoDataFrame

program

QVR source, or a source file path and a program name, as in fit.

TYPE: str or tuple[str or Path, str] or None DEFAULT: None

entry

The program name when it is given separately from the source text.

TYPE: str or None DEFAULT: None

static

Finite extents of the program, by binder name.

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

parameters

Formulas of the program's parameters, by name.

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

response

The site the program observes.

TYPE: str or None DEFAULT: None

family

Registered response family or a family value with selected links.

TYPE: str or Family DEFAULT: 'gaussian'

weights

Numeric column of finite nonnegative likelihood weights. Values multiply each response's log density, retain their original scale, and do not weight priors or posterior predictions.

TYPE: str or None DEFAULT: None

decision

Wiener boundary-choice column, equivalent to response-side dec(column). Numeric codes must be exactly zero/lower or one/upper.

TYPE: str or None DEFAULT: None

data2

Named matrices referenced by autocorrelation terms, as in brms: the spatial weights of sar(M) and the fixed covariance of fcor(M), each over the included response rows. A group-level gr(g, cov = M) reads a labeled DataFrame covariance between the levels of g.

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

distributional

Separate formulas for auxiliary parameters.

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

fixed_parameters

Auxiliary parameters held constant; these have no prior entries.

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

fixed_prior

Default coefficient, group-scale, and LKJ Cholesky priors.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

random_scale_prior

Default coefficient, group-scale, and LKJ Cholesky priors.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

correlation_prior

Default coefficient, group-scale, and LKJ Cholesky priors.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

group_covariances

Known covariance between labeled levels, keyed by grouping factor. The same declaration serves compilation, inspection, and prediction.

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

priors

Named overrides or typed selectors, including sampled shrinkage hierarchies. Unknown, unused, or ambiguous rules raise ValueError.

TYPE: PriorInput or None DEFAULT: None

reparameterize

Group parameterization; its conditional draws are not overrideable.

TYPE: ('centered', 'noncentered') DEFAULT: "centered"

binomial_trials

Fixed trial count or a column of counts.

TYPE: int or str DEFAULT: None

thresholds_by

Grouping column for ordinal cutpoints.

TYPE: str or None DEFAULT: None

mixture_components

Number of Gaussian mixture components.

TYPE: int DEFAULT: 2

predictor_name

External contribution on the linear-predictor scale.

TYPE: str or None DEFAULT: None

default_priors

Default prior policy: the proper, autoscaled quivers defaults, or brms::default_prior (flat b; Student-t intercept, sd and sigma priors scaled by the response). Explicit priors win either way.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

center

brms bf(center = ): sample the intercept of the column-centered design and report b_Intercept = Intercept_c - mean(X) b. None centers under the brms policy only.

TYPE: bool or None DEFAULT: None

decomp

brms bf(decomp = "QR"): sample the location coefficients in scaled QR coordinates; class b priors act on those coordinates.

TYPE: ('none', 'QR') DEFAULT: "none"

cmc

brms cmc: with False, a formula without intercept keeps treatment coding (no cell-mean coding of its first factor).

TYPE: bool DEFAULT: True

sparse

brms sparse: the same model with centering disabled, as brms disables it for sparse designs; incompatible with decomp="QR".

TYPE: bool DEFAULT: False

unused

brms unused: further columns kept with the model rows, so rows missing them are excluded as for model variables.

TYPE: Sequence[str] DEFAULT: ()

knots

brms knots: knot values keyed by smooth covariate, passed to the cr, cs, cc, ps and bs constructors of s() as mgcv's smoothCon(knots = ) does.

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

drop_unused_levels

brms drop_unused_levels: with False, factor levels that no row uses keep their population columns (of zeros) and grouping-factor levels their group effects, as brms keeps them.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
dict[str, str]

Actual overrideable site names and canonical prior calls.

RAISES DESCRIPTION
ValueError

If a formula or family setting is invalid, or a prior is unused.

Source code in src/quivers/formulas/_fit.py
def get_prior(
    formula: str | ResponseModel | MultivariateFormula | None = None,
    *,
    data: IntoDataFrame,
    program: str | tuple[str | Path, str] | None = None,
    entry: str | None = None,
    static: Mapping[str, int] | None = None,
    parameters: Mapping[str, str | NonlinearExpression] | None = None,
    response: str | None = None,
    family: str | Family = "gaussian",
    weights: str | None = None,
    decision: str | None = None,
    data2: Mapping[str, AutocorMatrix] | None = None,
    distributional: Mapping[str, str | NonlinearExpression] | None = None,
    nonlinear: Mapping[str, str | NonlinearExpression] | None = None,
    fixed_parameters: Mapping[str, float] | None = None,
    fixed_prior: str = "Normal(0.0, 5.0)",
    random_scale_prior: str = "HalfNormal(1.0)",
    correlation_prior: str = "LKJCholesky(1.0)",
    group_covariances: Mapping[str, GroupCovariance] | None = None,
    priors: PriorInput | None = None,
    reparameterize: Literal["centered", "noncentered"] = "noncentered",
    binomial_trials: int | str | None = None,
    thresholds_by: str | None = None,
    mixture_components: int = 2,
    predictor_name: str | None = None,
    default_priors: DefaultPriorPolicy = "quivers",
    center: bool | None = None,
    decomp: Literal["none", "QR"] = "none",
    cmc: bool = True,
    sparse: bool = False,
    unused: Sequence[str] = (),
    knots: Knots | None = None,
    drop_unused_levels: bool = True,
) -> dict[str, str]:
    """Return effective named priors without running inference.

    The arguments match `formula_to_qvr`, except for its output path.
    Priors reflect evaluated design columns, selected links, distributional
    formulas, group correlations, and explicit overrides. Default coefficient
    scales include column autoscaling; explicit overrides are emitted as given.

    Parameters
    ----------
    formula : str or ResponseModel or MultivariateFormula or None
        Response formula in brms/lme4 notation, a single-response `bf`
        carrying its response keywords, or a joint formula whose
        namespaced sites (``response_<resp>__...``, ``rescor``) are listed;
        None for a program.
    data : IntoDataFrame
        Rows used to evaluate design matrices and autoscale default priors.
    program : str or tuple[str or Path, str] or None
        QVR source, or a source file path and a program name, as in `fit`.
    entry : str or None
        The program name when it is given separately from the source text.
    static : Mapping[str, int] or None
        Finite extents of the program, by binder name.
    parameters : Mapping[str, str or NonlinearExpression] or None
        Formulas of the program's parameters, by name.
    response : str or None
        The site the program observes.
    family : str or Family
        Registered response family or a family value with selected links.
    weights : str or None
        Numeric column of finite nonnegative likelihood weights. Values
        multiply each response's log density, retain their original scale,
        and do not weight priors or posterior predictions.
    decision : str or None
        Wiener boundary-choice column, equivalent to response-side dec(column).
        Numeric codes must be exactly zero/lower or one/upper.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Named matrices referenced by autocorrelation terms, as in brms:
        the spatial weights of ``sar(M)`` and the fixed covariance of
        ``fcor(M)``, each over the included response rows. A group-level
        ``gr(g, cov = M)`` reads a labeled ``DataFrame`` covariance between
        the levels of ``g``.
    distributional : Mapping[str, str] or None
        Separate formulas for auxiliary parameters.
    fixed_parameters : Mapping[str, float] or None
        Auxiliary parameters held constant; these have no prior entries.
    fixed_prior, random_scale_prior, correlation_prior : str
        Default coefficient, group-scale, and LKJ Cholesky priors.
    group_covariances : Mapping[str, GroupCovariance] or None
        Known covariance between labeled levels, keyed by grouping factor.
        The same declaration serves compilation, inspection, and prediction.
    priors : PriorInput or None
        Named overrides or typed selectors, including sampled shrinkage
        hierarchies. Unknown, unused, or ambiguous rules raise ValueError.
    reparameterize : {"centered", "noncentered"}
        Group parameterization; its conditional draws are not overrideable.
    binomial_trials : int or str
        Fixed trial count or a column of counts.
    thresholds_by : str or None
        Grouping column for ordinal cutpoints.
    mixture_components : int
        Number of Gaussian mixture components.
    predictor_name : str or None
        External contribution on the linear-predictor scale.

    default_priors : {"quivers", "brms"}
        Default prior policy: the proper, autoscaled quivers defaults, or
        ``brms::default_prior`` (flat ``b``; Student-t intercept, ``sd`` and
        ``sigma`` priors scaled by the response). Explicit priors win either way.
    center : bool or None
        brms ``bf(center = )``: sample the intercept of the column-centered
        design and report ``b_Intercept = Intercept_c - mean(X) b``. None
        centers under the brms policy only.
    decomp : {"none", "QR"}
        brms ``bf(decomp = "QR")``: sample the location coefficients in scaled
        QR coordinates; class ``b`` priors act on those coordinates.
    cmc : bool
        brms ``cmc``: with False, a formula without intercept keeps treatment
        coding (no cell-mean coding of its first factor).
    sparse : bool
        brms ``sparse``: the same model with centering disabled, as brms
        disables it for sparse designs; incompatible with ``decomp="QR"``.
    unused : Sequence[str]
        brms ``unused``: further columns kept with the model rows, so rows
        missing them are excluded as for model variables.
    knots : Mapping[str, Sequence[float]] or None
        brms ``knots``: knot values keyed by smooth covariate, passed to the
        ``cr``, ``cs``, ``cc``, ``ps`` and ``bs`` constructors of ``s()`` as
        mgcv's ``smoothCon(knots = )`` does.
    drop_unused_levels : bool
        brms ``drop_unused_levels``: with False, factor levels that no row
        uses keep their population columns (of zeros) and grouping-factor
        levels their group effects, as brms keeps them.
    Returns
    -------
    dict[str, str]
        Actual overrideable site names and canonical prior calls.

    Raises
    ------
    ValueError
        If a formula or family setting is invalid, or a prior is unused.
    """
    # Joint (multivariate) formulas read priors from the composed program.
    if isinstance(formula, MultivariateFormula):
        with formula_data_options(knots, drop_unused_levels):
            module, targets = _joint_fit.joint_module(
                formula.with_default_priors(default_priors),
                data,
                fixed_prior=fixed_prior,
                random_scale_prior=random_scale_prior,
                correlation_prior=correlation_prior,
                group_covariances=group_covariances,
                priors=priors,
                reparameterize=reparameterize,
                data2=data2,
                caller="get_prior",
            )
        return _joint_fit.joint_prior(module, targets)
    formula, family, distributional = program_arguments(
        formula,
        program=program,
        entry=entry,
        static=static,
        parameters=parameters,
        response=response,
        family=family,
        distributional=distributional,
        nonlinear=nonlinear,
        fixed_parameters=fixed_parameters,
        caller="get_prior",
    )
    _refuse_joint_syntax(formula, "get_prior")
    prepared = _prepare_formula_entry(
        formula,
        data=data,
        family=family,
        weights=weights,
        decision=decision,
        data2=data2,
        distributional=distributional,
        nonlinear=nonlinear,
        fixed_parameters=fixed_parameters,
        fixed_prior=fixed_prior,
        random_scale_prior=random_scale_prior,
        correlation_prior=correlation_prior,
        group_covariances=group_covariances,
        priors=priors,
        reparameterize=reparameterize,
        binomial_trials=binomial_trials,
        thresholds_by=thresholds_by,
        mixture_components=mixture_components,
        predictor_name=predictor_name,
        default_priors=default_priors,
        center=center,
        decomp=decomp,
        cmc=cmc,
        sparse=sparse,
        unused=unused,
        knots=knots,
        drop_unused_levels=drop_unused_levels,
    )
    if prepared.missing is not None:
        emission = prepared.missing.emission
        return prepared.lens._prior_calls(
            prepared.formula, emission.module, targets=emission.prior_targets
        )
    return prepared.lens.get_prior(prepared.formula)

residual_lens

residual_lens(law: ResidualLaw | None, fixed_parameters: Mapping[str, float], build: Callable[[dict[str, float]], FormulaToQVRModule]) -> FormulaToQVRModule

Build a formula lens that observes the response through a residual law.

PARAMETER DESCRIPTION
law

Residual law of the response, or None for the family's own law.

TYPE: ResidualLaw or None

fixed_parameters

Constant values of family parameters and of the law's structural sites.

TYPE: Mapping[str, float]

build

The lens of the family from its own fixed values.

TYPE: Callable[[dict[str, float]], FormulaToQVRModule]

RETURNS DESCRIPTION
FormulaToQVRModule

The lens, with the law bound.

Source code in src/quivers/formulas/_fit.py
def residual_lens(
    law: ResidualLaw | None,
    fixed_parameters: Mapping[str, float],
    build: Callable[[dict[str, float]], FormulaToQVRModule],
) -> FormulaToQVRModule:
    """Build a formula lens that observes the response through a residual law.

    Parameters
    ----------
    law : ResidualLaw or None
        Residual law of the response, or None for the family's own law.
    fixed_parameters : Mapping[str, float]
        Constant values of family parameters and of the law's structural
        sites.
    build : Callable[[dict[str, float]], FormulaToQVRModule]
        The lens of the family from its own fixed values.

    Returns
    -------
    FormulaToQVRModule
        The lens, with the law bound.
    """
    structural = set(law.coefficients) if law is not None else set()
    lens = build(
        {
            name: value
            for name, value in fixed_parameters.items()
            if name not in structural
        }
    )
    lens._bind_residual(
        law,
        {name: value for name, value in fixed_parameters.items() if name in structural},
    )
    return lens