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:
|
syntax
|
Language of the expression text.
TYPE:
|
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:
|
values
|
Scalar expressions aligned to those coordinate labels.
TYPE:
|
at
¶
at(component: str) -> LetExprNode
Return the expression of one coordinate.
| PARAMETER | DESCRIPTION |
|---|---|
component
|
Coordinate label.
TYPE:
|
| 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
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:
|
expressions
|
Deterministic intermediate nodes in dependency order.
TYPE:
|
roots
|
Family link-scale outputs, keyed by distributional parameter.
TYPE:
|
inputs
|
Numeric raw columns with their exact fitted carriers and row axis.
TYPE:
|
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:
|
decision
|
Joint binary decisions on the same sample axes, zero lower and one upper; None for a response without a decision modifier.
TYPE:
|
decision_labels
|
Semantic labels of the binary codes, or an empty tuple.
TYPE:
|
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:
|
term
|
Smooth or GP term exactly as the fitted formula's evaluator names
it, for instance
TYPE:
|
new_data
|
Rows holding the smooth's covariates and any
TYPE:
|
parameter
|
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws and for the latent function of an exact
TYPE:
|
draws
|
Explicit constrained draws to read in place of the fit's own.
TYPE:
|
site_prefix
|
Namespace of that response's sites within
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Contributions with shape |
| 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
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:
|
family
|
Family description.
TYPE:
|
nobs
|
Number of observations used in fitting.
TYPE:
|
ngrps
|
Number of levels of each grouping factor.
TYPE:
|
algorithm
|
TYPE:
|
chains
|
Chains, retained draws per chain, and warmup iterations per chain.
TYPE:
|
iterations
|
Chains, retained draws per chain, and warmup iterations per chain.
TYPE:
|
warmup
|
Chains, retained draws per chain, and warmup iterations per chain.
TYPE:
|
total_ndraws
|
Retained draws pooled over chains.
TYPE:
|
fixed
|
Population coefficients, named without their
TYPE:
|
spec_pars
|
Unregressed family parameters (
TYPE:
|
random
|
Per grouping factor,
TYPE:
|
splines
|
Smoothing standard deviations of
TYPE:
|
rescor
|
Residual correlations of a joint fit,
TYPE:
|
other
|
Native QVR sites without a brms counterpart.
TYPE:
|
divergences
|
Divergent transitions after warmup, zero without recorded chains.
TYPE:
|
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:
|
cor
|
Three-way summaries
TYPE:
|
cov
|
Three-way summaries
TYPE:
|
sd_draws
|
Draws
TYPE:
|
cor_draws
|
Draws
TYPE:
|
cov_draws
|
Draws
TYPE:
|
labels
|
Coefficient labels.
TYPE:
|
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:
|
cross_validation
|
Held-out scores, the partition, and the refits when saved.
TYPE:
|
data
|
Original rows of the fitted model.
TYPE:
|
positions
|
Original row position of every partitioned unit.
TYPE:
|
fold_type
|
TYPE:
|
joint_fit
|
Whether the refits are joint fits.
TYPE:
|
resp
|
Joint response selection of the scores.
TYPE:
|
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:
|
predicted
|
Draws
TYPE:
|
positions
|
Original row position of each predicted unit.
TYPE:
|
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
TYPE:
|
method
|
TYPE:
|
resp
|
Response of a joint fit; None for a single response.
TYPE:
|
num_samples
|
Draws per chain of each refit.
TYPE:
|
seed
|
Prediction seed.
TYPE:
|
| 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
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 | |
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
TYPE:
|
criterion
|
Criterion to compare.
TYPE:
|
| 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
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
TYPE:
|
method
|
Weighting method.
TYPE:
|
bayesian_bootstrap
|
Bayesian-bootstrap regularization of pseudo-BMA weights (loo's
TYPE:
|
seed
|
Seed of the Bayesian bootstrap.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float]
|
Weights summing to one. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
weights
|
Stacking or pseudo-BMA weights of PSIS-LOO, or Akaike-type weights
TYPE:
|
seed
|
Seed of the pseudo-BMA Bayesian bootstrap and of bridge sampling.
TYPE:
|
| 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
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
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
brms-named draws on chain and draw axes. |
Source code in src/quivers/formulas/_postprocess_methods.py
nobs
¶
Return the number of observations used in fitting, as brms nobs.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Fitted rows. |
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
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
draw_ids
|
0-based positions of the pooled draws to use (brms
TYPE:
|
**options
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable or Tensor
|
|
Source code in src/quivers/formulas/_postprocess_methods.py
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 (
TYPE:
|
parameter
|
A distributional or nonlinear parameter (brms
TYPE:
|
summary
|
Summarize; False returns the draws.
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
draw_ids
|
0-based pooled draw positions.
TYPE:
|
**options
|
Prediction keywords such as
TYPE:
|
| 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
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 | |
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
|
TYPE:
|
draw_ids
|
0-based pooled draw positions.
TYPE:
|
**options
|
Prediction keywords;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Float64 draws |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
For ordinal or categorical responses, where errors are undefined. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
type
|
TYPE:
|
summary
|
Summarize; False returns the draws.
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
draw_ids
|
0-based pooled draw positions.
TYPE:
|
**options
|
Prediction keywords;
TYPE:
|
| 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
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:
|
**options
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable
|
Lower and upper bounds per row. |
Source code in src/quivers/formulas/_postprocess_methods.py
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
TYPE:
|
reloo
|
Refit the model once per unit still above
TYPE:
|
k_threshold
|
Pareto shape threshold, 0.7 as in brms.
TYPE:
|
moment_match_args
|
TYPE:
|
method_factory
|
Fit settings of each exact refit; None keeps the original settings with the refit's own seed.
TYPE:
|
use_stored
|
Return a
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws and refits.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
PSIS-LOO estimate with Pareto diagnostics. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
k_threshold
|
Units above this Pareto shape are moment matched.
TYPE:
|
max_iters
|
Maximum iterations per unit.
TYPE:
|
split
|
Split moment matching with multiple importance sampling.
TYPE:
|
cov
|
Also match covariances.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
Updated estimate. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/formulas/_postprocess_methods.py
waic
¶
waic(*, num_samples: int | None = None, seed: int = 0) -> ELPDEstimate
Estimate WAIC, as brms waic.
| PARAMETER | DESCRIPTION |
|---|---|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
WAIC estimate. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PSISWeights
|
Smoothed log weights and Pareto diagnostics. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
approximation
|
Approximation of every row's term: the log density at the posterior mean (default) or the log predictive density.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed of the subsample and variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
Subsampled estimate with total and subsampling standard errors. |
Source code in src/quivers/formulas/_postprocess_methods.py
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
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws and responses.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LooExpectation
|
Statistics per training row with function-specific Pareto shapes. |
Source code in src/quivers/formulas/_postprocess_methods.py
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
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LooExpectation
|
Statistics per training row. |
Source code in src/quivers/formulas/_postprocess_methods.py
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
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LooExpectation
|
Statistics per training row. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws and responses.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LooExpectation
|
Weighted quantiles |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the mass is not strictly inside (0, 1). |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed of the Dirichlet weights and variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable or Tensor
|
A |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
For unordered categorical responses. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
Ksub
|
Number of randomly chosen folds, or explicit 0-based folds.
TYPE:
|
folds
|
None (random folds, or one fold per level of
TYPE:
|
group
|
Grouping column.
TYPE:
|
joint
|
Predictive unit: rows, whole folds, or groups within folds.
TYPE:
|
save_fits
|
Retain the refits for
TYPE:
|
method_factory
|
Fit settings per fold; None keeps the original settings with the fold's seed.
TYPE:
|
num_samples
|
Draws per chain of held-out scoring.
TYPE:
|
seed
|
Partition and refit seed.
TYPE:
|
allow_new_levels
|
Score held-out rows with new group levels, True as in brms.
TYPE:
|
sample_new_levels
|
New-level policy,
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KFoldResult
|
The |
Source code in src/quivers/formulas/_postprocess_methods.py
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 | |
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
TYPE:
|
overwrite
|
Recompute criteria already stored.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws and resampling.
TYPE:
|
kfold_options
|
Keywords of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesianFit
|
A fit sharing this fit's model with the criteria stored; they
persist through |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a criterion is unknown. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
resp
|
Response selection. None prefers the whole-fit criterion if it is stored, then the most recently stored selection of this criterion.
TYPE:
|
| 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
nobs
¶
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:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Row count. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
summary
|
Summarize; False returns the draws.
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
draw_ids
|
0-based pooled draw positions.
TYPE:
|
**options
|
TYPE:
|
| 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
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:
|
scale
|
Expected responses or linear predictors.
TYPE:
|
parameter
|
Distributional or nonlinear parameter of every selected response.
TYPE:
|
summary
|
Summarize; False returns the draws.
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
draw_ids
|
0-based pooled draw positions.
TYPE:
|
**options
|
Prediction keywords.
TYPE:
|
| 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
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 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 | |
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:
|
method
|
Prediction method or alias.
TYPE:
|
draw_ids
|
0-based pooled draw positions.
TYPE:
|
**options
|
Prediction keywords;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Error draws keyed by response. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
method
|
Prediction method or alias.
TYPE:
|
type
|
Residual type.
TYPE:
|
summary
|
Summarize; False returns the draws.
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
draw_ids
|
0-based pooled draw positions.
TYPE:
|
**options
|
Prediction keywords.
TYPE:
|
| 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
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:
|
prob
|
Central mass, 0.9 as in brms.
TYPE:
|
**options
|
Prediction keywords.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, SummaryTable]
|
Lower and upper bounds per row, keyed by response. |
Source code in src/quivers/formulas/_postprocess_methods.py
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
TYPE:
|
moment_match
|
Moment-match units above
TYPE:
|
reloo
|
Refit once per unit still above
TYPE:
|
k_threshold
|
Pareto shape threshold, 0.7 as in brms.
TYPE:
|
moment_match_args
|
TYPE:
|
method_factory
|
Fit settings of each refit; None keeps the original settings.
TYPE:
|
use_stored
|
Return a stored
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws and refits.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
PSIS-LOO estimate. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
resp
|
Scored responses.
TYPE:
|
k_threshold
|
Pareto shape threshold.
TYPE:
|
max_iters
|
Maximum iterations per unit.
TYPE:
|
split
|
Split moment matching.
TYPE:
|
cov
|
Also match covariances.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
Updated estimate. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
WAIC estimate. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PSISWeights
|
Smoothed log weights and Pareto diagnostics. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
observations
|
Subsample size or explicit 0-based rows.
TYPE:
|
approximation
|
Approximation of every row's term.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed of the subsample and variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDEstimate
|
Subsampled estimate. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
type
|
Weighted statistic.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws and responses.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, LooExpectation]
|
Statistics per row, keyed by response. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
type
|
Weighted statistic.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, LooExpectation]
|
Statistics per row, keyed by response. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
type
|
Weighted statistic.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, LooExpectation]
|
Statistics per row, keyed by response. |
Source code in src/quivers/formulas/_postprocess_methods.py
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:
|
prob
|
Central mass.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed for variational draws and responses.
TYPE:
|
| 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
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:
|
method
|
Requested form;
TYPE:
|
observed
|
Explicit observed responses by label, for the residual form.
TYPE:
|
mc_samples
|
Monte Carlo budget of conditional means without a closed form.
TYPE:
|
**options
|
Prediction keywords of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
|
| 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
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 | |
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:
|
summary
|
Summarize; False returns the bootstrap draws.
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed of the Dirichlet weights and variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable or dict[str, Tensor]
|
Rows |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
For unordered categorical responses. |
Source code in src/quivers/formulas/_postprocess_methods.py
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 | |
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:
|
K
|
Number of folds.
TYPE:
|
Ksub
|
Number of random folds, or explicit 0-based folds.
TYPE:
|
folds
|
Fold type or labels, as
TYPE:
|
group
|
Grouping column.
TYPE:
|
joint
|
Predictive unit.
TYPE:
|
save_fits
|
Retain the refits.
TYPE:
|
method_factory
|
Fit settings per fold.
TYPE:
|
num_samples
|
Draws per chain of held-out scoring.
TYPE:
|
seed
|
Partition and refit seed.
TYPE:
|
allow_new_levels
|
Score new group levels.
TYPE:
|
sample_new_levels
|
New-level policy.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KFoldResult
|
The criterion and the refits. |
Source code in src/quivers/formulas/_postprocess_methods.py
3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 | |
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
TYPE:
|
resp
|
Responses the criterion scores, as brms's
TYPE:
|
overwrite
|
Recompute stored criteria.
TYPE:
|
num_samples
|
Draws per chain.
TYPE:
|
seed
|
Seed.
TYPE:
|
kfold_options
|
Keywords of
TYPE:
|
| 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
3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 | |
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:
|
method
|
Proposal of the
TYPE:
|
repetitions
|
Independent proposal draws.
TYPE:
|
use_neff
|
Use the effective size of the iteration draws.
TYPE:
|
maxiter
|
Iteration bound of the fixed-point scheme.
TYPE:
|
seed
|
Seed of the proposal draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BridgeResult
|
The estimate, with the retained log densities. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fit is refused by |
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
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
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:
|
x2
|
Numerator and denominator models, or their bridge estimates.
TYPE:
|
log
|
Return the log Bayes factor.
TYPE:
|
model_names
|
Names of the two models.
TYPE:
|
method
|
TYPE:
|
repetitions
|
TYPE:
|
use_neff
|
TYPE:
|
maxiter
|
TYPE:
|
seed
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesFactor
|
:math: |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fits model different response data or are refused by
|
Source code in src/quivers/formulas/_evidence.py
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:
|
prior_prob
|
Prior model probabilities in the order of
TYPE:
|
method
|
TYPE:
|
repetitions
|
TYPE:
|
use_neff
|
TYPE:
|
maxiter
|
TYPE:
|
seed
|
TYPE:
|
| 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
BayesFactor
didactic-model
¶
Bases: ValueModel
A Bayes factor of two models, as a bf_bridge object.
| PARAMETER | DESCRIPTION |
|---|---|
bf
|
:math:
TYPE:
|
log
|
Whether
TYPE:
|
numerator
|
Names of the numerator and denominator models.
TYPE:
|
denominator
|
Names of the numerator and denominator models.
TYPE:
|
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:
|
variable
|
brms variable names (see
TYPE:
|
weights
|
Weighting method of
TYPE:
|
ndraws
|
Total draws; the first model's draw count by default.
TYPE:
|
missing
|
Value of a variable in models that lack it; None requires every variable in every model.
TYPE:
|
seed
|
Seed of the draw selection and of the weights.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PosteriorAverage
|
Pooled draws, weights and draw counts. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a variable is absent from the required models, |
Source code in src/quivers/formulas/_model_averaging.py
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
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:
|
weights
|
Weighting method of
TYPE:
|
method
|
Prediction method.
TYPE:
|
ndraws
|
Total draws; the first model's draw count by default.
TYPE:
|
summary
|
Also summarize the pooled draws.
TYPE:
|
probs
|
Quantile probabilities of the summary.
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
resp
|
Response of joint fits; required when a joint fit has several.
TYPE:
|
**options
|
Prediction keywords such as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PredictionAverage
|
Pooled draws, weights, draw counts and the optional summary. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fits model different responses, |
Source code in src/quivers/formulas/_model_averaging.py
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | |
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
TYPE:
|
weights
|
Normalized model weights.
TYPE:
|
ndraws
|
Draws contributed by each model.
TYPE:
|
to_frame
¶
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
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
TYPE:
|
weights
|
Normalized model weights.
TYPE:
|
ndraws
|
Draws contributed by each model.
TYPE:
|
summary
|
brms's summary of the pooled draws, when requested.
TYPE:
|
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:
|
variables
|
Variables to condition on.
TYPE:
|
**labels
|
TYPE:
|
| 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 |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a variable is not a column of the data. |
Source code in src/quivers/formulas/_brms_effects.py
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:
|
smooths_only
|
Whether the effects are smooth contributions (
TYPE:
|
names
¶
Return the effect names in order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
brms's list names. |
__getitem__
¶
__getitem__(name: str) -> EffectFrame
Return one effect by name.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
brms's list name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectFrame
|
The effect. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If no effect has the name. |
Source code in src/quivers/formulas/_brms_effects.py
frames
¶
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
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
TYPE:
|
effects
|
Plotted variables in plotting order;
TYPE:
|
response
|
Response, distributional parameter, or nonlinear parameter predicted.
TYPE:
|
frame
|
Grid and condition columns,
TYPE:
|
draws
|
Prediction draws
TYPE:
|
surface
|
Whether both effects are numeric and plotted as a surface.
TYPE:
|
categorical
|
Whether rows are per category.
TYPE:
|
spaghetti
|
One row per draw and grid row with
TYPE:
|
points
|
Observed data assigned to conditions, with
TYPE:
|
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 (
TYPE:
|
type
|
bayesplot type without prefix (
TYPE:
|
ndraws
|
Random draws; every draw for summary types and ten otherwise.
TYPE:
|
prefix
|
Compare with observed data, or show the predictive distribution only.
TYPE:
|
group
|
Grouping variable; required by
TYPE:
|
x
|
Covariate of
TYPE:
|
newdata
|
Rows to predict, holding the response for
TYPE:
|
resp
|
Response of a joint fit; required when it has several.
TYPE:
|
draw_ids
|
Explicit 0-based draws.
TYPE:
|
stat
|
Test statistic;
TYPE:
|
prob
|
Interval probabilities of interval types;
TYPE:
|
prob_outer
|
Interval probabilities of interval types;
TYPE:
|
bins
|
Bins of
TYPE:
|
freq
|
Counts instead of proportions for
TYPE:
|
style
|
Rootogram style.
TYPE:
|
seed
|
Seed of the draw selection and predictions.
TYPE:
|
| 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 |
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
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | |
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:
|
prefix
|
Posterior predictive check or predictive distribution.
TYPE:
|
data
|
bayesplot's table for the type (see the
TYPE:
|
y
|
Observed responses
TYPE:
|
yrep
|
Predictive draws
TYPE:
|
draw_ids
|
Pooled 0-based draws used.
TYPE:
|
group
|
Group label per observation.
TYPE:
|
x
|
Covariate per observation.
TYPE:
|
status
|
Event indicator of censored responses (
TYPE:
|
log_weights
|
Normalized PSIS log weights
TYPE:
|
log_likelihood
|
Pointwise log-likelihoods
TYPE:
|
pit
|
PIT or LOO-PIT values per observation.
TYPE:
|
to_datatree
¶
Return an ArviZ data tree of the check.
| RETURNS | DESCRIPTION |
|---|---|
DataTree
|
|
Source code in src/quivers/formulas/_pp_check.py
plot
¶
Draw the check with its ArviZ counterpart.
| PARAMETER | DESCRIPTION |
|---|---|
backend
|
ArviZ plotting backend (
TYPE:
|
**kwargs
|
Further keyword arguments of the ArviZ function.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PlotCollection
|
The plot. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If ArviZ has no counterpart of the type; its data remain in |
Source code in src/quivers/formulas/_pp_check.py
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:
|
type
|
bayesplot
TYPE:
|
variable
|
brms variable names or regular expressions; None for all.
TYPE:
|
regex
|
brms
TYPE:
|
backend
|
ArviZ plotting backend (
TYPE:
|
**kwargs
|
Further ArviZ keyword arguments.
TYPE:
|
| 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
_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
¶
Bases: ValueModel
A Bayes factor of two models, as a bf_bridge object.
| PARAMETER | DESCRIPTION |
|---|---|
bf
|
:math:
TYPE:
|
log
|
Whether
TYPE:
|
numerator
|
Names of the numerator and denominator models.
TYPE:
|
denominator
|
Names of the numerator and denominator models.
TYPE:
|
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
TYPE:
|
repetitions
|
Independent proposal draws.
TYPE:
|
use_neff
|
Use the effective size of the iteration draws.
TYPE:
|
maxiter
|
Iteration bound of the fixed-point scheme.
TYPE:
|
seed
|
Seed of the proposal draws.
TYPE:
|
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
TYPE:
|
repetitions
|
Independent proposal draws.
TYPE:
|
use_neff
|
Use the effective size of the iteration draws.
TYPE:
|
maxiter
|
Iteration bound of the fixed-point scheme.
TYPE:
|
seed
|
Seed of the proposal draws.
TYPE:
|
| 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
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:
|
log
|
Return the log Bayes factor.
TYPE:
|
method
|
TYPE:
|
repetitions
|
TYPE:
|
use_neff
|
TYPE:
|
maxiter
|
TYPE:
|
seed
|
TYPE:
|
| 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
require_normalized
¶
Refuse a fit whose log joint is not a normalized posterior kernel.
| PARAMETER | DESCRIPTION |
|---|---|
fit
|
Fitted model.
TYPE:
|
purpose
|
Operation named in the error.
TYPE:
|
| 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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[ndarray, PotentialFn]
|
Float64 draws |
| 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
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:
|
method
|
Proposal of the
TYPE:
|
repetitions
|
Independent proposal draws.
TYPE:
|
use_neff
|
Use the effective size of the iteration draws.
TYPE:
|
maxiter
|
Iteration bound of the fixed-point scheme.
TYPE:
|
seed
|
Seed of the proposal draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BridgeResult
|
The estimate, with the retained log densities. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fit is refused by |
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
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
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:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If two fits score different observed responses. |
Source code in src/quivers/formulas/_evidence.py
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:
|
x2
|
Numerator and denominator models, or their bridge estimates.
TYPE:
|
log
|
Return the log Bayes factor.
TYPE:
|
model_names
|
Names of the two models.
TYPE:
|
method
|
TYPE:
|
repetitions
|
TYPE:
|
use_neff
|
TYPE:
|
maxiter
|
TYPE:
|
seed
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesFactor
|
:math: |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fits model different response data or are refused by
|
Source code in src/quivers/formulas/_evidence.py
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:
|
prior_prob
|
Prior model probabilities in the order of
TYPE:
|
method
|
TYPE:
|
repetitions
|
TYPE:
|
use_neff
|
TYPE:
|
maxiter
|
TYPE:
|
seed
|
TYPE:
|
| 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
_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
¶
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
TYPE:
|
weights
|
Normalized model weights.
TYPE:
|
ndraws
|
Draws contributed by each model.
TYPE:
|
to_frame
¶
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
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
TYPE:
|
weights
|
Normalized model weights.
TYPE:
|
ndraws
|
Draws contributed by each model.
TYPE:
|
summary
|
brms's summary of the pooled draws, when requested.
TYPE:
|
round_largest_remainder
¶
Round to integers preserving the rounded total, as brms.
| PARAMETER | DESCRIPTION |
|---|---|
values
|
Nonnegative reals.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[int]
|
Floors, with one added to the largest fractional parts until the
total equals |
Source code in src/quivers/formulas/_model_averaging.py
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:
|
weights
|
A
TYPE:
|
seed
|
Seed of pseudo-BMA bootstrap weights and bridge-sampling proposals.
TYPE:
|
| 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
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:
|
variable
|
brms variable names (see
TYPE:
|
weights
|
Weighting method of
TYPE:
|
ndraws
|
Total draws; the first model's draw count by default.
TYPE:
|
missing
|
Value of a variable in models that lack it; None requires every variable in every model.
TYPE:
|
seed
|
Seed of the draw selection and of the weights.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PosteriorAverage
|
Pooled draws, weights and draw counts. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a variable is absent from the required models, |
Source code in src/quivers/formulas/_model_averaging.py
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
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:
|
weights
|
Weighting method of
TYPE:
|
method
|
Prediction method.
TYPE:
|
ndraws
|
Total draws; the first model's draw count by default.
TYPE:
|
summary
|
Also summarize the pooled draws.
TYPE:
|
probs
|
Quantile probabilities of the summary.
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
resp
|
Response of joint fits; required when a joint fit has several.
TYPE:
|
**options
|
Prediction keywords such as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PredictionAverage
|
Pooled draws, weights, draw counts and the optional summary. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fits model different responses, |
Source code in src/quivers/formulas/_model_averaging.py
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | |
_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.
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
TYPE:
|
effects
|
Plotted variables in plotting order;
TYPE:
|
response
|
Response, distributional parameter, or nonlinear parameter predicted.
TYPE:
|
frame
|
Grid and condition columns,
TYPE:
|
draws
|
Prediction draws
TYPE:
|
surface
|
Whether both effects are numeric and plotted as a surface.
TYPE:
|
categorical
|
Whether rows are per category.
TYPE:
|
spaghetti
|
One row per draw and grid row with
TYPE:
|
points
|
Observed data assigned to conditions, with
TYPE:
|
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:
|
smooths_only
|
Whether the effects are smooth contributions (
TYPE:
|
names
¶
Return the effect names in order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
brms's list names. |
__getitem__
¶
__getitem__(name: str) -> EffectFrame
Return one effect by name.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
brms's list name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectFrame
|
The effect. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If no effect has the name. |
Source code in src/quivers/formulas/_brms_effects.py
frames
¶
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
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
¶
Return the fitted rows of the retained training data, as model.frame.
| PARAMETER | DESCRIPTION |
|---|---|
fit
|
Fitted model with a refit recipe.
TYPE:
|
| 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
model_variables
¶
Return the data variables of the formulas, in order of appearance.
| PARAMETER | DESCRIPTION |
|---|---|
readouts
|
Response readouts.
TYPE:
|
data
|
Model frame.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
Responses, predictors, group variables and addition-term variables. |
Source code in src/quivers/formulas/_brms_effects.py
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:
|
digits
|
Decimal places of numeric values.
TYPE:
|
sep
|
Separator between variables.
TYPE:
|
incl_vars
|
Prefix each value with
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
One label per row. |
Source code in src/quivers/formulas/_brms_effects.py
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:
|
variables
|
Variables to condition on.
TYPE:
|
**labels
|
TYPE:
|
| 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 |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a variable is not a column of the data. |
Source code in src/quivers/formulas/_brms_effects.py
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:
|
readouts
|
Response readouts.
TYPE:
|
conditions
|
User conditions, one row per condition, optionally with
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[DataFrame, list[str]]
|
Completed conditions (without |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the conditions are empty or their labels repeat. |
Source code in src/quivers/formulas/_brms_effects.py
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:
|
effects
|
One or two variables.
TYPE:
|
conditions
|
Completed conditions.
TYPE:
|
labels
|
Condition labels.
TYPE:
|
int_conditions
|
Values of chosen effect variables.
TYPE:
|
surface
|
Grid a numeric second variable over its range.
TYPE:
|
resolution
|
Numeric grid size.
TYPE:
|
reorder
|
Put numeric effects first (default effects only).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[DataFrame, tuple[str, ...], tuple[str, ...], list[str] or None]
|
Grid rows replicated per condition with |
Source code in src/quivers/formulas/_brms_effects.py
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 | |
exclude_too_far
¶
Flag grid points far from the data, as mgcv exclude.too.far.
| PARAMETER | DESCRIPTION |
|---|---|
g1
|
Grid coordinates.
TYPE:
|
g2
|
Grid coordinates.
TYPE:
|
d1
|
Data coordinates.
TYPE:
|
d2
|
Data coordinates.
TYPE:
|
dist
|
Distance threshold on the grid's unit square.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
True where the nearest data point is farther than |
Source code in src/quivers/formulas/_brms_effects.py
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:
|
effects
|
Effects such as
TYPE:
|
conditions
|
Rows of values of other variables, each one condition, optionally
labeled by
TYPE:
|
int_conditions
|
Values (a sequence, a labeled mapping, or a function of the data) of effect variables, replacing brms's default grid values.
TYPE:
|
re_formula
|
Varying effects included:
TYPE:
|
prob
|
Interval probability.
TYPE:
|
robust
|
Median and MAD (brms's default) instead of mean and SD.
TYPE:
|
method
|
Prediction method.
TYPE:
|
spaghetti
|
Also return per-draw lines of numeric first effects.
TYPE:
|
surface
|
Grid a numeric second effect over its range.
TYPE:
|
categorical
|
Per-category probabilities of categorical and ordinal models.
TYPE:
|
ordinal
|
brms's deprecated alias of
TYPE:
|
resolution
|
Numeric grid size.
TYPE:
|
select_points
|
Unit-scaled distance for assigning data points to numeric conditions.
TYPE:
|
too_far
|
Drop surface grid points farther than this from the data.
TYPE:
|
resp
|
Responses of a joint fit.
TYPE:
|
dpar
|
Distributional or nonlinear parameter to predict instead of the mean.
TYPE:
|
nlpar
|
Distributional or nonlinear parameter to predict instead of the mean.
TYPE:
|
ndraws
|
Random subset of draws.
TYPE:
|
draw_ids
|
Explicit 0-based draws.
TYPE:
|
seed
|
Seed of draw selection and predictions.
TYPE:
|
mc_samples
|
Monte Carlo budget of a conditional mean without a closed form
(
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BrmsConditionalEffects
|
One |
| 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
|
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
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 | |
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
TYPE:
|
smooths
|
Smooth term labels (white space ignored); None for all.
TYPE:
|
resp
|
Responses of a joint fit whose smooths are evaluated; None for all.
TYPE:
|
int_conditions
|
Values of covariates or
TYPE:
|
prob
|
Interval probability.
TYPE:
|
spaghetti
|
Also return per-draw curves of one-dimensional smooths.
TYPE:
|
surface
|
Grid a numeric second covariate over its range (brms's default).
TYPE:
|
resolution
|
Grid size per numeric covariate.
TYPE:
|
too_far
|
Drop surface grid points farther than this from the data.
TYPE:
|
ndraws
|
Random subset of draws.
TYPE:
|
draw_ids
|
Explicit 0-based draws.
TYPE:
|
seed
|
Seed of draw selection.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BrmsConditionalEffects
|
One |
| 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
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 | |
joint_grid_options
¶
joint_grid_options(options: JointConditionalEffectsOptions) -> JointPredictionOptions
Return the prediction keywords of an explicit joint-grid request.
| PARAMETER | DESCRIPTION |
|---|---|
options
|
Method keywords. |
| 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
grid_options
¶
grid_options(options: ConditionalEffectsOptions) -> ExpectationOptions
Return the prediction keywords of an explicit-grid request.
| PARAMETER | DESCRIPTION |
|---|---|
options
|
Method keywords. |
| 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
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:
|
effects
|
brms
TYPE:
|
method
|
TYPE:
|
parameter
|
TYPE:
|
transform
|
Must be False; brms applies no inverse link to
TYPE:
|
resp
|
Joint responses.
TYPE:
|
options
|
brms arguments and
TYPE:
|
| 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
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 | |
_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
¶
Posterior predictive check (ppc) or predictive distribution (ppd).
StatisticSpec
¶
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:
|
prefix
|
Posterior predictive check or predictive distribution.
TYPE:
|
data
|
bayesplot's table for the type (see the
TYPE:
|
y
|
Observed responses
TYPE:
|
yrep
|
Predictive draws
TYPE:
|
draw_ids
|
Pooled 0-based draws used.
TYPE:
|
group
|
Group label per observation.
TYPE:
|
x
|
Covariate per observation.
TYPE:
|
status
|
Event indicator of censored responses (
TYPE:
|
log_weights
|
Normalized PSIS log weights
TYPE:
|
log_likelihood
|
Pointwise log-likelihoods
TYPE:
|
pit
|
PIT or LOO-PIT values per observation.
TYPE:
|
to_datatree
¶
Return an ArviZ data tree of the check.
| RETURNS | DESCRIPTION |
|---|---|
DataTree
|
|
Source code in src/quivers/formulas/_pp_check.py
plot
¶
Draw the check with its ArviZ counterpart.
| PARAMETER | DESCRIPTION |
|---|---|
backend
|
ArviZ plotting backend (
TYPE:
|
**kwargs
|
Further keyword arguments of the ArviZ function.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PlotCollection
|
The plot. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If ArviZ has no counterpart of the type; its data remain in |
Source code in src/quivers/formulas/_pp_check.py
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 (
TYPE:
|
type
|
bayesplot type without prefix (
TYPE:
|
ndraws
|
Random draws; every draw for summary types and ten otherwise.
TYPE:
|
prefix
|
Compare with observed data, or show the predictive distribution only.
TYPE:
|
group
|
Grouping variable; required by
TYPE:
|
x
|
Covariate of
TYPE:
|
newdata
|
Rows to predict, holding the response for
TYPE:
|
resp
|
Response of a joint fit; required when it has several.
TYPE:
|
draw_ids
|
Explicit 0-based draws.
TYPE:
|
stat
|
Test statistic;
TYPE:
|
prob
|
Interval probabilities of interval types;
TYPE:
|
prob_outer
|
Interval probabilities of interval types;
TYPE:
|
bins
|
Bins of
TYPE:
|
freq
|
Counts instead of proportions for
TYPE:
|
style
|
Rootogram style.
TYPE:
|
seed
|
Seed of the draw selection and predictions.
TYPE:
|
| 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 |
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
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | |
_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.
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:
|
variable
|
brms variable names, or regular expressions matched against them; None for every variable.
TYPE:
|
regex
|
brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataTree
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no variable matches. |
Source code in src/quivers/formulas/_mcmc_plot.py
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:
|
type
|
bayesplot
TYPE:
|
variable
|
brms variable names or regular expressions; None for all.
TYPE:
|
regex
|
brms
TYPE:
|
backend
|
ArviZ plotting backend (
TYPE:
|
**kwargs
|
Further ArviZ keyword arguments.
TYPE:
|
| 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
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:
|
seed
|
Isolated CPU seed.
TYPE:
|
method
|
Independent conditional sampling, or a configured driver for global score potentials. The driver controls its own budgets.
TYPE:
|
| 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
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
TYPE:
|
resp
|
Responses of a joint fit, as brms's
TYPE:
|
int_conditions
|
Values of covariates or
TYPE:
|
prob
|
Interval probability.
TYPE:
|
spaghetti
|
Also return per-draw curves.
TYPE:
|
surface
|
Grid a numeric second covariate over its range.
TYPE:
|
resolution
|
Grid size per numeric covariate.
TYPE:
|
too_far
|
Drop surface points farther than this from the data.
TYPE:
|
ndraws
|
Random subset of draws.
TYPE:
|
draw_ids
|
Explicit 0-based draws.
TYPE:
|
seed
|
Seed of draw selection.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BrmsConditionalEffects
|
One frame per smooth term. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fit has no matching smooth term, or |
Source code in src/quivers/formulas/_evidence_effects.py
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:
|
ndraws
|
Random draws; brms's default by type.
TYPE:
|
prefix
|
Compare with observed data, or show the predictive distribution.
TYPE:
|
group
|
Grouping variable and covariate.
TYPE:
|
x
|
Grouping variable and covariate.
TYPE:
|
newdata
|
Prediction rows.
TYPE:
|
resp
|
Joint response.
TYPE:
|
draw_ids
|
Explicit 0-based draws.
TYPE:
|
stat
|
Test statistic(s).
TYPE:
|
prob
|
Interval probabilities.
TYPE:
|
prob_outer
|
Interval probabilities.
TYPE:
|
bins
|
Bins of
TYPE:
|
freq
|
Counts instead of proportions for
TYPE:
|
style
|
Rootogram style.
TYPE:
|
seed
|
Seed of draw selection and predictions.
TYPE:
|
| 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
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
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
TYPE:
|
variable
|
brms variable names or regular expressions.
TYPE:
|
regex
|
brms
TYPE:
|
backend
|
ArviZ backend.
TYPE:
|
**kwargs
|
ArviZ keyword arguments.
TYPE:
|
| 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
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:
|
regex
|
brms
TYPE:
|
backend
|
ArviZ backend.
TYPE:
|
**kwargs
|
ArviZ keyword arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PlotCollection
|
ArviZ |
Source code in src/quivers/formulas/_evidence_effects.py
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:
|
regex
|
brms
TYPE:
|
backend
|
ArviZ backend.
TYPE:
|
**kwargs
|
ArviZ keyword arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PlotMatrix
|
ArviZ |
Source code in src/quivers/formulas/_evidence_effects.py
_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:
|
family
|
Response family used at compile time.
TYPE:
|
residual
|
Residual law of the response: natural residuals correlated across rows by an autocorrelation term; None for independent rows.
TYPE:
|
program
|
The compiled program.
TYPE:
|
posterior
|
TYPE:
|
sample_prior
|
Ordinary fitting, additionally retained independent priors, or observation-free inference with explicit score potentials retained.
TYPE:
|
prior
|
Independent prior samples, or explicitly factor-conditioned chains.
TYPE:
|
losses
|
Finite optimization losses for SVI; empty for recorded MCMC chains.
TYPE:
|
observations
|
Inference-time observations dict (response + per-column covariates + per-group plate indices).
TYPE:
|
group_covariances
|
Known labeled covariance between grouping levels, including any explicitly supplied future labels. Coefficient correlations remain separate.
TYPE:
|
fixed_parameters
|
Auxiliary parameters bound to constants rather than sampled or regressed.
TYPE:
|
distributional
|
Evaluated auxiliary-parameter design matrices, retained so source inspection emits the fitted model without re-evaluating transforms.
TYPE:
|
predictor_graph
|
Named nonlinear designs, typed expressions, and numeric input contracts.
TYPE:
|
refit_recipe
|
Retained original data and canonical fitting configuration, held by identity. Clone ownership is the default; explicit reference ownership observes mutations.
TYPE:
|
prediction_plan
|
Live fitted evaluators for new-data prediction. The versioned runtime plan is held by identity and explicitly refuses durable serialization.
TYPE:
|
criteria
|
Criteria stored by
TYPE:
|
default_priors
|
Default prior policy the model was compiled with.
TYPE:
|
center
|
brms intercept centering option.
TYPE:
|
decomp
|
brms population-coefficient decomposition.
TYPE:
|
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
¶
Lazily emit the AST-equivalent .qvr source for display.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Canonical source emitted from the retained formula AST. |
included_rows
property
¶
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 |
category_labels
property
¶
Response-category labels in posterior probability-array order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[int or str, ...]
|
Factor levels, the integer values |
threshold_labels
property
¶
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
¶
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
¶
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:
|
**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:
|
| 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
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:
|
partition
|
Optional nonmutating original-frame row selection. By default, Narwhals preserves the dataframe backend and authored columns.
TYPE:
|
num_samples
|
Per-chain draw budget for raw held-out likelihood scoring.
TYPE:
|
**prediction
|
Existing log_likelihood options, including re_formula and explicit new-group policies. The adapter owns rows, neural inputs, and seeds.
TYPE:
|
| 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
evidence
¶
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:
|
| 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
prior_summary
¶
prior_summary() -> PriorTable
Tabulate the effective prior of every parameter, as brms prior_summary.
| RETURNS | DESCRIPTION |
|---|---|
PriorTable
|
brms's columns, with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fit retains no emission. |
Source code in src/quivers/formulas/_fit.py
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
TYPE:
|
method
|
TYPE:
|
parameter
|
Predictor selected only for linpred; other methods require mu.
TYPE:
|
transform
|
Apply the inverse link only for linpred.
TYPE:
|
**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
TYPE:
|
| 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
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | |
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:
|
seed
|
Isolated CPU seed for fresh ancestral draws.
TYPE:
|
method
|
Conditional sampling or explicitly factor-conditioned inference.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesianFit
|
A new view sharing the fitted model, encodings, and data. |
Source code in src/quivers/formulas/_fit.py
dump_qvr
¶
Write the AST-equivalent .qvr source to path and
return the resulting Path.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Destination for canonical QVR source.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Path
|
Written source path. |
Source code in src/quivers/formulas/_fit.py
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
|
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Original column labels and coefficient arrays, shape
|
Source code in src/quivers/formulas/_fit.py
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
|
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, Tensor]]
|
Group name, then original coefficient label, mapped to arrays
|
Source code in src/quivers/formulas/_fit.py
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
|
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, Tensor]]
|
Arrays with the structure of |
Source code in src/quivers/formulas/_fit.py
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:
|
predictor_data
|
Explicit neural input for fresh prediction rows when required.
TYPE:
|
re_formula
|
Varying-effect selector, with the same meaning as
TYPE:
|
allow_new_levels
|
Permit unseen grouping identities under the selected policy.
TYPE:
|
sample_new_levels
|
Joint donor or Gaussian policy. Explicit
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for separate posterior and group-effect random streams.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Effective thresholds with shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the family is not ordinal or a requested profile crosses. |
Source code in src/quivers/formulas/_fit.py
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 | |
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
|
TYPE:
|
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
TYPE:
|
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:
|
predictor_data
|
Explicit input for a neural predictor on new rows. Required for neural fits with new_data; otherwise must be None.
TYPE:
|
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:
|
re_formula
|
None includes all fitted varying effects;
TYPE:
|
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:
|
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:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
incl_autocor
|
Include an autocorrelation term (brms
TYPE:
|
data2
|
Matrices of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Shape |
| 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
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 | |
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:
|
predictor_data
|
Explicit neural input for new_data, required for neural fits.
TYPE:
|
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:
|
re_formula
|
None includes all fitted varying effects;
TYPE:
|
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:
|
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:
|
num_samples
|
Draw count under the convention of
TYPE:
|
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:
|
component
|
Wiener response means are positive reaction times, including delay. Decision returns lower/upper probabilities for a decision response.
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
incl_autocor
|
Include an autocorrelation term (brms
TYPE:
|
data2
|
Matrices of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Native response means, shape |
| 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
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 | |
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:
|
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:
|
**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:
|
| 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
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 | |
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:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Probabilities shaped chain x draw x row x (lower, upper). |
Source code in src/quivers/formulas/_fit.py
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:
|
re_formula
|
Varying-effect selector, as for prediction.
TYPE:
|
allow_new_levels
|
Permit unseen grouping levels in
TYPE:
|
sample_new_levels
|
Policy for unseen grouping levels.
TYPE:
|
log
|
Return log probabilities.
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws and new-level policies.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fit is not a mixture model. |
Source code in src/quivers/formulas/_fit.py
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 | |
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:
|
| 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
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:
|
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:
|
parameter
|
Distributional or nonlinear predictor for b, Intercept, and sd.
TYPE:
|
group
|
Grouping factor for scale/correlation filtering or per-level scopes.
TYPE:
|
scope
|
Named parameters, per-level random adjustments, or per-level population plus random coefficients. The latter two require b/group.
TYPE:
|
prior
|
Also evaluate the same contrast on the corresponding joint prior stream, yielding prior-corrected region evidence.
TYPE:
|
num_samples
|
Posterior and prior counts. None follows retained-draw conventions; retained prior samples are reused when available.
TYPE:
|
num_prior_samples
|
Posterior and prior counts. None follows retained-draw conventions; retained prior samples are reused when available.
TYPE:
|
seed
|
Isolated seed for guide or fresh prior draws.
TYPE:
|
null
|
Finite comparison value on event axes only.
TYPE:
|
probs
|
Quantile probabilities, in requested order.
TYPE:
|
robust
|
Return median/scaled MAD rather than mean/sample SD.
TYPE:
|
point
|
Optional marginal point-density comparison using these same joint contrast streams. Requires prior=True and a checked Real result.
TYPE:
|
name
|
Output contrast label.
TYPE:
|
alpha
|
brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HypothesisSummary or HypothesisTable
|
For a brms hypothesis string, brms's table ( |
| 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
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 | |
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:
|
seed
|
Variational seed; the caller's CPU RNG is preserved.
TYPE:
|
| 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
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:
|
predictor_data
|
Neural inputs aligned with fresh rows before any subset selection.
TYPE:
|
trials
|
Existing count-trial override. Fresh vector counts otherwise infer their totals from their recorded components.
TYPE:
|
re_formula
|
Existing varying-effect selector;
TYPE:
|
allow_new_levels
|
Permit fresh grouping identities under the selected prediction policy.
TYPE:
|
sample_new_levels
|
Existing joint donor or conditional Gaussian group-effect policy.
TYPE:
|
num_samples
|
Maximum retained draws per chain, or fresh variational draws.
TYPE:
|
seed
|
Seed for variational draws; the caller's CPU RNG is preserved.
TYPE:
|
incl_autocor
|
Include an autocorrelation term (brms
TYPE:
|
data2
|
Matrices of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Response name to raw scores with shape |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If a hidden response needs a marginal-likelihood observer. |
Source code in src/quivers/formulas/_fit.py
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 | |
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:
|
predictor_data
|
Explicit neural input for new_data, required for neural fits.
TYPE:
|
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:
|
re_formula
|
None includes all fitted varying effects;
TYPE:
|
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:
|
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:
|
num_samples
|
Maximum draws per MCMC chain, or fresh guide draws, following
TYPE:
|
seed
|
Seed for separate latent and response random streams. The caller's CPU RNG state is restored on return or failure.
TYPE:
|
incl_autocor
|
Include an autocorrelation term (brms
TYPE:
|
data2
|
Matrices of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Predictive responses, shape |
| 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
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 | |
predictor_labels
¶
Label the last axis returned by posterior_linpred for one graph output.
| PARAMETER | DESCRIPTION |
|---|---|
parameter
|
Family parameter or named nonlinear intermediate.
TYPE:
|
| 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
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
TYPE:
|
data
|
Pandas, Polars, or another Narwhals-compatible dataframe.
TYPE:
|
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
TYPE:
|
entry
|
The program name when it is given separately from the source text.
TYPE:
|
static
|
Finite extents of the program, by binder name.
TYPE:
|
parameters
|
Formulas of the program's parameters, as
TYPE:
|
response
|
The site the program observes, a data column.
TYPE:
|
family
|
Registered response family or a family value.
TYPE:
|
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:
|
decision
|
Wiener boundary-choice column: numeric zero/lower or one/upper, or the labels lower and upper. Equivalent to response-side dec(column).
TYPE:
|
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:
|
data2
|
Named matrices referenced by autocorrelation terms, as in brms:
the spatial weights of
TYPE:
|
distributional
|
Auxiliary-parameter formulas, for instance
TYPE:
|
fixed_parameters
|
Auxiliary parameters held constant on their natural scale, for instance
TYPE:
|
method
|
Inference algorithm.
TYPE:
|
num_warmup
|
MCMC warmup iterations per chain (NUTS and HMC only); 500 when omitted.
TYPE:
|
num_samples
|
MCMC draws kept per chain after warmup (NUTS and HMC only); 1000 when omitted.
TYPE:
|
num_chains
|
MCMC chains (NUTS and HMC only), or Pathfinder paths as brms's
TYPE:
|
num_steps
|
SVI optimization steps (SVI only); 1000 when omitted.
TYPE:
|
learning_rate
|
The Adam learning rate of the SVI optimizer (SVI only).
TYPE:
|
fixed_prior
|
Prior of every fixed-effect coefficient.
TYPE:
|
random_scale_prior
|
Prior of every random-effect standard deviation.
TYPE:
|
correlation_prior
|
Default prior for correlated group blocks, in LKJ Cholesky form. Explicit shared IDs join coefficients across distributional formulas.
TYPE:
|
group_covariances
|
Known covariance between labeled levels, keyed by grouping factor. The same declaration serves compilation, inspection, and prediction.
TYPE:
|
priors
|
Named overrides or typed selectors, including sampled shrinkage hierarchies. Unknown, unused, or ambiguous rules raise ValueError.
TYPE:
|
guide
|
The SVI guide class;
TYPE:
|
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
TYPE:
|
reparameterize
|
Parameterization of the random effects.
TYPE:
|
binomial_trials
|
Trials per row for binomial or beta-binomial responses: a constant or a column.
TYPE:
|
thresholds_by
|
Column grouping the cutpoints of an ordinal family.
TYPE:
|
mixture_components
|
Number of Gaussian components for the mixture family.
TYPE:
|
predictor
|
Optional differentiable contribution on the linear-predictor scale.
TYPE:
|
predictor_data
|
Input passed to
TYPE:
|
seed
|
Seed for compilation and inference. The caller's CPU random state is restored on return or failure.
TYPE:
|
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:
|
num_prior_samples
|
Positive independent draw budget for mode "yes".
TYPE:
|
prior_seed
|
Isolated prior stream. None uses seed + 1 modulo 2**64. Retaining prior draws does not change fitted posterior draws or losses.
TYPE:
|
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:
|
default_priors
|
Default prior policy: the proper, autoscaled quivers defaults, or
TYPE:
|
center
|
brms
TYPE:
|
decomp
|
brms
TYPE:
|
cmc
|
brms
TYPE:
|
sparse
|
brms
TYPE:
|
unused
|
brms
TYPE:
|
control
|
brms
TYPE:
|
thin
|
Keep every
TYPE:
|
init
|
brms
TYPE:
|
init_r
|
Half-width of
TYPE:
|
algorithm
|
brms
TYPE:
|
file
|
brms
TYPE:
|
file_refit
|
brms
TYPE:
|
pathfinder
|
cmdstanr
TYPE:
|
cores
|
brms
TYPE:
|
knots
|
brms
TYPE:
|
drop_unused_levels
|
brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesianFit or MultivariateFit
|
Parsed formula, compiled program, fitted posterior, and observations;
a |
| 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 ( |
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 | |
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
TYPE:
|
data
|
Original training columns, including response modifiers.
TYPE:
|
program
|
QVR source, or a source file path and a program name, as in
TYPE:
|
entry
|
The program name when it is given separately from the source text.
TYPE:
|
static
|
Finite extents of the program, by binder name.
TYPE:
|
parameters
|
Formulas of the program's parameters, by name.
TYPE:
|
response
|
The site the program observes.
TYPE:
|
family
|
Checked response law and retained link, threshold, and event choices.
TYPE:
|
weights
|
Optional existing response-role columns.
TYPE:
|
decision
|
Optional existing response-role columns.
TYPE:
|
data2
|
Named matrices referenced by autocorrelation terms, as in brms:
the spatial weights of
TYPE:
|
distributional
|
Auxiliary designs and checked derived predictor graph.
TYPE:
|
nonlinear
|
Auxiliary designs and checked derived predictor graph.
TYPE:
|
fixed_parameters
|
Bound auxiliary constants.
TYPE:
|
fixed_prior
|
Defaults consumed by the existing typed prior catalog.
TYPE:
|
random_scale_prior
|
Defaults consumed by the existing typed prior catalog.
TYPE:
|
correlation_prior
|
Defaults consumed by the existing typed prior catalog.
TYPE:
|
group_covariances
|
Known group covariance structures.
TYPE:
|
priors
|
Typed selectors or existing exact-name overrides.
TYPE:
|
reparameterize
|
Shared group coordinate policy.
TYPE:
|
binomial_trials
|
Finite-trial count or retained column.
TYPE:
|
thresholds_by
|
Group with an identified full threshold profile.
TYPE:
|
mixture_components
|
Finite-mixture component count.
TYPE:
|
predictor_name
|
Checked external neural binding.
TYPE:
|
default_priors
|
Default prior policy: the proper, autoscaled quivers defaults, or
TYPE:
|
center
|
brms
TYPE:
|
decomp
|
brms
TYPE:
|
cmc
|
brms
TYPE:
|
sparse
|
brms
TYPE:
|
unused
|
brms
TYPE:
|
knots
|
brms
TYPE:
|
drop_unused_levels
|
brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Canonical checked source, without fitting a posterior. |
Source code in src/quivers/formulas/_fit.py
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 | |
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
TYPE:
|
data
|
Rows used to evaluate design matrices and autoscale default priors.
TYPE:
|
program
|
QVR source, or a source file path and a program name, as in
TYPE:
|
entry
|
The program name when it is given separately from the source text.
TYPE:
|
static
|
Finite extents of the program, by binder name.
TYPE:
|
parameters
|
Formulas of the program's parameters, by name.
TYPE:
|
response
|
The site the program observes.
TYPE:
|
family
|
Registered response family or a family value with selected links.
TYPE:
|
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:
|
decision
|
Wiener boundary-choice column, equivalent to response-side dec(column). Numeric codes must be exactly zero/lower or one/upper.
TYPE:
|
data2
|
Named matrices referenced by autocorrelation terms, as in brms:
the spatial weights of
TYPE:
|
distributional
|
Separate formulas for auxiliary parameters.
TYPE:
|
fixed_parameters
|
Auxiliary parameters held constant; these have no prior entries.
TYPE:
|
fixed_prior
|
Default coefficient, group-scale, and LKJ Cholesky priors.
TYPE:
|
random_scale_prior
|
Default coefficient, group-scale, and LKJ Cholesky priors.
TYPE:
|
correlation_prior
|
Default coefficient, group-scale, and LKJ Cholesky priors.
TYPE:
|
group_covariances
|
Known covariance between labeled levels, keyed by grouping factor. The same declaration serves compilation, inspection, and prediction.
TYPE:
|
priors
|
Named overrides or typed selectors, including sampled shrinkage hierarchies. Unknown, unused, or ambiguous rules raise ValueError.
TYPE:
|
reparameterize
|
Group parameterization; its conditional draws are not overrideable.
TYPE:
|
binomial_trials
|
Fixed trial count or a column of counts.
TYPE:
|
thresholds_by
|
Grouping column for ordinal cutpoints.
TYPE:
|
mixture_components
|
Number of Gaussian mixture components.
TYPE:
|
predictor_name
|
External contribution on the linear-predictor scale.
TYPE:
|
default_priors
|
Default prior policy: the proper, autoscaled quivers defaults, or
TYPE:
|
center
|
brms
TYPE:
|
decomp
|
brms
TYPE:
|
cmc
|
brms
TYPE:
|
sparse
|
brms
TYPE:
|
unused
|
brms
TYPE:
|
knots
|
brms
TYPE:
|
drop_unused_levels
|
brms
TYPE:
|
| 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
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 | |
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:
|
fixed_parameters
|
Constant values of family parameters and of the law's structural sites.
TYPE:
|
build
|
The lens of the family from its own fixed values.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FormulaToQVRModule
|
The lens, with the law bound. |