Skip to content

quivers.formulas

The formula front end compiles a regression formula in the style of brms (BΓΌrkner, 2017) to QVR source and fits the resulting Bayesian model. In y ~ x + (1 | group), x contributes a common slope and each group receives its own intercept adjustment (Gelman et al., 2013). The family and the priors complete the statistical specification.

Joint count and compositional responses use cbind(a, b, c) ~ x. A retained ResponseLayout distinguishes component axes from scalar factor codes, and Family.with_reference selects predictor coordinates without reordering response components. The vector response guide gives count totals, compositional means, and new-row predictions.

Response-side declarations such as rt | dec(choice) + weights(importance) ~ x are retained in the immutable ResponseModifiers value. For the Wiener family, the compiler emits a visible map from positive reaction times and binary choices to signed joint responses. BayesianFit.posterior_predict retains those signed responses, while posterior_response returns a ResponseDraws record with positive times and matching choices. posterior_epred gives expected positive time; posterior_choice_probs gives lower/upper probabilities. These methods share the fitted prediction plan and the existing posterior replay machinery; PredictionOptions and ExpectationOptions describe their shared keywords. See the joint response example and formal response law.

formulas

Brms-style formula frontend over the QVR DSL.

A user writes a regression formula (Wilkinson notation, extended with brms-style random-effect groups) and gets a fitted Bayesian model without hand-writing .qvr source. The compiler emits programs that route through the existing QVR DSL surface:

  • fixed-effect linear predictors as morphism composition X >> beta over observed design-matrix morphisms,
  • random-effect groups as plate-gather of per-level latent draws,
  • responses as observe sites with the family-link kernel (Gaussian / Bernoulli / Binomial / Categorical / Poisson / NegativeBinomial / Cumulative / Beta / Gamma / Student-t / ZeroInflatedPoisson / HurdlePoisson / Mixture) registered in quivers.formulas.family.

The implementation reuses formulae for formula parsing (the Bambi team's pure-Python parser; supports brms-style (slope | group) random effects, smooth terms, and custom contrasts) and lifts the resulting DesignMatrices into a typed Formula didactic.api.Model.

The frontend is the formula→QVR direction of a panproto lens; the QVR DSL is the canonical source of truth, and the formula compiler is a structure-preserving translation from the smaller formula language to the QVR DSL.

links: Mapping[str, Link] = {'identity': _IDENTITY, 'logit': _LOGIT, 'log': _LOG, 'softmax': _SOFTMAX, 'inverse': _INVERSE, 'probit': Link(name='probit', inverse_expr='0.5 * (1.0 + erf({eta} / 1.4142135623730951))', image=_UNIT_OPEN), 'probit_approx': Link(name='probit_approx', inverse_expr='sigmoid(0.07056 * ({eta} * ({eta} * {eta})) + 1.5976 * {eta})', image=_UNIT_OPEN), 'log1p': Link(name='log1p', inverse_expr='expm1({eta})', image=Domain(lower=-1.0)), 'cloglog': Link(name='cloglog', inverse_expr='-1.0 * expm1(-1.0 * exp({eta}))', image=_UNIT_OPEN), 'cauchit': Link(name='cauchit', inverse_expr='0.5 + atan({eta}) / 3.141592653589793', image=_UNIT_OPEN), 'sqrt': Link(name='sqrt', inverse_expr='{eta} * {eta}', image=_NONNEGATIVE, brms_response_expr='sqrt({y})'), 'inverse_square': Link(name='inverse_square', inverse_expr='1.0 / sqrt({eta})', image=Domain(), brms_response_expr='1.0 / ({y} * {y})'), 'logm1': Link(name='logm1', inverse_expr='1.0 + exp({eta})', image=Domain(lower=1.0)), 'softplus': Link(name='softplus', inverse_expr=_SOFTPLUS_EXPR, image=Domain()), 'squareplus': Link(name='squareplus', image=Domain(), intermediates=(Binding(name='{name}_link_half', expr='0.5 * {eta}'), Binding(name='{name}_link_scale', expr='max(1.0, abs({name}_link_half))'), Binding(name='{name}_link_root', expr='{name}_link_scale * sqrt({name}_link_half / {name}_link_scale * ({name}_link_half / {name}_link_scale) + 1.0 / {name}_link_scale * (1.0 / {name}_link_scale))'), Binding(name='{name}_link_magnitude', expr='{name}_link_root + select({name}_link_half >= 0.0, {name}_link_half, -1.0 * {name}_link_half)')), inverse_expr='select({name}_link_half >= 0.0, {name}_link_magnitude, 1.0 / {name}_link_magnitude)'), 'softit': Link(name='softit', image=_UNIT_OPEN, intermediates=(Binding(name='{name}_link_positive', expr=_SOFTPLUS_EXPR),), inverse_expr='{name}_link_positive / (1.0 + {name}_link_positive)'), 'tan_half': Link(name='tan_half', inverse_expr='2.0 * atan({eta})', image=Domain(lower=-math.pi, upper=math.pi), brms_intercept_prior='StudentT(1.0, 0.0, 1.0)')}

The built-in inverse links, keyed by link name.

families module-attribute

families: Mapping[str, Family] = FamilyRegistry({'wiener': Family(name='wiener', location_link=_IDENTITY, location_links=('identity', 'log', 'softplus', 'squareplus'), observe_family='Wiener', response_domain=Domain(), decision_event='formula_response * (2.0 * real(formula_decision) - 1.0)', observe_args=('bs', 'ndt', 'bias', 'mu'), aux_params=(AuxParam(name='bs', prior='Gamma(1.0, 1.0)', link=_LOG), AuxParam(name='ndt', prior='LogNormal(-2.0, 0.5)', link=_LOG, domain=_NONNEGATIVE, below_response=True, brms_prior='Uniform(0.0, response_min)'), AuxParam(name='bias', prior='Beta(1.0, 1.0)', link=_LOGIT, domain=_UNIT_OPEN))), 'com_poisson': Family(name='com_poisson', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='COMPoisson', recorded_events=True, log_location_argument='log_rate', observe_args=('mu', 'shape'), aux_params=(AuxParam(name='shape', prior='Gamma(0.01, 0.01)', link=_LOG),)), 'discrete_weibull': Family(name='discrete_weibull', location_link=_LOGIT, location_links=_UNIT_LINKS[:-1], observe_family='DiscreteWeibull', recorded_events=True, observe_args=('mu', 'shape'), aux_params=(AuxParam(name='shape', prior='HalfCauchy(2.0)', link=_LOG),)), 'zero_inflated_asym_laplace': Family(name='zero_inflated_asym_laplace', location_link=_IDENTITY, location_links=_SHIFTED_LINKS, observe_family='ZeroInflatedAsymmetricLaplace', recorded_events=True, observe_args=('zi', 'mu', 'sigma', 'quantile'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='quantile', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_OPEN), AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'negbinomial2': Family(name='negbinomial2', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='NegativeBinomial', recorded_events=True, exposure=Exposure(observe_lets=(Binding(name='rate_shape', expr='negative_binomial_shape * exposure'),), observe_args=('rate_shape', 'negative_binomial_probs')), observe_lets=(Binding(name='negative_binomial_shape', expr='1.0 / sigma'), Binding(name='negative_binomial_probs', expr='mu / (mu + negative_binomial_shape)')), observe_args=('negative_binomial_shape', 'negative_binomial_probs'), aux_params=(AuxParam(name='sigma', prior='Gamma(0.4, 0.3)', link=_LOG, brms_prior='Gamma(0.4, 0.3)'),)), 'skew_normal': Family(name='skew_normal', location_link=_IDENTITY, location_links=_REAL_LINKS + _REAL_EXTENSIONS, observe_family='SkewNormal', recorded_events=True, error_scale='sigma', observe_lets=(Binding(name='skew_delta', expr='sin(atan(alpha))'), Binding(name='skew_center', expr='skew_delta * 0.7978845608028654'), Binding(name='skew_scale', expr='sigma / sqrt(1.0 - skew_center * skew_center)'), Binding(name='skew_location', expr='mu - skew_scale * skew_center')), observe_args=('skew_location', 'skew_scale', 'alpha'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='alpha', prior='Normal(0.0, 4.0)', link=_IDENTITY, domain=_REAL, links=('identity', 'log', 'softplus', 'squareplus')))), 'shifted_lognormal': Family(name='shifted_lognormal', location_link=_IDENTITY, location_links=_LOG_LOCATION_LINKS, observe_family='ShiftedLogNormal', recorded_events=True, log_response=True, response_domain=Domain(), observe_args=('mu', 'sigma', 'ndt'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='ndt', prior='Uniform(0.0, response_min)', link=_LOG, domain=_NONNEGATIVE, below_response=True, brms_prior='Uniform(0.0, response_min)'))), 'frechet': Family(name='frechet', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='Frechet', recorded_events=True, observe_lets=(Binding(name='frechet_scale', expr='mu * exp(-1.0 * lgamma(1.0 - 1.0 / nu))'),), observe_args=('frechet_scale', 'nu'), aux_params=(AuxParam(name='nu', prior='Restrict(base=Gamma(concentration=2.0, rate=0.1), low=1.0)', link=links['logm1'], domain=Domain(lower=1.0), links=('logm1',)),)), 'gen_extreme_value': Family(name='gen_extreme_value', location_link=_IDENTITY, location_links=_SHIFTED_LINKS, observe_family='GeneralizedExtremeValue', recorded_events=True, observe_args=('mu', 'sigma', 'xi'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='xi', prior='Normal(0.0, 0.3)', link=_IDENTITY, domain=_REAL, links=('log1p', 'identity')))), 'gaussian': _GAUSSIAN, 'bernoulli': Family(name='bernoulli', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='Bernoulli', r_squared='model'), 'binomial': Family(name='binomial', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='Binomial', recorded_events=True, factor_levels=2, observe_args=('trials', 'mu'), trials_parameter='total_count'), 'beta_binomial': Family(name='beta_binomial', location_link=_LOGIT, location_links=_UNIT_LINKS[:-1], observe_family='BetaBinomial', recorded_events=True, observe_lets=(Binding(name='beta_binomial_concentration1', expr='mu * phi'), Binding(name='beta_binomial_concentration0', expr='(1.0 - mu) * phi')), observe_args=('trials', 'beta_binomial_concentration1', 'beta_binomial_concentration0'), trials_parameter='total_count', aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG),)), 'categorical': Family(name='categorical', location_link=_SOFTMAX, location_links=_COMPOSITIONAL_LINKS, observe_family='Categorical', response=ResponseSpec(kind='categorical')), 'multinomial': Family(name='multinomial', location_link=_SOFTMAX, location_links=_COMPOSITIONAL_LINKS, observe_family='Multinomial', observe_args=('trials', 'mu'), trials_parameter='total_count', response=ResponseSpec(kind='multinomial')), 'dirichlet_multinomial': Family(name='dirichlet_multinomial', location_link=_SOFTMAX, location_links=_COMPOSITIONAL_LINKS, observe_family='DirichletMultinomial', observe_args=('trials', 'mu'), trials_parameter='total_count', aux_params=(AuxParam(name='phi', prior='Gamma(2.0, 0.1)', link=_LOG),), response=ResponseSpec(kind='dirichlet_multinomial')), 'dirichlet': Family(name='dirichlet', location_link=_SOFTMAX, location_links=_COMPOSITIONAL_LINKS, observe_family='Dirichlet', aux_params=(AuxParam(name='phi', prior='Gamma(2.0, 0.1)', link=_LOG),), response=ResponseSpec(kind='dirichlet')), 'dirichlet2': Family(name='dirichlet2', location_link=_LOG, location_links=('log', 'softplus', 'squareplus', 'identity', 'logm1'), observe_family='Dirichlet', response=ResponseSpec(kind='dirichlet2', reference=None)), 'logistic_normal': Family(name='logistic_normal', location_link=_IDENTITY, location_links=('identity',), observe_family='AdditiveLogRatioNormal', aux_params=(AuxParam(name='sigma', prior='HalfNormal(1.0)', link=_LOG, per_component=True),), response=ResponseSpec(kind='logistic_normal')), 'poisson': Family(name='poisson', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='Poisson', recorded_events=True, exposure=Exposure(observe_lets=(Binding(name='rate_mu', expr='mu * exposure'),), observe_args=('rate_mu',))), 'negative_binomial': Family(name='negative_binomial', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='NegativeBinomial', recorded_events=True, exposure=Exposure(observe_lets=(Binding(name='rate_shape', expr='disp * exposure'),), observe_args=('rate_shape', 'negative_binomial_probs')), observe_lets=(Binding(name='negative_binomial_probs', expr='mu / (mu + disp)'),), observe_args=('disp', 'negative_binomial_probs'), aux_params=(AuxParam(name='disp', prior='Gamma(2.0, 2.0)', link=_LOG, brms_class='shape', brms_prior='InverseGamma(0.4, 0.3)'),)), 'gamma': Family(name='gamma', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='Gamma', recorded_events=True, observe_lets=(Binding(name='gamma_rate', expr='shape / mu'),), observe_args=('shape', 'gamma_rate'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'beta': Family(name='beta', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='Beta', recorded_events=True, observe_lets=(Binding(name='beta_concentration1', expr='mu * phi'), Binding(name='beta_concentration0', expr='(1.0 - mu) * phi')), observe_args=('beta_concentration1', 'beta_concentration0'), aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG),)), 'student_t': Family(name='student_t', location_link=_IDENTITY, location_links=_REAL_LINKS + _REAL_EXTENSIONS, observe_family='StudentT', recorded_events=True, error_scale='sigma', elliptical=Elliptical(scale='sigma', df='nu'), observe_args=('nu', 'mu', 'sigma'), aux_params=(AuxParam(name='nu', prior='Gamma(2.0, 0.1)', link=links['logm1'], links=('logm1', 'identity')), AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG))), 'cumulative': Family(name='cumulative', location_link=_IDENTITY, location_links=_ORDINAL_LINKS, observe_family='OrderedLogistic', ordinal=OrdinalSpec(kind='cumulative'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0),)), 'hurdle_cumulative': Family(name='hurdle_cumulative', location_link=_LOGIT, location_links=_ORDINAL_LINKS, observe_family='Categorical', ordinal=OrdinalSpec(kind='hurdle_cumulative'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0), AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'acat': Family(name='acat', location_link=_LOGIT, location_links=_ORDINAL_LINKS, observe_family='Categorical', ordinal=OrdinalSpec(kind='acat'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0),)), 'sratio': Family(name='sratio', location_link=_LOGIT, location_links=_RATIO_LINKS, observe_family='Categorical', ordinal=OrdinalSpec(kind='sratio'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0),)), 'cratio': Family(name='cratio', location_link=_LOGIT, location_links=_RATIO_LINKS, observe_family='Categorical', ordinal=OrdinalSpec(kind='cratio'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0),)), 'zero_inflated_poisson': Family(name='zero_inflated_poisson', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='ZeroInflatedPoisson', recorded_events=True, observe_args=('zi', 'mu'), aux_params=(AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED),)), 'hurdle_poisson': Family(name='hurdle_poisson', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='HurdlePoisson', recorded_events=True, observe_args=('hu', 'mu'), aux_params=(AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED),)), 'zero_inflated_negbinomial': Family(name='zero_inflated_negbinomial', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='ZeroInflatedNegativeBinomial', recorded_events=True, observe_lets=(Binding(name='negative_binomial_probs', expr='mu / (mu + shape)'),), observe_args=('zi', 'shape', 'negative_binomial_probs'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG, brms_prior='InverseGamma(0.4, 0.3)'), AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'zero_inflated_binomial': Family(name='zero_inflated_binomial', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ZeroInflatedBinomial', recorded_events=True, observe_args=('zi', 'trials', 'mu'), trials_parameter='total_count', aux_params=(AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED),)), 'zero_inflated_beta_binomial': Family(name='zero_inflated_beta_binomial', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ZeroInflatedBetaBinomial', recorded_events=True, observe_lets=(Binding(name='beta_binomial_concentration1', expr='mu * phi'), Binding(name='beta_binomial_concentration0', expr='(1.0 - mu) * phi')), observe_args=('zi', 'trials', 'beta_binomial_concentration1', 'beta_binomial_concentration0'), trials_parameter='total_count', aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'hurdle_negbinomial': Family(name='hurdle_negbinomial', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='HurdleNegativeBinomial', recorded_events=True, observe_lets=(Binding(name='negative_binomial_probs', expr='mu / (mu + shape)'),), observe_args=('hu', 'shape', 'negative_binomial_probs'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG, brms_prior='InverseGamma(0.4, 0.3)'), AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'hurdle_gamma': Family(name='hurdle_gamma', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='HurdleGamma', recorded_events=True, observe_lets=(Binding(name='hurdle_gamma_rate', expr='shape / mu'),), observe_args=('hu', 'shape', 'hurdle_gamma_rate'), aux_params=(AuxParam(name='shape', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'hurdle_lognormal': Family(name='hurdle_lognormal', location_link=_IDENTITY, location_links=_LOG_LOCATION_LINKS, observe_family='HurdleLogNormal', recorded_events=True, log_response=True, observe_args=('hu', 'mu', 'sigma'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'zero_inflated_beta': Family(name='zero_inflated_beta', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ZeroOneInflatedBeta', recorded_events=True, response_domain=Domain(upper=1.0, lower_closed=True), observe_args=('mu', 'phi', 'zi', 0.0), aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'xbeta': Family(name='xbeta', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ExtendedBeta', observe_args=('mu', 'phi', 'kappa'), aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='kappa', prior='Gamma(0.01, 0.01)', link=_LOG, brms_prior='Gamma(0.01, 0.01)'))), 'zero_one_inflated_beta': Family(name='zero_one_inflated_beta', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ZeroOneInflatedBeta', observe_args=('mu', 'phi', 'zoi', 'coi'), aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='zoi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED), AuxParam(name='coi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'lognormal': Family(name='lognormal', location_link=_IDENTITY, location_links=_LOG_LOCATION_LINKS, observe_family='LogNormal', recorded_events=True, log_response=True, observe_args=('mu', 'sigma'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG),)), 'asym_laplace': Family(name='asym_laplace', location_link=_IDENTITY, location_links=_SHIFTED_LINKS, observe_family='AsymmetricLaplace', recorded_events=True, observe_args=('mu', 'sigma', 'quantile'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='quantile', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_OPEN))), 'exgaussian': Family(name='exgaussian', location_link=_IDENTITY, location_links=_SHIFTED_LINKS, observe_family='ExGaussian', recorded_events=True, observe_lets=(Binding(name='exgaussian_location', expr='mu - beta'), Binding(name='exgaussian_rate', expr='1.0 / beta')), observe_args=('exgaussian_location', 'sigma', 'exgaussian_rate'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='beta', prior='HalfNormal(1.0)', link=_LOG))), 'inverse_gaussian': Family(name='inverse_gaussian', location_link=_LOG, location_links=('inverse_square', 'inverse', 'identity', 'log', 'softplus', 'squareplus'), observe_family='InverseGaussian', recorded_events=True, observe_args=('mu', 'shape'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'exponential': Family(name='exponential', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='Exponential', recorded_events=True, observe_lets=(Binding(name='exponential_rate', expr='1.0 / mu'),), observe_args=('exponential_rate',)), 'geometric': Family(name='geometric', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='Geometric', recorded_events=True, exposure=Exposure(observe_family='NegativeBinomial', observe_lets=(Binding(name='rate_probs', expr='mu / (1.0 + mu)'),), observe_args=('exposure', 'rate_probs')), observe_lets=(Binding(name='geometric_probs', expr='1.0 / (1.0 + mu)'),), observe_args=('geometric_probs',)), 'weibull': Family(name='weibull', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='Weibull', recorded_events=True, observe_lets=(Binding(name='weibull_scale', expr='mu * exp(-1.0 * lgamma(1.0 + 1.0 / shape))'),), observe_args=('weibull_scale', 'shape'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'von_mises': Family(name='von_mises', location_link=links['tan_half'], location_links=('tan_half', 'identity'), observe_family='VonMises', recorded_events=True, circular=True, observe_args=('mu', 'kappa'), aux_params=(AuxParam(name='kappa', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'cox': Family(name='cox', location_link=_LOG, location_links=('log', 'identity', 'softplus', 'squareplus'), observe_family='BernsteinHazard', recorded_events=True, observe_args=('baseline_breaks', 'baseline_controls', 'mu'), log_location_argument='log_rate', baseline=BaselineSpec()), 'mixture': Family(name='mixture', location_link=_IDENTITY, observe_family='Mixture', recorded_events=True, mixture=MixtureSpec(components=(_GAUSSIAN,)))})

The built-in response families, keyed by brms-style family name.

Each family states its link and its map to the native constructor; the compiler emits them without consulting the family name. Lookup also accepts the brms spellings of a name (negbinomial, student, Gamma, inverse.gaussian, zi_poisson), each resolving to the one registered family.

FormulaField

FormulaField = Literal['fixed_columns', 'design_terms', 'random_terms', 'latent_terms', 'monotonic_terms', 'offsets']

A field of Formula whose elements terms contribute.

PriorInput

PriorInput = Mapping[str, str] | PriorSpec | PriorSet | Sequence[PriorSpec]

Authored exact-name overrides or typed rules normalized to one immutable PriorSet.

PriorDistribution

PriorDistribution = str | RegularizedHorseshoe | R2D2 | ImproperFlat | ConstantPrior

A compositional QVR prior expression, a sampled shrinkage hierarchy, the improper flat prior, or a constant.

FixedColumn didactic-model

FixedColumn(*, term: str, name: str, qvr_name: str, is_intercept: bool = False, category_specific: bool = False, data: ndarray = field(opaque=True, extras=opaque_by_value(_read_only)))

Bases: ValueModel

One evaluated numeric column retained by a regression formula.

Fixed-design columns receive coefficients. Offset and response-weight columns reuse the same immutable data record without coefficient sites.

Columns compare by value: data is stored as a read-only copy made at construction and compared exactly (dtype, shape, and bytes), so two columns are equal only when their labels and data agree.

ATTRIBUTE DESCRIPTION
term

Originating term name (e.g. "poly(x, 2)" or "x").

TYPE: str

name

Per-column label, equal to term for single-column terms and f"{term}_{k+1}" (1-indexed, matching R's display) for multi-column terms like poly(x, 2).

TYPE: str

qvr_name

QVR-legal identifier derived from name (alnum / _ only). Fixed-design inputs use this identifier; offsets and response weights use compiler-owned input names.

TYPE: str

is_intercept

True for the constant-1 proportional predictor column.

TYPE: bool

category_specific

Whether cs(expr) gives this column one coefficient per ordinal transition.

TYPE: bool

data

The column's values, shape (N,); read-only.

TYPE: ndarray

GaussianDesignTerm didactic-model

GaussianDesignTerm(*, term: str, qvr_name: str, column_indices: tuple[int, ...], data: ndarray = field(opaque=True, extras=opaque_by_value(_read_only)), basis: SplineBasis | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), coefficient_map: tuple[tuple[float, ...], ...] = (), constraint: tuple[float, ...] = (), scale_group: str = '', category_specific: bool = False, gp: GaussianProcessBlock | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

One coupled Gaussian coefficient block evaluated on response rows.

ATTRIBUTE DESCRIPTION
term, qvr_name

Authored term label and normalized runtime design identifier.

TYPE: str

column_indices

Columns of the retained formula evaluator carrying penalized coordinates.

TYPE: tuple[int, ...]

data

Read-only response-row by Gaussian-coordinate design matrix. Coordinates multiply standard-Normal innovations and one independently sampled scale. Unpenalized null-space columns retain ordinary population priors.

TYPE: ndarray

basis

Retained structural basis state when generated from a spline.

TYPE: SplineBasis or None

coefficient_map

Original basis coordinates to evaluated null and Gaussian coordinates, in their retained evaluator-column order; empty for a supplied design. For one level of a factor by smooth, the map applies before the rows of other levels are set to zero.

TYPE: tuple[tuple[float, ...], ...]

constraint

Original training-basis mean defining the identification constraint.

TYPE: tuple[float, ...]

scale_group

Name of a smoothing scale shared with other blocks (an mgcv id), or empty when this block samples its own scale.

TYPE: str

category_specific

Whether the block has one coefficient vector per ordinal transition.

TYPE: bool

gp

For an approximate gp() term, the block whose coordinates take per-coordinate scales sqrt(spd) of sampled sdgp and lscale in place of one smoothing scale. For an exact gp() term, the block whose coordinates are its distinct inputs: data maps rows to inputs with their by contrast values, and column_indices name the 1 + D evaluated columns it reads.

TYPE: GaussianProcessBlock or None

SplineBasis didactic-model

SplineBasis(*, knots: tuple[float, ...], degree: int)

Bases: ValueModel

Immutable structural state of an evaluated B-spline basis.

ATTRIBUTE DESCRIPTION
knots

Complete nondecreasing knot sequence, including repeated boundaries.

TYPE: tuple[float, ...]

degree

Nonnegative polynomial degree. The source basis width is the knot count minus degree minus one.

TYPE: int

RandomTerm didactic-model

RandomTerm(*, slope: str, group: str, correlation_id: str | None = None, shared: bool = False, specific: bool = False, column: FixedColumn | SymbolicColumn | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), options: GroupOptions | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), covariance: GroupCovariance | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), bar: int = 0)

Bases: ValueModel

One random-effect group, e.g. (1 | g) or (x | g).

ATTRIBUTE DESCRIPTION
slope

"Intercept" for (1 | g); otherwise the slope variable name.

TYPE: str

group

Grouping factor name.

TYPE: str

correlation_id

Correlation-block identity; None requests independent effects.

TYPE: str or None

shared

Whether the identity was explicitly named and can join blocks across location and auxiliary formulas.

TYPE: bool

column

Evaluated slope column, including categorical contrasts and numeric transforms. The intercept uses a constant column.

TYPE: FixedColumn or None

specific

Whether a slope the program computes has one coefficient per ordinal transition.

TYPE: bool

options

gr() or mm() options of the term; None without any.

TYPE: GroupOptions or None

covariance

Known covariance between the levels that the options name.

TYPE: GroupCovariance or None

bar

Position of the term's bar in the formula.

TYPE: int

category_specific property

category_specific: bool

Return whether the slope has one coefficient per transition.

RETURNS DESCRIPTION
bool

True for a cs() slope.

Formula didactic-model

Formula(*, formula: str, response_name: str, fixed_columns: tuple[FixedColumn | SymbolicColumn, ...] = field(default_factory=tuple, opaque=True, extras=OPAQUE_BY_VALUE), design_terms: tuple[GaussianDesignTerm, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), random_terms: tuple[RandomTerm, ...] = field(default_factory=tuple, opaque=True, extras=OPAQUE_BY_VALUE), response_layout: ResponseLayout = field(default_factory=ResponseLayout, opaque=True, extras=OPAQUE_BY_VALUE), response_values: ndarray = field(opaque=True, extras=opaque_by_value(_read_only)), group_levels: dict[str, tuple[str, ...]] = field(default_factory=dict), group_indices: dict[str, tuple[int, ...]] = field(default_factory=dict), offsets: tuple[FixedColumn, ...] = field(default_factory=tuple, opaque=True, extras=OPAQUE_BY_VALUE), modifiers: ResponseModifiers = field(default_factory=ResponseModifiers, opaque=True, extras=OPAQUE_BY_VALUE), latent_terms: tuple[LatentTerm, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), monotonic_terms: tuple[MonotonicTerm, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), grouping: GroupingPlan = field(default_factory=GroupingPlan, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A parsed regression formula plus the data it was parsed against.

Formulas compare by value over every field: two formulas are equal only when their formula strings, response names, fixed columns (labels and data), random terms, offsets, response weights, response values, group levels, and group indices all agree. The arrays are stored as read-only copies made at construction.

ATTRIBUTE DESCRIPTION
formula

Original formula string.

TYPE: str

response_name

Name of the response column.

TYPE: str

fixed_columns

One entry per design-matrix column (matches R/brms's one-coefficient-per-column convention).

TYPE: tuple[FixedColumn, ...]

design_terms

Coupled Gaussian basis contributions with separate penalty-scale priors.

TYPE: tuple[GaussianDesignTerm, ...]

random_terms

Random-effect group specifications.

TYPE: tuple[RandomTerm, ...]

response_values

Response values with shape (N, *response_layout.event_shape); read-only.

TYPE: ndarray

response_layout

Event coordinates and evaluated numeric carrier.

TYPE: ResponseLayout

group_levels

Canonical level ordering per grouping factor, used to derive deterministic plate-index tensors.

TYPE: dict[str, tuple[str, ...]]

modifiers

Checked response-row weights and decision columns, independent of predictor coefficients.

TYPE: ResponseModifiers

offsets

Evaluated offset(expr) and exposure(expr) contributions on the linear-predictor scale. These columns receive no coefficients.

TYPE: tuple[FixedColumn, ...]

group_indices

Per-group integer index array, shape (N,).

TYPE: dict[str, tuple[int, ...]]

latent_terms

Structured latent vectors added to the location predictor, such as brms car terms, with their retained row-to-coordinate coding.

TYPE: tuple[LatentTerm, ...]

monotonic_terms

brms mo() special-effects columns: cumulative category indicators of each monotonic factor and the covariate of the other components.

TYPE: tuple[MonotonicTerm, ...]

grouping

brms interaction (g1:g2) and multi-membership (mm()) grouping factors, multi-membership codes and weights, member covariates, and gr(cov = ) matrix names.

TYPE: GroupingPlan

category_specific property

category_specific: bool

Return whether a term has one coefficient per ordinal transition.

RETURNS DESCRIPTION
bool

True for a formula with a cs() term.

without

without(parts: Collection[FormulaPart]) -> Formula

Return the formula without some of its elements.

PARAMETER DESCRIPTION
parts

Elements to leave out.

TYPE: Collection[FormulaPart]

RETURNS DESCRIPTION
Formula

The formula with every other element, in authored order.

Source code in src/quivers/formulas/formula.py
def without(self, parts: Collection[FormulaPart]) -> Formula:
    """Return the formula without some of its elements.

    Parameters
    ----------
    parts : Collection[FormulaPart]
        Elements to leave out.

    Returns
    -------
    Formula
        The formula with every other element, in authored order.
    """

    def absent(field: FormulaField, key: str) -> bool:
        return FormulaPart(field=field, key=key) in parts

    return self.with_(
        fixed_columns=tuple(
            column
            for column in self.fixed_columns
            if not absent("fixed_columns", column.name)
        ),
        design_terms=tuple(
            term
            for term in self.design_terms
            if not absent("design_terms", term.qvr_name)
        ),
        random_terms=tuple(
            term
            for term in self.random_terms
            if not absent("random_terms", f"{term.group}:{term.slope}")
        ),
        latent_terms=tuple(
            term
            for term in self.latent_terms
            if not absent("latent_terms", term.name)
        ),
        monotonic_terms=tuple(
            term
            for term in self.monotonic_terms
            if not absent("monotonic_terms", term.name)
        ),
        offsets=tuple(
            column
            for index, column in enumerate(self.offsets)
            if not absent("offsets", str(index))
        ),
    )

FormulaData didactic-model

FormulaData(*, source: Formula = field(opaque=True, extras=OPAQUE_BY_VALUE), witnesses: tuple[Witness, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), group_laws: tuple[GroupBlockLaw, ...] = field(default_factory=tuple, opaque=True, extras=OPAQUE_BY_VALUE), level_sites: tuple[LevelSite, ...] = field(default_factory=tuple, opaque=True, extras=OPAQUE_BY_VALUE), prior_targets: tuple[PriorTarget, ...] = field(default_factory=tuple, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The complement of a Formula under its translation to a program.

The program states which terms a model has. The complement holds what a program cannot state: the data, the authored names, and the binding by which each authored element is recognized. backward(module, complement) reads the terms from the module and their content from here.

PARAMETER DESCRIPTION
source

The translated formula.

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

witnesses

Binding of each element of the formula in the program.

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

group_laws

Laws of the group blocks of the program.

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

level_sites

Sites holding values for every level of a grouping factor.

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

prior_targets

Parameter roles, authored labels, and nominal coefficient axes of the program's sites.

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

group_layouts property

group_layouts: tuple[GroupBlockLayout, ...]

Return the coordinate layout of each group block.

RETURNS DESCRIPTION
tuple[GroupBlockLayout, ...]

Raw sites and coefficient slices derived from the block laws.

ResponseLayout didactic-model

ResponseLayout(*, component_names: tuple[str, ...] = (), carrier: Literal['real', 'integer'] = 'real', category_levels: tuple[str, ...] = (), ordered: bool = False, category_values: tuple[int, ...] = ())

Bases: ValueModel

Retain event coordinates independently of the observation-row axis.

PARAMETER DESCRIPTION
component_names

Ordered labels of a vector event; empty for a scalar response.

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

carrier

Numeric carrier of the evaluated response, before family validation.

TYPE: Literal['real', 'integer'] DEFAULT: 'real'

category_levels

Scalar factor labels in their evaluated contrast order; distinct from vector event component names.

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

ordered

Whether the original factor declares an ordering.

TYPE: bool DEFAULT: False

category_values

Integer response value of each category, for a response whose categories are integers read as brms reads them (ordinal codes 1, ..., K). Empty for a factor response and for the zero-based codes 0, ..., K - 1.

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

event_shape property

event_shape: tuple[int, ...]

Return event dimensions, excluding observation rows.

RETURNS DESCRIPTION
tuple[int, ...]

Empty for a scalar response, or one extent for vector components.

ResponseModifiers didactic-model

ResponseModifiers(*, weights: FixedColumn | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), decision: FixedColumn | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), censoring: CensoringSpec | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), truncation: TruncationSpec | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), standard_error: StandardErrorSpec | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), subset: RowSelection | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), trials: FixedColumn | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), rate: FixedColumn | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), thresholds: int | None = None, threshold_groups: ThresholdGroups | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), weights_scale: bool = False, sources: tuple[tuple[str, str | int | float | bool], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Retain typed response-row inputs independently of predictor coefficients.

ATTRIBUTE DESCRIPTION
weights

Finite nonnegative observation weights, optionally scaled after selection.

TYPE: FixedColumn or None

decision

Binary boundary decisions, zero for lower and one for upper. Numeric 0/1 and lower/upper labels normalize to the same integer carrier.

TYPE: FixedColumn or None

censoring

Recorded exact or censored outcome events.

TYPE: CensoringSpec or None

truncation

Inclusive bounds on the response sampling law.

TYPE: TruncationSpec or None

standard_error

Known measurement errors and optional residual scale.

TYPE: StandardErrorSpec or None

subset

Structural row selection performed before evaluating the design: the rows kept by subset and by removing rows with missing model values, as original positions.

TYPE: RowSelection or None

trials

Exact finite trial counts supplied by a response modifier.

TYPE: FixedColumn or None

rate

Positive response denominators of brms rate(), multiplying the count mean (and the negative binomial shape) of each row.

TYPE: FixedColumn or None

thresholds

Number of ordinal thresholds declared by brms thres() or cat() (one fewer than the number of categories), which may exceed the number of observed categories.

TYPE: int or None

threshold_groups

Row codes, labels, and threshold counts of brms thres(n, gr), whose groups each own one threshold vector.

TYPE: ThresholdGroups or None

weights_scale

Whether weights were normalized to the number of included rows.

TYPE: bool

sources

Authored column references and scalar literals used to bind fresh sampling-law inputs without requiring recorded outcomes.

TYPE: tuple[tuple[str, str or int or float or bool], ...]

columns

columns() -> tuple[tuple[str, FixedColumn], ...]

Return supplied role-column pairs in canonical input order.

RETURNS DESCRIPTION
tuple of role and FixedColumn

Checked modifier inputs with no fitted coefficient.

Source code in src/quivers/formulas/formula.py
def columns(self) -> tuple[tuple[str, FixedColumn], ...]:
    """Return supplied role-column pairs in canonical input order.

    Returns
    -------
    tuple of role and FixedColumn
        Checked modifier inputs with no fitted coefficient.
    """
    columns = [("weights", self.weights), ("decision", self.decision)]
    if self.censoring is not None:
        columns.extend(
            (
                ("censoring", self.censoring.status),
                ("censoring_upper", self.censoring.upper),
            )
        )
    if self.truncation is not None:
        columns.extend(
            (
                ("trunc_lower", self.truncation.lower),
                ("trunc_upper", self.truncation.upper),
            )
        )
    if self.standard_error is not None:
        columns.append(("standard_error", self.standard_error.column))
    columns.append(("trials", self.trials))
    columns.append(("rate", self.rate))
    if self.threshold_groups is not None:
        columns.append(("threshold_group", self.threshold_groups.column))
    return tuple((role, column) for role, column in columns if column is not None)

CensoringSpec didactic-model

CensoringSpec(*, status: FixedColumn = field(opaque=True, extras=OPAQUE_BY_VALUE), upper: FixedColumn | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Retain recorded event codes and interval endpoints on response rows.

PARAMETER DESCRIPTION
status

Codes minus one left, zero exact, one right, and two interval.

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

upper

Interval upper endpoints with safe placeholders on inactive rows.

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

TruncationSpec didactic-model

TruncationSpec(*, lower: FixedColumn | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), upper: FixedColumn | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Retain inclusive sampling bounds without changing predictor columns.

PARAMETER DESCRIPTION
lower

Constant or rowwise inclusive bounds; None leaves that side unbounded.

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

upper

Constant or rowwise inclusive bounds; None leaves that side unbounded.

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

StandardErrorSpec didactic-model

StandardErrorSpec(*, column: FixedColumn = field(opaque=True, extras=OPAQUE_BY_VALUE), sigma: bool = False)

Bases: ValueModel

Retain known measurement errors and the residual-scale policy.

PARAMETER DESCRIPTION
column

Finite nonnegative standard errors in response units.

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

sigma

Whether to include the estimated residual scale in quadrature. The default False matches brms: known errors alone scale the likelihood.

TYPE: bool DEFAULT: False

RowSelection didactic-model

RowSelection(*, size: int, positions: tuple[int, ...])

Bases: ValueModel

Map included response rows to their original dataframe positions.

PARAMETER DESCRIPTION
size

Original row count before selection.

TYPE: int

positions

Included positions in original order.

TYPE: tuple[int, ...]

FormulaPart didactic-model

FormulaPart(*, field: FormulaField, key: str)

Bases: ValueModel

One authored element of a formula.

PARAMETER DESCRIPTION
field

Field of Formula that holds the element.

TYPE: str

key

Name of the element within the field.

TYPE: str

Link(*, name: str, inverse_expr: str, intermediates: tuple[Binding, ...] = (), image: Domain | None = None, brms_intercept_prior: str | None = None, brms_response_expr: str | None = None)

Bases: Model

Inverse-link function bridging a linear predictor on :math:\mathbb{R} to the family's natural parameter space.

ATTRIBUTE DESCRIPTION
name

Canonical name (e.g. "identity", "logit", "log", "probit", "cloglog").

TYPE: str

inverse_expr

QVR expression giving the family parameter from the linear predictor, written {eta}. The compiler emits exactly this expression. {name} is the parameter being defined, for referring to intermediates.

TYPE: str

intermediates

Shared quantities bound, in order, before the inverse; each name and expression may use {eta} and {name}.

TYPE: tuple[Binding, ...]

image

Interval the inverse maps the real line onto, coordinate by coordinate for a vector link. None when it is not declared, which a parameter whose domain has a lower endpoint above zero refuses.

TYPE: Domain or None

brms_intercept_prior

brms's default prior of a centered location intercept under this link, where it is not the response-scaled Student-t.

TYPE: str or None

brms_response_expr

The link applied to the response {y}, where brms reads the scales of its default priors from the linked response; None where brms keeps its fixed scale.

TYPE: str or None

is_identity property

is_identity: bool

Whether the parameter is its linear predictor.

RETURNS DESCRIPTION
bool

True when the inverse is the identity.

is_log property

is_log: bool

Whether the linear predictor is the logarithm of the parameter.

RETURNS DESCRIPTION
bool

True when the inverse is the exponential.

AuxParam didactic-model

AuxParam(*, name: str, prior: str, link: Link, fixed_default: float | None = None, domain: Domain = Domain(), brms_class: str | None = None, brms_prior: str | None = None, links: tuple[str, ...] | None = None, below_response: bool = False, per_component: bool = False, coordinates: ParameterCoordinates | None = None)

Bases: Model

An auxiliary family parameter (scale, dispersion, etc.).

ATTRIBUTE DESCRIPTION
name

Variable name to emit in the .qvr source.

TYPE: str

prior

Prior distribution expression (e.g. "HalfCauchy(2.0)").

TYPE: str

link

Link applied to a per-row linear predictor if the parameter is itself distributionally regressed (y ~ x, sigma ~ x, etc.); otherwise unused.

TYPE: Link

fixed_default

Optional constant used unless the parameter is explicitly regressed, fixed, or given a prior. Ordinal discrimination defaults to one.

TYPE: float or None

brms_class

brms parameter class when it differs from name.

TYPE: str or None

brms_prior

brms's default prior where it is specific to this family's parameter; otherwise the default of the parameter's brms class applies.

TYPE: str or None

domain

Values the parameter may take; the positive half-line by default. A fixed value is checked against it. A lower endpoint above zero is narrower than the native constraint, so a prior is restricted to it and a link must map into it.

TYPE: Domain

links

Links Family.with_links admits for the parameter, where they are not those brms gives every parameter of the domain (admissible_links).

TYPE: tuple[str, ...] or None

below_response

Whether the parameter is a shift every response exceeds. A fixed value is checked against the responses, prior and brms_prior may name the smallest response as response_min, and inference starts at a quarter of it unless the prior is already bounded by it.

TYPE: bool

per_component

Whether the parameter has one value per free component of the family's ResponseSpec.

TYPE: bool

coordinates

The axis of a parameter that takes one value per element of an axis of its own; None for a scalar parameter.

TYPE: ParameterCoordinates or None

parameter_class property

parameter_class: str

The brms class of the parameter.

RETURNS DESCRIPTION
str

The declared class, or the parameter's own name.

admissible_links: tuple[str, ...] | None

The links brms admits for the parameter.

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

The declared links, or those brms gives every parameter on the positive half-line or the unit interval. None for a parameter on another interval that declares no links.

bounded_by_response property

bounded_by_response: bool

Whether the default prior is bounded by the smallest response.

RETURNS DESCRIPTION
bool

True when prior names response_min.

with_response_minimum

with_response_minimum(prior: str, response: ndarray) -> str

Bind the smallest response in a prior of this parameter.

PARAMETER DESCRIPTION
prior

Prior expression, possibly naming response_min.

TYPE: str

response

Training responses.

TYPE: ndarray

RETURNS DESCRIPTION
str

The prior with response_min replaced by its value.

RAISES DESCRIPTION
ValueError

If the prior names response_min for a parameter that does not declare below_response.

Source code in src/quivers/formulas/family.py
def with_response_minimum(self, prior: str, response: np.ndarray) -> str:
    """Bind the smallest response in a prior of this parameter.

    Parameters
    ----------
    prior : str
        Prior expression, possibly naming ``response_min``.
    response : np.ndarray
        Training responses.

    Returns
    -------
    str
        The prior with ``response_min`` replaced by its value.

    Raises
    ------
    ValueError
        If the prior names ``response_min`` for a parameter that does
        not declare `below_response`.
    """
    if RESPONSE_MIN not in prior:
        return prior
    if not self.below_response:
        raise ValueError(
            f"the prior of {self.name!r} names {RESPONSE_MIN}, which only a "
            "parameter declaring AuxParam.below_response may"
        )
    return prior.replace(RESPONSE_MIN, repr(float(np.min(response))))

Binding didactic-model

Binding(*, name: str, expr: str)

Bases: Model

One named quantity defined by a QVR expression over earlier names.

ATTRIBUTE DESCRIPTION
name

Name bound in the emitted program.

TYPE: str

expr

Deterministic QVR expression defining it.

TYPE: str

Domain didactic-model

Domain(*, lower: float | None = 0.0, upper: float | None = None, lower_closed: bool = False, upper_closed: bool = False)

Bases: Model

The interval of values a family parameter or response may take.

ATTRIBUTE DESCRIPTION
lower

Lower endpoint, or None when unbounded below.

TYPE: float or None

upper

Upper endpoint, or None when unbounded above.

TYPE: float or None

lower_closed

Whether the lower endpoint belongs to the interval.

TYPE: bool

upper_closed

Whether the upper endpoint belongs to the interval.

TYPE: bool

contains

contains(value: float) -> bool

Test membership of one finite value.

PARAMETER DESCRIPTION
value

Candidate value.

TYPE: float

RETURNS DESCRIPTION
bool

True when the value lies in the interval.

Source code in src/quivers/formulas/family.py
def contains(self, value: float) -> bool:
    """Test membership of one finite value.

    Parameters
    ----------
    value : float
        Candidate value.

    Returns
    -------
    bool
        True when the value lies in the interval.
    """
    above = self.lower is None or (
        value >= self.lower if self.lower_closed else value > self.lower
    )
    below = self.upper is None or (
        value <= self.upper if self.upper_closed else value < self.upper
    )
    return above and below

within

within(other: Domain) -> bool

Test whether this interval is contained in another.

PARAMETER DESCRIPTION
other

Candidate enclosing interval.

TYPE: Domain

RETURNS DESCRIPTION
bool

True when every value of this interval lies in other.

Source code in src/quivers/formulas/family.py
def within(self, other: Domain) -> bool:
    """Test whether this interval is contained in another.

    Parameters
    ----------
    other : Domain
        Candidate enclosing interval.

    Returns
    -------
    bool
        True when every value of this interval lies in ``other``.
    """
    above = other.lower is None or (
        self.lower is not None
        and (
            self.lower > other.lower
            or self.lower == other.lower
            and (other.lower_closed or not self.lower_closed)
        )
    )
    below = other.upper is None or (
        self.upper is not None
        and (
            self.upper < other.upper
            or self.upper == other.upper
            and (other.upper_closed or not self.upper_closed)
        )
    )
    return above and below

requirement

requirement() -> str

Describe the interval as the completion of "must ...".

RETURNS DESCRIPTION
str

A verb phrase stating the constraint.

Source code in src/quivers/formulas/family.py
def requirement(self) -> str:
    """Describe the interval as the completion of "must ...".

    Returns
    -------
    str
        A verb phrase stating the constraint.
    """
    if self.lower is None and self.upper is None:
        return "be a real number"
    if self.upper is None:
        if self.lower == 0:
            return "be nonnegative" if self.lower_closed else "be strictly positive"
        return (
            f"be at least {self.lower:g}"
            if self.lower_closed
            else f"exceed {self.lower:g}"
        )
    if self.lower is None:
        return (
            f"be at most {self.upper:g}"
            if self.upper_closed
            else f"be below {self.upper:g}"
        )
    if not self.lower_closed and not self.upper_closed:
        return f"be strictly between {self.lower:g} and {self.upper:g}"
    left = "[" if self.lower_closed else "("
    right = "]" if self.upper_closed else ")"
    return f"be in {left}{self.lower:g}, {self.upper:g}{right}"

Elliptical didactic-model

Elliptical(*, scale: str, df: str | None = None)

Bases: Model

The elliptical residual law of a location-scale family.

A family declaring one has the density of a multivariate Normal or Student-t in one coordinate, so residuals may be correlated across rows (autocorrelation terms) or across responses (set_rescor) under the multivariate law with the same scale and degrees of freedom.

ATTRIBUTE DESCRIPTION
scale

Auxiliary parameter scaling the residual.

TYPE: str

df

Auxiliary parameter giving the Student degrees of freedom; None for the Normal law.

TYPE: str or None

kernel property

kernel: str

The native law of a correlated residual vector.

RETURNS DESCRIPTION
str

The multivariate Normal, or Student-t under degrees of freedom.

parameterization property

parameterization: tuple[str, ...]

The constructor parameters of kernel in schema order.

RETURNS DESCRIPTION
tuple[str, ...]

Location and Cholesky scale factor, after the degrees of freedom of a Student-t.

Exposure didactic-model

Exposure(*, observe_lets: tuple[Binding, ...] = (), observe_args: tuple[str | float, ...], observe_family: str | None = None)

Bases: Model

The law of a count accumulated over exposure unit denominators.

A family carrying one is closed under summing independent unit-exposure counts, which is what a rate() response term requires.

ATTRIBUTE DESCRIPTION
observe_lets

Quantities bound after the family's own, written over the formula parameters, the family's bindings and exposure.

TYPE: tuple[Binding, ...]

observe_args

Native constructor arguments of the accumulated count; "exposure" names the denominator itself.

TYPE: tuple[str or float, ...]

observe_family

Native law of the accumulated count when it leaves the family's own.

TYPE: str or None

OrdinalSpec didactic-model

OrdinalSpec(*, kind: Literal['cumulative', 'acat', 'sratio', 'cratio', 'hurdle_cumulative'], link: Literal['logit', 'probit', 'probit_approx', 'cloglog', 'cauchit', 'softit'] = 'logit', thresholds: Literal['flexible', 'equidistant', 'sum_to_zero'] = 'flexible')

Bases: Model

Static ordinal likelihood and threshold configuration.

ATTRIBUTE DESCRIPTION
kind

Cumulative, adjacent-category, stopping-ratio, or continuation-ratio construction. The hurdle variant adds a separate lowest category zero.

TYPE: str

link

Inverse link for cumulative or transition probabilities.

TYPE: str

thresholds

Flexible, equally spaced, or explicitly sum-centered thresholds.

TYPE: str

ResponseSpec didactic-model

ResponseSpec(*, kind: Literal['categorical', 'multinomial', 'dirichlet_multinomial', 'dirichlet', 'dirichlet2', 'logistic_normal'], reference: int | str | None = 0)

Bases: Model

Retain the component coordinate system of a categorical or vector law.

PARAMETER DESCRIPTION
kind

Native response construction using the shared component predictor.

TYPE: str

reference

Zero-predictor component by position or retained label. None gives every component its own predictor under proper coefficient priors.

TYPE: int or str or None DEFAULT: 0

reference_index

reference_index(labels: tuple[str, ...]) -> int | None

Resolve a reference against retained component or factor labels.

PARAMETER DESCRIPTION
labels

Complete component order.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
int or None

Reference position, or None for all-component predictors.

RAISES DESCRIPTION
ValueError

If the reference is missing, invalid, or incompatible with ALR.

Source code in src/quivers/formulas/family.py
def reference_index(self, labels: tuple[str, ...]) -> int | None:
    """Resolve a reference against retained component or factor labels.

    Parameters
    ----------
    labels : tuple[str, ...]
        Complete component order.

    Returns
    -------
    int or None
        Reference position, or None for all-component predictors.

    Raises
    ------
    ValueError
        If the reference is missing, invalid, or incompatible with ALR.
    """
    reference = self.reference
    if reference is None:
        if self.kind == "logistic_normal":
            raise ValueError(
                "logistic_normal requires an explicit reference component"
            )
        return None
    if isinstance(reference, str):
        if reference not in labels:
            raise ValueError(
                f"unknown reference component {reference!r}; choices are {labels}"
            )
        return labels.index(reference)
    if (
        isinstance(reference, bool)
        or not isinstance(reference, int)
        or not 0 <= reference < len(labels)
    ):
        raise ValueError("reference component must identify a retained component")
    return reference

coordinate_indices

coordinate_indices(labels: tuple[str, ...]) -> tuple[int, ...]

Return coefficient coordinates in retained component order.

PARAMETER DESCRIPTION
labels

Complete component order.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
tuple[int, ...]

Component positions carrying free predictors.

Source code in src/quivers/formulas/family.py
def coordinate_indices(self, labels: tuple[str, ...]) -> tuple[int, ...]:
    """Return coefficient coordinates in retained component order.

    Parameters
    ----------
    labels : tuple[str, ...]
        Complete component order.

    Returns
    -------
    tuple[int, ...]
        Component positions carrying free predictors.
    """
    reference = self.reference_index(labels)
    return tuple(index for index in range(len(labels)) if index != reference)

BaselineSpec didactic-model

BaselineSpec(*, df: int = 5, degree: int = 3, boundary_knots: tuple[float, ...] | None = None, interior_knots: tuple[float, ...] = (), by: str | None = None)

Bases: Model

Retain spline structure independently of fitted baseline weights.

PARAMETER DESCRIPTION
df

Number of normalized M-spline components when selecting knots.

TYPE: int DEFAULT: 5

degree

Polynomial degree when selecting knots.

TYPE: int DEFAULT: 3

boundary_knots

Explicit finite boundary span, starting at zero. None selects knots once from training events and follow-up times.

TYPE: tuple[float, float] or None DEFAULT: None

interior_knots

Explicit interior knots when boundary_knots is supplied.

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

by

Grouping factor for separate normalized profiles on this common basis.

TYPE: str or None DEFAULT: None

resolve

resolve(formula: Formula) -> MSplineBasis

Resolve the baseline once from retained training responses.

PARAMETER DESCRIPTION
formula

Evaluated positive scalar response and modifier columns.

TYPE: Formula

RETURNS DESCRIPTION
MSplineBasis

Explicit basis or event-quantile training basis.

RAISES DESCRIPTION
ValueError

If responses are not positive finite scalar event times or the requested automatic knot structure is not identified by the data.

Source code in src/quivers/formulas/_survival.py
def resolve(self, formula: Formula) -> MSplineBasis:
    """Resolve the baseline once from retained training responses.

    Parameters
    ----------
    formula : Formula
        Evaluated positive scalar response and modifier columns.

    Returns
    -------
    MSplineBasis
        Explicit basis or event-quantile training basis.

    Raises
    ------
    ValueError
        If responses are not positive finite scalar event times or the
        requested automatic knot structure is not identified by the data.
    """
    values = np.asarray(formula.response_values)
    if values.ndim != 1 or not np.isfinite(values).all() or np.any(values <= 0):
        raise ValueError(
            "cox responses require finite strictly positive event times"
        )
    if self.boundary_knots is not None:
        if len(self.boundary_knots) != 2:
            raise ValueError("cox baseline requires two boundary knots")
        if self.boundary_knots[0] != 0:
            raise ValueError("cox baseline must start at zero")
        return MSplineBasis(
            (self.boundary_knots[0], self.boundary_knots[1]),
            self.interior_knots,
            self.degree,
        )
    if self.interior_knots:
        raise ValueError("explicit interior knots require boundary knots")
    censoring = formula.modifiers.censoring
    events = values if censoring is None else values[censoring.status.data == 0]
    followup = values
    if censoring is not None and censoring.upper is not None:
        followup = np.concatenate(
            (followup, censoring.upper.data[censoring.status.data == 2])
        )
    return cox_spline_basis(
        events.tolist(), followup.tolist(), df=self.df, degree=self.degree
    )

MixtureSpec didactic-model

MixtureSpec(*, components: tuple[Family, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), order: Literal['mu', 'none'] = 'none', equal: tuple[tuple[str, str], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Retain the components and identification of a finite mixture family.

PARAMETER DESCRIPTION
components

Component families in brms order; nmix repetitions are expanded. One component is a template, repeated mixture_components times.

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

order

"mu" orders the component location intercepts; "none" applies no ordering constraint.

TYPE: ('mu', 'none') DEFAULT: "mu"

equal

Distributional parameters set equal to another parameter of the same class, brms sigma2 = "sigma1", as (target, source) pairs.

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

Family didactic-model

Family(*, name: str, location_link: Link, observe_family: str, observe_lets: tuple[Binding, ...] = (), observe_args: tuple[str | float, ...] = ('mu',), exposure: Exposure | None = None, log_location_argument: str | None = None, circular: bool = False, log_response: bool = False, response_domain: Domain | None = None, decision_event: str | None = None, location_links: tuple[str, ...] | None = None, recorded_events: bool = False, error_scale: str | None = None, elliptical: Elliptical | None = None, r_squared: Literal['model', 'residual'] = 'residual', factor_levels: int | None = None, mixture_law: str | None = None, aux_params: tuple[AuxParam, ...] = (), trials_parameter: str | None = None, ordinal: OrdinalSpec | None = None, response: ResponseSpec | None = None, baseline: BaselineSpec | None = None, custom: CustomFamilySpec | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), mixture: MixtureSpec | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), kernel_law: KernelLaw | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Response family: observation kernel plus its link and any auxiliary parameters.

The compiler emits, for each family-keyed regression:

  1. The auxiliary-parameter latent draws (intercept-only by default; one per parameter named in aux_params).
  2. A let eta = <linear predictor> binding the location's linear predictor.
  3. A let mu = <link.inverse_expr> binding the natural parameter.
  4. A single observe y : Resp <- <observe_family>(mu, ...) step parameterised by mu and the auxiliary parameters.

The native constructor rarely shares the formula parameterization (a mean and a shape against a concentration and a rate). observe_lets and observe_args state that map as data, so the compiler emits any family the same way.

trials_parameter identifies families that require a constant or per-row number of trials. It names the native constructor parameter; fitting and prediction use the same metadata to validate trial counts. ordinal retains static likelihood, inverse-link, and threshold choices; ordinary QVR expressions lower these choices to checked category logits. response retains joint component predictors, reference coordinates, and the distinction between scalar categorical and vector response events.

PARAMETER DESCRIPTION
name

Formula registry key.

TYPE: str

location_link

Location or mean inverse link.

TYPE: Link

observe_family

Checked native observation family.

TYPE: str

observe_lets

Quantities derived from mu and the auxiliary parameters, bound in order before the observation: the map from the formula parameterization to the native constructor's.

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

observe_args

Native constructor arguments in schema order: names of formula parameters or of observe_lets, literal constants, or "trials" for the per-row trial counts of a family with trials_parameter.

TYPE: tuple[str or float, ...] DEFAULT: ('mu',)

exposure

Law of the count over a rate() denominator; None when the family is not closed under summing unit-exposure counts.

TYPE: Exposure or None DEFAULT: None

log_location_argument

Native constructor parameter that accepts the location on the log scale. Under a log location link the linear predictor is passed to it directly, so a rate too large to exponentiate still scores.

TYPE: str or None DEFAULT: None

circular

Whether the response is an angle, for which an expectation needs an angular convention and no arithmetic mean is defined.

TYPE: bool DEFAULT: False

log_response

Whether the location and scale parameterize the logarithm of the response, so default prior scales are taken on the log response.

TYPE: bool DEFAULT: False

response_domain

Interval every observed response must lie in, stated only where the native support depends on parameters or the family narrows it; otherwise the native support and its atoms give it.

TYPE: Domain or None DEFAULT: None

decision_event

Expression forming the scored event from formula_response and the binary formula_decision of a dec() term. None for a family whose event is its response.

TYPE: str or None DEFAULT: None

location_links

Links with_links admits for the location; None declares no decision, and with_links refuses a location link.

TYPE: tuple[str, ...] or None DEFAULT: None

recorded_events

Whether the family admits the cens() and trunc() terms.

TYPE: bool DEFAULT: False

error_scale

Auxiliary parameter giving the residual scale that the known errors of a se() term replace, or join in quadrature; None when the family admits no se().

TYPE: str or None DEFAULT: None

elliptical

Elliptical residual law, under which residuals may be correlated across rows or responses.

TYPE: Elliptical or None DEFAULT: None

r_squared

Variance bayes_r2 reads by default: the law's own conditional variance or that of the residuals.

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

factor_levels

Number of levels of a factor response the family codes 0, ..., n - 1, stated only where the native support depends on parameters (coded_levels).

TYPE: int or None DEFAULT: None

mixture_law

Native law of a finite mixture whose components all have this family, over the stacked native arguments of the components. The law must truncate each component itself. None mixes the component laws.

TYPE: str or None DEFAULT: None

aux_params

Auxiliary priors and distributional links.

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

trials_parameter

Native parameter receiving exact per-row trial counts.

TYPE: str or None DEFAULT: None

ordinal

Retained ordinal thresholds and transition construction.

TYPE: OrdinalSpec or None DEFAULT: None

response

Joint component coordinate system and reference selection.

TYPE: ResponseSpec or None DEFAULT: None

baseline

Retained normalized spline structure for proportional hazards.

TYPE: BaselineSpec or None DEFAULT: None

custom

Checked custom constructor bindings and compilation-local native law.

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

mixture

Components and ordering of a finite mixture built by quivers.formulas.mixture.

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

kernel_law

A law that builds the family's kernel itself, such as a named QVR program; None for a family observed through its native law.

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

response_interval property

response_interval: Domain | None

The interval a scalar continuous response must lie in.

An atom of the native law at an endpoint of its support closes that endpoint.

RETURNS DESCRIPTION
Domain or None

The declared or native interval, or None for a discrete, vector or composite response, whose values are checked by their coding.

native property

The semantic record of the observed native law.

Support, element type, discreteness, atoms and event rank are read from it; the family does not restate them.

RETURNS DESCRIPTION
DistributionFamily

The record registered under observe_family, from the custom catalog of a custom family.

retains_log_location property

retains_log_location: bool

Whether the observation takes the linear predictor on the log scale.

RETURNS DESCRIPTION
bool

True when the native law accepts a log-scale location and the location link is the logarithm.

vector_response property

vector_response: bool

Whether one response event is a vector of components.

RETURNS DESCRIPTION
bool

True for compositional and count-vector responses.

coded_levels property

coded_levels: int | None

Number of levels of a factor the family reads as integer codes.

RETURNS DESCRIPTION
int or None

The declared number, or the size of a native support 0, ..., n - 1. None for a family without such codes; a category_response takes any number of levels.

scores_cutpoints property

scores_cutpoints: bool

Whether the native law of an ordinal family takes its cutpoints.

RETURNS DESCRIPTION
bool

True for a law over a predictor and cutpoints, False for a law over category logits.

component_scale property

component_scale: AuxParam | None

The auxiliary parameter with one value per free component.

RETURNS DESCRIPTION
AuxParam or None

The parameter declaring AuxParam.per_component, if any.

residual_scale property

residual_scale: AuxParam | None

The residual scale, the parameter of brms class sigma.

RETURNS DESCRIPTION
AuxParam or None

The parameter of that class, or None.

latent_response_obstacle property

latent_response_obstacle: str | None

Why a missing response cannot be a latent coordinate.

A missing mi() response is a latent coordinate drawn from the response law, so the law needs a density on an interval and nothing fixed by the recorded responses.

RETURNS DESCRIPTION
str or None

The property that rules it out, or None when the family admits mi() responses.

reads_location property

reads_location: bool

Whether the family's kernel reads the location mu.

RETURNS DESCRIPTION
bool

True for a native law; for a kernel law, whether mu is one of the parameters it replaces.

kernel_columns property

kernel_columns: tuple[str, ...]

The data columns the family's kernel reads at each row by name.

RETURNS DESCRIPTION
tuple[str, ...]

The columns of a kernel law; empty for a native law, which reads only the formulas' columns.

unordered_categories property

unordered_categories: bool

Whether the response is an unordered category code.

RETURNS DESCRIPTION
bool

True for a scalar categorical response.

category_response property

category_response: bool

Whether the response is a category code with class probabilities.

RETURNS DESCRIPTION
bool

True for ordinal and unordered categorical responses, and for a mixture of ordinal components.

native_parameter

native_parameter(name: str) -> str

Name the native constructor parameter that receives a quantity.

PARAMETER DESCRIPTION
name

Formula parameter or derived binding passed to the constructor.

TYPE: str

RETURNS DESCRIPTION
str

The constructor parameter in the native schema.

RAISES DESCRIPTION
ValueError

If the quantity is not itself a native constructor argument.

Source code in src/quivers/formulas/family.py
def native_parameter(self, name: str) -> str:
    """Name the native constructor parameter that receives a quantity.

    Parameters
    ----------
    name : str
        Formula parameter or derived binding passed to the constructor.

    Returns
    -------
    str
        The constructor parameter in the native schema.

    Raises
    ------
    ValueError
        If the quantity is not itself a native constructor argument.
    """
    arguments = {
        argument: native
        for argument, native in zip(
            self.observe_args, self.native.parameter_names, strict=False
        )
        if isinstance(argument, str)
    }
    if name not in arguments:
        raise ValueError(
            f"family {self.name!r} does not pass {name!r} to its native "
            "constructor (Family.observe_args)"
        )
    return arguments[name]
admissible_links(parameter: str) -> tuple[str, ...]

List the links the family admits for one parameter.

PARAMETER DESCRIPTION
parameter

mu for the location or an auxiliary parameter name.

TYPE: str

RETURNS DESCRIPTION
tuple[str, ...]

Admissible link names; those of its component for a mixture template.

RAISES DESCRIPTION
ValueError

If the parameter is unknown or declares no links.

Source code in src/quivers/formulas/family.py
def admissible_links(self, parameter: str) -> tuple[str, ...]:
    """List the links the family admits for one parameter.

    Parameters
    ----------
    parameter : str
        ``mu`` for the location or an auxiliary parameter name.

    Returns
    -------
    tuple[str, ...]
        Admissible link names; those of its component for a mixture
        template.

    Raises
    ------
    ValueError
        If the parameter is unknown or declares no links.
    """
    if self.mixture is not None and len(self.mixture.components) == 1:
        return self.mixture.components[0].admissible_links(parameter)
    if parameter == "mu":
        declared, field = self.location_links, "Family.location_links"
    else:
        aux = next((aux for aux in self.aux_params if aux.name == parameter), None)
        if aux is None:
            raise ValueError(
                f"unknown family parameter {parameter!r} of {self.name!r}"
            )
        declared, field = aux.admissible_links, "AuxParam.links"
    if declared is None:
        raise ValueError(
            f"family {self.name!r} declares no admissible links for parameter "
            f"{parameter!r} ({field})"
        )
    return declared

kernel_bindings

kernel_bindings(frame: DataFrame, data2: Mapping[str, ndarray | DataFrame | Tensor | float | int] | None) -> dict[str, Tensor]

Bind the data the family's kernel reads by name.

PARAMETER DESCRIPTION
frame

The rows of the response, in row order.

TYPE: DataFrame

data2

Values that are not indexed by the rows.

TYPE: Mapping[str, ndarray or DataFrame or Tensor or float or int] or None

RETURNS DESCRIPTION
dict[str, Tensor]

Values by input name; empty for a native law.

Source code in src/quivers/formulas/family.py
def kernel_bindings(
    self,
    frame: pd.DataFrame,
    data2: Mapping[str, np.ndarray | pd.DataFrame | torch.Tensor | float | int]
    | None,
) -> dict[str, torch.Tensor]:
    """Bind the data the family's kernel reads by name.

    Parameters
    ----------
    frame : pandas.DataFrame
        The rows of the response, in row order.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame or torch.Tensor or float or int] or None
        Values that are not indexed by the rows.

    Returns
    -------
    dict[str, torch.Tensor]
        Values by input name; empty for a native law.
    """
    return {} if self.kernel_law is None else self.kernel_law.bindings(frame, data2)

check_kernel

check_kernel(module: Module, families: FamilyCatalog | None) -> None

Check a model emitted with the family's kernel law.

A native law's model is correct by its construction; a kernel law states a body the formulas change, so its model is checked.

PARAMETER DESCRIPTION
module

The emitted model.

TYPE: Module

families

Compilation-local laws of the model.

TYPE: FamilyCatalog or None

Source code in src/quivers/formulas/family.py
def check_kernel(self, module: Module, families: FamilyCatalog | None) -> None:
    """Check a model emitted with the family's kernel law.

    A native law's model is correct by its construction; a kernel law
    states a body the formulas change, so its model is checked.

    Parameters
    ----------
    module : Module
        The emitted model.
    families : FamilyCatalog or None
        Compilation-local laws of the model.
    """
    if self.kernel_law is not None:
        self.kernel_law.check(module, families)

with_baseline

with_baseline(basis: MSplineBasis | None = None, *, df: int = 5, degree: int = 3, by: str | None = None) -> Family

Configure a retained normalized baseline for proportional hazards.

PARAMETER DESCRIPTION
basis

Explicit immutable knots and tail policy, or automatic training knots.

TYPE: MSplineBasis or None DEFAULT: None

df

Number of basis components for automatic selection.

TYPE: int DEFAULT: 5

degree

Polynomial degree for automatic selection.

TYPE: int DEFAULT: 3

by

Grouping factor with a separate normalized baseline simplex per level. Every group retains the same knot structure and endpoint tail policy.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
Family

Independent family retaining the selected baseline structure.

RAISES DESCRIPTION
ValueError

If this is not a baseline-hazard family or automatic dimensions are invalid.

Source code in src/quivers/formulas/family.py
def with_baseline(
    self,
    basis: MSplineBasis | None = None,
    *,
    df: int = 5,
    degree: int = 3,
    by: str | None = None,
) -> Family:
    """Configure a retained normalized baseline for proportional hazards.

    Parameters
    ----------
    basis : MSplineBasis or None
        Explicit immutable knots and tail policy, or automatic training knots.
    df : int
        Number of basis components for automatic selection.
    degree : int
        Polynomial degree for automatic selection.
    by : str or None
        Grouping factor with a separate normalized baseline simplex per level.
        Every group retains the same knot structure and endpoint tail policy.

    Returns
    -------
    Family
        Independent family retaining the selected baseline structure.

    Raises
    ------
    ValueError
        If this is not a baseline-hazard family or automatic dimensions are invalid.
    """
    if self.baseline is None:
        raise ValueError(
            "baseline configuration requires a proportional-hazards family"
        )
    if basis is not None and not isinstance(basis, MSplineBasis):
        raise ValueError("basis must be an immutable MSplineBasis")
    if isinstance(degree, bool) or not isinstance(degree, int) or degree < 0:
        raise ValueError("baseline degree must be a nonnegative integer")
    if isinstance(df, bool) or not isinstance(df, int) or df < degree + 1:
        raise ValueError("baseline df must be an integer at least degree + 1")
    if by is not None and (not isinstance(by, str) or not by):
        raise ValueError("baseline by must be a nonempty grouping column name")
    return self.with_(
        baseline=BaselineSpec(
            df=basis.size if basis is not None else df,
            degree=basis.degree if basis is not None else degree,
            boundary_knots=basis.boundary_knots if basis is not None else None,
            interior_knots=basis.interior_knots if basis is not None else (),
            by=by,
        )
    )

response_ordinal

response_ordinal() -> OrdinalSpec | None

Read the ordinal construction that codes the response categories.

RETURNS DESCRIPTION
OrdinalSpec or None

The family's own ordinal specification, that of the first component for a mixture of ordinal families, or None for a response without ordered categories.

Source code in src/quivers/formulas/family.py
def response_ordinal(self) -> OrdinalSpec | None:
    """Read the ordinal construction that codes the response categories.

    Returns
    -------
    OrdinalSpec or None
        The family's own ordinal specification, that of the first
        component for a mixture of ordinal families, or None for a
        response without ordered categories.
    """
    if self.mixture is not None:
        return self.mixture.components[0].ordinal
    return self.ordinal

with_reference

with_reference(reference: int | str | None) -> Family

Select the reference component of a joint categorical predictor.

PARAMETER DESCRIPTION
reference

Component position or label; None estimates every component.

TYPE: int or str or None

RETURNS DESCRIPTION
Family

Independent family retaining the selected coordinate system.

RAISES DESCRIPTION
ValueError

If this family has no component predictor or forbids references.

Source code in src/quivers/formulas/family.py
def with_reference(self, reference: int | str | None) -> Family:
    """Select the reference component of a joint categorical predictor.

    Parameters
    ----------
    reference : int or str or None
        Component position or label; None estimates every component.

    Returns
    -------
    Family
        Independent family retaining the selected coordinate system.

    Raises
    ------
    ValueError
        If this family has no component predictor or forbids references.
    """
    if self.response is None:
        raise ValueError(
            "reference components require a categorical or vector family"
        )
    if self.response.kind == "dirichlet2" and reference is not None:
        raise ValueError(
            "dirichlet2 estimates every concentration and has no reference"
        )
    if self.response.kind == "logistic_normal" and reference is None:
        raise ValueError("logistic_normal requires an explicit reference component")
    return self.with_(response=self.response.with_(reference=reference))

with_thresholds

with_thresholds(thresholds: Literal['flexible', 'equidistant', 'sum_to_zero']) -> Family

Return an ordinal family with the requested threshold structure.

PARAMETER DESCRIPTION
thresholds

Threshold configuration; ordering applies only to cumulative models.

TYPE: ('flexible', 'equidistant', 'sum_to_zero') DEFAULT: "flexible"

RETURNS DESCRIPTION
Family

Independent family value preserving links and auxiliary parameters.

RAISES DESCRIPTION
ValueError

If the family is not ordinal or the threshold option is unknown.

Source code in src/quivers/formulas/family.py
def with_thresholds(
    self, thresholds: Literal["flexible", "equidistant", "sum_to_zero"]
) -> Family:
    """Return an ordinal family with the requested threshold structure.

    Parameters
    ----------
    thresholds : {"flexible", "equidistant", "sum_to_zero"}
        Threshold configuration; ordering applies only to cumulative models.

    Returns
    -------
    Family
        Independent family value preserving links and auxiliary parameters.

    Raises
    ------
    ValueError
        If the family is not ordinal or the threshold option is unknown.
    """
    if self.ordinal is None:
        raise ValueError("threshold configuration requires an ordinal family")
    if thresholds not in {"flexible", "equidistant", "sum_to_zero"}:
        raise ValueError(f"unknown ordinal threshold configuration {thresholds!r}")
    return self.with_(ordinal=self.ordinal.with_(thresholds=thresholds))
with_links(**parameters: str) -> Family

Return a family with selected parameter links.

PARAMETER DESCRIPTION
**parameters

Link names keyed by mu for the location or an auxiliary parameter name, for instance sigma="softplus". The links of a mixture template are those of its one component.

TYPE: str DEFAULT: {}

RETURNS DESCRIPTION
Family

An independent family value with the requested links.

RAISES DESCRIPTION
ValueError

If a parameter or link is unknown, or if brms does not admit the link for that family parameter; the error lists the admissible links. Categorical models require their multinomial softmax location link.

Source code in src/quivers/formulas/family.py
def with_links(self, **parameters: str) -> Family:
    """Return a family with selected parameter links.

    Parameters
    ----------
    **parameters : str
        Link names keyed by ``mu`` for the location or an auxiliary
        parameter name, for instance ``sigma="softplus"``. The links of
        a mixture template are those of its one component.

    Returns
    -------
    Family
        An independent family value with the requested links.

    Raises
    ------
    ValueError
        If a parameter or link is unknown, or if brms does not admit the
        link for that family parameter; the error lists the admissible
        links. Categorical models require their multinomial softmax
        location link.
    """
    if self.mixture is not None:
        if len(self.mixture.components) > 1:
            raise ValueError(
                "mixture links belong to the components; set them before mixture()"
            )
        template = self.mixture.components[0].with_links(**parameters)
        return self.with_(
            location_link=template.location_link,
            mixture=self.mixture.with_(components=(template,)),
        )
    known = {"mu", *(aux.name for aux in self.aux_params)}
    unknown = parameters.keys() - known
    if unknown:
        raise ValueError(
            f"unknown family parameters {sorted(unknown)}; choices are {sorted(known)}"
        )
    if self.response is not None and self.response.kind in {
        "categorical",
        "multinomial",
        "dirichlet_multinomial",
        "dirichlet",
    }:
        if parameters.get("mu") == "logit":
            parameters["mu"] = "softmax"
        if parameters.get("mu", "softmax") != "softmax":
            raise ValueError(
                "compositional means require the softmax location link"
            )
    if (
        self.response is not None
        and self.response.kind == "logistic_normal"
        and parameters.get("mu", "identity") != "identity"
    ):
        raise ValueError(
            "logistic_normal log ratios require the identity location link"
        )
    invalid = set(parameters.values()) - links.keys()
    if invalid:
        raise ValueError(
            f"unknown links {sorted(invalid)}; choices are {sorted(links)}"
        )
    ordinal = self.ordinal
    observe_family = self.observe_family
    requested = dict(parameters)
    if ordinal is not None and "mu" in parameters:
        # The location of a cumulative family is its own linear predictor;
        # the identity keeps it, with thresholds on the logit scale.
        if parameters["mu"] == "identity" and ordinal.kind == "cumulative":
            requested["mu"] = "logit"
    for parameter, link in requested.items():
        allowed = self.admissible_links(parameter)
        if link not in allowed:
            raise ValueError(
                f"link {link!r} is not supported for parameter {parameter!r} of "
                f"family {self.name!r}; admissible links are {list(allowed)}"
            )
    if ordinal is not None and "mu" in requested:
        ordinal = ordinal.with_(link=requested["mu"])
        observe_family = (
            _CUTPOINT_LAWS.get(ordinal.link, "Categorical")
            if ordinal.kind == "cumulative"
            else "Categorical"
        )
    return self.with_(
        location_link=links[parameters["mu"]]
        if "mu" in parameters
        else self.location_link,
        observe_family=observe_family,
        ordinal=ordinal,
        aux_params=tuple(
            aux.with_(link=links[parameters[aux.name]])
            if aux.name in parameters
            else aux
            for aux in self.aux_params
        ),
    )

FormulaToQVRModule

FormulaToQVRModule(family: Family, *, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', user_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, distributional: Mapping[str, Formula] | None = None, predictor_graph: PredictorGraph | None = None, correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, fixed_parameters: Mapping[str, float] | None = None, default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none')

Bases: Lens[Formula, Module, FormulaData]

Translate a Formula to a QVR Module AST.

A typed didactic.api.Lens whose complement is a FormulaData: the source formula and the program binding of each of its elements. Which terms a formula has is read back from the module.

PARAMETER DESCRIPTION
family

Response family from quivers.formulas.families.

TYPE: Family

fixed_prior

Default prior for fixed-effect coefficients, in the surface form "Family(arg, arg, ...)"; numeric args become floats, identifier args stay as variable references in the emitted program.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

random_scale_prior

Default prior for random-effect scale parameters.

TYPE: str DEFAULT: 'HalfNormal(1.0)'

correlation_prior

Default LKJ Cholesky prior for correlated coefficient blocks.

TYPE: str DEFAULT: 'LKJCholesky(1.0)'

group_covariances

Known covariance between labeled levels of each grouping factor. Coefficient correlations retain their existing LKJ hierarchy.

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

user_priors

Exact-name overrides or typed role selectors. More specific selectors refine broader rules; ambiguous and unused rules raise an error.

TYPE: PriorInput or None DEFAULT: None

reparameterize

Conditional Gaussian coordinates for scalar, category-specific and component-valued group effects, and grouped threshold log slacks.

TYPE: ('centered', 'noncentered') DEFAULT: "centered"

binomial_trials

Nonnegative common trial count or a per-row trial-count column.

TYPE: int or str DEFAULT: None

thresholds_by

Grouping factor whose levels receive partially pooled ordinal cutpoint spacings.

TYPE: str or None DEFAULT: None

mixture_components

Number of components for family="mixture"; must be at least two.

TYPE: int DEFAULT: 2

predictor_name

Host-data name for an external differentiable predictor.

TYPE: str or None DEFAULT: None

distributional

Auxiliary-parameter formulas on the same response rows. Each predictor receives its own coefficients, covariates, and group effects; a dpar_<parameter>_ prefix distinguishes their names. Group coding must agree across predictors.

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

fixed_parameters

Auxiliary parameters bound to constants on their natural scale, without latent sites or priors. Cannot overlap distributional formulas.

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

default_priors

Default policy for sites no prior rule selects: the proper, autoscaled quivers defaults, or brms::default_prior (flat b, Student-t intercept and scale priors scaled by the response).

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

center

brms center: sample the location intercept on the column-centered design and report it on the original scale. None centers under the brms policy and not under the quivers policy. Distributional predictors are centered under the brms policy or when True.

TYPE: bool or None DEFAULT: None

decomp

brms decomp: sample the location coefficients in scaled QR coordinates and report them on the original scale.

TYPE: ('none', 'QR') DEFAULT: "none"

RAISES DESCRIPTION
ValueError

If an option is out of range or does not apply to family: thresholds_by outside the cumulative family, binomial_trials for a family without trials or outside the exact finite-trial range from zero through 2**53, mixture_components below two or outside the mixture family, or an unknown reparameterize value.

Notes

GetPut: backward (forward(f)) = f for every Formula f. PutGet holds on pairs (t, c) for which t is in the image of forward and c is the corresponding FormulaData.

Source code in src/quivers/formulas/compile.py
def __init__(
    self,
    family: Family,
    *,
    fixed_prior: str = "Normal(0.0, 5.0)",
    random_scale_prior: str = "HalfNormal(1.0)",
    user_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,
    distributional: Mapping[str, Formula] | None = None,
    predictor_graph: PredictorGraph | None = None,
    correlation_prior: str = "LKJCholesky(1.0)",
    group_covariances: Mapping[str, GroupCovariance] | None = None,
    fixed_parameters: Mapping[str, float] | None = None,
    default_priors: DefaultPriorPolicy = "quivers",
    center: bool | None = None,
    decomp: Literal["none", "QR"] = "none",
) -> None:
    # mixtures: the registered "mixture" family is mixture(gaussian, nmix=K).
    family = expand_mixture(family, mixture_components)
    self._family = family
    self._residual: ResidualLaw | None = None
    self._observation: Observation | None = None
    # brms default prior policy and population-coordinate options.
    if default_priors not in ("quivers", "brms"):
        raise ValueError("default_priors must be 'quivers' or 'brms'")
    if center is not None and type(center) is not bool:
        raise TypeError("center must be True, False, or None")
    if decomp not in ("none", "QR"):
        raise ValueError("decomp must be 'none' or 'QR'")
    self._default_priors: DefaultPriorPolicy = default_priors
    # Recorded rows of an mi() response, the rows brms's default scales
    # read (median and mad with na.rm = TRUE; fit-followups).
    self._recorded_rows: np.ndarray | None = None
    self._center = center
    self._decomp: Literal["none", "QR"] = decomp
    self._group_covariances = dict(group_covariances or {})
    if any(
        not isinstance(value, GroupCovariance)
        for value in self._group_covariances.values()
    ):
        raise TypeError(
            "group_covariances values must be GroupCovariance declarations"
        )
    for aux in family.aux_params:
        # The native law checks its own constraint, not a narrower domain.
        if aux.domain.lower and not (
            aux.link.image is not None and aux.link.image.within(aux.domain)
        ):
            raise ValueError(
                f"parameter {aux.name!r} of family {family.name!r} must "
                f"{aux.domain.requirement()}, and its link {aux.link.name!r} "
                "does not map into that range (Link.image)"
            )
    self._fixed_parameters = dict(fixed_parameters or {})
    self._correlation_prior = correlation_prior
    self._distributional = dict(distributional or {})
    self._predictor_graph = predictor_graph
    auxiliary_names = {aux.name for aux in family.aux_params}
    expression_roots = (
        set(predictor_graph.roots) - {"mu"}
        if predictor_graph is not None
        else set()
    )
    unknown_roots = {
        name
        for name in expression_roots - auxiliary_names
        if not is_category_parameter(family, name)
    }
    if unknown_roots:
        raise ValueError(
            f"unknown distributional graph roots {sorted(unknown_roots)}"
        )
    if expression_roots & (
        self._distributional.keys() | self._fixed_parameters.keys()
    ):
        raise ValueError(
            "a family parameter cannot have multiple predictor definitions"
        )
    unknown_fixed = {
        name
        for name in self._fixed_parameters.keys() - auxiliary_names
        if not is_scale_parameter(family, name)
    }
    if unknown_fixed:
        raise ValueError(
            f"unknown fixed auxiliary parameters {sorted(unknown_fixed)}"
        )
    conflicting_fixed = self._fixed_parameters.keys() & self._distributional.keys()
    if conflicting_fixed:
        raise ValueError(
            f"fixed parameters cannot have distributional formulas: {sorted(conflicting_fixed)}"
        )
    for name, value in self._fixed_parameters.items():
        # mixtures: each component validates its own fixed values.
        if family.mixture is not None:
            break
        if (
            isinstance(value, bool)
            or not isinstance(value, (float, int))
            or not math.isfinite(value)
        ):
            raise ValueError(
                f"fixed parameter {name!r} must be a finite real number"
            )
        domain = next(
            (aux.domain for aux in family.aux_params if aux.name == name),
            Domain(),
        )
        if not domain.contains(value):
            raise ValueError(
                f"fixed parameter {name!r} must {domain.requirement()}"
            )
    unknown = self._distributional.keys() - auxiliary_names
    # Category-specific locations mu<c> are checked against the labels.
    unknown = {
        name
        for name in unknown
        if not is_category_parameter(family, name)
        and not is_scale_parameter(family, name)
    }
    if unknown:
        raise ValueError(
            f"FormulaToQVRModule: unknown distributional parameters {sorted(unknown)}; "
            f"choices are {sorted(auxiliary_names)}"
        )
    self._fixed_prior = fixed_prior
    self._random_scale_prior = random_scale_prior
    self._set_prior_configuration(user_priors)
    self._emitted_groups: list[GroupBlockLaw] = []
    # The response laws the kernel emits as nested blocks, and what the
    # latest forward pass took from them.
    self._nested = NestedBlocks()
    self._block_laws: tuple[GroupBlockLaw, ...] = ()
    self._block_targets: tuple[PriorTarget, ...] = ()
    self._grouping: tuple[Formula, dict[str, Formula]] | None = None
    self._baseline_level_sites: tuple[LevelSite, ...] = ()
    # Level hyperparameters another program draws, and those drawn so far.
    self._supplied_sites: frozenset[str] = frozenset()
    self._drawn_sites: frozenset[str] = frozenset()
    self._group_plan: dict[tuple[str, str, str], GroupBlockLaw] = {}
    self._predictors: tuple[Predictor, ...] = ()
    self._separated: tuple[PriorTarget, ...] = ()
    self._component_sites: frozenset[str] = frozenset()
    self._term_laws: FamilyCatalog | None = None
    self._rows: RowSource | None = None
    self._names = ProgramNames()
    conflicting = (
        self._distributional.keys() | expression_roots
    ) & self._named_prior_inputs.keys()
    if conflicting:
        raise ValueError(
            f"priors on distributionally regressed parameters {sorted(conflicting)} must name their coefficients, such as 'dpar_sigma_intercept'"
        )
    if thresholds_by is not None and (
        family.ordinal is None
        or family.ordinal.kind not in {"cumulative", "hurdle_cumulative"}
    ):
        raise ValueError(
            "FormulaToQVRModule: thresholds_by is only valid for the "
            "cumulative family or hurdle_cumulative family"
        )
    from quivers.formulas._response import resolve_trials

    binomial_trials = resolve_trials(family, binomial_trials)
    if family.trials_parameter is None and binomial_trials != 1:
        raise ValueError(
            "FormulaToQVRModule: binomial_trials is only valid for the "
            "families with a trial-count parameter"
        )
    if binomial_trials is not None and (
        not isinstance(binomial_trials, (int, str))
        or isinstance(binomial_trials, bool)
    ):
        raise ValueError(
            "FormulaToQVRModule: binomial_trials must be a nonnegative integer "
            "or a data-column name"
        )
    if isinstance(binomial_trials, int) and binomial_trials < 0:
        raise ValueError("FormulaToQVRModule: binomial_trials must be nonnegative")
    if isinstance(binomial_trials, int) and binomial_trials > _MAX_EXACT_COUNT:
        raise ValueError(
            "FormulaToQVRModule: binomial_trials must be at most 2**53"
        )
    if (
        not isinstance(mixture_components, int)
        or isinstance(mixture_components, bool)
        or mixture_components < 2
    ):
        raise ValueError(
            "FormulaToQVRModule: mixture_components must be an integer "
            "of at least two"
        )
    if family.mixture is None and mixture_components != 2:
        raise ValueError(
            "FormulaToQVRModule: mixture_components is only valid for the "
            "mixture family"
        )
    self._binomial_trials = binomial_trials
    self._thresholds_by = thresholds_by
    self._mixture_components = mixture_components
    if family.mixture is not None:
        validate_mixture_options(
            family,
            self._distributional,
            self._fixed_parameters,
            predictor_name=predictor_name,
            nonlinear=predictor_graph is not None and bool(predictor_graph.leaves),
            thresholds_by=thresholds_by,
        )
    self._predictor_name = (
        _qvr_name(predictor_name) if predictor_name is not None else None
    )
    if reparameterize not in ("centered", "noncentered"):
        raise ValueError(
            f"FormulaToQVRModule: reparameterize must be 'centered' "
            f"or 'noncentered', got {reparameterize!r}"
        )
    self._reparameterize: Literal["centered", "noncentered"] = reparameterize

group_covariances property

group_covariances: dict[str, GroupCovariance]

Read the known level covariances of this emission's grouping factors.

RETURNS DESCRIPTION
dict[str, GroupCovariance]

Covariances given directly and those read from gr(cov = M).

group_layouts property

group_layouts: tuple[GroupBlockLayout, ...]

Read the raw-coordinate layouts emitted by the latest forward pass.

RETURNS DESCRIPTION
tuple[GroupBlockLayout, ...]

Immutable group blocks shared with retained prediction plans.

level_sites property

level_sites: tuple[LevelSite, ...]

Return the sites of the latest forward pass indexed by levels.

RETURNS DESCRIPTION
tuple[LevelSite, ...]

Every level-indexed site once, of the group blocks and of a grouped baseline hazard.

predictors property

predictors: tuple[Predictor, ...]

Return the linear predictors of the latest forward pass.

RETURNS DESCRIPTION
tuple[Predictor, ...]

The location, the distributional parameters, and the nonlinear parameters. Empty for a mixture, whose components have their own.

group_laws property

group_laws: tuple[GroupBlockLaw, ...]

Return the law of each group block of the latest forward pass.

RETURNS DESCRIPTION
tuple[GroupBlockLaw, ...]

Laws in emission order: the program's own, then those of its nested blocks.

rows property

rows: RowSource | None

Return the rows the latest forward pass covers.

RETURNS DESCRIPTION
RowSource or None

Fresh rows of a request, or None for the training rows.

site_priors property

site_priors: Mapping[str, str]

Return the priors configured for exact sites.

RETURNS DESCRIPTION
Mapping[str, str]

Prior source by site name.

observation property

observation: Observation | None

Return the observation of the latest forward pass.

RETURNS DESCRIPTION
Observation or None

The observation of the response, or None before a pass.

names property

names: ProgramNames

Return the names the latest forward pass gives columns and bindings.

RETURNS DESCRIPTION
ProgramNames

The names that differ from the terms' own.

term_laws property

term_laws: FamilyCatalog | None

Return the laws the terms of the latest forward pass draw from.

RETURNS DESCRIPTION
FamilyCatalog or None

Compilation-local laws, or None when every law is built in.

prior_targets property

prior_targets: tuple[PriorTarget, ...]

Read immutable role and axis metadata from the latest emitted model.

prior_set property

prior_set: PriorSet

Read the canonical authored prior rules retained for replay.

response_laws property

response_laws: FamilyCatalog | None

Return the compilation-local laws of the response.

RETURNS DESCRIPTION
FamilyCatalog or None

The catalog of a custom family joined with that of the residual law, or None when the response law is built in.

families

families(response: FamilyCatalog | None = None) -> FamilyCatalog | None

Return every compilation-local law of the latest forward pass.

PARAMETER DESCRIPTION
response

Laws of the response on the rows in use; None for those of the fitted family.

TYPE: FamilyCatalog or None DEFAULT: None

RETURNS DESCRIPTION
FamilyCatalog or None

The response laws joined with those of the terms.

Source code in src/quivers/formulas/compile.py
def families(self, response: FamilyCatalog | None = None) -> FamilyCatalog | None:
    """Return every compilation-local law of the latest forward pass.

    Parameters
    ----------
    response : FamilyCatalog or None
        Laws of the response on the rows in use; None for those of the
        fitted family.

    Returns
    -------
    FamilyCatalog or None
        The response laws joined with those of the terms.
    """
    if response is None:
        response = self.response_laws
    if response is None or self._term_laws is None:
        return response if response is not None else self._term_laws
    return response.with_catalog(self._term_laws)

forward

forward(formula: Formula) -> tuple[Module, FormulaData]

Compile one formula through the shared response emitter.

PARAMETER DESCRIPTION
formula

Evaluated response and design metadata.

TYPE: Formula

RETURNS DESCRIPTION
tuple[Module, FormulaData]

Existing QVR program and its retained formula complement.

Source code in src/quivers/formulas/compile.py
def forward(self, formula: Formula, /) -> tuple[Module, FormulaData]:
    """Compile one formula through the shared response emitter.

    Parameters
    ----------
    formula : Formula
        Evaluated response and design metadata.

    Returns
    -------
    tuple[Module, FormulaData]
        Existing QVR program and its retained formula complement.
    """
    return self._forward(formula)

get_prior

get_prior(formula: Formula) -> dict[str, str]

Inspect the effective priors without compiling or fitting a model.

PARAMETER DESCRIPTION
formula

Evaluated response and predictor columns.

TYPE: Formula

RETURNS DESCRIPTION
dict[str, str]

Overrideable parameter names and their canonical distribution calls, including the actual scales after column autoscaling. Sampled shrinkage includes hyperprior calls and conditional scale references; retain prior_set to reconstruct that specification. Conditional group draws and standard-normal innovations are excluded: their laws define the group parameterization.

RAISES DESCRIPTION
ValueError

If a prior override does not name an available parameter.

Source code in src/quivers/formulas/compile.py
def get_prior(self, formula: Formula, /) -> dict[str, str]:
    """Inspect the effective priors without compiling or fitting a model.

    Parameters
    ----------
    formula : Formula
        Evaluated response and predictor columns.

    Returns
    -------
    dict[str, str]
        Overrideable parameter names and their canonical distribution
        calls, including the actual scales after column autoscaling.
        Sampled shrinkage includes hyperprior calls and conditional scale
        references; retain ``prior_set`` to reconstruct that specification.
        Conditional group draws and standard-normal innovations are
        excluded: their laws define the group parameterization.

    Raises
    ------
    ValueError
        If a prior override does not name an available parameter.
    """
    module, _ = self.forward(formula)
    return self._prior_calls(formula, module)

backward

backward(target: Module, complement: FormulaData) -> Formula

Recover a formula from a QVR module and its complement.

The terms are those the module states; their data and authored names come from the complement.

PARAMETER DESCRIPTION
target

A QVR module in the image of forward.

TYPE: Module

complement

The complement forward returned with that module.

TYPE: FormulaData

RETURNS DESCRIPTION
Formula

The complement's formula without the elements whose bindings the module lacks.

Source code in src/quivers/formulas/compile.py
def backward(self, target: Module, complement: FormulaData, /) -> Formula:
    """Recover a formula from a QVR module and its complement.

    The terms are those the module states; their data and authored names
    come from the complement.

    Parameters
    ----------
    target : Module
        A QVR module in the image of `forward`.
    complement : FormulaData
        The complement `forward` returned with that module.

    Returns
    -------
    Formula
        The complement's formula without the elements whose bindings the
        module lacks.
    """
    names = _program_names(target)
    witnessed: dict[FormulaPart, bool] = {}
    for witness in complement.witnesses:
        witnessed[witness.part] = (
            witnessed.get(witness.part, False) or witness.binding in names
        )
    return complement.source.without(
        [part for part, present in witnessed.items() if not present]
    )

symbolic_column_expressions

symbolic_column_expressions(formula: Formula) -> dict[str, LetExprNode]

Read declared latent-dependent inputs using the ordinary predictor layout.

PARAMETER DESCRIPTION
formula

Primary predictor, together with configured auxiliary and graph leaves.

TYPE: Formula

RETURNS DESCRIPTION
dict[str, LetExprNode]

Actual local input names and canonical expressions. Fixed and random uses of one column retain their existing, separately declared aliases.

RAISES DESCRIPTION
ValueError

If two uses assign different expressions to the same local input.

Source code in src/quivers/formulas/compile.py
def symbolic_column_expressions(self, formula: Formula) -> dict[str, LetExprNode]:
    """Read declared latent-dependent inputs using the ordinary predictor layout.

    Parameters
    ----------
    formula : Formula
        Primary predictor, together with configured auxiliary and graph leaves.

    Returns
    -------
    dict[str, LetExprNode]
        Actual local input names and canonical expressions. Fixed and random
        uses of one column retain their existing, separately declared aliases.

    Raises
    ------
    ValueError
        If two uses assign different expressions to the same local input.
    """
    expressions: dict[str, LetExprNode] = {}
    for name, column in self._symbolic_columns(formula):
        previous = expressions.setdefault(name, column.expression)
        if previous != column.expression:
            raise ValueError(f"symbolic input {name!r} has conflicting expressions")
    return expressions

fixed_column_observations

fixed_column_observations(formula: Formula) -> dict[str, Tensor]

Bind retained covariates, offsets, and response likelihood weights.

PARAMETER DESCRIPTION
formula

The formula whose fixed-effect columns are bound.

TYPE: Formula

RETURNS DESCRIPTION
dict[str, Tensor]

Numeric predictor and offset columns as float32 tensors, keyed by their QVR input names. Auxiliary columns use the prefix dpar_<parameter>_. Response weights retain their stored float64 precision under the formula_weights key.

Source code in src/quivers/formulas/compile.py
def fixed_column_observations(self, formula: Formula) -> dict[str, torch.Tensor]:
    """Bind retained covariates, offsets, and response likelihood weights.

    Parameters
    ----------
    formula : Formula
        The formula whose fixed-effect columns are bound.

    Returns
    -------
    dict[str, torch.Tensor]
        Numeric predictor and offset columns as ``float32`` tensors,
        keyed by their QVR input names. Auxiliary columns use the prefix
        ``dpar_<parameter>_``. Response weights retain their stored
        ``float64`` precision under the ``formula_weights`` key.
    """
    obs: dict[str, torch.Tensor] = {}
    obs.update(bind_inputs(law_inputs(self.group_laws)))
    if (
        formula.response_layout.event_shape
        and self._family.trials_parameter is not None
    ):
        from quivers.formulas._response import count_totals

        obs["formula_trials"] = count_totals(formula)
    if formula.modifiers.weights is not None:
        obs["formula_weights"] = torch.as_tensor(
            formula.modifiers.weights.data.copy()
        )
    if formula.modifiers.decision is not None:
        obs["formula_decision"] = torch.as_tensor(
            formula.modifiers.decision.data.copy(), dtype=torch.bool
        )
    for role, column in self._response_data(formula).column_items():
        if role not in {"weights", "decision"}:
            obs[column.qvr_name] = torch.as_tensor(column.data.copy())
    if formula.modifiers.threshold_groups is not None and threshold_kinds(
        self._family
    ):
        obs.update(
            threshold_inputs(
                formula.modifiers.threshold_groups, threshold_kinds(self._family)
            )
        )
    obs.update(
        bind_inputs(item for term in self._terms(formula) for item in term.inputs())
    )
    if self._predictor_graph is not None:
        from quivers.formulas._predictor_graph import graph_input_bindings

        obs.update(
            graph_input_bindings(
                self._predictor_graph,
                {
                    name: column.data
                    for name, column in self._predictor_graph.inputs.items()
                },
            )
        )
    return obs

GroupBlockLayout didactic-model

GroupBlockLayout(*, group: str, identity: str, coordinate_axis: str | None, parameterization: Literal['centered', 'noncentered'], members: tuple[GroupMemberLayout, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), correlation_site: str | None = None, level_covariance: GroupCovarianceBasis | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Share Gaussian coefficient slices between compilation and prediction.

PARAMETER DESCRIPTION
group

Original grouping factor and correlation-block identity.

TYPE: str

identity

Original grouping factor and correlation-block identity.

TYPE: str

coordinate_axis

Joint finite coordinate axis, absent for one scalar coefficient.

TYPE: str or None

parameterization

Whether raw sites contain coefficients or standard-normal innovations.

TYPE: ('centered', 'noncentered') DEFAULT: "centered"

members

Ordered nonoverlapping coefficient slices.

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

correlation_site

Actual emitted Cholesky site; None denotes an independent block.

TYPE: str or None DEFAULT: None

level_covariance

Known covariance support over labeled levels. Its raw coordinates index this support rather than physical levels. Centered coordinates carry Gaussian deviations; noncentered coordinates are standardized.

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

width property

width: int

Return the joint coordinate count.

RETURNS DESCRIPTION
int

Sum of the retained member widths.

raw_sites property

raw_sites: dict[str, int]

Read the number of coordinates per group at each raw site.

RETURNS DESCRIPTION
dict[str, int]

Sum of member widths at each retained sample-site name. Joint centered members share one site; independent members need not.

GroupMemberLayout didactic-model

GroupMemberLayout(*, prefix: str, slope: str, axis: str | None, width: int, offset: int, coefficient: str, raw_site: str | None, scale_site: str | None = None, mean_site: str | None = None)

Bases: ValueModel

Locate one named coefficient within its joint Gaussian block.

PARAMETER DESCRIPTION
prefix

Predictor namespace and expanded slope label.

TYPE: str

slope

Predictor namespace and expanded slope label.

TYPE: str

axis

Component axis; None denotes a scalar coefficient.

TYPE: str or None

width

Component count and first coordinate in the joint block.

TYPE: int

offset

Component count and first coordinate in the joint block.

TYPE: int

coefficient

Retained deterministic coefficient binding.

TYPE: str

raw_site

Sample site supplying this member's coordinates; None denotes a deterministic zero-rank deviation.

TYPE: str or None

scale_site

Actual emitted conditional scale site for noncentered reconstruction.

TYPE: str or None DEFAULT: None

mean_site

Optional affine hypermean, retained outside the supported deviation subspace for grouped threshold log-spacing profiles.

TYPE: str or None DEFAULT: None

GroupCovariance didactic-model

GroupCovariance(*, levels: tuple[str, ...], matrix: tuple[tuple[float, ...], ...] | Tensor = field(opaque=True, extras=opaque_by_value(_matrix_values)), rank: int | None = None)

Bases: ValueModel

A known covariance between explicitly labeled grouping levels.

PARAMETER DESCRIPTION
levels

Unique authored labels in matrix row and column order. The matrix can include future levels absent from the fitting data.

TYPE: tuple[str, ...]

matrix

Finite symmetric covariance, copied from nested numeric sequences or a fixed Tensor. Its scale is retained; it need not be a correlation.

TYPE: tuple[tuple[float, ...], ...] DEFAULT: field(opaque=True, extras=opaque_by_value(_matrix_values))

rank

None requires positive definiteness. An explicit nonnegative rank declares a positive-semidefinite law on its actual affine support. Eigenvalues below the declared rank must vanish within a relative Double-precision eigensolver tolerance; negative eigenvalues beyond that tolerance are rejected.

TYPE: int or None DEFAULT: None

tensor

tensor() -> Tensor

Read a fresh Double-precision covariance matrix.

RETURNS DESCRIPTION
Tensor

Independent CPU storage; modifying it cannot change this value.

Source code in src/quivers/formulas/_group_covariance.py
def tensor(self) -> torch.Tensor:
    """Read a fresh Double-precision covariance matrix.

    Returns
    -------
    torch.Tensor
        Independent CPU storage; modifying it cannot change this value.
    """
    return torch.tensor(_matrix_values(self.matrix), dtype=torch.float64)

subset

subset(levels: Sequence[str]) -> GroupCovariance

Retain a labeled principal submatrix in the requested order.

PARAMETER DESCRIPTION
levels

Unique known grouping labels.

TYPE: Sequence[str]

RETURNS DESCRIPTION
GroupCovariance

Reordered covariance, retaining explicit PSD support when declared.

RAISES DESCRIPTION
ValueError

If a requested label is unknown or repeated.

Source code in src/quivers/formulas/_group_covariance.py
def subset(self, levels: Sequence[str]) -> GroupCovariance:
    """Retain a labeled principal submatrix in the requested order.

    Parameters
    ----------
    levels : Sequence[str]
        Unique known grouping labels.

    Returns
    -------
    GroupCovariance
        Reordered covariance, retaining explicit PSD support when declared.

    Raises
    ------
    ValueError
        If a requested label is unknown or repeated.
    """
    labels = tuple(levels)
    if not labels or len(set(labels)) != len(labels):
        raise ValueError(
            "group covariance subset labels must be nonempty and unique"
        )
    positions = {label: index for index, label in enumerate(self.levels)}
    missing = set(labels) - positions.keys()
    if missing:
        raise ValueError(
            f"group covariance has no entries for levels {sorted(missing)!r}"
        )
    indices = torch.tensor([positions[label] for label in labels])
    matrix = self.tensor()[indices[:, None], indices[None, :]]
    rank = None
    if self.rank is not None:
        rank = int((torch.linalg.eigvalsh(matrix) > _tolerance(matrix)).sum())
    return GroupCovariance(levels=labels, matrix=matrix, rank=rank)

basis

basis(levels: Sequence[str]) -> GroupCovarianceBasis

Factor a principal covariance without adding artificial dimensions.

PARAMETER DESCRIPTION
levels

Ordered labels used by one emitted Gaussian block.

TYPE: Sequence[str]

RETURNS DESCRIPTION
GroupCovarianceBasis

Orthogonal support projection and exact positive coordinate law.

Source code in src/quivers/formulas/_group_covariance.py
def basis(self, levels: Sequence[str]) -> GroupCovarianceBasis:
    """Factor a principal covariance without adding artificial dimensions.

    Parameters
    ----------
    levels : Sequence[str]
        Ordered labels used by one emitted Gaussian block.

    Returns
    -------
    GroupCovarianceBasis
        Orthogonal support projection and exact positive coordinate law.
    """
    covariance = self.subset(levels)
    matrix = covariance.tensor()
    if covariance.rank is None or covariance.rank == len(covariance.levels):
        projection = torch.eye(len(covariance.levels), dtype=torch.float64)
        coordinate = matrix
    else:
        eigenvalues, eigenvectors = torch.linalg.eigh(matrix)
        rank = covariance.rank
        projection = eigenvectors[:, -rank:] if rank else eigenvectors[:, :0]
        coordinate = torch.diag(eigenvalues[-rank:] if rank else eigenvalues[:0])
    cholesky = (
        torch.linalg.cholesky(coordinate) if coordinate.numel() else coordinate
    )
    return GroupCovarianceBasis(
        levels=covariance.levels,
        projection=_matrix_values(projection),
        covariance=_matrix_values(coordinate),
        coordinate_factor=_matrix_values(cholesky),
        sampling_factor=_matrix_values(projection @ cholesky),
    )

conditional

conditional(fitted_levels: Sequence[str], new_levels: Sequence[str]) -> tuple[Tensor, GroupCovarianceBasis]

Condition new Gaussian levels on the complete fitted level vector.

PARAMETER DESCRIPTION
fitted_levels

Disjoint known labels, in retained and requested order.

TYPE: Sequence[str]

new_levels

Disjoint known labels, in retained and requested order.

TYPE: Sequence[str]

RETURNS DESCRIPTION
tuple[Tensor, GroupCovarianceBasis]

Mean map A_new,fitted A_fitted,fitted^+ and a support factor of the Schur-complement conditional row covariance. Nonzero hypermeans are applied outside this deviation-space operation.

RAISES DESCRIPTION
ValueError

If labels overlap or the conditional covariance is not PSD.

Source code in src/quivers/formulas/_group_covariance.py
def conditional(
    self, fitted_levels: Sequence[str], new_levels: Sequence[str]
) -> tuple[torch.Tensor, GroupCovarianceBasis]:
    """Condition new Gaussian levels on the complete fitted level vector.

    Parameters
    ----------
    fitted_levels, new_levels : Sequence[str]
        Disjoint known labels, in retained and requested order.

    Returns
    -------
    tuple[torch.Tensor, GroupCovarianceBasis]
        Mean map ``A_new,fitted A_fitted,fitted^+`` and a support factor
        of the Schur-complement conditional row covariance. Nonzero
        hypermeans are applied outside this deviation-space operation.

    Raises
    ------
    ValueError
        If labels overlap or the conditional covariance is not PSD.
    """
    fitted, new = tuple(fitted_levels), tuple(new_levels)
    if set(fitted) & set(new):
        raise ValueError(
            "conditional group covariance requires disjoint level sets"
        )
    joined = self.subset((*fitted, *new)).tensor()
    count = len(fitted)
    aa, ba, bb = (
        joined[:count, :count],
        joined[count:, :count],
        joined[count:, count:],
    )
    if self.rank is None:
        factor = torch.linalg.cholesky(aa)
        mean_map = torch.cholesky_solve(ba.T, factor).T
    else:
        eigenvalues, vectors = torch.linalg.eigh(aa)
        positive = eigenvalues > _tolerance(aa)
        inverse = (vectors[:, positive] / eigenvalues[positive]) @ vectors[
            :, positive
        ].T
        mean_map = ba @ inverse
    schur = bb - mean_map @ ba.T
    schur = (schur + schur.T) * 0.5
    values, vectors = torch.linalg.eigh(schur)
    tolerance = _tolerance(joined) * 8
    if bool((values < -tolerance).any()):
        raise ValueError(
            "conditional group covariance is not positive semidefinite"
        )
    if self.rank is None and bool((values <= 0).any()):
        raise ValueError(
            "conditional covariance lost positive definiteness at Double precision"
        )
    positive = values > (0 if self.rank is None else tolerance)
    return mean_map, GroupCovarianceBasis(
        levels=new,
        projection=_matrix_values(vectors[:, positive]),
        covariance=_matrix_values(torch.diag(values[positive])),
        coordinate_factor=_matrix_values(torch.diag(values[positive].sqrt())),
        sampling_factor=_matrix_values(
            vectors[:, positive] * values[positive].sqrt()
        ),
    )

GroupCovarianceBasis didactic-model

GroupCovarianceBasis(*, levels: tuple[str, ...], projection: tuple[tuple[float, ...], ...] = field(opaque=True, extras=opaque_by_value(_matrix_values)), covariance: tuple[tuple[float, ...], ...] = field(opaque=True, extras=opaque_by_value(_matrix_values)), coordinate_factor: tuple[tuple[float, ...], ...] = field(opaque=True, extras=opaque_by_value(_matrix_values)), sampling_factor: tuple[tuple[float, ...], ...] = field(opaque=True, extras=opaque_by_value(_matrix_values)))

Bases: ValueModel

Retain the physical-level map and a nonsingular support-coordinate law.

PARAMETER DESCRIPTION
levels

Physical grouping labels.

TYPE: tuple[str, ...]

projection

Orthonormal columns mapping support coordinates to physical levels.

TYPE: tuple[tuple[float, ...], ...] DEFAULT: field(opaque=True, extras=opaque_by_value(_matrix_values))

covariance

Positive-definite support covariance; an empty matrix denotes rank zero.

TYPE: tuple[tuple[float, ...], ...] DEFAULT: field(opaque=True, extras=opaque_by_value(_matrix_values))

coordinate_factor

Cached Cholesky factor of the support covariance.

TYPE: tuple[tuple[float, ...], ...] DEFAULT: field(opaque=True, extras=opaque_by_value(_matrix_values))

sampling_factor

Cached projection times coordinate_factor. Prediction materializes this factor without repeating an eigendecomposition or Cholesky.

TYPE: tuple[tuple[float, ...], ...] DEFAULT: field(opaque=True, extras=opaque_by_value(_matrix_values))

rank property

rank: int

Return the number of stochastic level coordinates.

RETURNS DESCRIPTION
int

Support dimension, including zero for a deterministic deviation.

tensors

tensors(*, like: Tensor | None = None) -> tuple[Tensor, Tensor, Tensor]

Materialize projection, coordinate covariance, and sampling factor.

PARAMETER DESCRIPTION
like

Optional floating dtype and device context.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
tuple[Tensor, Tensor, Tensor]

Q, C, and Q chol(C) with explicit physical/support axes.

Source code in src/quivers/formulas/_group_covariance.py
def tensors(
    self, *, like: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Materialize projection, coordinate covariance, and sampling factor.

    Parameters
    ----------
    like : torch.Tensor or None
        Optional floating dtype and device context.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor, torch.Tensor]
        ``Q``, ``C``, and ``Q chol(C)`` with explicit physical/support axes.
    """
    dtype = torch.float64 if like is None else like.dtype
    device = None if like is None else like.device
    projection = torch.tensor(self.projection, dtype=dtype, device=device).reshape(
        len(self.levels), self.rank
    )
    covariance = torch.tensor(self.covariance, dtype=dtype, device=device).reshape(
        self.rank, self.rank
    )
    factor = torch.tensor(self.sampling_factor, dtype=dtype, device=device).reshape(
        len(self.levels), self.rank
    )
    return projection, covariance, factor

NonlinearExpression didactic-model

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

Bases: ValueModel

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

PARAMETER DESCRIPTION
expression

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

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

syntax

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

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

ComponentExpression didactic-model

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

Bases: ValueModel

An explicitly labelled vector value whose coordinates keep nominal order.

PARAMETER DESCRIPTION
components

Authored coordinate labels, never inferred from extent equality.

TYPE: tuple[str, ...]

values

Scalar expressions aligned to those coordinate labels.

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

at

at(component: str) -> LetExprNode

Return the expression of one coordinate.

PARAMETER DESCRIPTION
component

Coordinate label.

TYPE: str

RETURNS DESCRIPTION
LetExprNode

Scalar expression of the coordinate.

RAISES DESCRIPTION
ValueError

If the value has no such coordinate.

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

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

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

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

PredictorGraph didactic-model

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

Bases: ValueModel

Retain additive parameter designs and a checked deterministic dependency DAG.

PARAMETER DESCRIPTION
leaves

Nonlinear parameters whose coefficients use ordinary formula emission.

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

expressions

Deterministic intermediate nodes in dependency order.

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

roots

Family link-scale outputs, keyed by distributional parameter.

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

inputs

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

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

PriorSpec didactic-model

PriorSpec(*, distribution: PriorDistribution = field(opaque=True, extras=OPAQUE_BY_VALUE), class_: str | None = 'b', coef: str | None = None, group: str | None = None, dpar: str | None = None, nlpar: str | None = None, site: str | None = None, response: str | None = None, lower: float | None = None, upper: float | None = None, block: str | None = None, tag: str | None = None)

Bases: ValueModel

Select a prior using authored formula labels rather than generated names.

PARAMETER DESCRIPTION
distribution

A compositional QVR distribution or a sampled shrinkage hierarchy.

TYPE: str or RegularizedHorseshoe or R2D2 DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

class_

Parameter class: b excludes intercepts, except the intercept of a nonlinear parameter, which brms names class b with coefficient Intercept; Intercept, sd, cor, and auxiliary parameter names select their corresponding roles.

TYPE: str or None DEFAULT: 'b'

coef

Expanded coefficient label, original group name, distributional or nonlinear parameter name, exact generated site, or authored joint-response label. None is a wildcard.

TYPE: str or None DEFAULT: None

group

Expanded coefficient label, original group name, distributional or nonlinear parameter name, exact generated site, or authored joint-response label. None is a wildcard.

TYPE: str or None DEFAULT: None

dpar

Expanded coefficient label, original group name, distributional or nonlinear parameter name, exact generated site, or authored joint-response label. None is a wildcard.

TYPE: str or None DEFAULT: None

nlpar

Expanded coefficient label, original group name, distributional or nonlinear parameter name, exact generated site, or authored joint-response label. None is a wildcard.

TYPE: str or None DEFAULT: None

site

Expanded coefficient label, original group name, distributional or nonlinear parameter name, exact generated site, or authored joint-response label. None is a wildcard.

TYPE: str or None DEFAULT: None

response

Expanded coefficient label, original group name, distributional or nonlinear parameter name, exact generated site, or authored joint-response label. None is a wildcard.

TYPE: str or None DEFAULT: None

lower

Optional finite bounds, intersected with the target's domain.

TYPE: float or None DEFAULT: None

upper

Optional finite bounds, intersected with the target's domain.

TYPE: float or None DEFAULT: None

block

Shared shrinkage identity. Rules with the same block share global hyperparameters and allocations and must specify identical hierarchies.

TYPE: str or None DEFAULT: None

tag

brms tag: a label carried into the prior table, so a subset of priors can be selected for sensitivity analysis.

TYPE: str or None DEFAULT: None

selector property

selector: dict[str, str]

Return exactly the explicitly selected role coordinates.

PriorSet didactic-model

PriorSet(*, rules: tuple[PriorSpec, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

An immutable collection of prior rules with explicit override semantics.

PARAMETER DESCRIPTION
rules

Ordered rules. A strict selector refinement overrides a broader rule; ambiguous competing rules and unused rules are errors.

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

PriorTarget didactic-model

PriorTarget(*, site: str, class_: str, coef: str | None = None, group: str | None = None, dpar: str | None = None, nlpar: str | None = None, response: str | None = None, axes: tuple[str, ...] = (), shape: tuple[int, ...] = (), lower: float | None = None, upper: float | None = None, event_rank: int = 0, component_labels: tuple[str, ...] = (), parameters: tuple[str, ...] = (), partition_labels: tuple[str, ...] = (), partition_axis: str | None = None, vector: str | None = None, whole: str | None = None)

Bases: ValueModel

One overrideable site with semantic labels and nominal component axes.

PARAMETER DESCRIPTION
site

Generated binder and semantic parameter class.

TYPE: str

class_

Generated binder and semantic parameter class.

TYPE: str

coef

Authored coefficient, grouping, predictor, and joint-response labels.

TYPE: str or None DEFAULT: None

group

Authored coefficient, grouping, predictor, and joint-response labels.

TYPE: str or None DEFAULT: None

dpar

Authored coefficient, grouping, predictor, and joint-response labels.

TYPE: str or None DEFAULT: None

nlpar

Authored coefficient, grouping, predictor, and joint-response labels.

TYPE: str or None DEFAULT: None

response

Authored coefficient, grouping, predictor, and joint-response labels.

TYPE: str or None DEFAULT: None

axes

Nominal independent coefficient axes in source order.

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

shape

Their declared cardinalities, distinct from native event dimensions.

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

lower

Admissible coefficient-domain bounds.

TYPE: float or None DEFAULT: None

upper

Admissible coefficient-domain bounds.

TYPE: float or None DEFAULT: None

event_rank

Native distribution event rank, separate from independent axes.

TYPE: int DEFAULT: 0

component_labels

Free response-component labels in the retained coefficient order.

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

parameters

Parameter of each component, when every component belongs to a parameter of its own, as muB and muC of a categorical location.

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

partition_labels

Levels of the by variable of a group-level scale, whose components vary fastest along its axis.

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

partition_axis

Axis over those levels.

TYPE: str or None DEFAULT: None

vector

Parameter dpar is a component of, for a site that holds one component alone.

TYPE: str or None DEFAULT: None

whole

Site the component is part of.

TYPE: str or None DEFAULT: None

width property

width: int

Return the number of independent selected coordinates.

sites property

sites: tuple[str, ...]

Return the target's site and the site it is part of.

RETURNS DESCRIPTION
tuple[str, ...]

One or two names.

component_site

component_site(parameter: str) -> str

Name the site of one component drawn on its own.

PARAMETER DESCRIPTION
parameter

Parameter of the component.

TYPE: str

RETURNS DESCRIPTION
str

Site name.

Source code in src/quivers/formulas/_priors.py
def component_site(self, parameter: str) -> str:
    """Name the site of one component drawn on its own.

    Parameters
    ----------
    parameter : str
        Parameter of the component.

    Returns
    -------
    str
        Site name.
    """
    return f"{self.site}__{parameter}"

components

components() -> tuple[PriorTarget, ...]

Return the target of each component drawn on its own.

RETURNS DESCRIPTION
tuple[PriorTarget, ...]

One target per parameter, with the component's own site.

Source code in src/quivers/formulas/_priors.py
def components(self) -> tuple[PriorTarget, ...]:
    """Return the target of each component drawn on its own.

    Returns
    -------
    tuple[PriorTarget, ...]
        One target per parameter, with the component's own site.
    """
    partitioned = self.partition_axis is not None
    return tuple(
        self.with_(
            site=self.component_site(parameter),
            dpar=parameter,
            vector=self.dpar,
            whole=self.site,
            axes=(self.partition_axis,) if partitioned else (),
            shape=(len(self.partition_labels),) if partitioned else (),
            component_labels=(),
            parameters=(),
        )
        for parameter in self.parameters
    )

RegularizedHorseshoe didactic-model

RegularizedHorseshoe(*, df: float = 1.0, scale_global: float = 1.0, df_global: float = 1.0, scale_slab: float = 2.0, df_slab: float = 4.0, par_ratio: float | None = None, autoscale: bool = True, main: bool = False)

Bases: ValueModel

A sampled global/local shrinkage hierarchy with a Student-t slab.

PARAMETER DESCRIPTION
df

Positive degrees of freedom for local, global, and slab priors.

TYPE: float DEFAULT: 1.0

df_global

Positive degrees of freedom for local, global, and slab priors.

TYPE: float DEFAULT: 1.0

df_slab

Positive degrees of freedom for local, global, and slab priors.

TYPE: float DEFAULT: 1.0

scale_global

Positive global and slab scales.

TYPE: float DEFAULT: 1.0

scale_slab

Positive global and slab scales.

TYPE: float DEFAULT: 1.0

par_ratio

If supplied, replace scale_global by par_ratio/sqrt(training_rows).

TYPE: float or None DEFAULT: None

autoscale

Multiply the global scale by a scalar residual sigma when available. Distributional-parameter coefficients are not autoscaled.

TYPE: bool DEFAULT: True

main

brms main = TRUE: when one predictor's shrinkage spans several parameter classes, the classes join one hierarchy whose arguments are taken from the single rule marked main.

TYPE: bool DEFAULT: False

R2D2 didactic-model

R2D2(*, mean_R2: float = 0.5, prec_R2: float = 2.0, cons_D2: float | tuple[float, ...] = field(default=0.5, opaque=True, extras=OPAQUE_BY_VALUE), autoscale: bool = True, main: bool = False)

Bases: ValueModel

A Gaussian-kernel R2D2 variance-allocation hierarchy.

PARAMETER DESCRIPTION
mean_R2

Mean of the Beta prior on explained-variance fraction, in (0,1).

TYPE: float DEFAULT: 0.5

prec_R2

Positive Beta precision.

TYPE: float DEFAULT: 2.0

cons_D2

Positive Dirichlet concentration, shared or per selected coordinate.

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

autoscale

Multiply coefficient scales by a scalar residual sigma when available.

TYPE: bool DEFAULT: True

main

brms main = TRUE: the rule whose arguments a hierarchy spanning several parameter classes of one predictor uses.

TYPE: bool DEFAULT: False

CustomFamilySpec didactic-model

CustomFamilySpec(*, catalog: FamilyCatalog = field(opaque=True, extras=OPAQUE_BY_IDENTITY), data: tuple[tuple[str, str], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The compilation-local law of a custom family and its data parameters.

The family's Family.observe_args name the formula binding passed to each native parameter.

PARAMETER DESCRIPTION
catalog

Checked semantic contracts and native implementations, held by identity.

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

data

Deterministic distributional parameters paired with source data columns.

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

BayesianFit didactic-model

BayesianFit(*, program: MonadicProgram = field(opaque=True, extras=OPAQUE_BY_IDENTITY), posterior: MCMCResult | PriorDraws | Guide = field(opaque=True, extras=OPAQUE_BY_IDENTITY), observations: Mapping[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), sample_prior: PriorMode = 'no', prior: PriorDraws | MCMCResult | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), losses: tuple[float, ...] = (), reparameterize: Literal['centered', 'noncentered'] = 'noncentered', fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: dict[str, GroupCovariance] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), priors: PriorSet = field(default_factory=PriorSet, opaque=True, extras=OPAQUE_BY_VALUE), criteria: Mapping[str, ELPDEstimate | Tensor] = field(default=NO_CRITERIA, opaque=True, extras=OPAQUE_BY_IDENTITY), formula: Formula = field(opaque=True, extras=OPAQUE_BY_VALUE), family: Family = field(opaque=True, extras=OPAQUE_BY_VALUE), residual: ResidualLaw | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor: Module | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), predictor_data: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), predictor_name: str | None = None, fixed_parameters: dict[str, float] = field(default_factory=dict), distributional: Mapping[str, Formula] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), predictor_graph: PredictorGraph | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), prediction_plan: FormulaPredictionPlan | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), refit_recipe: RefitRecipe[IntoDataFrame, Mapping[str, object], BayesianFit] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none')

Bases: SinglePostprocess, EvidenceEffectsMethods, FormulaFit

A fitted Bayesian regression: the compiled program, the parsed formula, the family, the user-supplied data, and the posterior samples.

PARAMETER DESCRIPTION
formula

Parsed formula IR.

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

family

Response family used at compile time.

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

residual

Residual law of the response: natural residuals correlated across rows by an autocorrelation term; None for independent rows.

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

program

The compiled program.

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

posterior

quivers.inference.MCMCResult from NUTS / HMC, or a quivers.inference.guides.base.Guide from SVI. A prior view instead retains independently generated PriorDraws.

TYPE: MCMCResult or PriorDraws or Guide DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

sample_prior

Ordinary fitting, additionally retained independent priors, or observation-free inference with explicit score potentials retained.

TYPE: ('no', 'yes', 'only') DEFAULT: "no"

prior

Independent prior samples, or explicitly factor-conditioned chains.

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

losses

Finite optimization losses for SVI; empty for recorded MCMC chains.

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

observations

Inference-time observations dict (response + per-column covariates + per-group plate indices).

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

group_covariances

Known labeled covariance between grouping levels, including any explicitly supplied future labels. Coefficient correlations remain separate.

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

fixed_parameters

Auxiliary parameters bound to constants rather than sampled or regressed.

TYPE: dict[str, float] DEFAULT: field(default_factory=dict)

distributional

Evaluated auxiliary-parameter design matrices, retained so source inspection emits the fitted model without re-evaluating transforms.

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

predictor_graph

Named nonlinear designs, typed expressions, and numeric input contracts.

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

refit_recipe

Retained original data and canonical fitting configuration, held by identity. Clone ownership is the default; explicit reference ownership observes mutations.

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

prediction_plan

Live fitted evaluators for new-data prediction. The versioned runtime plan is held by identity and explicitly refuses durable serialization.

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

criteria

Criteria stored by add_criterion: ELPD estimates, or R-squared draws.

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

default_priors

Default prior policy the model was compiled with.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

center

brms intercept centering option.

TYPE: bool or None DEFAULT: None

decomp

brms population-coefficient decomposition.

TYPE: ('none', 'QR') DEFAULT: "none"

Notes

Fits compare by value over the formula, family, and settings, and by identity over the live objects: the program, the posterior, the observations mapping, the predictor, its data, the prediction plan, and the refit recipe. Two fits are thus equal exactly when they share those objects and agree on everything else.

qvr_source property

qvr_source: str

Lazily emit the AST-equivalent .qvr source for display.

RETURNS DESCRIPTION
str

Canonical source emitted from the retained formula AST.

included_rows property

included_rows: tuple[int, ...]

Positions of the input data rows the model was fitted to.

Rows excluded by subset or by a missing value in any model variable are absent. Pointwise likelihoods and predictions on the training rows follow this order.

RETURNS DESCRIPTION
tuple[int, ...]

Zero-based positions in the data passed to fit.

category_labels property

category_labels: tuple[int | str, ...]

Response-category labels in posterior probability-array order.

RETURNS DESCRIPTION
tuple[int or str, ...]

Factor levels, the integer values 1..K of an ordinal response coded as brms codes it, or the codes 0..K-1; empty for other families. Predicted categories are positions in this tuple. Categorical coefficient arrays omit the first category.

threshold_labels property

threshold_labels: tuple[tuple[int | str, int | str], ...]

Adjacent category pairs identifying the ordinal transition axis.

RETURNS DESCRIPTION
tuple of pair of int

Adjacent category labels, excluding the structural-zero boundary in a hurdle cumulative model; empty for nonordinal families.

group_levels property

group_levels: dict[str, tuple[str, ...]]

Retained group labels in each coefficient array's level-axis order.

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

Group names and the ordered labels used in coefficient arrays.

coefficient_labels property

coefficient_labels: tuple[int | str, ...]

Label free component coefficients in their retained coordinate order.

RETURNS DESCRIPTION
tuple[int | str, ...]

Nonreference component labels, or all labels without a reference.

update

update(data: IntoDataFrame | None = None, **overrides: object) -> BayesianFit

Fit retained or replacement rows through the original fitting recipe.

PARAMETER DESCRIPTION
data

Original-frame snapshot by default, or replacement unprepared rows.

TYPE: IntoDataFrame or None DEFAULT: None

**overrides

Explicit overrides of the canonical fit arguments, including formula, family, priors, inference method, budgets, or random seed. Changing methods resets inactive budgets unless explicitly overridden.

TYPE: object DEFAULT: {}

RETURNS DESCRIPTION
BayesianFit

A fresh fitted result; the retained posterior and predictor are unchanged.

RAISES DESCRIPTION
(ValueError, TypeError)

If no recipe was retained or an override fails canonical fit validation.

Source code in src/quivers/formulas/_fit.py
def update(
    self, data: IntoDataFrame | None = None, **overrides: object
) -> BayesianFit:
    """Fit retained or replacement rows through the original fitting recipe.

    Parameters
    ----------
    data : IntoDataFrame or None
        Original-frame snapshot by default, or replacement unprepared rows.
    **overrides : object
        Explicit overrides of the canonical fit arguments, including formula,
        family, priors, inference method, budgets, or random seed. Changing
        methods resets inactive budgets unless explicitly overridden.

    Returns
    -------
    BayesianFit
        A fresh fitted result; the retained posterior and predictor are unchanged.

    Raises
    ------
    ValueError, TypeError
        If no recipe was retained or an override fails canonical fit validation.
    """
    from quivers.formulas._refit import update_fit

    return update_fit(self.refit_recipe, data, overrides)

refit_callback

refit_callback(*, method_factory: Callable[[Mapping[str, object], int], Mapping[str, object]], partition: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame] | None = None, num_samples: int | None = None, **prediction: object) -> Callable[[FoldSplit], FoldPrediction]

Adapt retained included rows and neural inputs to explicit refits.

PARAMETER DESCRIPTION
method_factory

Fold-specific canonical fit settings and seed. Retained row attachments are partitioned automatically and cannot be replaced.

TYPE: Callable[[Mapping[str, object], int], Mapping[str, object]]

partition

Optional nonmutating original-frame row selection. By default, Narwhals preserves the dataframe backend and authored columns.

TYPE: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame] or None DEFAULT: None

num_samples

Per-chain draw budget for raw held-out likelihood scoring.

TYPE: int or None DEFAULT: None

**prediction

Existing log_likelihood options, including re_formula and explicit new-group policies. The adapter owns rows, neural inputs, and seeds.

TYPE: object DEFAULT: {}

RETURNS DESCRIPTION
Callable[[FoldSplit], FoldPrediction]

Callback for cross_validate. Fold indices address fitted included rows; subset positions map them to the original raw frame once. Neural predictor_data follows the same train/test selection.

RAISES DESCRIPTION
(ValueError, TypeError)

If retained rows or attachments do not align, a partition has the wrong included-row count, or options fail canonical validation.

Source code in src/quivers/formulas/_fit.py
def refit_callback(
    self,
    *,
    method_factory: Callable[[Mapping[str, object], int], Mapping[str, object]],
    partition: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame]
    | None = None,
    num_samples: int | None = None,
    **prediction: object,
) -> Callable[[FoldSplit], FoldPrediction]:
    """Adapt retained included rows and neural inputs to explicit refits.

    Parameters
    ----------
    method_factory : Callable[[Mapping[str, object], int], Mapping[str, object]]
        Fold-specific canonical fit settings and seed. Retained row
        attachments are partitioned automatically and cannot be replaced.
    partition : Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame] or None
        Optional nonmutating original-frame row selection. By default,
        Narwhals preserves the dataframe backend and authored columns.
    num_samples : int or None
        Per-chain draw budget for raw held-out likelihood scoring.
    **prediction : object
        Existing log_likelihood options, including re_formula and explicit
        new-group policies. The adapter owns rows, neural inputs, and seeds.

    Returns
    -------
    Callable[[FoldSplit], FoldPrediction]
        Callback for cross_validate. Fold indices address fitted included
        rows; subset positions map them to the original raw frame once.
        Neural predictor_data follows the same train/test selection.

    Raises
    ------
    ValueError, TypeError
        If retained rows or attachments do not align, a partition has the
        wrong included-row count, or options fail canonical validation.
    """
    from quivers.formulas._cross_validation import formula_refitter

    return formula_refitter(
        self,
        method_factory=method_factory,
        partition=partition,
        num_samples=num_samples,
        prediction=prediction,
    )

evidence

evidence(sampler: SMC) -> SMCResult

Estimate the retained formula target's normalizing constant with SMC.

PARAMETER DESCRIPTION
sampler

Configured likelihood-tempered driver, including its particle budget, rejuvenation kernel, and random stream.

TYPE: SMC

RETURNS DESCRIPTION
SMCResult

Independent particles and the estimated log normalizing constant. Ordinary data evidence requires a normalized prior and likelihood; response weights define a powered target's normalizer instead.

RAISES DESCRIPTION
ValueError

If SMC cannot partition the target, normalize its prior, or use an exact likelihood without observation subsampling.

RuntimeError

If no temperature step meets the driver's ESS requirement.

Notes

The compiled program, retained designs, fixed parameters, and observed tensors are reused without recompilation. The fitted posterior is neither sampled nor modified. Seeded drivers restore the caller's RNG.

Source code in src/quivers/formulas/_fit.py
def evidence(self, sampler: SMC) -> SMCResult:
    """Estimate the retained formula target's normalizing constant with SMC.

    Parameters
    ----------
    sampler : SMC
        Configured likelihood-tempered driver, including its particle
        budget, rejuvenation kernel, and random stream.

    Returns
    -------
    SMCResult
        Independent particles and the estimated log normalizing constant.
        Ordinary data evidence requires a normalized prior and likelihood;
        response weights define a powered target's normalizer instead.

    Raises
    ------
    ValueError
        If SMC cannot partition the target, normalize its prior, or use
        an exact likelihood without observation subsampling.
    RuntimeError
        If no temperature step meets the driver's ESS requirement.

    Notes
    -----
    The compiled program, retained designs, fixed parameters, and observed
    tensors are reused without recompilation. The fitted posterior is
    neither sampled nor modified. Seeded drivers restore the caller's RNG.
    """
    # An improper flat prior has no normalizing constant.
    self._require_proper("SMC evidence")
    return sampler.run(self.program, torch.zeros(1, 1), dict(self.observations))

prior_summary

prior_summary() -> PriorTable

Tabulate the effective prior of every parameter, as brms prior_summary.

RETURNS DESCRIPTION
PriorTable

brms's columns, with source user for rules given to fit.

RAISES DESCRIPTION
ValueError

If the fit retains no emission.

Source code in src/quivers/formulas/_fit.py
def prior_summary(self) -> PriorTable:
    """Tabulate the effective prior of every parameter, as brms ``prior_summary``.

    Returns
    -------
    PriorTable
        brms's columns, with ``source`` ``user`` for rules given to `fit`.

    Raises
    ------
    ValueError
        If the fit retains no emission.
    """
    plan = self.prediction_plan
    if plan is None:
        raise ValueError("prior_summary requires the fit's retained emission")
    return prior_table(
        plan.module,
        plan.prior_targets,
        user_selection(self.priors, plan.prior_targets),
        policy=self.default_priors,
    )

conditional_effects

conditional_effects(grid: PredictionGrid, *, method: EffectMethod = ..., parameter: str = ..., transform: bool = ..., **options: Unpack[ConditionalEffectsOptions]) -> ConditionalEffects
conditional_effects(grid: str | Sequence[str] | None = ..., *, method: EffectMethod = ..., parameter: str = ..., transform: bool = ..., **options: Unpack[ConditionalEffectsOptions]) -> BrmsConditionalEffects
conditional_effects(grid: PredictionGrid | str | Sequence[str] | None = None, *, method: EffectMethod = 'epred', parameter: str = 'mu', transform: bool = False, **options: Unpack[ConditionalEffectsOptions]) -> ConditionalEffects | BrmsConditionalEffects

Predict one joint grid and retain conditional or empirical effects.

Without a grid, or with brms effects such as "x" or "x:z", this computes brms's automatic conditional effects (quivers.formulas._brms_effects.brms_conditional_effects): default effects and conditions, grids, and labeled summary frames.

PARAMETER DESCRIPTION
grid

Explicit effect coordinates and conditioning/reference rows, constructed with quivers.diagnostics.prediction_grid; or brms effects (None for brms's default effects).

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

method

epred, linpred, predict, or brms's names posterior_epred, posterior_linpred, posterior_predict. Expectations average response laws, not sampled replications.

TYPE: str DEFAULT: 'epred'

parameter

Predictor selected only for linpred; other methods require mu.

TYPE: str DEFAULT: 'mu'

transform

Apply the inverse link only for linpred.

TYPE: bool DEFAULT: False

**options

Existing prediction keywords, including varying-effect selectors, new-level policies, trial/neural inputs, draw budget, and seed. The grid supplies new_data; mc_samples applies only to epred. Without a grid, brms's conditional_effects arguments (conditions, int_conditions, re_formula defaulting to "~0", prob, robust, spaghetti, surface, categorical, ordinal, resolution, select_points, too_far, dpar, nlpar, ndraws, draw_ids, seed).

TYPE: ConditionalEffectsOptions DEFAULT: {}

RETURNS DESCRIPTION
ConditionalEffects or BrmsConditionalEffects

Joint chain/draw/point/condition/event predictions, with reference rows averaged within each draw only for empirical grids. Retained draws support paired contrasts, covariance, and common summaries. Without a grid, brms's labeled effect frames.

RAISES DESCRIPTION
(ValueError, TypeError)

If the method/options or grid are invalid, or the existing fitted prediction contract rejects a predictor, group, or response law.

Source code in src/quivers/formulas/_fit.py
def conditional_effects(
    self,
    grid: PredictionGrid | str | Sequence[str] | None = None,
    *,
    method: EffectMethod = "epred",
    parameter: str = "mu",
    transform: bool = False,
    **options: Unpack[ConditionalEffectsOptions],
) -> ConditionalEffects | BrmsConditionalEffects:
    """Predict one joint grid and retain conditional or empirical effects.

    Without a grid, or with brms ``effects`` such as ``"x"`` or
    ``"x:z"``, this computes brms's automatic conditional effects
    (`quivers.formulas._brms_effects.brms_conditional_effects`): default
    effects and conditions, grids, and labeled summary frames.

    Parameters
    ----------
    grid : PredictionGrid or str or Sequence[str] or None
        Explicit effect coordinates and conditioning/reference rows,
        constructed with `quivers.diagnostics.prediction_grid`; or brms
        ``effects`` (None for brms's default effects).
    method : str
        ``epred``, ``linpred``, ``predict``, or brms's names
        ``posterior_epred``, ``posterior_linpred``, ``posterior_predict``.
        Expectations average response laws, not sampled replications.
    parameter : str
        Predictor selected only for linpred; other methods require mu.
    transform : bool
        Apply the inverse link only for linpred.
    **options : ConditionalEffectsOptions
        Existing prediction keywords, including varying-effect selectors,
        new-level policies, trial/neural inputs, draw budget, and seed.
        The grid supplies new_data; mc_samples applies only to epred.
        Without a grid, brms's ``conditional_effects`` arguments
        (``conditions``, ``int_conditions``, ``re_formula`` defaulting to
        ``"~0"``, ``prob``, ``robust``, ``spaghetti``, ``surface``,
        ``categorical``, ``ordinal``, ``resolution``, ``select_points``,
        ``too_far``, ``dpar``, ``nlpar``, ``ndraws``, ``draw_ids``, ``seed``).

    Returns
    -------
    ConditionalEffects or BrmsConditionalEffects
        Joint chain/draw/point/condition/event predictions, with reference
        rows averaged within each draw only for empirical grids. Retained
        draws support paired contrasts, covariance, and common summaries.
        Without a grid, brms's labeled effect frames.

    Raises
    ------
    ValueError, TypeError
        If the method/options or grid are invalid, or the existing fitted
        prediction contract rejects a predictor, group, or response law.
    """
    # brms automatic conditional effects.
    if not isinstance(grid, PredictionGrid):
        return automatic_conditional_effects(
            self,
            grid,
            method=method,
            parameter=parameter,
            transform=transform,
            resp=None,
            options=options,
        )
    expectation = grid_options(options)
    short = method.removeprefix("posterior_")
    if "new_data" in options:
        raise ValueError("conditional_effects takes new_data from its grid")
    if short not in {"epred", "linpred", "predict"}:
        raise ValueError("method must be epred, linpred, or predict")
    method = cast(Literal["epred", "linpred", "predict"], short)
    if method != "linpred" and (parameter != "mu" or transform):
        raise ValueError("parameter and transform apply only to linpred effects")
    if method != "epred" and "mc_samples" in options:
        raise ValueError("mc_samples applies only to epred effects")
    request = expectation.copy()
    request["new_data"] = grid.to_frame()
    if method == "epred":
        predictions = self.posterior_epred(**request)
    else:
        # The guard above excludes the sole expectation-only key.
        prediction_options = cast(PredictionOptions, request)
        if method == "linpred":
            predictions = self.posterior_linpred(
                parameter=parameter,
                transform=transform,
                **prediction_options,
            )
        else:
            predictions = self.posterior_predict(**prediction_options)
    return grid.result(
        predictions,
        kind=draw_provenance(self.posterior),
        method=method,
        labels=self.predictor_labels(parameter)
        if method == "linpred"
        else self.category_labels,
    )

prior_view

prior_view(*, num_samples: int | None = None, seed: int = 0, method: Literal['ancestral'] | MCMC = 'ancestral') -> BayesianFit

Reuse prediction, likelihood, and analysis methods with prior draws.

PARAMETER DESCRIPTION
num_samples

Fresh independent draw count. None reuses retained prior samples, or draws 100 if none were retained.

TYPE: int or None DEFAULT: None

seed

Isolated CPU seed for fresh ancestral draws.

TYPE: int DEFAULT: 0

method

Conditional sampling or explicitly factor-conditioned inference.

TYPE: 'ancestral' DEFAULT: "ancestral"

RETURNS DESCRIPTION
BayesianFit

A new view sharing the fitted model, encodings, and data.

Source code in src/quivers/formulas/_fit.py
def prior_view(
    self,
    *,
    num_samples: int | None = None,
    seed: int = 0,
    method: Literal["ancestral"] | MCMC = "ancestral",
) -> BayesianFit:
    """Reuse prediction, likelihood, and analysis methods with prior draws.

    Parameters
    ----------
    num_samples : int or None
        Fresh independent draw count. None reuses retained prior samples,
        or draws 100 if none were retained.
    seed : int
        Isolated CPU seed for fresh ancestral draws.
    method : {"ancestral"} or MCMC
        Conditional sampling or explicitly factor-conditioned inference.

    Returns
    -------
    BayesianFit
        A new view sharing the fitted model, encodings, and data.
    """
    prior = (
        self.prior
        if self.prior is not None and num_samples is None and method == "ancestral"
        else self.prior_draws(
            num_samples=100 if num_samples is None else num_samples,
            seed=seed,
            method=method,
        )
    )
    return self.with_(posterior=prior, prior=prior, sample_prior="only", losses=())

dump_qvr

dump_qvr(path: str | Path) -> Path

Write the AST-equivalent .qvr source to path and return the resulting Path.

PARAMETER DESCRIPTION
path

Destination for canonical QVR source.

TYPE: str or Path

RETURNS DESCRIPTION
Path

Written source path.

Source code in src/quivers/formulas/_fit.py
def dump_qvr(self, path: str | Path) -> Path:
    """Write the AST-equivalent ``.qvr`` source to ``path`` and
    return the resulting `Path`.

    Parameters
    ----------
    path : str or Path
        Destination for canonical QVR source.

    Returns
    -------
    Path
        Written source path.
    """
    out = Path(path)
    out.write_text(self.qvr_source)
    return out

fixed_effects

fixed_effects(*, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, Tensor]

Extract the population coefficients of one predictor.

PARAMETER DESCRIPTION
parameter

mu or a distributionally regressed auxiliary parameter.

TYPE: str DEFAULT: 'mu'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, Tensor]

Original column labels and coefficient arrays, shape (chain, draw) or (chain, draw, K-1) for categorical reference-category coefficients.

Source code in src/quivers/formulas/_fit.py
def fixed_effects(
    self, *, parameter: str = "mu", num_samples: int | None = None, seed: int = 0
) -> dict[str, torch.Tensor]:
    """Extract the population coefficients of one predictor.

    Parameters
    ----------
    parameter : str
        ``mu`` or a distributionally regressed auxiliary parameter.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws, restored on exit.

    Returns
    -------
    dict[str, torch.Tensor]
        Original column labels and coefficient arrays, shape
        ``(chain, draw)`` or ``(chain, draw, K-1)`` for categorical
        reference-category coefficients.
    """
    _, prefix = self._formula_predictor(parameter)
    draws = self.draws(num_samples=num_samples, seed=seed)
    return {
        name: self._at_parameter(parameter, values)
        for name, values in self._fixed_effects(draws, prefix).items()
    }

random_effects

random_effects(*, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, dict[str, Tensor]]

Extract native group adjustments, including correlations and scales.

PARAMETER DESCRIPTION
parameter

mu or a distributionally regressed auxiliary parameter.

TYPE: str DEFAULT: 'mu'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, dict[str, Tensor]]

Group name, then original coefficient label, mapped to arrays (chain, draw, level) or (chain, draw, level, K-1). Level order follows group_levels; categorical coefficients follow category_labels[1:].

Source code in src/quivers/formulas/_fit.py
def random_effects(
    self, *, parameter: str = "mu", num_samples: int | None = None, seed: int = 0
) -> dict[str, dict[str, torch.Tensor]]:
    """Extract native group adjustments, including correlations and scales.

    Parameters
    ----------
    parameter : str
        ``mu`` or a distributionally regressed auxiliary parameter.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws, restored on exit.

    Returns
    -------
    dict[str, dict[str, torch.Tensor]]
        Group name, then original coefficient label, mapped to arrays
        ``(chain, draw, level)`` or ``(chain, draw, level, K-1)``.
        Level order follows `group_levels`; categorical coefficients
        follow ``category_labels[1:]``.
    """

    predictor, prefix = self._formula_predictor(parameter)
    shape = draw_count(self.posterior, num_samples)
    if not predictor.random_terms:
        return {}
    draws = self.draws(num_samples=num_samples, seed=seed)
    return {
        group: {
            name: self._at_parameter(parameter, values)
            for name, values in coefficients.items()
        }
        for group, coefficients in self._random_effects(
            draws, shape, predictor, prefix
        ).items()
    }

coefficients

coefficients(*, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, dict[str, Tensor]]

Combine population coefficients and group adjustments by level.

PARAMETER DESCRIPTION
parameter

mu or a distributionally regressed auxiliary parameter.

TYPE: str DEFAULT: 'mu'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, dict[str, Tensor]]

Arrays with the structure of random_effects, now including population coefficients. A group-only slope has population coefficient zero; fixed-only coefficients repeat over levels.

Source code in src/quivers/formulas/_fit.py
def coefficients(
    self, *, parameter: str = "mu", num_samples: int | None = None, seed: int = 0
) -> dict[str, dict[str, torch.Tensor]]:
    """Combine population coefficients and group adjustments by level.

    Parameters
    ----------
    parameter : str
        ``mu`` or a distributionally regressed auxiliary parameter.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws, restored on exit.

    Returns
    -------
    dict[str, dict[str, torch.Tensor]]
        Arrays with the structure of `random_effects`, now including
        population coefficients. A group-only slope has population
        coefficient zero; fixed-only coefficients repeat over levels.
    """

    predictor, prefix = self._formula_predictor(parameter)
    shape = draw_count(self.posterior, num_samples)
    if not predictor.random_terms:
        return {}
    draws = self.draws(num_samples=num_samples, seed=seed)
    fixed = self._fixed_effects(draws, prefix)
    varying = self._random_effects(draws, shape, predictor, prefix)
    for group, coefficients in varying.items():
        for name, coefficient in fixed.items():
            population = coefficient.unsqueeze(2)
            coefficients[name] = (
                coefficients[name] + population
                if name in coefficients
                else population.expand(
                    *population.shape[:2],
                    len(predictor.group_levels[group]),
                    *population.shape[3:],
                )
            )
    return {
        group: {
            name: self._at_parameter(parameter, values)
            for name, values in coefficients.items()
        }
        for group, coefficients in varying.items()
    }

posterior_thresholds

posterior_thresholds(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0) -> Tensor

Replay complete ordinal threshold profiles at each requested row.

PARAMETER DESCRIPTION
new_data

Fresh predictors evaluated with fitted encodings, or training rows.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Explicit neural input for fresh prediction rows when required.

TYPE: Tensor or None DEFAULT: None

re_formula

Varying-effect selector, with the same meaning as posterior_epred.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen grouping identities under the selected policy.

TYPE: bool DEFAULT: False

sample_new_levels

Joint donor or Gaussian policy. Explicit feasible_ policies condition new category-specific effects on ordered row support.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for separate posterior and group-effect random streams.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Tensor

Effective thresholds with shape (chain, draw, row, threshold) and axis labels threshold_labels. They include centered group shapes, selected varying location/slope shifts, and category-specific shifts. The proportional population predictor, its offsets, neural contribution, and discrimination are excluded. With threshold groups (thres(n, gr)) a row holds its group's thresholds and NaN at the positions its group lacks. Cumulative profiles are strictly ordered at every row.

RAISES DESCRIPTION
ValueError

If the family is not ordinal or a requested profile crosses.

Source code in src/quivers/formulas/_fit.py
def posterior_thresholds(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
) -> torch.Tensor:
    """Replay complete ordinal threshold profiles at each requested row.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Fresh predictors evaluated with fitted encodings, or training rows.
    predictor_data : torch.Tensor or None
        Explicit neural input for fresh prediction rows when required.
    re_formula : str or None
        Varying-effect selector, with the same meaning as `posterior_epred`.
    allow_new_levels : bool
        Permit unseen grouping identities under the selected policy.
    sample_new_levels : str
        Joint donor or Gaussian policy. Explicit ``feasible_`` policies
        condition new category-specific effects on ordered row support.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for separate posterior and group-effect random streams.

    Returns
    -------
    torch.Tensor
        Effective thresholds with shape ``(chain, draw, row, threshold)``
        and axis labels `threshold_labels`. They include centered group
        shapes, selected varying location/slope shifts, and category-specific
        shifts. The proportional population predictor, its offsets, neural
        contribution, and discrimination are excluded. With threshold
        groups (``thres(n, gr)``) a row holds its group's thresholds and
        NaN at the positions its group lacks. Cumulative profiles
        are strictly ordered at every row.

    Raises
    ------
    ValueError
        If the family is not ordinal or a requested profile crosses.
    """
    from quivers.formulas._prediction import prepare_prediction

    if self.family.ordinal is None:
        raise ValueError("posterior_thresholds requires an ordinal response family")
    context = prepare_prediction(
        self,
        new_data,
        predictor_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
    )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    width = len(self.threshold_labels)
    plan = self.prediction_plan
    shifts = tuple(
        contribution.name
        for predictor in (plan.predictors if plan is not None else ())
        if not predictor.prefix
        for term in predictor.part(None)
        for contribution in term.contributions()
        if contribution.varying
    )

    def values():
        """Yield retained row values through the shared posterior replay.

        Yields
        ------
        torch.Tensor
            One checked row/event value per retained chain and draw.
        """
        for recorded in replay(self, draws, shape, context=context):
            if width == 0:
                yield torch.empty(context.rows, 0)
                continue
            cuts = row_binding(
                recorded.sites[
                    "row_cutpoints"
                    if self.thresholds_by
                    or self.formula.modifiers.threshold_groups is not None
                    else "cutpoints"
                ].value,
                context.rows,
                width,
            )
            threshold_groups = self.formula.modifiers.threshold_groups
            if threshold_groups is not None:
                # brms thres(n, gr): a row has only its group's thresholds.
                cuts = absent_thresholds(
                    cuts,
                    threshold_groups,
                    context.observations[threshold_groups.column.qvr_name],
                )
            if "eta_nonbaseline" in recorded.sites:
                cuts = cuts - row_binding(
                    recorded.sites["eta_nonbaseline"].value, context.rows, width
                )
            for name in shifts:
                cuts = cuts - row_binding(
                    recorded.sites[name].value, context.rows
                ).unsqueeze(-1)
            yield cuts

    return collect_draws(values(), shape)

posterior_linpred

posterior_linpred(*, parameter: str = 'mu', transform: bool = False, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> Tensor

Replay a fitted linear predictor on training or fresh predictor rows.

PARAMETER DESCRIPTION
parameter

mu or an auxiliary parameter of the family. An auxiliary parameter without a formula is constant over the rows: its draws are repeated for every row on the parameter's own scale whatever transform is, as brms does.

TYPE: str DEFAULT: 'mu'

transform

Return the native inverse-link binding instead of its linear predictor. For binomial data this is a probability, not a count. Ordinal probabilities are supplied by posterior_epred.

TYPE: bool DEFAULT: False

new_data

Fresh predictor rows evaluated with fitted transforms, contrasts, and known group levels. None reuses the retained training rows. Response and likelihood-weight columns are not required.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Explicit input for a neural predictor on new rows. Required for neural fits with new_data; otherwise must be None.

TYPE: Tensor or None DEFAULT: None

trials

Response trial count or column for prediction rows. Vector count fits infer training totals; fresh rows require explicit totals unless a retained trial column supplies them. Linear predictors do not require totals.

TYPE: int or str or None DEFAULT: None

re_formula

None includes all fitted varying effects; "~0" excludes them; a one-sided group formula selects fitted slopes. This sets excluded contributions to zero; it does not marginalize them.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen or missing grouping identities in new_data. Repeated missing values share one new identity per group. Ordinary categorical predictors still require fitted levels.

TYPE: bool DEFAULT: False

sample_new_levels

For each new identity, uncertainty chooses one fitted donor jointly across slopes per posterior draw; old_levels retains one donor across all chains and draws; gaussian samples the fitted conditional zero-mean group law. Existing groups retain their posterior effects. Group and response noise use distinct random streams, and the caller's CPU RNG is restored. Explicit feasible_uncertainty and feasible_gaussian policies condition joint new-group proposals on cumulative row-order support; at most 1024 attempts are made per posterior draw, with an error on failure. Fitted draws and cutpoints are retained.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

incl_autocor

Include an autocorrelation term (brms incl_autocor). False treats rows as independent with the fitted residual scale.

TYPE: bool DEFAULT: True

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Shape (chain, draw, row) or (chain, draw, row, category) for categorical logits/probabilities, including reference zero.

RAISES DESCRIPTION
ValueError

If a parameter has no fitted predictor or an ordinal inverse link is requested without its thresholds.

Source code in src/quivers/formulas/_fit.py
def posterior_linpred(
    self,
    *,
    parameter: str = "mu",
    transform: bool = False,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    trials: int | str | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
    incl_autocor: bool = True,
    data2: Mapping[str, AutocorMatrix] | None = None,
) -> torch.Tensor:
    """Replay a fitted linear predictor on training or fresh predictor rows.

    Parameters
    ----------
    parameter : str
        ``mu`` or an auxiliary parameter of the family. An auxiliary
        parameter without a formula is constant over the rows: its
        draws are repeated for every row on the parameter's own scale
        whatever ``transform`` is, as brms does.
    transform : bool
        Return the native inverse-link binding instead of its linear
        predictor. For binomial data this is a probability, not a count.
        Ordinal probabilities are supplied by `posterior_epred`.
    new_data : IntoDataFrame or None
        Fresh predictor rows evaluated with fitted transforms, contrasts,
        and known group levels. None reuses the retained training rows.
        Response and likelihood-weight columns are not required.
    predictor_data : torch.Tensor or None
        Explicit input for a neural predictor on new rows. Required for
        neural fits with new_data; otherwise must be None.
    trials : int or str or None
        Response trial count or column for prediction rows. Vector count
        fits infer training totals; fresh rows require explicit totals
        unless a retained trial column supplies them. Linear predictors
        do not require totals.
    re_formula : str or None
        None includes all fitted varying effects; ``"~0"`` excludes
        them; a one-sided group formula selects fitted slopes. This
        sets excluded contributions to zero; it does not marginalize them.
    allow_new_levels : bool
        Permit unseen or missing grouping identities in new_data.
        Repeated missing values share one new identity per group.
        Ordinary categorical predictors still require fitted levels.
    sample_new_levels : str
        For each new identity, uncertainty chooses one fitted donor
        jointly across slopes per posterior draw; old_levels retains
        one donor across all chains and draws; gaussian samples the
        fitted conditional zero-mean group law. Existing groups retain
        their posterior effects. Group and response noise use distinct
        random streams, and the caller's CPU RNG is restored. Explicit
        feasible_uncertainty and feasible_gaussian policies condition joint
        new-group proposals on cumulative row-order support; at most 1024
        attempts are made per posterior draw, with an error on failure.
        Fitted draws and cutpoints are retained.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws, restored on exit.
    incl_autocor : bool
        Include an autocorrelation term (brms ``incl_autocor``). False
        treats rows as independent with the fitted residual scale.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).

    Returns
    -------
    torch.Tensor
        Shape ``(chain, draw, row)`` or ``(chain, draw, row, category)``
        for categorical logits/probabilities, including reference zero.

    Raises
    ------
    ValueError
        If a parameter has no fitted predictor or an ordinal inverse
        link is requested without its thresholds.
    """
    from quivers.formulas._prediction import prepare_prediction

    readout = self._predictor_readout
    binding = readout._linpred_binding(parameter, transform)
    constant = readout._constant_parameter(parameter)
    context = prepare_prediction(
        self,
        new_data,
        predictor_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        trials=trials,
        require_trials=False,
        incl_autocor=incl_autocor,
        data2=data2,
        retain_law=False,
    )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    rows = context.rows

    def values():
        """Yield retained row values through the shared posterior replay.

        Yields
        ------
        torch.Tensor
            One checked row/event value per retained chain and draw.
        """
        for recorded in replay(self, draws, shape, context=context):
            if constant:
                fixed = recorded.sites[parameter].value
                if fixed.numel() != 1:
                    raise ValueError(
                        f"parameter {parameter!r} has no fitted predictor "
                        "and is not one scalar per draw"
                    )
                yield fixed.reshape(()).expand(rows)
                continue

            yield binding.read(
                readout._row_reader(
                    parameter, binding, recorded, lambda name: name
                ),
                rows,
            )

    return collect_draws(values(), shape)

posterior_epred

posterior_epred(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, mc_samples: int | None = None, component: Literal['response', 'decision'] = 'response', seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> Tensor

Evaluate native expected responses on training or fresh rows.

PARAMETER DESCRIPTION
new_data

Fresh predictor rows using fitted encodings and known levels, or None for training rows. No response or weight column is needed.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Explicit neural input for new_data, required for neural fits.

TYPE: Tensor or None DEFAULT: None

trials

Response trial count or column for prediction rows. Vector count fits infer training totals; fresh rows require explicit totals unless a retained trial column supplies them. Linear predictors do not require totals.

TYPE: int or str or None DEFAULT: None

re_formula

None includes all fitted varying effects; "~0" excludes them; a one-sided group formula selects fitted slopes. This sets excluded contributions to zero; it does not marginalize them.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen or missing grouping identities in new_data. Repeated missing values share one new identity per group. Ordinary categorical predictors still require fitted levels.

TYPE: bool DEFAULT: False

sample_new_levels

For each new identity, uncertainty chooses one fitted donor jointly across slopes per posterior draw; old_levels retains one donor across all chains and draws; gaussian samples the fitted conditional zero-mean group law. Existing groups retain their posterior effects. Group and response noise use distinct random streams, and the caller's CPU RNG is restored. Explicit feasible_uncertainty and feasible_gaussian policies condition joint new-group proposals on cumulative row-order support; at most 1024 attempts are made per posterior draw, with an error on failure. Fitted draws and cutpoints are retained.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

mc_samples

Explicit Monte Carlo budget for bounded or certified finite-mean response laws without a closed mean. Sampling uses chunks of at most 64; None requires an analytic expectation. Logistic-normal and Cox response means require a budget.

TYPE: int or None DEFAULT: None

component

Wiener response means are positive reaction times, including delay. Decision returns lower/upper probabilities for a decision response.

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

seed

Seed for variational draws, restored on exit.

TYPE: int DEFAULT: 0

incl_autocor

Include an autocorrelation term (brms incl_autocor). False treats rows as independent with the fitted residual scale.

TYPE: bool DEFAULT: True

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Native response means, shape (chain, draw, row). Binomial results are expected counts; mixtures include their weights; asymmetric Laplace results are means, not modeled quantiles. Ordinal and categorical responses instead return probabilities, (chain, draw, row, category), in category_labels order. Decision probabilities use a final axis ordered lower, upper.

RAISES DESCRIPTION
ValueError

If a draw has an undefined or nonfinite response mean.

TypeError

If the native family exposes no expectation, or a circular response would require a specified angular convention.

Source code in src/quivers/formulas/_fit.py
def posterior_epred(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    trials: int | str | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    mc_samples: int | None = None,
    component: Literal["response", "decision"] = "response",
    seed: int = 0,
    incl_autocor: bool = True,
    data2: Mapping[str, AutocorMatrix] | None = None,
) -> torch.Tensor:
    """Evaluate native expected responses on training or fresh rows.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Fresh predictor rows using fitted encodings and known levels,
        or None for training rows. No response or weight column is needed.
    predictor_data : torch.Tensor or None
        Explicit neural input for new_data, required for neural fits.
    trials : int or str or None
        Response trial count or column for prediction rows. Vector count
        fits infer training totals; fresh rows require explicit totals
        unless a retained trial column supplies them. Linear predictors
        do not require totals.
    re_formula : str or None
        None includes all fitted varying effects; ``"~0"`` excludes
        them; a one-sided group formula selects fitted slopes. This
        sets excluded contributions to zero; it does not marginalize them.
    allow_new_levels : bool
        Permit unseen or missing grouping identities in new_data.
        Repeated missing values share one new identity per group.
        Ordinary categorical predictors still require fitted levels.
    sample_new_levels : str
        For each new identity, uncertainty chooses one fitted donor
        jointly across slopes per posterior draw; old_levels retains
        one donor across all chains and draws; gaussian samples the
        fitted conditional zero-mean group law. Existing groups retain
        their posterior effects. Group and response noise use distinct
        random streams, and the caller's CPU RNG is restored. Explicit
        feasible_uncertainty and feasible_gaussian policies condition joint
        new-group proposals on cumulative row-order support; at most 1024
        attempts are made per posterior draw, with an error on failure.
        Fitted draws and cutpoints are retained.
    num_samples : int or None
        Draw count under the convention of `draws`.
    mc_samples : int or None
        Explicit Monte Carlo budget for bounded or certified finite-mean
        response laws without a closed mean. Sampling uses chunks of at most
        64; None requires an analytic expectation. Logistic-normal and Cox
        response means require a budget.
    component : {"response", "decision"}
        Wiener response means are positive reaction times, including delay.
        Decision returns lower/upper probabilities for a decision response.
    seed : int
        Seed for variational draws, restored on exit.
    incl_autocor : bool
        Include an autocorrelation term (brms ``incl_autocor``). False
        treats rows as independent with the fitted residual scale.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).

    Returns
    -------
    torch.Tensor
        Native response means, shape ``(chain, draw, row)``. Binomial
        results are expected counts; mixtures include their weights;
        asymmetric Laplace results are means, not modeled quantiles.
        Ordinal and categorical responses instead return probabilities,
        ``(chain, draw, row, category)``, in `category_labels` order.
        Decision probabilities use a final axis ordered lower, upper.

    Raises
    ------
    ValueError
        If a draw has an undefined or nonfinite response mean.
    TypeError
        If the native family exposes no expectation, or a circular
        response would require a specified angular convention.
    """
    from quivers.formulas._prediction import prepare_prediction

    if component not in {"response", "decision"}:
        raise ValueError("expected response component must be response or decision")
    data = self._response_data
    if component == "decision" and data.modifiers.decision is None:
        raise ValueError(
            "decision probabilities require a decision response modifier"
        )
    readout = self._response_readout
    if readout.circular:
        raise TypeError(
            "a circular response expectation requires an angular convention"
        )
    context = prepare_prediction(
        self,
        new_data,
        predictor_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        trials=trials,
        incl_autocor=incl_autocor,
        data2=data2,
    )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    rows = context.rows
    response = _qvr_name(data.name)
    categories = 2 if component == "decision" else readout.categories

    def values():
        """Yield retained row values through the shared posterior replay.

        Yields
        ------
        torch.Tensor
            One checked row/event value per retained chain and draw.

        Raises
        ------
        TypeError
            If the selected response has no requested native operation.
        """
        for recorded in replay(self, draws, shape, context=context):
            distribution = response_distribution(recorded, response)
            value = expected_response(
                distribution,
                readout,
                decision=component == "decision",
                mc_samples=mc_samples,
            )
            yield row_binding(value, rows, data.layout.event_shape or categories)

    with response_rng(seed + 2, (*draws.values(), *context.observations.values())):
        try:
            return collect_draws(values(), shape)
        except TypeError as error:
            if self.family.baseline is not None:
                # brms: "Cannot compute expected values of the posterior
                # predictive distribution for family 'cox'."
                error.add_note(
                    "brms refuses posterior_epred for family "
                    f"{self.family.name!r} as well: "
                    "the baseline hazard is a spline on the observed time "
                    "range, which fixes no mean survival time. Use "
                    "posterior_linpred for the log hazard ratio."
                )
            raise

bayes_r2

bayes_r2(*, method: Literal['auto', 'model', 'residual'] = 'auto', observed: Tensor | None = None, **options: Unpack[ExpectationOptions]) -> Tensor

Compute per-draw explained variance on the response scale.

PARAMETER DESCRIPTION
method

Model-variance ratios use native conditional means and variances; residual ratios use actual minus expected responses. Auto selects model variances for ordinary Gaussian and Bernoulli responses, and residual variances otherwise. Explicit observations select residual variances under auto.

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

observed

Explicit actual responses on row/event axes for the residual method. Otherwise use retained training responses or evaluate their fitted transform in new_data. Censoring bounds cannot stand in for actual responses.

TYPE: Tensor or None DEFAULT: None

**options

Shared posterior expectation options, including new_data, group policies, trials, draw counts, and seed. Model variances require analytic native moments; mc_samples applies to residual means.

TYPE: Unpack[ExpectationOptions] DEFAULT: {}

RETURNS DESCRIPTION
Tensor

Ratios on chain, draw, and event axes. Ordinal residual ratios use ordered integer scores. Unordered categories require a separately specified response metric. Zero total variance is NaN.

Source code in src/quivers/formulas/_fit.py
def bayes_r2(
    self,
    *,
    method: Literal["auto", "model", "residual"] = "auto",
    observed: torch.Tensor | None = None,
    **options: Unpack[ExpectationOptions],
) -> torch.Tensor:
    """Compute per-draw explained variance on the response scale.

    Parameters
    ----------
    method : {"auto", "model", "residual"}
        Model-variance ratios use native conditional means and variances;
        residual ratios use actual minus expected responses. Auto selects
        model variances for ordinary Gaussian and Bernoulli responses,
        and residual variances otherwise. Explicit observations select
        residual variances under auto.
    observed : torch.Tensor or None
        Explicit actual responses on row/event axes for the residual
        method. Otherwise use retained training responses or evaluate
        their fitted transform in new_data. Censoring bounds cannot stand
        in for actual responses.
    **options
        Shared posterior expectation options, including new_data, group
        policies, trials, draw counts, and seed. Model variances require
        analytic native moments; mc_samples applies to residual means.

    Returns
    -------
    torch.Tensor
        Ratios on chain, draw, and event axes. Ordinal residual ratios
        use ordered integer scores. Unordered categories require a
        separately specified response metric. Zero total variance is NaN.
    """

    def laws() -> tuple[Generator[Distribution, None, None], tuple[int, int], int]:
        context = prepare_prediction(
            self,
            options.get("new_data"),
            options.get("predictor_data"),
            re_formula=options.get("re_formula"),
            allow_new_levels=options.get("allow_new_levels", False),
            sample_new_levels=options.get("sample_new_levels", "uncertainty"),
            seed=options.get("seed", 0),
            trials=options.get("trials"),
        )
        shape = draw_count(self.posterior, options.get("num_samples"))
        draws = self.draws(
            num_samples=options.get("num_samples"), seed=options.get("seed", 0)
        )
        response = _qvr_name(self.formula.response_name)
        return (
            (
                response_distribution(recorded, response)
                for recorded in replay(self, draws, shape, context=context)
            ),
            shape,
            context.rows,
        )

    return formula_r2(
        self._response_data,
        self._response_readout,
        self.residual,
        method,
        observed,
        new_data=options.get("new_data"),
        mc_samples=options.get("mc_samples"),
        recorded=lambda: _responses(self, options),
        expected=lambda: self.posterior_epred(**options),
        laws=laws,
    )

posterior_choice_probs

posterior_choice_probs(**options: Unpack[ExpectationOptions]) -> Tensor

Return joint-model lower/upper decision probabilities.

PARAMETER DESCRIPTION
**options

Shared posterior expectation options, including new_data, varying effect selection, draw count, and seed.

TYPE: Unpack[ExpectationOptions] DEFAULT: {}

RETURNS DESCRIPTION
Tensor

Probabilities shaped chain x draw x row x (lower, upper).

Source code in src/quivers/formulas/_fit.py
def posterior_choice_probs(
    self, **options: Unpack[ExpectationOptions]
) -> torch.Tensor:
    """Return joint-model lower/upper decision probabilities.

    Parameters
    ----------
    **options
        Shared posterior expectation options, including new_data, varying
        effect selection, draw count, and seed.

    Returns
    -------
    torch.Tensor
        Probabilities shaped chain x draw x row x (lower, upper).
    """
    return self.posterior_epred(component="decision", **options)

pp_mixture

pp_mixture(*, new_data: IntoDataFrame | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', log: bool = False, num_samples: int | None = None, seed: int = 0) -> Tensor

Posterior probabilities of mixture component membership, brms pp_mixture.

P(K = k | y_i) = theta_k p_k(y_i) / sum_j theta_j p_j(y_i) at each posterior draw, scoring censored rows by their recorded event. Cost: O(S n K) for S draws, n rows and K components.

PARAMETER DESCRIPTION
new_data

Rows with recorded responses and any censoring columns; None scores the training rows.

TYPE: IntoDataFrame or None DEFAULT: None

re_formula

Varying-effect selector, as for prediction.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen grouping levels in new_data.

TYPE: bool DEFAULT: False

sample_new_levels

Policy for unseen grouping levels.

TYPE: str DEFAULT: 'uncertainty'

log

Return log probabilities.

TYPE: bool DEFAULT: False

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws and new-level policies.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Tensor

Shape (chain, draw, row, component).

RAISES DESCRIPTION
ValueError

If the fit is not a mixture model.

Source code in src/quivers/formulas/_fit.py
def pp_mixture(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    log: bool = False,
    num_samples: int | None = None,
    seed: int = 0,
) -> torch.Tensor:
    """Posterior probabilities of mixture component membership, brms ``pp_mixture``.

    ``P(K = k | y_i) = theta_k p_k(y_i) / sum_j theta_j p_j(y_i)`` at each
    posterior draw, scoring censored rows by their recorded event. Cost:
    O(S n K) for S draws, n rows and K components.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Rows with recorded responses and any censoring columns; None
        scores the training rows.
    re_formula : str or None
        Varying-effect selector, as for prediction.
    allow_new_levels : bool
        Permit unseen grouping levels in ``new_data``.
    sample_new_levels : str
        Policy for unseen grouping levels.
    log : bool
        Return log probabilities.
    num_samples : int or None
        Draw count under the convention of `draws`.
    seed : int
        Seed for variational draws and new-level policies.

    Returns
    -------
    torch.Tensor
        Shape ``(chain, draw, row, component)``.

    Raises
    ------
    ValueError
        If the fit is not a mixture model.
    """
    return pp_mixture(
        self,
        new_data=new_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        log=log,
        num_samples=num_samples,
        seed=seed,
    )

posterior_response

posterior_response(**options: Unpack[PredictionOptions]) -> ResponseDraws

Draw responses in original measurement coordinates in one replay.

PARAMETER DESCRIPTION
**options

Shared posterior_predict options, including new_data, varying effect selection, draw count, and seed.

TYPE: Unpack[PredictionOptions] DEFAULT: {}

RETURNS DESCRIPTION
ResponseDraws

Positive reaction time and its joint binary decision for Wiener; ordinary response values with no decision for other families.

Source code in src/quivers/formulas/_fit.py
def posterior_response(self, **options: Unpack[PredictionOptions]) -> ResponseDraws:
    """Draw responses in original measurement coordinates in one replay.

    Parameters
    ----------
    **options
        Shared posterior_predict options, including new_data, varying
        effect selection, draw count, and seed.

    Returns
    -------
    ResponseDraws
        Positive reaction time and its joint binary decision for Wiener;
        ordinary response values with no decision for other families.
    """
    from quivers.formulas._response_modifiers import decode_response_draws

    return decode_response_draws(self.formula, self.posterior_predict(**options))

hypothesis

hypothesis(expression: str | ContrastExpression | Sequence[str] | Mapping[str, str], *, class_: str | None = 'b', parameter: str = 'mu', group: str | None = None, scope: Literal['standard', 'ranef', 'coef'] = 'standard', prior: bool = False, num_samples: int | None = None, num_prior_samples: int | None = None, seed: int = 0, null: float | int | Tensor = 0.0, probs: Sequence[float] = (0.025, 0.975), robust: bool = False, point: PointNullSpec | None = None, name: str = 'contrast', alpha: float = 0.05) -> HypothesisSummary | HypothesisTable

Test a brms hypothesis string, or evaluate a checked contrast.

A string of the form "left (= | < | >) right", or several such strings, is a brms hypothesis: every name is prefixed with the class ("x > 0" tests b_x, and with class_="sd" and group="g" the name Intercept is sd_g__Intercept), the sides are R expressions (^, exp), and the result is brms's table. class_=None reads names as variables reports them.

PARAMETER DESCRIPTION
expression

brms hypothesis strings (a mapping names them), or a QVR value expression over authored labels, with optional aliases.

TYPE: str or ContrastExpression or Sequence[str] or Mapping[str, str]

class_

Parameter role such as b, Intercept, sd, cor, or an auxiliary name. The b role includes population intercepts. None selects exact constrained latent site names.

TYPE: str or None DEFAULT: 'b'

parameter

Distributional or nonlinear predictor for b, Intercept, and sd.

TYPE: str DEFAULT: 'mu'

group

Grouping factor for scale/correlation filtering or per-level scopes.

TYPE: str or None DEFAULT: None

scope

Named parameters, per-level random adjustments, or per-level population plus random coefficients. The latter two require b/group.

TYPE: ('standard', 'ranef', 'coef') DEFAULT: "standard"

prior

Also evaluate the same contrast on the corresponding joint prior stream, yielding prior-corrected region evidence.

TYPE: bool DEFAULT: False

num_samples

Posterior and prior counts. None follows retained-draw conventions; retained prior samples are reused when available.

TYPE: int or None DEFAULT: None

num_prior_samples

Posterior and prior counts. None follows retained-draw conventions; retained prior samples are reused when available.

TYPE: int or None DEFAULT: None

seed

Isolated seed for guide or fresh prior draws.

TYPE: int DEFAULT: 0

null

Finite comparison value on event axes only.

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

probs

Quantile probabilities, in requested order.

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

robust

Return median/scaled MAD rather than mean/sample SD.

TYPE: bool DEFAULT: False

point

Optional marginal point-density comparison using these same joint contrast streams. Requires prior=True and a checked Real result.

TYPE: PointNullSpec or None DEFAULT: None

name

Output contrast label.

TYPE: str DEFAULT: 'contrast'

alpha

brms alpha of a hypothesis string: the interval is alpha to 1 - alpha for a one-sided hypothesis and alpha / 2 to 1 - alpha / 2 for a two-sided one.

TYPE: float DEFAULT: 0.05

RETURNS DESCRIPTION
HypothesisSummary or HypothesisTable

For a brms hypothesis string, brms's table (Estimate, Est.Error, CI.Lower, CI.Upper, Evid.Ratio, Post.Prob, Star); its evidence ratio of a point hypothesis needs prior draws (sample_prior or prior=True). For a contrast expression, chain/draw/event-aware uncertainty and strict-region evidence. Posterior odds and prior-corrected region Bayes factors are distinct; equality frequencies do not estimate a point-null Bayes factor. Optional point_evidence uses the shared density estimator and retains its bandwidth and explicit assumption declarations.

RAISES DESCRIPTION
ValueError

If a hypothesis string is malformed or names a parameter that is not in the model (the message lists the class's parameters), or the contrast selectors match nothing.

Source code in src/quivers/formulas/_fit.py
def hypothesis(
    self,
    expression: str | ContrastExpression | Sequence[str] | Mapping[str, str],
    *,
    class_: str | None = "b",
    parameter: str = "mu",
    group: str | None = None,
    scope: Literal["standard", "ranef", "coef"] = "standard",
    prior: bool = False,
    num_samples: int | None = None,
    num_prior_samples: int | None = None,
    seed: int = 0,
    null: float | int | torch.Tensor = 0.0,
    probs: Sequence[float] = (0.025, 0.975),
    robust: bool = False,
    point: PointNullSpec | None = None,
    name: str = "contrast",
    alpha: float = 0.05,
) -> HypothesisSummary | HypothesisTable:
    """Test a brms hypothesis string, or evaluate a checked contrast.

    A string of the form ``"left (= | < | >) right"``, or several such
    strings, is a brms hypothesis: every name is prefixed with the
    class (``"x > 0"`` tests ``b_x``, and with ``class_="sd"`` and
    ``group="g"`` the name ``Intercept`` is ``sd_g__Intercept``), the
    sides are R expressions (``^``, ``exp``), and the result is brms's
    table. ``class_=None`` reads names as `variables` reports them.

    Parameters
    ----------
    expression : str or ContrastExpression or Sequence[str] or Mapping[str, str]
        brms hypothesis strings (a mapping names them), or a QVR value
        expression over authored labels, with optional aliases.
    class_ : str or None
        Parameter role such as b, Intercept, sd, cor, or an auxiliary name.
        The b role includes population intercepts. None selects exact
        constrained latent site names.
    parameter : str
        Distributional or nonlinear predictor for b, Intercept, and sd.
    group : str or None
        Grouping factor for scale/correlation filtering or per-level scopes.
    scope : {"standard", "ranef", "coef"}
        Named parameters, per-level random adjustments, or per-level
        population plus random coefficients. The latter two require b/group.
    prior : bool
        Also evaluate the same contrast on the corresponding joint prior
        stream, yielding prior-corrected region evidence.
    num_samples, num_prior_samples : int or None
        Posterior and prior counts. None follows retained-draw conventions;
        retained prior samples are reused when available.
    seed : int
        Isolated seed for guide or fresh prior draws.
    null : float, int, or torch.Tensor
        Finite comparison value on event axes only.
    probs : Sequence[float]
        Quantile probabilities, in requested order.
    robust : bool
        Return median/scaled MAD rather than mean/sample SD.
    point : PointNullSpec or None
        Optional marginal point-density comparison using these same joint
        contrast streams. Requires prior=True and a checked Real result.
    name : str
        Output contrast label.
    alpha : float
        brms ``alpha`` of a hypothesis string: the interval is
        ``alpha`` to ``1 - alpha`` for a one-sided hypothesis and
        ``alpha / 2`` to ``1 - alpha / 2`` for a two-sided one.

    Returns
    -------
    HypothesisSummary or HypothesisTable
        For a brms hypothesis string, brms's table (``Estimate``,
        ``Est.Error``, ``CI.Lower``, ``CI.Upper``, ``Evid.Ratio``,
        ``Post.Prob``, ``Star``); its evidence ratio of a point
        hypothesis needs prior draws (``sample_prior`` or
        ``prior=True``). For a contrast expression,
        chain/draw/event-aware uncertainty and strict-region evidence.
        Posterior odds and prior-corrected region Bayes factors are distinct;
        equality frequencies do not estimate a point-null Bayes factor.
        Optional point_evidence uses the shared density estimator and retains
        its bandwidth and explicit assumption declarations.

    Raises
    ------
    ValueError
        If a hypothesis string is malformed or names a parameter that
        is not in the model (the message lists the class's parameters),
        or the contrast selectors match nothing.
    """
    from quivers.formulas._hypothesis import _formula_hypothesis

    if is_brms_hypothesis(expression):
        return fit_hypothesis(
            self,
            cast("HypothesisInput", expression),
            class_=class_,
            group=group,
            scope=scope,
            alpha=alpha,
            robust=robust,
            prior=prior,
            num_samples=num_samples,
            num_prior_samples=num_prior_samples,
            seed=seed,
        )
    return _formula_hypothesis(
        self,
        expression,
        class_=class_,
        parameter=parameter,
        group=group,
        scope=scope,
        prior=prior,
        num_samples=num_samples,
        num_prior_samples=num_prior_samples,
        seed=seed,
        null=null,
        probs=probs,
        robust=robust,
        point=point,
        name=name,
    )

analysis

analysis(*, num_samples: int | None = None, seed: int = 0) -> PosteriorAnalysis

Prepare reusable posterior summaries and predictive comparisons.

PARAMETER DESCRIPTION
num_samples

Maximum MCMC draws per chain or fresh variational draw count.

TYPE: int or None DEFAULT: None

seed

Variational seed; the caller's CPU RNG is preserved.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PosteriorAnalysis

Retained draws, raw training-row likelihoods, response data, and actual sampler statistics. Later analysis reuses these tensors.

Source code in src/quivers/formulas/_fit.py
def analysis(
    self, *, num_samples: int | None = None, seed: int = 0
) -> PosteriorAnalysis:
    """Prepare reusable posterior summaries and predictive comparisons.

    Parameters
    ----------
    num_samples : int or None
        Maximum MCMC draws per chain or fresh variational draw count.
    seed : int
        Variational seed; the caller's CPU RNG is preserved.

    Returns
    -------
    quivers.diagnostics.PosteriorAnalysis
        Retained draws, raw training-row likelihoods, response data,
        and actual sampler statistics. Later analysis reuses these tensors.
    """
    from quivers.diagnostics.posterior import PosteriorAnalysis, _sample_stats

    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    response = _qvr_name(self.formula.response_name)
    plan = self.prediction_plan
    missing = plan.missing if plan is not None else None
    values = self.formula
    if missing is not None and missing.recorded is not None:
        values = values.with_(response_values=self._response_data.values)
    return PosteriorAnalysis(
        samples=draws,
        log_likelihood=self._response_scores(draws, shape, missing=missing),
        observed_data={response: response_tensor(values, self.family)},
        sample_stats=_sample_stats(self.posterior, shape[1]),
        kind=draw_provenance(self.posterior),
    )

log_likelihood

log_likelihood(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> dict[str, Tensor]

Evaluate raw response log likelihoods on fitted or recorded fresh rows.

PARAMETER DESCRIPTION
new_data

Fresh predictors, outcomes, and authored observation-event columns. None scores the fitted rows. Fitting weight columns are not required.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Neural inputs aligned with fresh rows before any subset selection.

TYPE: Tensor or None DEFAULT: None

trials

Existing count-trial override. Fresh vector counts otherwise infer their totals from their recorded components.

TYPE: int or str or None DEFAULT: None

re_formula

Existing varying-effect selector; ~0 excludes varying effects.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit fresh grouping identities under the selected prediction policy.

TYPE: bool DEFAULT: False

sample_new_levels

Existing joint donor or conditional Gaussian group-effect policy.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Maximum retained draws per chain, or fresh variational draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws; the caller's CPU RNG is preserved.

TYPE: int DEFAULT: 0

incl_autocor

Include an autocorrelation term (brms incl_autocor). False treats rows as independent with the fitted residual scale.

TYPE: bool DEFAULT: True

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

RETURNS DESCRIPTION
dict[str, Tensor]

Response name to raw scores with shape (chain, draw, row). Likelihood weights are excluded and event coordinates are reduced. Rows without a recorded mi() outcome score zero.

RAISES DESCRIPTION
TypeError

If a hidden response needs a marginal-likelihood observer.

Source code in src/quivers/formulas/_fit.py
def log_likelihood(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    trials: int | str | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
    incl_autocor: bool = True,
    data2: Mapping[str, AutocorMatrix] | None = None,
) -> dict[str, torch.Tensor]:
    """Evaluate raw response log likelihoods on fitted or recorded fresh rows.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Fresh predictors, outcomes, and authored observation-event columns.
        None scores the fitted rows. Fitting weight columns are not required.
    predictor_data : torch.Tensor or None
        Neural inputs aligned with fresh rows before any subset selection.
    trials : int or str or None
        Existing count-trial override. Fresh vector counts otherwise infer
        their totals from their recorded components.
    re_formula : str or None
        Existing varying-effect selector; ``~0`` excludes varying effects.
    allow_new_levels : bool
        Permit fresh grouping identities under the selected prediction policy.
    sample_new_levels : str
        Existing joint donor or conditional Gaussian group-effect policy.
    num_samples : int or None
        Maximum retained draws per chain, or fresh variational draws.
    seed : int
        Seed for variational draws; the caller's CPU RNG is preserved.
    incl_autocor : bool
        Include an autocorrelation term (brms ``incl_autocor``). False
        treats rows as independent with the fitted residual scale.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).

    Returns
    -------
    dict[str, torch.Tensor]
        Response name to raw scores with shape ``(chain, draw, row)``.
        Likelihood weights are excluded and event coordinates are reduced.
        Rows without a recorded ``mi()`` outcome score zero.

    Raises
    ------
    TypeError
        If a hidden response needs a marginal-likelihood observer.
    """

    if new_data is not None:
        from quivers.formulas._likelihood import prepare_likelihood

        context = prepare_likelihood(
            self,
            new_data,
            predictor_data,
            trials=trials,
            re_formula=re_formula,
            allow_new_levels=allow_new_levels,
            sample_new_levels=sample_new_levels,
            seed=seed,
            incl_autocor=incl_autocor,
            data2=data2,
        )
    else:
        from quivers.formulas._prediction import prepare_prediction

        if trials is not None:
            if self.family.trials_parameter is None:
                raise ValueError(
                    "trial overrides require a count family with a trial parameter"
                )
            _response_trials(
                self.formula,
                self._response_data.training_data,
                trials,
                caller="log_likelihood",
            )
        context = prepare_prediction(
            self,
            None,
            predictor_data,
            trials=trials,
            re_formula=re_formula,
            allow_new_levels=allow_new_levels,
            sample_new_levels=sample_new_levels,
            seed=seed,
            incl_autocor=incl_autocor,
            data2=data2,
            retain_law=False,
        )
        if trials is not None:
            name = response_input_name(self.formula)
            context = context.with_(
                observations=dict(context.observations)
                | {
                    name: self.observations[name],
                }
            )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    plan = self.prediction_plan
    missing = plan.missing if plan is not None and new_data is None else None
    return self._response_scores(draws, shape, context=context, missing=missing)

posterior_predict

posterior_predict(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> Tensor

Sample native response distributions on training or fresh rows.

PARAMETER DESCRIPTION
new_data

Fresh predictor rows using fitted encodings and known levels, or None for training rows. No response or weight column is needed.

TYPE: IntoDataFrame or None DEFAULT: None

predictor_data

Explicit neural input for new_data, required for neural fits.

TYPE: Tensor or None DEFAULT: None

trials

Response trial count or column for prediction rows. Vector count fits infer training totals; fresh rows require explicit totals unless a retained trial column supplies them. Linear predictors do not require totals.

TYPE: int or str or None DEFAULT: None

re_formula

None includes all fitted varying effects; "~0" excludes them; a one-sided group formula selects fitted slopes. This sets excluded contributions to zero; it does not marginalize them.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit unseen or missing grouping identities in new_data. Repeated missing values share one new identity per group. Ordinary categorical predictors still require fitted levels.

TYPE: bool DEFAULT: False

sample_new_levels

For each new identity, uncertainty chooses one fitted donor jointly across slopes per posterior draw; old_levels retains one donor across all chains and draws; gaussian samples the fitted conditional zero-mean group law. Existing groups retain their posterior effects. Group and response noise use distinct random streams, and the caller's CPU RNG is restored. Explicit feasible_uncertainty and feasible_gaussian policies condition joint new-group proposals on cumulative row-order support; at most 1024 attempts are made per posterior draw, with an error on failure. Fitted draws and cutpoints are retained.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Maximum draws per MCMC chain, or fresh guide draws, following draws. Each posterior draw supplies one response per row.

TYPE: int or None DEFAULT: None

seed

Seed for separate latent and response random streams. The caller's CPU RNG state is restored on return or failure.

TYPE: int DEFAULT: 0

incl_autocor

Include an autocorrelation term (brms incl_autocor). False treats rows as independent with the fitted residual scale.

TYPE: bool DEFAULT: True

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Predictive responses, shape (chain, draw, row, *event). Categorical and ordinal responses contain integer codes in category_labels; binomial responses contain counts. Likelihood weights do not alter the response sampling law at a fixed posterior draw. Wiener draws retain their joint signed representation: positive upper-boundary and negative lower-boundary reaction times. Use posterior_response for positive times and their joint decisions.

RAISES DESCRIPTION
ValueError

If the requested count or retained posterior layout is invalid.

TypeError

If the response has no native sampling operation.

Source code in src/quivers/formulas/_fit.py
def posterior_predict(
    self,
    *,
    new_data: IntoDataFrame | None = None,
    predictor_data: torch.Tensor | None = None,
    trials: int | str | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: Literal[
        "uncertainty",
        "old_levels",
        "gaussian",
        "feasible_uncertainty",
        "feasible_gaussian",
    ] = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
    incl_autocor: bool = True,
    data2: Mapping[str, AutocorMatrix] | None = None,
) -> torch.Tensor:
    """Sample native response distributions on training or fresh rows.

    Parameters
    ----------
    new_data : IntoDataFrame or None
        Fresh predictor rows using fitted encodings and known levels,
        or None for training rows. No response or weight column is needed.
    predictor_data : torch.Tensor or None
        Explicit neural input for new_data, required for neural fits.
    trials : int or str or None
        Response trial count or column for prediction rows. Vector count
        fits infer training totals; fresh rows require explicit totals
        unless a retained trial column supplies them. Linear predictors
        do not require totals.
    re_formula : str or None
        None includes all fitted varying effects; ``"~0"`` excludes
        them; a one-sided group formula selects fitted slopes. This
        sets excluded contributions to zero; it does not marginalize them.
    allow_new_levels : bool
        Permit unseen or missing grouping identities in new_data.
        Repeated missing values share one new identity per group.
        Ordinary categorical predictors still require fitted levels.
    sample_new_levels : str
        For each new identity, uncertainty chooses one fitted donor
        jointly across slopes per posterior draw; old_levels retains
        one donor across all chains and draws; gaussian samples the
        fitted conditional zero-mean group law. Existing groups retain
        their posterior effects. Group and response noise use distinct
        random streams, and the caller's CPU RNG is restored. Explicit
        feasible_uncertainty and feasible_gaussian policies condition joint
        new-group proposals on cumulative row-order support; at most 1024
        attempts are made per posterior draw, with an error on failure.
        Fitted draws and cutpoints are retained.
    num_samples : int or None
        Maximum draws per MCMC chain, or fresh guide draws, following
        `draws`. Each posterior draw supplies one response per row.
    seed : int
        Seed for separate latent and response random streams. The
        caller's CPU RNG state is restored on return or failure.
    incl_autocor : bool
        Include an autocorrelation term (brms ``incl_autocor``). False
        treats rows as independent with the fitted residual scale.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).

    Returns
    -------
    torch.Tensor
        Predictive responses, shape ``(chain, draw, row, *event)``. Categorical
        and ordinal responses contain integer codes in `category_labels`;
        binomial responses contain counts. Likelihood weights do not
        alter the response sampling law at a fixed posterior draw.
        Wiener draws retain their joint signed representation: positive
        upper-boundary and negative lower-boundary reaction times. Use
        `posterior_response` for positive times and their joint decisions.

    Raises
    ------
    ValueError
        If the requested count or retained posterior layout is invalid.
    TypeError
        If the response has no native sampling operation.
    """
    from quivers.formulas._prediction import prepare_prediction
    from quivers.inference._response import response_sample

    context = prepare_prediction(
        self,
        new_data,
        predictor_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        trials=trials,
        incl_autocor=incl_autocor,
        data2=data2,
    )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    rows = context.rows
    response = _qvr_name(self.formula.response_name)

    def values():
        """Yield retained row values through the shared posterior replay.

        Yields
        ------
        torch.Tensor
            One checked row/event value per retained chain and draw.

        Raises
        ------
        TypeError
            If the selected response has no requested native operation.
        """
        for recorded in replay(self, draws, shape, context=context):
            yield row_binding(
                response_sample(recorded, response),
                rows,
                self.formula.response_layout.event_shape,
            )

    # Guide sampling uses its own seed and restores the caller's RNG.
    # A distinct stream avoids coupling response noise to guide noise.
    with (
        response_rng(seed + 1, (*draws.values(), *context.observations.values())),
        torch.no_grad(),
    ):
        return collect_draws(values(), shape)

predictor_labels

predictor_labels(parameter: str = 'mu') -> tuple[int | str, ...]

Label the last axis returned by posterior_linpred for one graph output.

PARAMETER DESCRIPTION
parameter

Family parameter or named nonlinear intermediate.

TYPE: str DEFAULT: 'mu'

RETURNS DESCRIPTION
tuple[int or str, ...]

Output coordinate order; empty for scalar-row values. Family coordinates use fitted response order, with the ALR reference omitted. Intermediate vectors retain authored label order.

RAISES DESCRIPTION
ValueError

If the parameter has no retained predictor or graph binding.

Source code in src/quivers/formulas/_fit.py
def predictor_labels(self, parameter: str = "mu") -> tuple[int | str, ...]:
    """Label the last axis returned by posterior_linpred for one graph output.

    Parameters
    ----------
    parameter : str
        Family parameter or named nonlinear intermediate.

    Returns
    -------
    tuple[int or str, ...]
        Output coordinate order; empty for scalar-row values. Family
        coordinates use fitted response order, with the ALR reference
        omitted. Intermediate vectors retain authored label order.

    Raises
    ------
    ValueError
        If the parameter has no retained predictor or graph binding.
    """
    return self._predictor_readout.predictor_labels(parameter)

HypothesisRow didactic-model

HypothesisRow(*, hypothesis: str, estimate: float, est_error: float, ci_lower: float, ci_upper: float, evid_ratio: float, post_prob: float, star: str, group: str | None = None)

Bases: ValueModel

One row of brms's hypothesis table.

PARAMETER DESCRIPTION
hypothesis

The hypothesis name, by default "(left)-(right) > 0".

TYPE: str

estimate

Mean and standard deviation of the contrast draws, or median and scaled median absolute deviation when robust.

TYPE: float

est_error

Mean and standard deviation of the contrast draws, or median and scaled median absolute deviation when robust.

TYPE: float

ci_lower

Quantiles of the contrast: alpha / 2 and 1 - alpha / 2 for a two-sided hypothesis, alpha and 1 - alpha for a one-sided one.

TYPE: float

ci_upper

Quantiles of the contrast: alpha / 2 and 1 - alpha / 2 for a two-sided hypothesis, alpha and 1 - alpha for a one-sided one.

TYPE: float

evid_ratio

Posterior odds of a one-sided hypothesis, or the ratio of posterior to prior density at zero for a point hypothesis (NaN without prior draws, brms's NA).

TYPE: float

post_prob

evid_ratio / (1 + evid_ratio), one for an infinite ratio.

TYPE: float

star

"*" when a one-sided posterior probability exceeds 1 - alpha or a two-sided interval excludes zero, else "".

TYPE: str

group

Level of the grouping factor for the ranef and coef scopes.

TYPE: str or None DEFAULT: None

HypothesisTable didactic-model

HypothesisTable(*, rows: tuple[HypothesisRow, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), samples: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), prior_samples: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), class_: str = '', alpha: float = 0.05)

Bases: ValueModel

The value of brms hypothesis().

PARAMETER DESCRIPTION
rows

One row per hypothesis (and per level for the per-level scopes).

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

samples

Contrast draws (draw, row), chains concatenated, brms's samples with columns H1, H2, ....

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

prior_samples

Contrast draws under the prior, when prior draws were available for every row.

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

class_

Parameter class prefix without its trailing underscores.

TYPE: str DEFAULT: ''

alpha

The level of the intervals and stars.

TYPE: float DEFAULT: 0.05

to_frame

to_frame() -> DataFrame

Return the table with brms's column names.

RETURNS DESCRIPTION
DataFrame

Columns Hypothesis, Estimate, Est.Error, CI.Lower, CI.Upper, Evid.Ratio, Post.Prob and Star, preceded by Group for the per-level scopes.

Source code in src/quivers/formulas/_brms_hypothesis.py
def to_frame(self) -> pd.DataFrame:
    """Return the table with brms's column names.

    Returns
    -------
    pandas.DataFrame
        Columns ``Hypothesis``, ``Estimate``, ``Est.Error``,
        ``CI.Lower``, ``CI.Upper``, ``Evid.Ratio``, ``Post.Prob`` and
        ``Star``, preceded by ``Group`` for the per-level scopes.
    """
    frame = pd.DataFrame(
        {
            "Hypothesis": [row.hypothesis for row in self.rows],
            "Estimate": [row.estimate for row in self.rows],
            "Est.Error": [row.est_error for row in self.rows],
            "CI.Lower": [row.ci_lower for row in self.rows],
            "CI.Upper": [row.ci_upper for row in self.rows],
            "Evid.Ratio": [row.evid_ratio for row in self.rows],
            "Post.Prob": [row.post_prob for row in self.rows],
            "Star": [row.star for row in self.rows],
        }
    )
    if any(row.group is not None for row in self.rows):
        frame.insert(0, "Group", [row.group for row in self.rows])
    return frame

__str__

__str__() -> str

Render the table as brms prints it.

RETURNS DESCRIPTION
str

The header, the table rounded to two digits, and the legend.

Source code in src/quivers/formulas/_brms_hypothesis.py
def __str__(self) -> str:
    """Render the table as brms prints it.

    Returns
    -------
    str
        The header, the table rounded to two digits, and the legend.
    """
    one, two = (1 - self.alpha * 2) * 100, (1 - self.alpha) * 100
    return (
        f"Hypothesis Tests for class {self.class_}:\n"
        f"{self.to_frame().round(2).to_string()}\n---\n"
        f"'CI': {one:g}%-CI for one-sided and {two:g}%-CI for two-sided "
        "hypotheses.\n"
        "'*': For one-sided hypotheses, the posterior probability exceeds "
        f"{two:g}%;\nfor two-sided hypotheses, the value tested against lies "
        f"outside the {two:g}%-CI.\n"
        "Posterior probabilities of point hypotheses assume equal prior "
        "probabilities."
    )

GaussianProcessBlock didactic-model

GaussianProcessBlock(*, label: str, lscale_labels: tuple[str, ...], kernel: GpKernel, frequencies: ndarray = field(opaque=True, extras=opaque_by_value(_frozen)), lscale_priors: tuple[str, ...], inputs: ndarray | None = field(default=None, opaque=True, extras=opaque_by_value(_frozen_or_none)), gr: bool = True, dmax: float = 1.0, prediction_inputs: ndarray | None = field(default=None, opaque=True, extras=opaque_by_value(_frozen_or_none)))

Bases: ValueModel

One approximate GP (one by contrast) as a Gaussian design block.

ATTRIBUTE DESCRIPTION
label

brms sdgp coefficient label, for instance gpx or gpxga.

TYPE: str

lscale_labels

brms lscale coefficient labels: one for an isotropic GP, one per covariate otherwise.

TYPE: tuple[str, ...]

kernel

Covariance kernel.

TYPE: GpKernel

frequencies

(m, D) square roots of the Laplacian eigenvalues, brms's slambda, read-only.

TYPE: ndarray

lscale_priors

Default prior of each length scale, in lscale_labels order.

TYPE: tuple[str, ...]

inputs

For an exact GP, the (u, D) distinct scaled training inputs, brms's Xgp, in order of first appearance (every active row when gr is false); None for the approximation, whose frequencies then hold the basis.

TYPE: ndarray or None

gr

Whether rows sharing an input share one latent value.

TYPE: bool

dmax

Divisor applied to the covariates (one when scale = FALSE).

TYPE: float

prediction_inputs

For an exact GP specialized to prediction rows, their (m, D) distinct scaled inputs, at which the latent function is drawn given its training values.

TYPE: ndarray or None

exact property

exact: bool

Report whether the block is brms's exact GP.

RETURNS DESCRIPTION
bool

True when the block retains its training inputs.

dimension property

dimension: int

Count the GP's covariates.

RETURNS DESCRIPTION
int

Input dimension D.

isotropic property

isotropic: bool

Report whether one length scale serves every covariate.

RETURNS DESCRIPTION
bool

True for a single length scale.

specific

specific() -> GaussianProcessBlock

Return the block of one process per ordinal transition.

RETURNS DESCRIPTION
GaussianProcessBlock

The same block, with labels distinct from those of a block shared by the transitions.

Source code in src/quivers/formulas/_gp.py
def specific(self) -> GaussianProcessBlock:
    """Return the block of one process per ordinal transition.

    Returns
    -------
    GaussianProcessBlock
        The same block, with labels distinct from those of a block
        shared by the transitions.
    """
    return self.with_(
        label="cs" + self.label,
        lscale_labels=tuple("cs" + label for label in self.lscale_labels),
    )

sites

sites(prefix: str) -> tuple[str, tuple[str, ...]]

Name the block's sdgp and lscale latent sites.

PARAMETER DESCRIPTION
prefix

Owning predictor namespace.

TYPE: str

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

The sdgp site and the lscale sites.

Source code in src/quivers/formulas/_gp.py
def sites(self, prefix: str) -> tuple[str, tuple[str, ...]]:
    """Name the block's ``sdgp`` and ``lscale`` latent sites.

    Parameters
    ----------
    prefix : str
        Owning predictor namespace.

    Returns
    -------
    tuple[str, tuple[str, ...]]
        The ``sdgp`` site and the ``lscale`` sites.
    """
    return (
        f"{prefix}sdgp_{_qvr(self.label)}",
        tuple(f"{prefix}lscale_{_qvr(label)}" for label in self.lscale_labels),
    )

GaussianProcessConditional

GaussianProcessConditional(block: GaussianProcessBlock, values: Tensor, sdgp: Tensor, lscales: tuple[Tensor, ...])

Bases: Distribution

The latent function of an exact GP at fresh inputs given its training values.

PARAMETER DESCRIPTION
block

Exact block specialized to prediction rows.

TYPE: GaussianProcessBlock

values

Latent function at the training inputs.

TYPE: Tensor

sdgp

Marginal standard deviation.

TYPE: Tensor

lscales

Length scales.

TYPE: tuple[Tensor, ...]

Source code in src/quivers/formulas/_gp.py
def __init__(
    self,
    block: GaussianProcessBlock,
    values: torch.Tensor,
    sdgp: torch.Tensor,
    lscales: tuple[torch.Tensor, ...],
) -> None:
    assert block.prediction_inputs is not None
    batch = torch.broadcast_shapes(
        values.shape[:-1], sdgp.shape, *(lscale.shape for lscale in lscales)
    )
    self._loc, self._scale_tril = conditional_moments(
        block,
        values.expand(*batch, values.shape[-1]),
        sdgp.expand(batch),
        tuple(lscale.expand(batch) for lscale in lscales),
        np.asarray(block.prediction_inputs),
    )
    super().__init__(
        batch,
        torch.Size((len(block.prediction_inputs),)),
        validate_args=False,
    )

arg_constraints property

arg_constraints: dict[str, Constraint]

Declare no torch-validated arguments.

RETURNS DESCRIPTION
dict[str, Constraint]

An empty mapping.

support property

support: Constraint

Give the real vectors.

RETURNS DESCRIPTION
Constraint

Support of the law.

mean property

mean: Tensor

Give the conditional mean.

RETURNS DESCRIPTION
Tensor

Mean at the fresh inputs.

rsample

rsample(sample_shape: _size = Size()) -> Tensor

Draw the latent function at the fresh inputs.

PARAMETER DESCRIPTION
sample_shape

Leading sample shape.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws with the sample, batch, and event shapes.

Source code in src/quivers/formulas/_gp.py
def rsample(self, sample_shape: _size = torch.Size()) -> torch.Tensor:
    """Draw the latent function at the fresh inputs.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading sample shape.

    Returns
    -------
    torch.Tensor
        Draws with the sample, batch, and event shapes.
    """
    shape = self._extended_shape(sample_shape)
    noise = torch.randn(shape, dtype=self._loc.dtype)
    return self._loc + (self._scale_tril @ noise[..., None])[..., 0]

log_prob

log_prob(value: Tensor) -> Tensor

Score latent values at the fresh inputs.

PARAMETER DESCRIPTION
value

Values at the fresh inputs.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Multivariate Normal log density.

Source code in src/quivers/formulas/_gp.py
def log_prob(self, value: torch.Tensor) -> torch.Tensor:
    """Score latent values at the fresh inputs.

    Parameters
    ----------
    value : torch.Tensor
        Values at the fresh inputs.

    Returns
    -------
    torch.Tensor
        Multivariate Normal log density.
    """
    return MultivariateNormal(self._loc, scale_tril=self._scale_tril).log_prob(
        value.double()
    )

MecorSetting didactic-model

MecorSetting(*, mecor: bool)

Bases: ValueModel

The me() latent-correlation setting added to a response formula.

PARAMETER DESCRIPTION
mecor

Correlate the latent values of me() terms sharing a grouping.

TYPE: bool

MultivariateFormula

MultivariateFormula(*, responses: Mapping[str, ResponseModel], rescor: bool | None = None, response_names: tuple[str, ...] | None = None, rescor_explicit: bool | None = None)

Bases: ValueModel

Combine named response graphs into one probabilistic program.

PARAMETER DESCRIPTION
responses

At least two explicitly named responses, in authored coordinate order. Names select priors and result views and form brms parameter names such as b_<resp>_<coef>. They contain only letters and digits.

TYPE: dict[str, ResponseModel]

rescor

Estimate residual correlation between aligned scalar Gaussian or Student responses. None applies the brms default (default_rescor). Shared group-effect identifiers apply in either mode.

TYPE: bool or None DEFAULT: None

response_names

Explicit response coordinate order. None retains mapping insertion order. The order is part of equality, hashing, and serialization.

TYPE: tuple[str, ...] or None DEFAULT: None

rescor_explicit

Whether the setting was given rather than defaulted. A defaulted setting is resolved again when responses are added, as brms resolves an unset rescor only for the complete model. None records whether rescor was given.

TYPE: bool or None DEFAULT: None

Retain the responses with an explicit coordinate order.

PARAMETER DESCRIPTION
responses

Named responses, copied into a plain dictionary.

TYPE: Mapping[str, ResponseModel]

rescor

Estimate residual correlation between aligned responses, or None for the brms default.

TYPE: bool or None DEFAULT: None

response_names

Explicit response order, or None for the mapping's insertion order.

TYPE: tuple[str, ...] or None DEFAULT: None

rescor_explicit

Whether the setting was given, or None to record whether rescor is None.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/formulas/_multivariate.py
def __init__(
    self,
    *,
    responses: Mapping[str, ResponseModel],
    rescor: bool | None = None,
    response_names: tuple[str, ...] | None = None,
    rescor_explicit: bool | None = None,
) -> None:
    """Retain the responses with an explicit coordinate order.

    Parameters
    ----------
    responses : Mapping[str, ResponseModel]
        Named responses, copied into a plain dictionary.
    rescor : bool or None
        Estimate residual correlation between aligned responses, or None
        for the brms default.
    response_names : tuple[str, ...] or None
        Explicit response order, or None for the mapping's insertion order.
    rescor_explicit : bool or None
        Whether the setting was given, or None to record whether
        ``rescor`` is None.
    """
    construct = cast(Callable[..., None], super().__init__)
    construct(
        responses=dict(responses),
        rescor=default_rescor(responses)
        if rescor is None and len(responses) > 1
        else bool(rescor),
        response_names=tuple(responses)
        if response_names is None
        else response_names,
        rescor_explicit=rescor is not None
        if rescor_explicit is None
        else rescor_explicit,
    )

__add__

Add responses, the residual-correlation, or the me() setting.

PARAMETER DESCRIPTION
other

Further responses, set_rescor's setting, or set_mecor's setting applied to every response.

TYPE: ResponseModel or MultivariateFormula or RescorSetting or MecorSetting

RETURNS DESCRIPTION
MultivariateFormula

The extended specification.

Source code in src/quivers/formulas/_multivariate.py
def __add__(
    self, other: ResponseModel | MultivariateFormula | RescorSetting | MecorSetting
) -> MultivariateFormula:
    """Add responses, the residual-correlation, or the ``me()`` setting.

    Parameters
    ----------
    other : ResponseModel or MultivariateFormula or RescorSetting or MecorSetting
        Further responses, `set_rescor`'s setting, or `set_mecor`'s
        setting applied to every response.

    Returns
    -------
    MultivariateFormula
        The extended specification.
    """
    if isinstance(other, MecorSetting):
        return MultivariateFormula(
            responses={
                name: response.with_(mecor=other.mecor)
                for name, response in self.responses.items()
            },
            rescor=self.rescor,
            response_names=self.response_names,
            rescor_explicit=self.rescor_explicit,
        )
    if isinstance(other, RescorSetting):
        return MultivariateFormula(
            responses=self.responses,
            rescor=other.rescor,
            response_names=self.response_names,
        )
    return mvbf(self, other)

response

response(name: str) -> ResponseModel

Return one named response.

PARAMETER DESCRIPTION
name

Response label.

TYPE: str

RETURNS DESCRIPTION
ResponseModel

The response specification.

RAISES DESCRIPTION
ValueError

If no response has this label.

Source code in src/quivers/formulas/_multivariate.py
def response(self, name: str) -> ResponseModel:
    """Return one named response.

    Parameters
    ----------
    name : str
        Response label.

    Returns
    -------
    ResponseModel
        The response specification.

    Raises
    ------
    ValueError
        If no response has this label.
    """
    if name not in self.responses:
        raise ValueError(
            f"unknown response {name!r}; expected one of {self.response_names!r}"
        )
    return self.responses[name]

with_default_priors

with_default_priors(policy: Literal['quivers', 'brms']) -> MultivariateFormula

Apply one default prior policy to every response.

PARAMETER DESCRIPTION
policy

Default prior policy, as fit keyword default_priors.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

RETURNS DESCRIPTION
MultivariateFormula

The same specification, each response under policy.

Source code in src/quivers/formulas/_multivariate.py
def with_default_priors(
    self, policy: Literal["quivers", "brms"]
) -> MultivariateFormula:
    """Apply one default prior policy to every response.

    Parameters
    ----------
    policy : {"quivers", "brms"}
        Default prior policy, as `fit` keyword ``default_priors``.

    Returns
    -------
    MultivariateFormula
        The same specification, each response under ``policy``.
    """
    return MultivariateFormula(
        responses={
            name: response.with_(default_priors=policy)
            for name, response in self.responses.items()
        },
        rescor=self.rescor,
        response_names=self.response_names,
        rescor_explicit=self.rescor_explicit,
    )

RescorSetting didactic-model

RescorSetting(*, rescor: bool)

Bases: ValueModel

The residual-correlation setting added to a joint formula.

PARAMETER DESCRIPTION
rescor

Estimate residual correlations between the responses.

TYPE: bool

ResponseModel didactic-model

ResponseModel(*, formula: str, family: str | Family = field(default='gaussian', opaque=True, extras=OPAQUE_BY_VALUE), distributional: dict[str, str | NonlinearExpression] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), nonlinear: dict[str, str | NonlinearExpression] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), fixed_parameters: dict[str, float] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), weights: str | None = None, decision: str | None = None, binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, mecor: bool = True, center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', default_priors: Literal['quivers', 'brms'] = 'quivers', cmc: bool = True, sparse: bool = False, unused: tuple[str, ...] = (), family_given: bool = True, parameter_formulas: tuple[str, ...] = (), nonlinear_formulas: tuple[str, ...] = (), nl: bool = False)

Bases: ValueModel

Specify one response using the ordinary formula preparation contract.

PARAMETER DESCRIPTION
formula

Authored response formula, including ordinary response modifiers.

TYPE: str

family

Registered family or a configured family value.

TYPE: str or Family DEFAULT: field(default='gaussian', opaque=True, extras=OPAQUE_BY_VALUE)

distributional

Existing distributional predictors and nonlinear dependency graph.

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

nonlinear

Existing distributional predictors and nonlinear dependency graph.

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

fixed_parameters

Auxiliary parameters fixed on their natural scale.

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

weights

Ordinary likelihood-weight and decision column shortcuts.

TYPE: str or None DEFAULT: None

decision

Ordinary likelihood-weight and decision column shortcuts.

TYPE: str or None DEFAULT: None

binomial_trials

Finite count total or trial column, following the ordinary family API.

TYPE: int or str or None DEFAULT: None

thresholds_by

Retained grouping factor for ordinal thresholds.

TYPE: str or None DEFAULT: None

mixture_components

Number of components for a finite mixture response.

TYPE: int DEFAULT: 2

mecor

Correlate the latent values of the response's me() terms that share a grouping, the brms set_mecor default.

TYPE: bool DEFAULT: True

center

brms bf(center = ) for this response's location intercept.

TYPE: bool or None DEFAULT: None

decomp

brms bf(decomp = ) for this response's location coefficients.

TYPE: ('none', 'QR') DEFAULT: "none"

default_priors

Default prior policy of this response, set from fit.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

cmc

brms bf(cmc = , sparse = ).

TYPE: bool DEFAULT: True

sparse

brms bf(cmc = , sparse = ).

TYPE: bool DEFAULT: True

unused

brms bf(unused = ): further columns joining row retention.

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

family_given

Whether the family was stated. A response built by bf without a family takes the family of the entry point it is passed to, as brm(bf(...), family = ...) does.

TYPE: bool DEFAULT: True

parameter_formulas

Authored additive (bf, lf) and nonlinear (nlf) parameter formulas, from which distributional and nonlinear are classified under the family.

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

nonlinear_formulas

Authored additive (bf, lf) and nonlinear (nlf) parameter formulas, from which distributional and nonlinear are classified under the family.

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

nl

Whether the main formula is a nonlinear expression.

TYPE: bool DEFAULT: False

Notes

Data, priors, inference options, and group covariance declarations belong to the joint fit. Each response retains its own component and category axes. A response label does not replace either coordinate system. Adding two responses with + returns a MultivariateFormula, as bf(...) + bf(...) does in brms.

resolved_family property

resolved_family: Family

Resolve a family name without changing its configured links.

RETURNS DESCRIPTION
Family

Existing family metadata used by ordinary preparation.

label property

label: str

Return the brms response name derived from the left-hand side.

RETURNS DESCRIPTION
str

Left-hand-side variable with non-alphanumeric characters removed.

__add__

Combine this response with another response, a family, or a setting.

PARAMETER DESCRIPTION
other

Further responses, the residual-correlation setting, the me() correlation setting of this response, its family (brms bf(...) + skew_normal()), or the parameter formulas of lf, nlf and set_nl.

TYPE: ResponseModel or MultivariateFormula or RescorSetting or MecorSetting or Family or ParameterFormulas

RETURNS DESCRIPTION
MultivariateFormula or ResponseModel

The joint specification, responses in authored order, or this response with the setting, family, or formulas applied.

RAISES DESCRIPTION
TypeError

If the operand is not a response, joint formula, or setting.

ValueError

If a setting is added to a single response.

Source code in src/quivers/formulas/_multivariate.py
def __add__(
    self,
    other: ResponseModel
    | MultivariateFormula
    | RescorSetting
    | MecorSetting
    | Family
    | ParameterFormulas,
) -> MultivariateFormula | ResponseModel:
    """Combine this response with another response, a family, or a setting.

    Parameters
    ----------
    other : ResponseModel or MultivariateFormula or RescorSetting or MecorSetting or Family or ParameterFormulas
        Further responses, the residual-correlation setting, the
        ``me()`` correlation setting of this response, its family
        (brms ``bf(...) + skew_normal()``), or the parameter formulas of
        `lf`, `nlf` and `set_nl`.

    Returns
    -------
    MultivariateFormula or ResponseModel
        The joint specification, responses in authored order, or this
        response with the setting, family, or formulas applied.

    Raises
    ------
    TypeError
        If the operand is not a response, joint formula, or setting.
    ValueError
        If a setting is added to a single response.
    """
    if isinstance(other, MecorSetting):
        return self.with_(mecor=other.mecor)
    if isinstance(other, RescorSetting):
        raise ValueError(
            "set_rescor() applies to a multivariate formula of at least two responses"
        )
    if isinstance(other, Family):
        return self.with_family(other)
    if isinstance(other, ParameterFormulas):
        return self.with_parameters(other)
    return mvbf(self, other)

with_family

with_family(family: str | Family) -> ResponseModel

Return this response under a stated family.

PARAMETER DESCRIPTION
family

Registered family name or configured family.

TYPE: str or Family

RETURNS DESCRIPTION
ResponseModel

The response with its authored parameter formulas classified as distributional or nonlinear under family.

RAISES DESCRIPTION
ValueError

If an authored parameter formula names neither an auxiliary parameter of family nor, with nl, a nonlinear parameter.

Source code in src/quivers/formulas/_multivariate.py
def with_family(self, family: str | Family) -> ResponseModel:
    """Return this response under a stated family.

    Parameters
    ----------
    family : str or Family
        Registered family name or configured family.

    Returns
    -------
    ResponseModel
        The response with its authored parameter formulas classified as
        distributional or nonlinear under ``family``.

    Raises
    ------
    ValueError
        If an authored parameter formula names neither an auxiliary
        parameter of ``family`` nor, with ``nl``, a nonlinear parameter.
    """
    if not (self.parameter_formulas or self.nonlinear_formulas or self.nl):
        return self.with_(family=family, family_given=True)
    distributional, nonlinear = classify_parameters(
        family,
        self.parameter_formulas,
        self.nonlinear_formulas,
        nl=self.nl,
        mixture_components=self.mixture_components,
        strict=True,
    )
    return self.with_(
        family=family,
        family_given=True,
        distributional=distributional or None,
        nonlinear=nonlinear if self.nl else None,
    )

with_parameters

with_parameters(added: ParameterFormulas) -> ResponseModel

Return this response with further parameter formulas.

PARAMETER DESCRIPTION
added

The value of lf, nlf, or set_nl.

TYPE: ParameterFormulas

RETURNS DESCRIPTION
ResponseModel

The response with the formulas appended and classified under its family; a family not yet stated classifies them when it is.

RAISES DESCRIPTION
ValueError

If the response was built with explicit distributional or nonlinear mappings and not by bf, or a formula names no parameter of the stated family.

Source code in src/quivers/formulas/_multivariate.py
def with_parameters(self, added: ParameterFormulas) -> ResponseModel:
    """Return this response with further parameter formulas.

    Parameters
    ----------
    added : ParameterFormulas
        The value of `lf`, `nlf`, or `set_nl`.

    Returns
    -------
    ResponseModel
        The response with the formulas appended and classified under its
        family; a family not yet stated classifies them when it is.

    Raises
    ------
    ValueError
        If the response was built with explicit ``distributional`` or
        ``nonlinear`` mappings and not by `bf`, or a formula names no
        parameter of the stated family.
    """
    authored = bool(self.parameter_formulas or self.nonlinear_formulas or self.nl)
    if not authored and (self.distributional or self.nonlinear is not None):
        raise ValueError(
            "lf(), nlf() and set_nl() extend a response built by bf(); this "
            "response gives its distributional and nonlinear mappings directly"
        )
    nl = self.nl if added.nl is None else added.nl
    formulas = (*self.parameter_formulas, *added.formulas)
    nonlinear_formulas = (*self.nonlinear_formulas, *added.nonlinear)
    distributional, nonlinear = classify_parameters(
        self.family,
        formulas,
        nonlinear_formulas,
        nl=nl,
        mixture_components=self.mixture_components,
        strict=self.family_given,
        pending=True,
    )
    return self.with_(
        parameter_formulas=formulas,
        nonlinear_formulas=nonlinear_formulas,
        nl=nl,
        distributional=distributional or None,
        nonlinear=nonlinear if nl else None,
    )

ParameterFormulas didactic-model

ParameterFormulas(*, formulas: tuple[str, ...] = (), nonlinear: tuple[str, ...] = (), nl: bool | None = None)

Bases: ValueModel

Parameter formulas added to a response with +.

PARAMETER DESCRIPTION
formulas

Additive formulas of distributional or nonlinear parameters, the arguments of brms lf().

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

nonlinear

Formulas whose right-hand side is a nonlinear expression, the arguments of brms nlf().

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

nl

brms set_nl(): whether the main formula is nonlinear. None leaves the response's setting.

TYPE: bool or None DEFAULT: None

MultivariateFit didactic-model

MultivariateFit(*, 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(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), specification: MultivariateFormula = field(opaque=True, extras=OPAQUE_BY_VALUE), emission: _JointEmission = field(opaque=True, extras=OPAQUE_BY_IDENTITY), prepared: Mapping[str, _PreparedFormula] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), preparation_data: IntoDataFrame | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), refit_recipe: RefitRecipe[IntoDataFrame, Mapping[str, object], MultivariateFit] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), response_fits: dict[str, BayesianFit] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), missing: MissingPlan = field(default_factory=MissingPlan, opaque=True, extras=OPAQUE_BY_VALUE), missing_specs: dict[str, LatentResponseSpec] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), data2: dict[str, AutocorMatrix] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: JointPostprocess, EvidenceEffectsMethods, FormulaFit

A fitted joint (multivariate) formula model.

PARAMETER DESCRIPTION
specification

The authored joint specification.

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

program

The single compiled joint program.

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

posterior

Retained posterior representation.

TYPE: MCMCResult or PriorDraws or Guide DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

observations

Runtime inputs and observations bound to the program.

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

emission

The composed emission with its response namespaces.

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

prepared

Ordinary preparation of each response, retaining design evaluators.

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

losses

SVI losses, empty for MCMC.

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

prior

Retained prior result, if one was requested.

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

sample_prior

Prior/likelihood scoring policy of the fit.

TYPE: ('no', 'yes', 'only') DEFAULT: "no"

priors

Joint prior rules, including response selectors.

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

fixed_prior

Default priors of every response preparation.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

random_scale_prior

Default priors of every response preparation.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

correlation_prior

Default priors of every response preparation.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

group_covariances

Known group covariances, keyed by grouping factor.

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

reparameterize

Group coordinate policy.

TYPE: ('centered', 'noncentered') DEFAULT: "centered"

preparation_data

Original-row snapshot used to rebuild designs.

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

refit_recipe

Retained original data and canonical fitting configuration.

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

response_fits

Lazily built response views used by row preparation.

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

missing

mi() declarations of the joint formula.

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

missing_specs

Recorded and latent coordinates of each mi() response.

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

data2

Named matrices given to fit as data2.

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

criteria

Criteria stored by add_criterion.

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

Notes

Equality follows BayesianFit: by value over the specification and settings, by identity over live objects.

response_names property

response_names: tuple[str, ...]

Return the response labels in authored order.

RETURNS DESCRIPTION
tuple[str, ...]

Response labels.

rescor property

rescor: bool

Report whether residual correlations were estimated.

RETURNS DESCRIPTION
bool

The fitted residual-correlation setting.

qvr_source property

qvr_source: str

Return the canonical QVR source of the fitted joint program.

RETURNS DESCRIPTION
str

Source emitted from the retained joint module.

group_levels property

group_levels: dict[str, tuple[str, ...]]

Return the joint level order of every grouping factor.

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

Group names and their joint level labels.

variables

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

Return draws under brms parameter names.

Population coefficients are b_<resp>_<coef> (location), b_<dpar>_<resp>_<coef> (distributional), and b_<resp>_<nlpar>_<coef> (nonlinear). Unregressed auxiliary parameters are <dpar>_<resp>; group standard deviations are sd_<group>__<resp>_<coef>; group correlations are cor_<group>__<term>__<term>; residual correlations are rescor__<a>__<b>; a shared Student degree of freedom is nu. Per-level group coefficients are r_<group>__<resp>[<level>,<coef>] (r_<group>__<dpar>_<resp>[...] for distributional predictors). Vector coefficients of categorical responses keep a trailing component axis. The thresholds of a cumulative response with one threshold vector are b_<resp>_Intercept[<k>], and those of a response with threshold groups are b_<resp>_Intercept[<group>,<k>].

PARAMETER DESCRIPTION
num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, Tensor]

brms-named draws on chain and draw axes.

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

    Population coefficients are ``b_<resp>_<coef>`` (location),
    ``b_<dpar>_<resp>_<coef>`` (distributional), and
    ``b_<resp>_<nlpar>_<coef>`` (nonlinear). Unregressed auxiliary
    parameters are ``<dpar>_<resp>``; group standard deviations are
    ``sd_<group>__<resp>_<coef>``; group correlations are
    ``cor_<group>__<term>__<term>``; residual correlations are
    ``rescor__<a>__<b>``; a shared Student degree of freedom is ``nu``.
    Per-level group coefficients are ``r_<group>__<resp>[<level>,<coef>]``
    (``r_<group>__<dpar>_<resp>[...]`` for distributional predictors).
    Vector coefficients of categorical responses keep a trailing
    component axis. The thresholds of a cumulative response with one
    threshold vector are ``b_<resp>_Intercept[<k>]``, and those of a
    response with threshold groups are
    ``b_<resp>_Intercept[<group>,<k>]``.

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

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

fixed_effects

fixed_effects(*, resp: str, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, Tensor]

Extract one response's population coefficients by column label.

PARAMETER DESCRIPTION
resp

Response label.

TYPE: str

parameter

mu or a regressed distributional or nonlinear parameter.

TYPE: str DEFAULT: 'mu'

num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, Tensor]

Column labels mapped to coefficient draws on chain and draw axes.

Source code in src/quivers/formulas/_joint_fit.py
def fixed_effects(
    self,
    *,
    resp: str,
    parameter: str = "mu",
    num_samples: int | None = None,
    seed: int = 0,
) -> dict[str, torch.Tensor]:
    """Extract one response's population coefficients by column label.

    Parameters
    ----------
    resp : str
        Response label.
    parameter : str
        ``mu`` or a regressed distributional or nonlinear parameter.
    num_samples : int or None
        Draws per chain under the convention of `draws`.
    seed : int
        Seed for variational draws.

    Returns
    -------
    dict[str, torch.Tensor]
        Column labels mapped to coefficient draws on chain and draw axes.
    """
    self._selection(resp)
    readout = self._predictor_readout(resp)
    _, prefix = readout._formula_predictor(parameter)
    return population_coefficients(
        readout.predictors,
        self.draws(num_samples=num_samples, seed=seed),
        prefix,
        self.emission.responses[resp].prefix,
    )

random_effects

random_effects(*, resp: str, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, dict[str, Tensor]]

Extract one response's group adjustments by group and coefficient.

PARAMETER DESCRIPTION
resp

Response label.

TYPE: str

parameter

mu or a regressed distributional or nonlinear parameter.

TYPE: str DEFAULT: 'mu'

num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, dict[str, Tensor]]

Group, then coefficient label, mapped to (chain, draw, level) arrays in group_levels order. Shared blocks are read from the joint Gaussian block.

Source code in src/quivers/formulas/_joint_fit.py
def random_effects(
    self,
    *,
    resp: str,
    parameter: str = "mu",
    num_samples: int | None = None,
    seed: int = 0,
) -> dict[str, dict[str, torch.Tensor]]:
    """Extract one response's group adjustments by group and coefficient.

    Parameters
    ----------
    resp : str
        Response label.
    parameter : str
        ``mu`` or a regressed distributional or nonlinear parameter.
    num_samples : int or None
        Draws per chain under the convention of `draws`.
    seed : int
        Seed for variational draws.

    Returns
    -------
    dict[str, dict[str, torch.Tensor]]
        Group, then coefficient label, mapped to ``(chain, draw, level)``
        arrays in `group_levels` order. Shared blocks are read from the
        joint Gaussian block.
    """
    self._selection(resp)
    predictor, prefix = self._predictor(resp, parameter)
    draws = self.draws(num_samples=num_samples, seed=seed)
    return self._random(draws, predictor, prefix)

coefficients

coefficients(*, resp: str, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, dict[str, Tensor]]

Combine one response's population coefficients and group adjustments.

PARAMETER DESCRIPTION
resp

Response label.

TYPE: str

parameter

mu or a regressed distributional or nonlinear parameter.

TYPE: str DEFAULT: 'mu'

num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, dict[str, Tensor]]

Arrays with the structure of random_effects, including population coefficients.

Source code in src/quivers/formulas/_joint_fit.py
def coefficients(
    self,
    *,
    resp: str,
    parameter: str = "mu",
    num_samples: int | None = None,
    seed: int = 0,
) -> dict[str, dict[str, torch.Tensor]]:
    """Combine one response's population coefficients and group adjustments.

    Parameters
    ----------
    resp : str
        Response label.
    parameter : str
        ``mu`` or a regressed distributional or nonlinear parameter.
    num_samples : int or None
        Draws per chain under the convention of `draws`.
    seed : int
        Seed for variational draws.

    Returns
    -------
    dict[str, dict[str, torch.Tensor]]
        Arrays with the structure of `random_effects`, including
        population coefficients.
    """
    self._selection(resp)
    readout = self._predictor_readout(resp)
    predictor, prefix = readout._formula_predictor(parameter)
    namespace = self.emission.responses[resp].prefix
    draws = self.draws(num_samples=num_samples, seed=seed)
    fixed = population_coefficients(readout.predictors, draws, prefix, namespace)
    varying = self._random(draws, predictor, namespace + prefix)
    for group, values in varying.items():
        for name, coefficient in fixed.items():
            population = coefficient.unsqueeze(2)
            values[name] = (
                values[name] + population
                if name in values
                else population.expand(
                    *population.shape[:2],
                    len(self.group_levels[group]),
                    *population.shape[3:],
                )
            )
    return varying

posterior_linpred

posterior_linpred(*, resp: ResponseSelection = None, parameter: str = 'mu', transform: bool = False, new_data: IntoDataFrame | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: NewLevelPolicy = 'uncertainty', num_samples: int | None = None, seed: int = 0, data2: Mapping[str, AutocorMatrix] | None = None, incl_autocor: bool = True) -> dict[str, Tensor]

Replay linear predictors of the selected responses.

PARAMETER DESCRIPTION
resp

Selected responses, or None for every response.

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

parameter

mu or a regressed distributional or nonlinear parameter of every selected response.

TYPE: str DEFAULT: 'mu'

transform

Return the inverse-link binding instead of the linear predictor.

TYPE: bool DEFAULT: False

new_data

Fresh rows holding every response's predictors, or None.

TYPE: IntoDataFrame or None DEFAULT: None

re_formula

Varying-effect selector applied to every response.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit new grouping identities.

TYPE: bool DEFAULT: False

sample_new_levels

Existing new-level policy, drawn once per shared grouping axis.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for posterior and group-effect streams.

TYPE: int DEFAULT: 0

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

incl_autocor

Include the dependence of residual laws and latent residual terms (brms incl_autocor). False treats correlated residuals as independent rows and drops latent residuals.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
dict[str, Tensor]

Response label mapped to (chain, draw, row[, component]).

RAISES DESCRIPTION
ValueError

If a selection, predictor, or row is invalid.

Source code in src/quivers/formulas/_joint_fit.py
def posterior_linpred(
    self,
    *,
    resp: ResponseSelection = None,
    parameter: str = "mu",
    transform: bool = False,
    new_data: IntoDataFrame | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: NewLevelPolicy = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
    data2: Mapping[str, AutocorMatrix] | None = None,
    incl_autocor: bool = True,
) -> dict[str, torch.Tensor]:
    """Replay linear predictors of the selected responses.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses, or None for every response.
    parameter : str
        ``mu`` or a regressed distributional or nonlinear parameter of
        every selected response.
    transform : bool
        Return the inverse-link binding instead of the linear predictor.
    new_data : IntoDataFrame or None
        Fresh rows holding every response's predictors, or None.
    re_formula : str or None
        Varying-effect selector applied to every response.
    allow_new_levels : bool
        Permit new grouping identities.
    sample_new_levels : str
        Existing new-level policy, drawn once per shared grouping axis.
    num_samples : int or None
        Draws per chain under the convention of `draws`.
    seed : int
        Seed for posterior and group-effect streams.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).
    incl_autocor : bool
        Include the dependence of residual laws and latent residual
        terms (brms ``incl_autocor``). False treats correlated residuals
        as independent rows and drops latent residuals.

    Returns
    -------
    dict[str, torch.Tensor]
        Response label mapped to ``(chain, draw, row[, component])``.

    Raises
    ------
    ValueError
        If a selection, predictor, or row is invalid.
    """
    names = self._selection(resp)
    readers = {name: self._predictor_readout(name) for name in names}
    bindings = {
        name: reader._linpred_binding(parameter, transform)
        for name, reader in readers.items()
    }
    prepared = self._prepare(
        new_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        require_trials=False,
        data2=data2,
        incl_autocor=incl_autocor,
    )

    def operation(recorded: Trace) -> dict[str, torch.Tensor]:
        """Read every selected linear predictor from one trace.

        Parameters
        ----------
        recorded : Trace
            One replayed joint trace.

        Returns
        -------
        dict[str, torch.Tensor]
            Linear predictors keyed by response.
        """
        result = {}
        for name in names:
            response = self.emission.responses[name]
            index = self.response_names.index(name)
            result[name] = bindings[name].read(
                readers[name]._row_reader(
                    parameter,
                    bindings[name],
                    recorded,
                    lambda binding, names=response.names: names[binding],
                    # Under residual correlation the response is one
                    # coordinate of the joint law.
                    (
                        lambda index=index: (
                            coordinate(
                                response_distribution(recorded, JOINT_RESPONSE),
                                index,
                            ).mean
                        )
                    )
                    if self.rescor
                    else None,
                ),
                prepared.rows[name],
            )
        return result

    return self._replay(
        prepared, operation, num_samples=num_samples, seed=seed, stream=2
    )

posterior_epred

posterior_epred(*, resp: ResponseSelection = None, new_data: IntoDataFrame | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: NewLevelPolicy = 'uncertainty', num_samples: int | None = None, mc_samples: int | None = None, seed: int = 0, data2: Mapping[str, AutocorMatrix] | None = None, incl_autocor: bool = True) -> dict[str, Tensor]

Return expected responses of the selected responses.

Under residual correlation the expectation is the mean vector of the joint residual law, whose components are the response means.

PARAMETER DESCRIPTION
resp

Selected responses, or None for every response.

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

new_data

Fresh rows holding every response's predictors, or None.

TYPE: IntoDataFrame or None DEFAULT: None

re_formula

Varying-effect selector applied to every response.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit new grouping identities.

TYPE: bool DEFAULT: False

sample_new_levels

Existing new-level policy, drawn once per shared grouping axis.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

mc_samples

Monte Carlo budget for responses without a closed mean.

TYPE: int or None DEFAULT: None

seed

Seed for posterior, group-effect, and Monte Carlo streams.

TYPE: int DEFAULT: 0

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

incl_autocor

Include the dependence of residual laws and latent residual terms (brms incl_autocor). False treats correlated residuals as independent rows and drops latent residuals.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
dict[str, Tensor]

Response label mapped to (chain, draw, row[, event]); ordinal and categorical responses give category probabilities.

Source code in src/quivers/formulas/_joint_fit.py
def posterior_epred(
    self,
    *,
    resp: ResponseSelection = None,
    new_data: IntoDataFrame | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: NewLevelPolicy = "uncertainty",
    num_samples: int | None = None,
    mc_samples: int | None = None,
    seed: int = 0,
    data2: Mapping[str, AutocorMatrix] | None = None,
    incl_autocor: bool = True,
) -> dict[str, torch.Tensor]:
    """Return expected responses of the selected responses.

    Under residual correlation the expectation is the mean vector of the
    joint residual law, whose components are the response means.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses, or None for every response.
    new_data : IntoDataFrame or None
        Fresh rows holding every response's predictors, or None.
    re_formula : str or None
        Varying-effect selector applied to every response.
    allow_new_levels : bool
        Permit new grouping identities.
    sample_new_levels : str
        Existing new-level policy, drawn once per shared grouping axis.
    num_samples : int or None
        Draws per chain under the convention of `draws`.
    mc_samples : int or None
        Monte Carlo budget for responses without a closed mean.
    seed : int
        Seed for posterior, group-effect, and Monte Carlo streams.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).
    incl_autocor : bool
        Include the dependence of residual laws and latent residual
        terms (brms ``incl_autocor``). False treats correlated residuals
        as independent rows and drops latent residuals.

    Returns
    -------
    dict[str, torch.Tensor]
        Response label mapped to ``(chain, draw, row[, event])``; ordinal
        and categorical responses give category probabilities.
    """
    names = self._selection(resp)
    prepared = self._prepare(
        new_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        data2=data2,
        incl_autocor=incl_autocor,
    )

    measurements = {}
    if not self.rescor:
        for name in names:
            response = self.emission.responses[name]
            site = response.names[_qvr_name(response.formula.response_name)]
            readout = self._response_readout(name)
            extent = (
                self._response_data(name).layout.event_shape or readout.categories
            )
            measurements[name] = (site, readout, extent)

    def operation(recorded: Trace) -> dict[str, torch.Tensor]:
        """Read every selected expected response from one trace.

        Parameters
        ----------
        recorded : Trace
            One replayed joint trace.

        Returns
        -------
        dict[str, torch.Tensor]
            Expected responses keyed by response.
        """
        if self.rescor:
            value = response_mean(
                response_distribution(recorded, JOINT_RESPONSE), mc_samples
            )
            rows = prepared.rows[names[0]]
            value = row_binding(value, rows, (len(self.response_names),))
            return {
                name: value[..., self.response_names.index(name)] for name in names
            }
        result: dict[str, torch.Tensor] = {}
        for name, (site, readout, extent) in measurements.items():
            value = expected_response(
                response_distribution(recorded, site),
                readout,
                mc_samples=mc_samples,
            )
            result[name] = row_binding(value, prepared.rows[name], extent)
        return result

    return self._replay(
        prepared, operation, num_samples=num_samples, seed=seed, stream=2
    )

posterior_predict

posterior_predict(*, resp: ResponseSelection = None, new_data: IntoDataFrame | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: NewLevelPolicy = 'uncertainty', num_samples: int | None = None, seed: int = 0, data2: Mapping[str, AutocorMatrix] | None = None, incl_autocor: bool = True) -> dict[str, Tensor]

Draw responses, keeping the residual correlation of joint events.

Every response is drawn in the same replay; under residual correlation one vector event is drawn per row and the selected components are returned, so selected responses keep their joint law.

PARAMETER DESCRIPTION
resp

Selected responses, or None for every response.

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

new_data

Fresh rows holding every response's predictors, or None.

TYPE: IntoDataFrame or None DEFAULT: None

re_formula

Varying-effect selector applied to every response.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit new grouping identities.

TYPE: bool DEFAULT: False

sample_new_levels

Existing new-level policy, drawn once per shared grouping axis.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for posterior, group-effect, and response streams.

TYPE: int DEFAULT: 0

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

incl_autocor

Include the dependence of residual laws and latent residual terms (brms incl_autocor). False treats correlated residuals as independent rows and drops latent residuals.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
dict[str, Tensor]

Response label mapped to (chain, draw, row[, event]).

Source code in src/quivers/formulas/_joint_fit.py
def posterior_predict(
    self,
    *,
    resp: ResponseSelection = None,
    new_data: IntoDataFrame | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: NewLevelPolicy = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
    data2: Mapping[str, AutocorMatrix] | None = None,
    incl_autocor: bool = True,
) -> dict[str, torch.Tensor]:
    """Draw responses, keeping the residual correlation of joint events.

    Every response is drawn in the same replay; under residual
    correlation one vector event is drawn per row and the selected
    components are returned, so selected responses keep their joint law.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses, or None for every response.
    new_data : IntoDataFrame or None
        Fresh rows holding every response's predictors, or None.
    re_formula : str or None
        Varying-effect selector applied to every response.
    allow_new_levels : bool
        Permit new grouping identities.
    sample_new_levels : str
        Existing new-level policy, drawn once per shared grouping axis.
    num_samples : int or None
        Draws per chain under the convention of `draws`.
    seed : int
        Seed for posterior, group-effect, and response streams.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).
    incl_autocor : bool
        Include the dependence of residual laws and latent residual
        terms (brms ``incl_autocor``). False treats correlated residuals
        as independent rows and drops latent residuals.

    Returns
    -------
    dict[str, torch.Tensor]
        Response label mapped to ``(chain, draw, row[, event])``.
    """
    names = self._selection(resp)
    prepared = self._prepare(
        new_data,
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        data2=data2,
        incl_autocor=incl_autocor,
    )

    def operation(recorded: Trace) -> dict[str, torch.Tensor]:
        """Sample every response from one trace.

        Parameters
        ----------
        recorded : Trace
            One replayed joint trace.

        Returns
        -------
        dict[str, torch.Tensor]
            Predicted responses keyed by response.
        """
        if self.rescor:
            value = row_binding(
                response_sample(recorded, JOINT_RESPONSE),
                prepared.rows[names[0]],
                (len(self.response_names),),
            )
            return {
                name: value[..., self.response_names.index(name)] for name in names
            }
        result: dict[str, torch.Tensor] = {}
        for name in self.response_names:
            response = self.emission.responses[name]
            site = response.names[_qvr_name(response.formula.response_name)]
            value = row_binding(
                response_sample(recorded, site),
                prepared.rows[name],
                response.formula.response_layout.event_shape,
            )
            if name in names:
                result[name] = value
        return result

    return self._replay(
        prepared, operation, num_samples=num_samples, seed=seed, stream=1
    )

log_likelihood

log_likelihood(*, resp: ResponseSelection = None, new_data: IntoDataFrame | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: NewLevelPolicy = 'uncertainty', num_samples: int | None = None, seed: int = 0, data2: Mapping[str, AutocorMatrix] | None = None, incl_autocor: bool = True) -> dict[str, Tensor]

Return pointwise log-likelihoods with brms observation units.

Under residual correlation the unit is one row's joint vector event; a strict subset of responses is scored by the exact marginal of that event (a multivariate Normal or Student law over the selected components). Without residual correlation a selection of one response gives its own pointwise scores, and a selection of several sums their scores per row, as brms log_lik does.

On the training rows only recorded values are scored. Where an mi() value is missing, the recorded values of the row are scored by the joint law conditional on the completed value (recorded_log_prob), and a row with no recorded value scores zero. brms reports these rows as missing (NA) instead.

PARAMETER DESCRIPTION
resp

Selected responses, or None for every response.

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

new_data

Fresh predictors and recorded outcomes of the selected responses, or None for the training rows.

TYPE: IntoDataFrame or None DEFAULT: None

re_formula

Varying-effect selector applied to every response.

TYPE: str or None DEFAULT: None

allow_new_levels

Permit new grouping identities.

TYPE: bool DEFAULT: False

sample_new_levels

Existing new-level policy, drawn once per shared grouping axis.

TYPE: str DEFAULT: 'uncertainty'

num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for posterior and group-effect streams.

TYPE: int DEFAULT: 0

data2

Matrices of sar and fcor terms over the rows of new_data (brms newdata2).

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

incl_autocor

Include the dependence of residual laws and latent residual terms (brms incl_autocor). False treats correlated residuals as independent rows and drops latent residuals.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
dict[str, Tensor]

One entry keyed by the selected labels joined by "__", shaped (chain, draw, row). Likelihood weights are excluded.

RAISES DESCRIPTION
ValueError

If summed responses have different row counts.

Source code in src/quivers/formulas/_joint_fit.py
def log_likelihood(
    self,
    *,
    resp: ResponseSelection = None,
    new_data: IntoDataFrame | None = None,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    sample_new_levels: NewLevelPolicy = "uncertainty",
    num_samples: int | None = None,
    seed: int = 0,
    data2: Mapping[str, AutocorMatrix] | None = None,
    incl_autocor: bool = True,
) -> dict[str, torch.Tensor]:
    """Return pointwise log-likelihoods with brms observation units.

    Under residual correlation the unit is one row's joint vector event;
    a strict subset of responses is scored by the exact marginal of that
    event (a multivariate Normal or Student law over the selected
    components). Without residual correlation a selection of one
    response gives its own pointwise scores, and a selection of several
    sums their scores per row, as brms ``log_lik`` does.

    On the training rows only recorded values are scored. Where an
    ``mi()`` value is missing, the recorded values of the row are scored
    by the joint law conditional on the completed value
    (`recorded_log_prob`), and a row with no recorded value scores zero.
    brms reports these rows as missing (NA) instead.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses, or None for every response.
    new_data : IntoDataFrame or None
        Fresh predictors and recorded outcomes of the selected responses,
        or None for the training rows.
    re_formula : str or None
        Varying-effect selector applied to every response.
    allow_new_levels : bool
        Permit new grouping identities.
    sample_new_levels : str
        Existing new-level policy, drawn once per shared grouping axis.
    num_samples : int or None
        Draws per chain under the convention of `draws`.
    seed : int
        Seed for posterior and group-effect streams.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Matrices of ``sar`` and ``fcor`` terms over the rows of
        ``new_data`` (brms ``newdata2``).
    incl_autocor : bool
        Include the dependence of residual laws and latent residual
        terms (brms ``incl_autocor``). False treats correlated residuals
        as independent rows and drops latent residuals.

    Returns
    -------
    dict[str, torch.Tensor]
        One entry keyed by the selected labels joined by ``"__"``, shaped
        ``(chain, draw, row)``. Likelihood weights are excluded.

    Raises
    ------
    ValueError
        If summed responses have different row counts.
    """
    names = self._selection(resp)
    key = "__".join(names)
    prepared = self._prepare(
        new_data,
        recorded=frozenset(names),
        re_formula=re_formula,
        allow_new_levels=allow_new_levels,
        sample_new_levels=sample_new_levels,
        seed=seed,
        require_trials=False,
        scoring=True,
        data2=data2,
        incl_autocor=incl_autocor,
    )

    if self.rescor:
        indices = [self.response_names.index(name) for name in names]
        width = len(self.response_names)
        rows = prepared.rows[names[0]]
        outcome = prepared.context.observations[JOINT_RESPONSE].reshape(rows, width)
        # On training rows a missing mi() value is completed by the
        # program; on new rows every value is recorded.
        recorded = (
            torch.stack(
                [
                    torch.as_tensor(self._response_data(name).recorded)
                    for name in self.response_names
                ],
                dim=-1,
            )
            if new_data is None
            else torch.ones((rows, width), dtype=torch.bool)
        )

        def selected(trace: Trace) -> dict[str, torch.Tensor]:
            """Score the recorded values of the selected responses.

            A missing value is conditioned on at its completion, which
            the recursions of later rows also read; a strict subset is
            scored by the exact marginal of the joint event.

            Parameters
            ----------
            trace : Trace
                One replayed joint trace.

            Returns
            -------
            dict[str, torch.Tensor]
                Pointwise scores.
            """
            values = outcome
            if not bool(recorded.all()):
                completed = torch.stack(
                    [
                        trace.sites[f"mi_{name}__completed"].value.reshape(rows)
                        if f"mi_{name}__completed" in trace.sites
                        else outcome[:, position]
                        for position, name in enumerate(self.response_names)
                    ],
                    dim=-1,
                ).to(outcome.dtype)
                values = torch.where(recorded, outcome, completed)
            law = response_distribution(trace, JOINT_RESPONSE)
            if isinstance(law, RecursiveResiduals):
                law = law.given(values)
            if len(indices) < width:
                law = marginal(law, indices)
            return {
                key: row_binding(
                    recorded_log_prob(
                        law, values[:, indices], recorded[:, indices]
                    ),
                    rows,
                )
            }

        return self._replay(
            prepared,
            selected,
            num_samples=num_samples,
            seed=seed,
            stream=2,
            score=True,
        )
    training = new_data is None and re_formula is None
    # On training rows an mi() response is scored on its recorded events;
    # a missing row has no recorded likelihood.
    events = {
        name: self.missing_specs[name]
        for name in names
        if training
        and name in self.missing_specs
        and (
            self.missing_specs[name].standard_error is not None
            or self.missing_specs[name].latent_positions
        )
    }
    sites = {
        name: f"mi_{name}__observed"
        if name in events
        else self.emission.responses[name].names[
            _qvr_name(self.emission.responses[name].formula.response_name)
        ]
        for name in names
    }
    counts = {prepared.rows[name] for name in names}
    if len(counts) != 1:
        raise ValueError(
            "summing log-likelihoods across responses requires equal row counts; "
            "select one response with resp"
        )
    shape = draw_count(self.posterior, num_samples)
    draws = self.draws(num_samples=num_samples, seed=seed)
    with torch.no_grad():
        # Correlated residuals score brms's leave-one-out conditionals, as
        # the single-response fit does.
        scores = pointwise_scores(
            replay(
                cast(BayesianFit, self),
                draws,
                shape,
                context=prepared.context,
                score_observations=True,
            ),
            set(sites.values()),
            {
                sites[name]
                for name in names
                if name not in events
                and self.emission.responses[name].lens._residual is not None
            },
            shape,
        )
    for name, spec in events.items():
        recorded = scores[sites[name]]
        full = recorded.new_zeros((*recorded.shape[:2], prepared.rows[name]))
        positions = torch.as_tensor(spec.observed_rows, dtype=torch.long)
        included = {row: index for index, row in enumerate(spec.rows.positions)}
        full[..., [included[int(row)] for row in positions]] = recorded
        scores[sites[name]] = full
    return {key: sum((scores[site] for site in sites.values()), torch.zeros(()))}

observed

observed(*, resp: ResponseSelection = None) -> dict[str, Tensor]

Return the training outcomes of the selected responses.

PARAMETER DESCRIPTION
resp

Selected responses, or None for every response.

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

RETURNS DESCRIPTION
dict[str, Tensor]

Native response carriers keyed by response.

Source code in src/quivers/formulas/_joint_fit.py
def observed(self, *, resp: ResponseSelection = None) -> dict[str, torch.Tensor]:
    """Return the training outcomes of the selected responses.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Selected responses, or None for every response.

    Returns
    -------
    dict[str, torch.Tensor]
        Native response carriers keyed by response.
    """
    return {
        name: response_tensor(
            self.emission.responses[name].formula, self.prepared[name].family
        )
        for name in self._selection(resp)
    }

analysis

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

Prepare reusable summaries and predictive comparisons.

PARAMETER DESCRIPTION
resp

Responses whose pointwise scores enter the analysis, with the units of log_likelihood.

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

num_samples

Draws per chain under the convention of draws.

TYPE: int or None DEFAULT: None

seed

Seed for variational draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PosteriorAnalysis

Native draws, pointwise scores, outcomes, and sampler statistics.

Source code in src/quivers/formulas/_joint_fit.py
def analysis(
    self,
    *,
    resp: ResponseSelection = None,
    num_samples: int | None = None,
    seed: int = 0,
) -> PosteriorAnalysis:
    """Prepare reusable summaries and predictive comparisons.

    Parameters
    ----------
    resp : str or Sequence[str] or None
        Responses whose pointwise scores enter the analysis, with the
        units of `log_likelihood`.
    num_samples : int or None
        Draws per chain under the convention of `draws`.
    seed : int
        Seed for variational draws.

    Returns
    -------
    PosteriorAnalysis
        Native draws, pointwise scores, outcomes, and sampler statistics.
    """
    shape = draw_count(self.posterior, num_samples)
    return PosteriorAnalysis(
        samples=self.draws(num_samples=num_samples, seed=seed),
        log_likelihood=self.log_likelihood(
            resp=resp, num_samples=num_samples, seed=seed
        ),
        observed_data=self.observed(resp=resp),
        sample_stats=_sample_stats(self.posterior, shape[1]),
        kind=_kind(self.posterior),
    )

conditional_effects

conditional_effects(grid: PredictionGrid, *, resp: ResponseSelection = ..., method: EffectMethod = ..., mc_samples: int | None = ..., **options: Unpack[JointConditionalEffectsOptions]) -> dict[str, ConditionalEffects]
conditional_effects(grid: str | Sequence[str] | None = ..., *, resp: ResponseSelection = ..., method: EffectMethod = ..., mc_samples: int | None = ..., **options: Unpack[JointConditionalEffectsOptions]) -> BrmsConditionalEffects
conditional_effects(grid: PredictionGrid | str | Sequence[str] | None = None, *, resp: ResponseSelection = None, method: EffectMethod = 'epred', mc_samples: int | None = None, **options: Unpack[JointConditionalEffectsOptions]) -> dict[str, ConditionalEffects] | BrmsConditionalEffects

Predict one grid jointly and retain each response's effects.

Without a grid, or with brms effects, this computes brms's automatic conditional effects of every selected response (quivers.formulas._brms_effects.brms_conditional_effects).

PARAMETER DESCRIPTION
grid

Effect coordinates and reference rows from quivers.diagnostics.prediction_grid, holding every response's predictors; or brms effects (None for brms's defaults).

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

resp

Selected responses, or None for every response.

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

method

epred, linpred, predict, or brms's posterior_* names.

TYPE: str DEFAULT: 'epred'

mc_samples

Monte Carlo budget of expectations without a closed mean.

TYPE: int or None DEFAULT: None

**options

Varying-effect selection, new-level policy, draw count, and seed; without a grid, brms's conditional_effects arguments.

TYPE: JointConditionalEffectsOptions DEFAULT: {}

RETURNS DESCRIPTION
dict[str, ConditionalEffects] or BrmsConditionalEffects

Effects keyed by response, or brms's labeled effect frames.

RAISES DESCRIPTION
ValueError

If the method is unknown or mc_samples is given outside epred.

Source code in src/quivers/formulas/_joint_fit.py
def conditional_effects(
    self,
    grid: PredictionGrid | str | Sequence[str] | None = None,
    *,
    resp: ResponseSelection = None,
    method: EffectMethod = "epred",
    mc_samples: int | None = None,
    **options: Unpack[JointConditionalEffectsOptions],
) -> dict[str, ConditionalEffects] | BrmsConditionalEffects:
    """Predict one grid jointly and retain each response's effects.

    Without a grid, or with brms ``effects``, this computes brms's
    automatic conditional effects of every selected response
    (`quivers.formulas._brms_effects.brms_conditional_effects`).

    Parameters
    ----------
    grid : PredictionGrid or str or Sequence[str] or None
        Effect coordinates and reference rows from
        `quivers.diagnostics.prediction_grid`, holding every response's
        predictors; or brms ``effects`` (None for brms's defaults).
    resp : str or Sequence[str] or None
        Selected responses, or None for every response.
    method : str
        ``epred``, ``linpred``, ``predict``, or brms's
        ``posterior_*`` names.
    mc_samples : int or None
        Monte Carlo budget of expectations without a closed mean.
    **options : JointConditionalEffectsOptions
        Varying-effect selection, new-level policy, draw count, and seed;
        without a grid, brms's ``conditional_effects`` arguments.

    Returns
    -------
    dict[str, ConditionalEffects] or BrmsConditionalEffects
        Effects keyed by response, or brms's labeled effect frames.

    Raises
    ------
    ValueError
        If the method is unknown or mc_samples is given outside epred.
    """
    # brms automatic conditional effects.
    if not isinstance(grid, PredictionGrid):
        if mc_samples is not None:
            raise ValueError("mc_samples applies only to explicit grids")
        return automatic_conditional_effects(
            self,
            grid,
            method=method,
            parameter="mu",
            transform=False,
            resp=resp,
            options=options,
        )
    prediction = joint_grid_options(options)
    short = method.removeprefix("posterior_")
    if short not in {"epred", "linpred", "predict"}:
        raise ValueError("method must be epred, linpred, or predict")
    method = cast(Literal["epred", "linpred", "predict"], short)
    if method != "epred" and mc_samples is not None:
        raise ValueError("mc_samples applies only to epred effects")
    frame = grid.to_frame()
    request = cast(JointEffectOptions, prediction)
    if method == "epred":
        predictions = self.posterior_epred(
            resp=resp, new_data=frame, mc_samples=mc_samples, **request
        )
    elif method == "linpred":
        predictions = self.posterior_linpred(resp=resp, new_data=frame, **request)
    else:
        predictions = self.posterior_predict(resp=resp, new_data=frame, **request)
    effects = {}
    for name, value in predictions.items():
        readout = self._predictor_readout(name)
        effects[name] = grid.result(
            value,
            kind=_kind(self.posterior),
            method=method,
            labels=readout.predictor_labels("mu")
            if method == "linpred"
            else readout.category_labels,
        )
    return effects

prior_view

prior_view(*, num_samples: int | None = None, seed: int = 0) -> MultivariateFit

Reuse every result method with joint prior draws.

PARAMETER DESCRIPTION
num_samples

Fresh draw count, or None to reuse retained prior samples.

TYPE: int or None DEFAULT: None

seed

Isolated seed of fresh draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
MultivariateFit

A view sharing the fitted model with the prior as its posterior.

Source code in src/quivers/formulas/_joint_fit.py
def prior_view(
    self, *, num_samples: int | None = None, seed: int = 0
) -> MultivariateFit:
    """Reuse every result method with joint prior draws.

    Parameters
    ----------
    num_samples : int or None
        Fresh draw count, or None to reuse retained prior samples.
    seed : int
        Isolated seed of fresh draws.

    Returns
    -------
    MultivariateFit
        A view sharing the fitted model with the prior as its posterior.
    """
    prior = (
        self.prior
        if self.prior is not None and num_samples is None
        else self.prior_draws(
            num_samples=100 if num_samples is None else num_samples, seed=seed
        )
    )
    return self.with_(
        posterior=prior,
        prior=prior,
        sample_prior="only",
        losses=(),
        response_fits=dict(self.response_fits),
    )

hypothesis

hypothesis(expression: str | ContrastExpression | Sequence[str] | Mapping[str, str], *, 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', class_: str | None = 'b', group: str | None = None, scope: Literal['standard', 'ranef', 'coef'] = 'standard', alpha: float = 0.05) -> HypothesisSummary | HypothesisTable

Test a brms hypothesis string, or a contrast over brms names.

PARAMETER DESCRIPTION
expression

brms hypothesis strings "left (= | < | >) right", whose names take the class prefix ("y1_x > y2_x" tests b_y1_x - b_y2_x); or a QVR expression over the names of variables, for instance "b_y1_x - b_y2_x" or "rescor__y1__y2".

TYPE: str or ContrastExpression or Sequence[str] or Mapping[str, str]

prior

Also evaluate the contrast on joint prior draws.

TYPE: bool DEFAULT: False

num_samples

Posterior and prior draw counts.

TYPE: int or None DEFAULT: None

num_prior_samples

Posterior and prior draw counts.

TYPE: int or None DEFAULT: None

seed

Isolated seed.

TYPE: int DEFAULT: 0

null

Comparison value.

TYPE: float or int or Tensor DEFAULT: 0.0

probs

Quantile probabilities.

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

robust

Use median and scaled MAD.

TYPE: bool DEFAULT: False

point

Optional point-density comparison; requires prior=True.

TYPE: PointNullSpec or None DEFAULT: None

name

Output contrast label.

TYPE: str DEFAULT: 'contrast'

class_

Class prefix of the names in a brms hypothesis string; None reads them as variables reports them.

TYPE: str or None DEFAULT: 'b'

group

Grouping factor of a brms hypothesis string.

TYPE: str or None DEFAULT: None

scope

Scope of a brms hypothesis string.

TYPE: ('standard', 'ranef', 'coef') DEFAULT: "standard"

alpha

brms alpha of a hypothesis string.

TYPE: float DEFAULT: 0.05

RETURNS DESCRIPTION
HypothesisSummary or HypothesisTable

brms's table for a hypothesis string; posterior summaries and region evidence for a contrast expression.

RAISES DESCRIPTION
ValueError

If point evidence or a prior count is requested without prior, or a hypothesis string is malformed or names an unknown parameter.

Source code in src/quivers/formulas/_joint_fit.py
def hypothesis(
    self,
    expression: str | ContrastExpression | Sequence[str] | Mapping[str, str],
    *,
    prior: bool = False,
    num_samples: int | None = None,
    num_prior_samples: int | None = None,
    seed: int = 0,
    null: float | int | torch.Tensor = 0.0,
    probs: Sequence[float] = (0.025, 0.975),
    robust: bool = False,
    point: PointNullSpec | None = None,
    name: str = "contrast",
    class_: str | None = "b",
    group: str | None = None,
    scope: Literal["standard", "ranef", "coef"] = "standard",
    alpha: float = 0.05,
) -> HypothesisSummary | HypothesisTable:
    """Test a brms hypothesis string, or a contrast over brms names.

    Parameters
    ----------
    expression : str or ContrastExpression or Sequence[str] or Mapping[str, str]
        brms hypothesis strings ``"left (= | < | >) right"``, whose
        names take the class prefix (``"y1_x > y2_x"`` tests
        ``b_y1_x - b_y2_x``); or a QVR expression over the names of
        `variables`, for instance ``"b_y1_x - b_y2_x"`` or
        ``"rescor__y1__y2"``.
    prior : bool
        Also evaluate the contrast on joint prior draws.
    num_samples, num_prior_samples : int or None
        Posterior and prior draw counts.
    seed : int
        Isolated seed.
    null : float or int or torch.Tensor
        Comparison value.
    probs : Sequence[float]
        Quantile probabilities.
    robust : bool
        Use median and scaled MAD.
    point : PointNullSpec or None
        Optional point-density comparison; requires prior=True.
    name : str
        Output contrast label.
    class_ : str or None
        Class prefix of the names in a brms hypothesis string; None
        reads them as `variables` reports them.
    group : str or None
        Grouping factor of a brms hypothesis string.
    scope : {"standard", "ranef", "coef"}
        Scope of a brms hypothesis string.
    alpha : float
        brms ``alpha`` of a hypothesis string.

    Returns
    -------
    HypothesisSummary or HypothesisTable
        brms's table for a hypothesis string; posterior summaries and
        region evidence for a contrast expression.

    Raises
    ------
    ValueError
        If point evidence or a prior count is requested without prior,
        or a hypothesis string is malformed or names an unknown
        parameter.
    """
    if is_brms_hypothesis(expression):
        return fit_hypothesis(
            self,
            cast("HypothesisInput", expression),
            class_=class_,
            group=group,
            scope=scope,
            alpha=alpha,
            robust=robust,
            prior=prior,
            num_samples=num_samples,
            num_prior_samples=num_prior_samples,
            seed=seed,
        )
    if point is not None and not prior:
        raise ValueError("point-density evidence requires prior=True")
    if num_prior_samples is not None and not prior:
        raise ValueError("num_prior_samples requires prior=True")
    samples = self.variables(num_samples=num_samples, seed=seed)
    prior_samples = (
        self.prior_view(
            num_samples=num_prior_samples, seed=(seed + 1) % 2**64
        ).variables()
        if prior
        else None
    )
    return _contrast_hypothesis(
        samples,
        cast("str | ContrastExpression", expression),
        prior=prior_samples,
        null=null,
        probs=probs,
        robust=robust,
        point=point,
        name=name,
        kind=_kind(self.posterior),
    )

update

update(data: IntoDataFrame | None = None, **overrides: object) -> MultivariateFit

Refit retained or replacement rows through the original recipe.

PARAMETER DESCRIPTION
data

Original-frame snapshot by default, or replacement rows.

TYPE: IntoDataFrame or None DEFAULT: None

**overrides

Overrides of the canonical fit arguments, including the joint formula, priors, method, budgets, or seed.

TYPE: object DEFAULT: {}

RETURNS DESCRIPTION
MultivariateFit

A fresh fit.

RAISES DESCRIPTION
ValueError

If no recipe was retained.

Source code in src/quivers/formulas/_joint_fit.py
def update(
    self, data: IntoDataFrame | None = None, **overrides: object
) -> MultivariateFit:
    """Refit retained or replacement rows through the original recipe.

    Parameters
    ----------
    data : IntoDataFrame or None
        Original-frame snapshot by default, or replacement rows.
    **overrides : object
        Overrides of the canonical `fit` arguments, including the joint
        formula, priors, method, budgets, or seed.

    Returns
    -------
    MultivariateFit
        A fresh fit.

    Raises
    ------
    ValueError
        If no recipe was retained.
    """
    return update_fit(self.refit_recipe, data, overrides)

refit_callback

refit_callback(*, method_factory: Callable[[Mapping[str, object], int], Mapping[str, object]], partition: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame] | None = None, num_samples: int | None = None, **prediction: object) -> Callable[[FoldSplit], FoldPrediction]

Adapt the retained rows to explicit refits for cross-validation.

As in brms kfold, each fold refits the joint model on every original row outside the held-out rows, so each response applies its own subset() within them, and scores the held-out rows with log_likelihood, whose units follow brms log_lik. Fold indices address the rows included by the scored responses; with subset() those are the included original rows, mapped back once. PosteriorAnalysis.reloo uses the same callback for exact leave-one-out refits.

PARAMETER DESCRIPTION
method_factory

Fold-specific canonical fit settings and seed.

TYPE: Callable

partition

Optional nonmutating row selection.

TYPE: Callable or None DEFAULT: None

num_samples

Draws per chain for held-out scoring.

TYPE: int or None DEFAULT: None

**prediction

Further log_likelihood options such as resp or allow_new_levels.

TYPE: object DEFAULT: {}

RETURNS DESCRIPTION
Callable[[FoldSplit], FoldPrediction]

Callback for cross_validate.

RAISES DESCRIPTION
ValueError

If no recipe was retained, the adapter's own options are given, the original rows changed, or scored responses include different rows (brms log_lik sums only responses with equal rows).

Source code in src/quivers/formulas/_joint_fit.py
def refit_callback(
    self,
    *,
    method_factory: Callable[[Mapping[str, object], int], Mapping[str, object]],
    partition: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame]
    | None = None,
    num_samples: int | None = None,
    **prediction: object,
) -> Callable[[FoldSplit], FoldPrediction]:
    """Adapt the retained rows to explicit refits for cross-validation.

    As in brms ``kfold``, each fold refits the joint model on every
    original row outside the held-out rows, so each response applies its
    own ``subset()`` within them, and scores the held-out rows with
    `log_likelihood`, whose units follow brms ``log_lik``. Fold indices
    address the rows included by the scored responses; with ``subset()``
    those are the included original rows, mapped back once.
    `PosteriorAnalysis.reloo` uses the same callback for exact
    leave-one-out refits.

    Parameters
    ----------
    method_factory : Callable
        Fold-specific canonical fit settings and seed.
    partition : Callable or None
        Optional nonmutating row selection.
    num_samples : int or None
        Draws per chain for held-out scoring.
    **prediction : object
        Further `log_likelihood` options such as ``resp`` or
        ``allow_new_levels``.

    Returns
    -------
    Callable[[FoldSplit], FoldPrediction]
        Callback for `cross_validate`.

    Raises
    ------
    ValueError
        If no recipe was retained, the adapter's own options are given,
        the original rows changed, or scored responses include different
        rows (brms ``log_lik`` sums only responses with equal rows).
    """
    recipe = self.refit_recipe
    if recipe is None:
        raise ValueError("this fit has no retained refit recipe")
    if forbidden := set(prediction) & {"new_data", "seed", "num_samples"}:
        raise ValueError(
            f"the refit adapter owns prediction arguments {sorted(forbidden)}"
        )
    inspect.signature(self.log_likelihood).bind(**prediction)
    scoring = cast(JointScoreOptions, dict(prediction))
    size = len(nw.from_native(recipe.data, eager_only=True))
    scored = self._selection(scoring.get("resp"))
    selections = {
        self.emission.responses[name].formula.modifiers.subset for name in scored
    }
    if len(selections) != 1:
        raise ValueError(
            "scored responses include different subset() rows; select one "
            "response with resp, as brms log_lik sums only equal rows"
        )
    (selection,) = selections
    if (selection.size if selection is not None else size) != size:
        raise ValueError(
            "retained original frame no longer has the fitted row layout"
        )
    included = selection.positions if selection is not None else tuple(range(size))
    # With mi() terms, held-out units are rows whose mi() values used by
    # the scored responses are recorded; brms scores other rows as NA.
    variables = {
        self.missing.responses[name].variable
        for name in scored
        if name in self.missing.responses
    } | {
        self.missing.responses[source].variable
        for item in self.missing.inputs
        if item.consumer in scored
        for source in item.sources
    }
    if variables:
        original = nw.from_native(recipe.data, eager_only=True).to_pandas()
        recorded = np.ones(size, dtype=bool)
        for variable in variables:
            recorded &= np.isfinite(np.asarray(original[variable], dtype=float))
        included = tuple(row for row in included if recorded[row])

    def select(data: IntoDataFrame, rows: tuple[int, ...]) -> IntoDataFrame:
        """Select original rows, preserving the dataframe backend.

        Parameters
        ----------
        data : IntoDataFrame
            Original rows.
        rows : tuple[int, ...]
            Row positions.

        Returns
        -------
        IntoDataFrame
            Selected rows.
        """
        return nw.from_native(data, eager_only=True)[list(rows), :].to_native()

    def score(
        result: MultivariateFit, rows: IntoDataFrame, seed: int
    ) -> Mapping[str, torch.Tensor]:
        """Score held-out rows with the fold's posterior.

        Parameters
        ----------
        result : MultivariateFit
            Fold fit.
        rows : IntoDataFrame
            Held-out rows.
        seed : int
            Fold seed.

        Returns
        -------
        Mapping[str, torch.Tensor]
            Pointwise held-out scores.
        """
        return result.log_likelihood(
            new_data=rows,
            seed=seed,
            num_samples=num_samples,
            **scoring,
        )

    callback = refit_callback(
        recipe,
        select if partition is None else partition,
        score,
        method_factory=method_factory,
    )

    def invoke(split: FoldSplit) -> FoldPrediction:
        """Map included-row folds to original rows and refit once.

        Parameters
        ----------
        split : FoldSplit
            Fold over the scored responses' included rows.

        Returns
        -------
        FoldPrediction
            Refitted result and held-out pointwise scores.
        """
        validate_split_rows(split, len(included))
        omitted = original_positions(split.omitted, included)
        removed = set(omitted)
        return callback(
            split.with_(
                train=tuple(row for row in range(size) if row not in removed),
                test=original_positions(split.test, included),
                omitted=omitted,
            )
        )

    return invoke

dump_qvr

dump_qvr(path: str | Path) -> Path

Write the canonical joint QVR source.

PARAMETER DESCRIPTION
path

Destination.

TYPE: str or Path

RETURNS DESCRIPTION
Path

Written path.

Source code in src/quivers/formulas/_joint_fit.py
def dump_qvr(self, path: str | Path) -> Path:
    """Write the canonical joint QVR source.

    Parameters
    ----------
    path : str or Path
        Destination.

    Returns
    -------
    Path
        Written path.
    """
    out = Path(path)
    out.write_text(self.qvr_source)
    return out

MultipleFit didactic-model

MultipleFit(*, pooled: BayesianFit | MultivariateFit = field(opaque=True, extras=OPAQUE_BY_IDENTITY), fits: tuple[BayesianFit | MultivariateFit, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Fits of one formula to several datasets and their pooled posterior.

PARAMETER DESCRIPTION
pooled

Fit retaining every dataset's chains (combine_models).

TYPE: BayesianFit or MultivariateFit DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

fits

The per-dataset fits, in dataset order.

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

Notes

Every public method and property of pooled is also an attribute of this value, acting on the pooled draws: summary(), posterior_predict(), conditional_effects(), loo() and the rest, as a brms brmsfit_multiple is an ordinary brmsfit. The methods defined here (rhats, update) take precedence. Data-dependent quantities use the first dataset, as in brms.

__getattr__

__getattr__(name: str) -> FieldValue | PooledMember

Read a field, or a method or property of the pooled fit.

brms treats a brmsfit_multiple as an ordinary brmsfit: summary, the prediction methods, conditional_effects, loo and every other method act on the pooled draws. A name that is not a field of this value is thus looked up on pooled, so the whole method surface of the pooled BayesianFit or MultivariateFit is available here through the one shared post-processing path.

PARAMETER DESCRIPTION
name

Field of this value, or public method or property of the pooled fit.

TYPE: str

RETURNS DESCRIPTION
FieldValue or PooledMember

The field value, or the pooled fit's bound method or property value.

RAISES DESCRIPTION
AttributeError

If the name is private, or neither a field nor a public member of the pooled fit.

Source code in src/quivers/formulas/_multiple.py
def __getattr__(self, name: str) -> FieldValue | PooledMember:
    """Read a field, or a method or property of the pooled fit.

    brms treats a ``brmsfit_multiple`` as an ordinary ``brmsfit``:
    ``summary``, the prediction methods, ``conditional_effects``,
    ``loo`` and every other method act on the pooled draws. A name that
    is not a field of this value is thus looked up on ``pooled``, so the
    whole method surface of the pooled `BayesianFit` or
    `MultivariateFit` is available here through the one shared
    post-processing path.

    Parameters
    ----------
    name : str
        Field of this value, or public method or property of the
        pooled fit.

    Returns
    -------
    FieldValue or PooledMember
        The field value, or the pooled fit's bound method or property
        value.

    Raises
    ------
    AttributeError
        If the name is private, or neither a field nor a public member
        of the pooled fit.
    """
    if name in type(self).__field_specs__ or name.startswith("_"):
        return super().__getattr__(name)
    pooled = super().__getattr__("pooled")
    if not hasattr(pooled, name):
        raise AttributeError(
            f"{type(self).__name__!r} has no field {name!r}, and its pooled "
            f"{type(pooled).__name__} has no method or property of that name"
        )
    return cast(PooledMember, getattr(pooled, name))

__dir__

__dir__() -> list[str]

List this value's names and the pooled fit's public names.

RETURNS DESCRIPTION
list[str]

Sorted names reachable as attributes.

Source code in src/quivers/formulas/_multiple.py
def __dir__(self) -> list[str]:
    """List this value's names and the pooled fit's public names.

    Returns
    -------
    list[str]
        Sorted names reachable as attributes.
    """
    own = set(super().__dir__())
    public = {name for name in dir(self.pooled) if not name.startswith("_")}
    return sorted(own | public)

rhats

rhats() -> list[dict[str, Tensor]]

Return split R-hat of every parameter for each dataset.

Convergence is assessed within each dataset, as brms reports in the rhats element of a brm_multiple fit.

RETURNS DESCRIPTION
list[dict[str, Tensor]]

One mapping per dataset from native site to R-hat.

Source code in src/quivers/formulas/_multiple.py
def rhats(self) -> list[dict[str, torch.Tensor]]:
    """Return split R-hat of every parameter for each dataset.

    Convergence is assessed within each dataset, as brms reports in the
    ``rhats`` element of a ``brm_multiple`` fit.

    Returns
    -------
    list[dict[str, torch.Tensor]]
        One mapping per dataset from native site to R-hat.
    """
    return [
        {name: rhat(value) for name, value in fitted.draws().items()}
        for fitted in self.fits
    ]

update

update(data: Sequence[IntoDataFrame] | None = None, *, data2: Sequence[Mapping[str, AutocorMatrix]] | None = None, **overrides: object) -> MultipleFit

Refit every dataset through the first fit's retained recipe.

This follows brms update of a brm_multiple fit: the first fit is the template, the datasets must be given again, and every other fitting argument is kept unless overridden. Each dataset is refitted by the template's update, so all submodels share the formula, priors, budgets, and seed, and their draws are pooled with combine_models. The number of datasets may differ from the original fit's.

Cost: one ordinary refit per dataset.

PARAMETER DESCRIPTION
data

Imputed datasets. Required, as brms requires newdata.

TYPE: Sequence[IntoDataFrame] or None DEFAULT: None

data2

One mapping of named matrices per dataset; None keeps the template's matrices for every dataset.

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

**overrides

Overrides of the canonical fit arguments, as in the update method of a single fit.

TYPE: object DEFAULT: {}

RETURNS DESCRIPTION
MultipleFit

Fresh per-dataset fits and their pooled fit.

RAISES DESCRIPTION
ValueError

If the datasets are missing or empty, data2 does not match them, the datasets are given as an override, or the updated method records no draws.

Source code in src/quivers/formulas/_multiple.py
def update(
    self,
    data: Sequence[IntoDataFrame] | None = None,
    *,
    data2: Sequence[Mapping[str, AutocorMatrix]] | None = None,
    **overrides: object,
) -> MultipleFit:
    """Refit every dataset through the first fit's retained recipe.

    This follows brms ``update`` of a ``brm_multiple`` fit: the first
    fit is the template, the datasets must be given again, and every
    other fitting argument is kept unless overridden. Each dataset is
    refitted by the template's `update`, so all submodels share the
    formula, priors, budgets, and seed, and their draws are pooled with
    `combine_models`. The number of datasets may differ from the
    original fit's.

    Cost: one ordinary refit per dataset.

    Parameters
    ----------
    data : Sequence[IntoDataFrame] or None
        Imputed datasets. Required, as brms requires ``newdata``.
    data2 : Sequence[Mapping[str, AutocorMatrix]] or None
        One mapping of named matrices per dataset; None keeps the
        template's matrices for every dataset.
    **overrides : object
        Overrides of the canonical `fit` arguments, as in the `update`
        method of a single fit.

    Returns
    -------
    MultipleFit
        Fresh per-dataset fits and their pooled fit.

    Raises
    ------
    ValueError
        If the datasets are missing or empty, ``data2`` does not match
        them, the datasets are given as an override, or the updated
        method records no draws.
    """
    if "newdata" in overrides:
        raise ValueError("Please use argument 'data' to update the data.")
    if data is None:
        raise ValueError("'data' is required when updating a 'MultipleFit' object.")
    if isinstance(data, Mapping) or not isinstance(data, Sequence):
        raise ValueError("'data' must be a sequence of dataframes.")
    datasets = list(data)
    if not datasets:
        raise ValueError("update requires at least one dataset")
    if data2 is not None:
        if isinstance(data2, Mapping) or not all(
            isinstance(item, Mapping) for item in data2
        ):
            raise ValueError("'data2' must be a sequence of named mappings.")
        if len(data2) != len(datasets):
            raise ValueError("'data2' must have the same length as 'data'.")
    if overrides.get("method") == "svi":
        raise ValueError(
            "fit_multiple pools recorded draws; use method='nuts' or 'hmc'"
        )
    template = self.fits[0]
    settings = [
        dict(overrides) if data2 is None else {**overrides, "data2": data2[index]}
        for index in range(len(datasets))
    ]
    if isinstance(template, MultivariateFit):
        joint = tuple(
            template.update(frame, **options)
            for frame, options in zip(datasets, settings, strict=True)
        )
        return MultipleFit(pooled=combine_models(*joint), fits=joint)
    single = tuple(
        template.update(frame, **options)
        for frame, options in zip(datasets, settings, strict=True)
    )
    return MultipleFit(pooled=combine_models(*single), fits=single)

ResponseDraws didactic-model

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

Bases: ValueModel

Posterior responses decoded into their original measurement coordinates.

PARAMETER DESCRIPTION
value

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

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

decision

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

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

decision_labels

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

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

PredictionOptions

Bases: TypedDict

Optional prediction keywords shared by native and decoded response draws.

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

ExpectationOptions

Bases: PredictionOptions

Optional expectation keywords shared by response and decision means.

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

KFoldPrediction didactic-model

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

Bases: ValueModel

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

PARAMETER DESCRIPTION
observed

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

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

predicted

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

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

positions

Original row position of each predicted unit.

TYPE: tuple[int, ...]

KFoldResult didactic-model

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

Bases: ValueModel

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

PARAMETER DESCRIPTION
estimate

The k-fold criterion.

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

cross_validation

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

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

data

Original rows of the fitted model.

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

positions

Original row position of every partitioned unit.

TYPE: tuple[int, ...]

fold_type

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

TYPE: str

joint_fit

Whether the refits are joint fits.

TYPE: bool

resp

Joint response selection of the scores.

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

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.

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.

FitSummary didactic-model

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

Bases: ValueModel

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

PARAMETER DESCRIPTION
formula

Authored formula text.

TYPE: str

family

Family description.

TYPE: str

nobs

Number of observations used in fitting.

TYPE: int

ngrps

Number of levels of each grouping factor.

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

algorithm

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

TYPE: str

chains

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

TYPE: int

iterations

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

TYPE: int

warmup

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

TYPE: int

total_ndraws

Retained draws pooled over chains.

TYPE: int

fixed

Population coefficients, named without their b_ prefix.

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

spec_pars

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

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

random

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

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

splines

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

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

rescor

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

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

other

Native QVR sites without a brms counterpart.

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

divergences

Divergent transitions after warmup, zero without recorded chains.

TYPE: int DEFAULT: 0

VarCorrBlock didactic-model

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

Bases: ValueModel

Standard deviations, correlations and covariances of one block.

PARAMETER DESCRIPTION
sd

Summary of the standard deviations, one row per coefficient.

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

cor

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

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

cov

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

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

sd_draws

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

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

cor_draws

Draws (chain, draw, coef, coef).

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

cov_draws

Draws (chain, draw, coef, coef).

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

labels

Coefficient labels.

TYPE: tuple[str, ...]

CriterionList didactic-model

CriterionList(*, estimates: dict[str, ELPDEstimate] = field(opaque=True, extras=OPAQUE_BY_VALUE), diffs: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The estimates of several models and their comparison, brms's loolist.

PARAMETER DESCRIPTION
estimates

One estimate per model, keyed by model name, in argument order (brms's loos).

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

diffs

The comparison table, best model first (brms's diffs); None for one model or with compare=False.

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

BrmsConditionalEffects didactic-model

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

Bases: ValueModel

Conditional effects of one call, as a brms_conditional_effects list.

PARAMETER DESCRIPTION
effects

Effects in brms's order.

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

smooths_only

Whether the effects are smooth contributions (conditional_smooths).

TYPE: bool DEFAULT: False

names

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

Return the effect names in order.

RETURNS DESCRIPTION
tuple[str, ...]

brms's list names.

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

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

__getitem__

__getitem__(name: str) -> EffectFrame

Return one effect by name.

PARAMETER DESCRIPTION
name

brms's list name.

TYPE: str

RETURNS DESCRIPTION
EffectFrame

The effect.

RAISES DESCRIPTION
KeyError

If no effect has the name.

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

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

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

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

frames

frames() -> dict[str, DataFrame]

Return every effect's data frame by name.

RETURNS DESCRIPTION
dict[str, DataFrame]

brms's data frames.

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

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

EffectFrame didactic-model

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

Bases: ValueModel

One conditional effect, as an element of brms_conditional_effects.

PARAMETER DESCRIPTION
name

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

TYPE: str

effects

Plotted variables in plotting order; cats__ for categories.

TYPE: tuple[str, ...]

response

Response, distributional parameter, or nonlinear parameter predicted.

TYPE: str

frame

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

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

draws

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

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

surface

Whether both effects are numeric and plotted as a surface.

TYPE: bool DEFAULT: False

categorical

Whether rows are per category.

TYPE: bool DEFAULT: False

spaghetti

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

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

points

Observed data assigned to conditions, with resp__.

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

BayesFactor didactic-model

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

Bases: ValueModel

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

PARAMETER DESCRIPTION
bf

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

TYPE: float

log

Whether bf is on the log scale.

TYPE: bool

numerator

Names of the numerator and denominator models.

TYPE: str DEFAULT: 'x1'

denominator

Names of the numerator and denominator models.

TYPE: str DEFAULT: 'x1'

PosteriorAverage didactic-model

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

Bases: ValueModel

Model-averaged posterior draws, as brms posterior_average.

PARAMETER DESCRIPTION
draws

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

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

weights

Normalized model weights.

TYPE: dict[str, float]

ndraws

Draws contributed by each model.

TYPE: dict[str, int]

to_frame

to_frame() -> DataFrame

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

RETURNS DESCRIPTION
DataFrame

One row per pooled draw.

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

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

PredictionAverage didactic-model

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

Bases: ValueModel

Model-averaged predictions, as brms pp_average.

PARAMETER DESCRIPTION
draws

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

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

weights

Normalized model weights.

TYPE: dict[str, float]

ndraws

Draws contributed by each model.

TYPE: dict[str, int]

summary

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

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

PPCheck didactic-model

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

Bases: ValueModel

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

PARAMETER DESCRIPTION
type

bayesplot type without its prefix.

TYPE: str

prefix

Posterior predictive check or predictive distribution.

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

data

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

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

y

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

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

yrep

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

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

draw_ids

Pooled 0-based draws used.

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

group

Group label per observation.

TYPE: tuple or None DEFAULT: None

x

Covariate per observation.

TYPE: tuple or None DEFAULT: None

status

Event indicator of censored responses (km_overlay).

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

log_weights

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

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

log_likelihood

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

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

pit

PIT or LOO-PIT values per observation.

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

to_datatree

to_datatree() -> DataTree

Return an ArviZ data tree of the check.

RETURNS DESCRIPTION
DataTree

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

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

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

plot

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

Draw the check with its ArviZ counterpart.

PARAMETER DESCRIPTION
backend

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

TYPE: str

**kwargs

Further keyword arguments of the ArviZ function.

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

RETURNS DESCRIPTION
PlotCollection

The plot.

RAISES DESCRIPTION
ValueError

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

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

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

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

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

PriorRow didactic-model

PriorRow(*, site: str, prior: str, class_: str, coef: str | None = None, group: str | None = None, response: str | None = None, dpar: str | None = None, nlpar: str | None = None, lower: float | None = None, upper: float | None = None, tag: str | None = None, source: Literal['user', 'default'] = 'default')

Bases: ValueModel

One row of a prior table, in brms's brmsprior columns.

PARAMETER DESCRIPTION
site

Generated latent site the row governs.

TYPE: str

prior

Effective prior: a canonical QVR distribution call, flat for the improper flat prior, or constant(v).

TYPE: str

class_

Parameter class.

TYPE: str

coef

brms coef, group, resp, dpar and nlpar columns.

TYPE: str or None DEFAULT: None

group

brms coef, group, resp, dpar and nlpar columns.

TYPE: str or None DEFAULT: None

response

brms coef, group, resp, dpar and nlpar columns.

TYPE: str or None DEFAULT: None

dpar

brms coef, group, resp, dpar and nlpar columns.

TYPE: str or None DEFAULT: None

nlpar

brms coef, group, resp, dpar and nlpar columns.

TYPE: str or None DEFAULT: None

lower

brms lb and ub.

TYPE: float or None DEFAULT: None

upper

brms lb and ub.

TYPE: float or None DEFAULT: None

tag

brms tag of the rule that set the prior.

TYPE: str or None DEFAULT: None

source

Whether a user rule or the default policy set the prior.

TYPE: ('user', 'default') DEFAULT: "user"

PriorTable didactic-model

PriorTable(*, rows: tuple[PriorRow, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), policy: DefaultPriorPolicy = 'quivers')

Bases: ValueModel

The effective prior of every overrideable site, as brms tabulates it.

PARAMETER DESCRIPTION
rows

One row per site, in emission order.

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

policy

Default policy that filled sites no user rule selects.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

to_pandas

to_pandas() -> DataFrame

Return the table with brms's column names.

RETURNS DESCRIPTION
DataFrame

Columns prior, class, coef, group, resp, dpar, nlpar, lb, ub, tag, source, site; absent labels are empty strings and absent bounds are NaN, as in brms.

Source code in src/quivers/formulas/_brms_priors.py
def to_pandas(self) -> pd.DataFrame:
    """Return the table with brms's column names.

    Returns
    -------
    pandas.DataFrame
        Columns ``prior, class, coef, group, resp, dpar, nlpar, lb, ub,
        tag, source, site``; absent labels are empty strings and absent
        bounds are NaN, as in brms.
    """
    return pd.DataFrame(
        {
            "prior": [row.prior for row in self.rows],
            "class": [row.class_ for row in self.rows],
            "coef": [row.coef or "" for row in self.rows],
            "group": [row.group or "" for row in self.rows],
            "resp": [row.response or "" for row in self.rows],
            "dpar": [
                "" if row.dpar in (None, "mu") else row.dpar for row in self.rows
            ],
            "nlpar": [row.nlpar or "" for row in self.rows],
            "lb": [
                math.nan if row.lower is None else row.lower for row in self.rows
            ],
            "ub": [
                math.nan if row.upper is None else row.upper for row in self.rows
            ],
            "tag": [row.tag or "" for row in self.rows],
            "source": [row.source for row in self.rows],
            "site": [row.site for row in self.rows],
        }
    )

row

row(site: str) -> PriorRow

Return the row of one site.

PARAMETER DESCRIPTION
site

Generated site name.

TYPE: str

RETURNS DESCRIPTION
PriorRow

Its row.

RAISES DESCRIPTION
KeyError

If the table has no such site.

Source code in src/quivers/formulas/_brms_priors.py
def row(self, site: str) -> PriorRow:
    """Return the row of one site.

    Parameters
    ----------
    site : str
        Generated site name.

    Returns
    -------
    PriorRow
        Its row.

    Raises
    ------
    KeyError
        If the table has no such site.
    """
    for item in self.rows:
        if item.site == site:
            return item
    raise KeyError(site)

PathfinderOptions didactic-model

PathfinderOptions(*, draws: int = 1000, single_path_draws: int = 1000, history_size: int = 5, max_lbfgs_iters: int = 1000, num_elbo_draws: int = 25, psis_resample: bool = True, calculate_lp: bool = True, save_single_paths: bool = False, init_alpha: float = 0.001, tol_obj: float = 1e-12, tol_rel_obj: float = 10000.0, tol_grad: float = 1e-08, tol_rel_grad: float = 10000000.0, tol_param: float = 1e-08)

Bases: ValueModel

CmdStan pathfinder arguments, as brms passes them to cmdstanr.

PARAMETER DESCRIPTION
draws

Draws returned after Pareto-smoothed importance resampling (cmdstanr draws, CmdStan num_psis_draws).

TYPE: int DEFAULT: 1000

single_path_draws

Draws per path (cmdstanr single_path_draws, CmdStan num_draws); with one path, the draws returned.

TYPE: int DEFAULT: 1000

history_size

L-BFGS history size.

TYPE: int DEFAULT: 5

max_lbfgs_iters

Maximum L-BFGS iterations per path.

TYPE: int DEFAULT: 1000

num_elbo_draws

Draws per ELBO estimate.

TYPE: int DEFAULT: 25

psis_resample

Whether to importance resample across paths.

TYPE: bool DEFAULT: True

calculate_lp

Whether to evaluate the log density at the returned draws; without it, no resampling takes place.

TYPE: bool DEFAULT: True

save_single_paths

Whether to keep each path's draws.

TYPE: bool DEFAULT: False

init_alpha

L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.

TYPE: float DEFAULT: 0.001

tol_obj

L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.

TYPE: float DEFAULT: 0.001

tol_rel_obj

L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.

TYPE: float DEFAULT: 0.001

tol_grad

L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.

TYPE: float DEFAULT: 0.001

tol_rel_grad

L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.

TYPE: float DEFAULT: 0.001

tol_param

L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.

TYPE: float DEFAULT: 0.001

lbfgs

lbfgs() -> LBFGSSettings

Return the L-BFGS settings these arguments select.

RETURNS DESCRIPTION
LBFGSSettings

History size, iteration budget, first step and tolerances.

Source code in src/quivers/formulas/_fit_controls.py
def lbfgs(self) -> LBFGSSettings:
    """Return the L-BFGS settings these arguments select.

    Returns
    -------
    LBFGSSettings
        History size, iteration budget, first step and tolerances.
    """
    return LBFGSSettings(
        history_size=self.history_size,
        max_iterations=self.max_lbfgs_iters,
        init_alpha=self.init_alpha,
        tol_obj=self.tol_obj,
        tol_rel_obj=self.tol_rel_obj,
        tol_grad=self.tol_grad,
        tol_rel_grad=self.tol_rel_grad,
        tol_param=self.tol_param,
    )

SamplerControl didactic-model

SamplerControl(*, adapt_delta: float = 0.8, max_treedepth: int = 10, stepsize: float | None = None, metric: Literal['diag_e', 'dense_e', 'unit_e'] = 'diag_e')

Bases: ValueModel

brms control: NUTS adaptation and trajectory settings.

PARAMETER DESCRIPTION
adapt_delta

Target mean acceptance statistic of step-size adaptation, in (0, 1).

TYPE: float DEFAULT: 0.8

max_treedepth

Maximum NUTS tree depth (at most 2**max_treedepth leapfrog steps).

TYPE: int DEFAULT: 10

stepsize

Initial step size before adaptation; None keeps the kernel default.

TYPE: float or None DEFAULT: None

metric

Diagonal, dense, or unit Euclidean metric (mass matrix).

TYPE: ('diag_e', 'dense_e', 'unit_e') DEFAULT: "diag_e"

ConstantPrior didactic-model

ConstantPrior(*, value: float | tuple[float, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), broadcast: bool = True)

Bases: ValueModel

brms constant(const, broadcast): fix a parameter to known values.

PARAMETER DESCRIPTION
value

One value, or one value per selected coordinate in the target's coefficient order.

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

broadcast

Repeat a single value over every coordinate of the target, as brms does by default. With False, a tuple must match the target's width.

TYPE: bool DEFAULT: True

ImproperFlat didactic-model

ImproperFlat()

Bases: ValueModel

The improper flat prior brms writes as an empty prior string.

Its density is constant on the target's domain, so it is the Lebesgue measure there and has no normalizing constant. Fitting accepts it, since the posterior can still be proper. Prior draws, sample_prior, and marginal-likelihood estimates require a normalized prior and refuse it with an error naming the flat sites.

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.

FormulaFitOptions

Bases: JointFitOptions

Keywords of fit for a single-response formula.

Each key has the meaning of the fit keyword of the same name.

PriorTableOptions

Bases: TypedDict

Keywords of default_prior and validate_prior.

Each key has the meaning of the get_prior keyword of the same name.

formula_from_data

formula_from_data(formula: str, data: IntoDataFrame, *, weights: str | None = None, decision: str | None = None, groups: tuple[str, ...] = (), extra_namespace: Mapping[str, object] | None = None, data2: Mapping[str, Data2Object] | None = None) -> Formula

Build a typed Formula IR by lifting formulae.design_matrices over a dataframe.

This is an adapter, not a parser: the brms-style formula syntax is parsed by the formulae library; we lift its formulae.matrices.DesignMatrices result into a typed didactic record, augmented with deterministic per-group level orderings and integer-code arrays derived from the dataframe.

The R-style numeric transforms (log, exp, sqrt, abs, sin, cos, tan, log10, log2, log1p, expm1, asin, acos, atan, sinh, cosh, tanh) are pre-loaded into the formulae evaluation namespace so users coming from R / brms get the expected base R behaviour without explicit registration. offset(expr) adds an evaluated expression with coefficient one; exposure(expr) adds its logarithm and requires positive finite values. These terms work in location and auxiliary formulas. Ordinal cs(expr) terms retain a category-specific transition axis; cs(1) uses an internal constant column so fresh-data evaluation preserves its row axis. Polynomial terms via poly(x, k) are orthogonal by default, matching R's stats::poly. As brms's na_omit, a row with a missing value in any variable the formula uses (response, predictors, grouping factors, and role columns) is removed with a warning before anything is evaluated, and modifiers.subset records the original positions of the rows kept.

PARAMETER DESCRIPTION
formula

Formula string in brms / lme4 syntax.

TYPE: str

data

Pandas, polars, or any other Narwhals-compatible dataframe.

TYPE: IntoDataFrame

weights

Name of a numeric, finite, nonnegative likelihood-weight column. Its values are retained without normalization and must align with every response row after formula evaluation.

TYPE: str or None DEFAULT: None

decision

Binary decision column, numeric 0/1 or lower/upper labels. Equivalent to response | dec(column); repeated declarations must agree.

TYPE: str or None DEFAULT: None

groups

Additional grouping columns retained for structural parameters without adding varying coefficients to the predictor.

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

extra_namespace

Additional names visible inside the formula's expression evaluation, merged on top of the R-style transforms.

TYPE: Mapping[str, object] DEFAULT: None

data2

Named matrices the formula reads, such as the cov matrix of a gr() term.

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

RETURNS DESCRIPTION
Formula

The formula IR: response values, one fixed column per design column, the random terms, and each grouping factor's levels and per-row level indices.

RAISES DESCRIPTION
ValueError

If the formula has no response on the left of ~, or a random term is invalid, an offset modifier is used inside an interaction or group, or weights are nonnumeric, negative, nonfinite, or misaligned with the evaluated response rows.

Source code in src/quivers/formulas/formula.py
def formula_from_data(
    formula: str,
    data: IntoDataFrame,
    *,
    weights: str | None = None,
    decision: str | None = None,
    groups: tuple[str, ...] = (),
    extra_namespace: Mapping[str, object] | None = None,
    data2: Mapping[str, Data2Object] | None = None,
) -> Formula:
    """Build a typed `Formula` IR by lifting
    `formulae.design_matrices` over a dataframe.

    This is an adapter, not a parser: the brms-style formula syntax
    is parsed by the [`formulae`](https://bambinos.github.io/formulae/)
    library; we lift its `formulae.matrices.DesignMatrices`
    result into a typed didactic record, augmented with deterministic
    per-group level orderings and integer-code arrays derived from
    the dataframe.

    The R-style numeric transforms (``log``, ``exp``, ``sqrt``,
    ``abs``, ``sin``, ``cos``, ``tan``, ``log10``, ``log2``,
    ``log1p``, ``expm1``, ``asin``, ``acos``, ``atan``, ``sinh``,
    ``cosh``, ``tanh``) are pre-loaded into the formulae evaluation
    namespace so users coming from R / brms get the expected base
    R behaviour without explicit registration.
    ``offset(expr)`` adds an evaluated expression with coefficient one;
    ``exposure(expr)`` adds its logarithm and requires positive finite values.
    These terms work in location and auxiliary formulas. Ordinal ``cs(expr)``
    terms retain a category-specific transition axis; ``cs(1)`` uses an internal
    constant column so fresh-data evaluation preserves its row axis.
    Polynomial terms via
    ``poly(x, k)`` are orthogonal by default, matching R's
    ``stats::poly``.
    As brms's ``na_omit``, a row with a missing value in any variable the
    formula uses (response, predictors, grouping factors, and role columns)
    is removed with a warning before anything is evaluated, and
    ``modifiers.subset`` records the original positions of the rows kept.

    Parameters
    ----------
    formula : str
        Formula string in brms / lme4 syntax.
    data : IntoDataFrame
        Pandas, polars, or any other Narwhals-compatible dataframe.
    weights : str or None
        Name of a numeric, finite, nonnegative likelihood-weight column.
        Its values are retained without normalization and must align with
        every response row after formula evaluation.
    decision : str or None
        Binary decision column, numeric 0/1 or lower/upper labels. Equivalent
        to ``response | dec(column)``; repeated declarations must agree.
    groups : tuple[str, ...]
        Additional grouping columns retained for structural parameters without
        adding varying coefficients to the predictor.
    extra_namespace : Mapping[str, object], optional
        Additional names visible inside the formula's expression
        evaluation, merged on top of the R-style transforms.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Named matrices the formula reads, such as the ``cov`` matrix of a
        ``gr()`` term.

    Returns
    -------
    Formula
        The formula IR: response values, one fixed column per design
        column, the random terms, and each grouping factor's levels
        and per-row level indices.

    Raises
    ------
    ValueError
        If the formula has no response on the left of ``~``, or a
        random term is invalid, an offset modifier is used inside an
        interaction or group, or weights are nonnumeric, negative, nonfinite,
        or misaligned with the evaluated response rows.
    """
    with formula_data_options(data2=data2):
        return _formula_and_design(
            formula,
            data,
            weights=weights,
            decision=decision,
            groups=groups,
            extra_namespace=extra_namespace,
        )[0]

brmsfamily

brmsfamily(family: str, link: str | None = None, *, threshold: Literal['flexible', 'equidistant', 'sum_to_zero'] | None = None, refcat: int | str | None = None, **links: str) -> Family

Build a response family as brms brmsfamily() does.

PARAMETER DESCRIPTION
family

brms family name, in any spelling brms reads: "negbinomial", "student", "Gamma", "zi_poisson", "cumulative".

TYPE: str

link

Link of the location parameter. None keeps the family's default.

TYPE: str or None DEFAULT: None

threshold

Threshold structure of an ordinal family.

TYPE: ('flexible', 'equidistant', 'sum_to_zero') DEFAULT: "flexible"

refcat

Reference category of a categorical or vector family.

TYPE: int or str or None DEFAULT: None

**links

Links of auxiliary parameters, keyed link_<parameter> as in brms (link_sigma="log").

TYPE: str DEFAULT: {}

RETURNS DESCRIPTION
Family

The configured family, for fit(..., family=...) or added to a bf response with +.

RAISES DESCRIPTION
ValueError

If the family is unknown, an option does not apply to it, a keyword is not link_<parameter>, or a link is not admissible.

Notes

A family that keeps the default links, thresholds and reference is the registered family itself. Cost is constant.

Source code in src/quivers/formulas/_brms_family.py
def brmsfamily(
    family: str,
    link: str | None = None,
    *,
    threshold: Literal["flexible", "equidistant", "sum_to_zero"] | None = None,
    refcat: int | str | None = None,
    **links: str,
) -> Family:
    """Build a response family as brms ``brmsfamily()`` does.

    Parameters
    ----------
    family : str
        brms family name, in any spelling brms reads: ``"negbinomial"``,
        ``"student"``, ``"Gamma"``, ``"zi_poisson"``, ``"cumulative"``.
    link : str or None
        Link of the location parameter. None keeps the family's default.
    threshold : {"flexible", "equidistant", "sum_to_zero"} or None
        Threshold structure of an ordinal family.
    refcat : int or str or None
        Reference category of a categorical or vector family.
    **links : str
        Links of auxiliary parameters, keyed ``link_<parameter>`` as in
        brms (``link_sigma="log"``).

    Returns
    -------
    Family
        The configured family, for ``fit(..., family=...)`` or added to a
        `bf` response with ``+``.

    Raises
    ------
    ValueError
        If the family is unknown, an option does not apply to it, a keyword
        is not ``link_<parameter>``, or a link is not admissible.

    Notes
    -----
    A family that keeps the default links, thresholds and reference is the
    registered family itself. Cost is constant.
    """
    if family not in families:
        raise ValueError(
            f"brmsfamily: unknown family {family!r}; the families are "
            f"{sorted(families)!r}"
        )
    resolved = families[family]
    misnamed = sorted(name for name in links if not name.startswith("link_"))
    if misnamed:
        raise ValueError(
            f"brmsfamily: {misnamed!r} are not link arguments; name the link of "
            "an auxiliary parameter link_<parameter>"
        )
    selected = {name.removeprefix("link_"): value for name, value in links.items()}
    if link is not None:
        selected["mu"] = link
    if selected:
        resolved = resolved.with_links(**selected)
    if threshold is not None:
        resolved = resolved.with_thresholds(threshold)
    if refcat is not None:
        resolved = resolved.with_reference(refcat)
    return resolved

mixture

mixture(*components: str | Family, nmix: int | Sequence[int] = 1, order: Literal['mu', 'none'] | bool | None = None, equal: Mapping[str, str] | None = None) -> Family

Build a finite mixture family, brms mixture().

The distributional parameters of component k are those of its family with k appended (mu1, sigma1, mu2, ...), plus a mixing proportion theta<k>. The main formula predicts every mu<k> that has no formula of its own; each component receives its own coefficients.

PARAMETER DESCRIPTION
*components

Component families, as registered names or configured family values (for instance with links set through Family.with_links).

TYPE: str or Family DEFAULT: ()

nmix

Number of repetitions of each component, brms nmix: one integer for every component or one per component.

TYPE: int or Sequence[int] DEFAULT: 1

order

Identification by ordered location intercepts. "mu" or True orders the intercepts of mu1, ..., muK; "none" or False applies no constraint. None selects "mu" when all components share one family and "none" otherwise, as brms does. For ordinal components "mu" gives every component one shared threshold vector, and None selects "none", where each component has its own thresholds.

TYPE: ('mu', 'none') DEFAULT: "mu"

equal

Parameters set equal to another parameter of the same class, brms bf(..., sigma2 = "sigma1"); keys are the equated parameters.

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

RETURNS DESCRIPTION
Family

The mixture family with suffixed auxiliary parameters.

RAISES DESCRIPTION
ValueError

If fewer than two components result, families mix real and integer support or ordinal and other families, nmix or order is invalid, a component is excluded, an equality is invalid, or shared thresholds are requested for components without flexible thresholds.

Source code in src/quivers/formulas/_mixture.py
def mixture(
    *components: str | Family,
    nmix: int | Sequence[int] = 1,
    order: Literal["mu", "none"] | bool | None = None,
    equal: Mapping[str, str] | None = None,
) -> Family:
    """Build a finite mixture family, brms ``mixture()``.

    The distributional parameters of component ``k`` are those of its family
    with ``k`` appended (``mu1``, ``sigma1``, ``mu2``, ...), plus a mixing
    proportion ``theta<k>``. The main formula predicts every ``mu<k>``
    that has no formula of its own; each component receives its own
    coefficients.

    Parameters
    ----------
    *components : str or Family
        Component families, as registered names or configured family values
        (for instance with links set through `Family.with_links`).
    nmix : int or Sequence[int]
        Number of repetitions of each component, brms ``nmix``: one integer
        for every component or one per component.
    order : {"mu", "none"} or bool or None
        Identification by ordered location intercepts. ``"mu"`` or True orders
        the intercepts of ``mu1, ..., muK``; ``"none"`` or False applies no
        constraint. None selects ``"mu"`` when all components share one
        family and ``"none"`` otherwise, as brms does. For ordinal components
        ``"mu"`` gives every component one shared threshold vector, and None
        selects ``"none"``, where each component has its own thresholds.
    equal : Mapping[str, str] or None
        Parameters set equal to another parameter of the same class, brms
        ``bf(..., sigma2 = "sigma1")``; keys are the equated parameters.

    Returns
    -------
    Family
        The mixture family with suffixed auxiliary parameters.

    Raises
    ------
    ValueError
        If fewer than two components result, families mix real and integer
        support or ordinal and other families, ``nmix`` or ``order`` is
        invalid, a component is excluded, an equality is invalid, or shared
        thresholds are requested for components without flexible thresholds.
    """
    resolved = tuple(_component_family(component) for component in components)
    counts = (nmix,) * len(resolved) if isinstance(nmix, int) else tuple(nmix)
    if len(counts) != len(resolved):
        raise ValueError(
            "mixture: the length of 'nmix' should be the same as the number of "
            "mixture components"
        )
    if any(
        isinstance(count, bool) or not isinstance(count, int) or count < 1
        for count in counts
    ):
        raise ValueError("mixture: nmix must contain positive integers")
    expanded = tuple(
        family
        for family, count in zip(resolved, counts, strict=True)
        for _ in range(count)
    )
    if len(expanded) < 2:
        raise ValueError("mixture: expecting at least 2 mixture components")
    integer = {family.native.discrete for family in expanded}
    if len(integer) > 1:
        raise ValueError("mixture: cannot mix families with real and integer support")
    ordinal = {family.ordinal is not None for family in expanded}
    if len(ordinal) > 1:
        raise ValueError("mixture: cannot mix ordinal and non-ordinal families")
    if order is None:
        chosen: Literal["mu", "none"] = (
            "mu"
            if len({family.name for family in expanded}) == 1 and ordinal == {False}
            else "none"
        )
    elif isinstance(order, bool):
        chosen = "mu" if order else "none"
    elif order in ("mu", "none"):
        chosen = order
    else:
        raise ValueError("mixture: argument 'order' must be 'mu', 'none', or a bool")
    if (
        chosen == "mu"
        and ordinal == {True}
        and any(
            family.ordinal is None
            or family.ordinal.kind == "hurdle_cumulative"
            or family.ordinal.thresholds != "flexible"
            for family in expanded
        )
    ):
        raise ValueError(
            "mixture: thresholds shared across ordinal components (order = 'mu') "
            "require flexible thresholds and no hurdle component; use order = 'none'"
        )
    aux_params: list[AuxParam] = []
    trials = None
    for index, family in enumerate(expanded, start=1):
        aux_params.append(
            AuxParam(
                name=f"mu{index}",
                prior="Normal(0.0, 5.0)",
                link=family.location_link,
            )
        )
        aux_params.extend(
            aux.with_(name=f"{aux.name}{index}") for aux in family.aux_params
        )
        if family.trials_parameter is not None:
            trials = family.trials_parameter
    aux_params.extend(
        AuxParam(name=f"theta{index}", prior="Normal(0.0, 5.0)", link=links["identity"])
        for index in range(1, len(expanded) + 1)
    )
    equalities = tuple(sorted((equal or {}).items()))
    _validate_equalities(equalities, {aux.name for aux in aux_params})
    return Family(
        name="mixture",
        location_link=links["identity"],
        observe_family="Mixture",
        aux_params=tuple(aux_params),
        trials_parameter=trials,
        recorded_events=all(family.recorded_events for family in expanded),
        mixture=MixtureSpec(components=expanded, order=chosen, equal=equalities),
    )

update_adterms

update_adterms(formula: str, adform: str, action: Literal['update', 'replace'] = 'update') -> str
update_adterms(formula: ResponseModel, adform: str, action: Literal['update', 'replace'] = 'update') -> ResponseModel
update_adterms(formula: str | ResponseModel, adform: str, action: Literal['update', 'replace'] = 'update') -> str | ResponseModel

Update or replace the response addition terms of a formula.

brms update_adterms: "update" replaces terms of the same kind and adds new kinds; "replace" drops every existing term first.

PARAMETER DESCRIPTION
formula

A formula such as "y | weights(w) ~ x", or a bf response.

TYPE: str or ResponseModel

adform

The new terms as a one-sided formula, "~ trials(10) + cens(c)".

TYPE: str

action

Keep unrelated existing terms, or drop them all.

TYPE: ('update', 'replace') DEFAULT: "update"

RETURNS DESCRIPTION
str or ResponseModel

The edited formula, of the same kind as formula.

RAISES DESCRIPTION
ValueError

If action is unknown, adform is not one-sided, or a term is not a named call.

Source code in src/quivers/formulas/_addition_terms.py
def update_adterms(
    formula: str | ResponseModel,
    adform: str,
    action: Literal["update", "replace"] = "update",
) -> str | ResponseModel:
    """Update or replace the response addition terms of a formula.

    brms ``update_adterms``: ``"update"`` replaces terms of the same kind
    and adds new kinds; ``"replace"`` drops every existing term first.

    Parameters
    ----------
    formula : str or ResponseModel
        A formula such as ``"y | weights(w) ~ x"``, or a `bf` response.
    adform : str
        The new terms as a one-sided formula, ``"~ trials(10) + cens(c)"``.
    action : {"update", "replace"}
        Keep unrelated existing terms, or drop them all.

    Returns
    -------
    str or ResponseModel
        The edited formula, of the same kind as ``formula``.

    Raises
    ------
    ValueError
        If ``action`` is unknown, ``adform`` is not one-sided, or a term is
        not a named call.
    """
    if action not in ("update", "replace"):
        raise ValueError("action must be 'update' or 'replace'")
    if isinstance(formula, ResponseModel):
        return formula.with_(formula=update_adterms(formula.formula, adform, action))
    left, separator, rhs = adform.partition("~")
    if not separator or left.strip():
        raise ValueError("adform must be a one-sided formula such as '~ trials(10)'")
    new = _terms(rhs)
    lhs, separator, right = formula.partition("~")
    if not separator:
        raise ValueError("formula requires '~'")
    response, bar, existing = lhs.partition("|")
    current = _terms(existing) if bar and action == "update" else []
    names = [call.func.id for call in new if isinstance(call.func, ast.Name)]
    kept = [
        call
        for call in current
        if isinstance(call.func, ast.Name) and call.func.id not in names
    ]
    terms = " + ".join(ast.unparse(call) for call in (*kept, *new))
    return (
        f"{response.strip()} | {terms} ~{right}"
        if terms
        else f"{response.strip()} ~{right}"
    )

normalize_priors

normalize_priors(value: PriorInput | None) -> PriorSet

Adapt legacy named priors and typed rules into one immutable representation.

PARAMETER DESCRIPTION
value

Exact-name mapping, one rule, or a collection of typed rules.

TYPE: PriorInput or None

RETURNS DESCRIPTION
PriorSet

The canonical representation retained for compilation and replay.

RAISES DESCRIPTION
TypeError

If values are neither named distribution strings nor typed rules.

Source code in src/quivers/formulas/_priors.py
def normalize_priors(value: PriorInput | None) -> PriorSet:
    """Adapt legacy named priors and typed rules into one immutable representation.

    Parameters
    ----------
    value : PriorInput or None
        Exact-name mapping, one rule, or a collection of typed rules.

    Returns
    -------
    PriorSet
        The canonical representation retained for compilation and replay.

    Raises
    ------
    TypeError
        If values are neither named distribution strings nor typed rules.
    """
    if value is None:
        return PriorSet()
    if isinstance(value, PriorSet):
        return value
    if isinstance(value, PriorSpec):
        return PriorSet(rules=(value,))
    if isinstance(value, Mapping):
        if not all(isinstance(k, str) and isinstance(v, str) for k, v in value.items()):
            raise TypeError("named priors must map site names to distribution strings")
        return PriorSet(
            rules=tuple(
                PriorSpec(distribution=v, class_=None, site=k) for k, v in value.items()
            )
        )
    if (
        not isinstance(value, Sequence)
        or isinstance(value, (str, bytes))
        or not all(isinstance(v, PriorSpec) for v in value)
    ):
        raise TypeError("priors require a named mapping or typed PriorSpec collection")
    return PriorSet(rules=tuple(value))

custom_family

custom_family(name: str, *, catalog: FamilyCatalog, location: str, link: str | Link = 'identity', auxiliary: tuple[AuxParam, ...] | Mapping[str, AuxParam] = (), data: Mapping[str, str] | None = None) -> Family

Bind an arbitrary checked native law to ordinary regression predictors.

PARAMETER DESCRIPTION
name

Custom distribution name already defined in the supplied catalog.

TYPE: str

catalog

Immutable semantic contracts and native distribution factories.

TYPE: FamilyCatalog

location

Native parameter receiving the linked main predictor named mu.

TYPE: str

link

Existing inverse link for that predictor.

TYPE: str or Link DEFAULT: 'identity'

auxiliary

Other native parameters, with ordinary priors and distributional links. A mapping separates native names from formula names, for instance native scale mapped to an auxiliary named sigma.

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

data

Native parameters supplied by typed numeric data columns. These enter the existing predictor graph as deterministic identity-linked roots.

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

RETURNS DESCRIPTION
Family

Response law using the same compiler, inference and replay operations.

RAISES DESCRIPTION
(ValueError, TypeError)

If parameter roles overlap, omit a constructor parameter, or use an unknown link, noncustom name, or invalid deterministic input name.

Source code in src/quivers/formulas/_custom_family.py
def custom_family(
    name: str,
    *,
    catalog: FamilyCatalog,
    location: str,
    link: str | Link = "identity",
    auxiliary: tuple[AuxParam, ...] | Mapping[str, AuxParam] = (),
    data: Mapping[str, str] | None = None,
) -> Family:
    """Bind an arbitrary checked native law to ordinary regression predictors.

    Parameters
    ----------
    name : str
        Custom distribution name already defined in the supplied catalog.
    catalog : FamilyCatalog
        Immutable semantic contracts and native distribution factories.
    location : str
        Native parameter receiving the linked main predictor named ``mu``.
    link : str or Link
        Existing inverse link for that predictor.
    auxiliary : tuple[AuxParam, ...] or Mapping[str, AuxParam]
        Other native parameters, with ordinary priors and distributional links.
        A mapping separates native names from formula names, for instance
        native ``scale`` mapped to an auxiliary named ``sigma``.
    data : Mapping[str, str] or None
        Native parameters supplied by typed numeric data columns. These enter
        the existing predictor graph as deterministic identity-linked roots.

    Returns
    -------
    Family
        Response law using the same compiler, inference and replay operations.

    Raises
    ------
    ValueError, TypeError
        If parameter roles overlap, omit a constructor parameter, or use an
        unknown link, noncustom name, or invalid deterministic input name.
    """
    if not isinstance(catalog, FamilyCatalog):
        raise TypeError("catalog must be an immutable FamilyCatalog")
    if name not in {record.name for record in catalog.definitions}:
        raise ValueError(f"{name!r} is not a custom law in this catalog")
    record = catalog[name]
    if isinstance(link, str):
        if link not in links:
            raise ValueError(f"unknown inverse link {link!r}")
        link = links[link]
    if not isinstance(link, Link):
        raise TypeError("link must be a registered inverse link or Link")
    if link.name not in links or link != links[link.name]:
        raise ValueError("custom families use a registered inverse link")
    extra = dict(data or {})
    if not isinstance(auxiliary, (tuple, Mapping)):
        raise TypeError("auxiliary must be a tuple or mapping of AuxParam values")
    auxiliary_values = (
        tuple(auxiliary.values()) if isinstance(auxiliary, Mapping) else auxiliary
    )
    if any(not isinstance(item, AuxParam) for item in auxiliary_values):
        raise TypeError("auxiliary parameters must be AuxParam values")
    auxiliary_map = (
        dict(auxiliary)
        if isinstance(auxiliary, Mapping)
        else {item.name: item for item in auxiliary_values}
    )
    names = [item.name for item in auxiliary_values]
    if len(auxiliary_map) != len(auxiliary) or len(set(names)) != len(names):
        raise ValueError("custom auxiliary formula names must be distinct")
    roles = (location, *auxiliary_map, *extra)
    if len(set(roles)) != len(roles) or set(roles) != set(record.parameter_names):
        raise ValueError(
            "location, auxiliary and data roles must partition all native parameters"
        )
    if any(
        not isinstance(value, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", value)
        for value in (*names, *extra, *extra.values())
    ):
        raise ValueError(
            "custom parameter and data column names require QVR identifiers"
        )
    if "mu" in names:
        raise ValueError("mu is reserved for the main formula predictor")
    # Deterministic inputs use private graph roots, avoiding collisions with
    # authored constructor names and ordinary population coefficient sites.
    data_roots = {parameter: f"custom_data_{parameter}" for parameter in extra}
    if set(names) & set(data_roots.values()):
        raise ValueError("custom_data_ names are reserved for declared data parameters")
    deterministic = tuple(
        AuxParam(name=root, prior="Normal(0.0, 1.0)", link=links["identity"])
        for root in data_roots.values()
    )
    binding_names = {
        location: "mu",
        **{native: value.name for native, value in auxiliary_map.items()},
        **data_roots,
    }
    return Family(
        name=name,
        observe_family=name,
        observe_args=tuple(
            binding_names[parameter] for parameter in record.parameter_names
        ),
        location_link=link,
        # The native law constrains its own parameters and recorded events.
        location_links=tuple(links),
        recorded_events=True,
        aux_params=tuple(
            aux if aux.links is not None else aux.with_(links=tuple(links))
            for aux in (*auxiliary_values, *deterministic)
        ),
        custom=CustomFamilySpec(
            catalog=catalog,
            data=tuple((data_roots[name], column) for name, column in extra.items()),
        ),
    )

fit

fit(formula: MultivariateFormula, *, data: IntoDataFrame, **options: Unpack[JointFitOptions]) -> MultivariateFit
fit(formula: str | ResponseModel, *, data: IntoDataFrame, **options: Unpack[FormulaFitOptions]) -> BayesianFit
fit(formula: None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str], response: str, entry: str | None = None, static: Mapping[str, int] | None = None, **options: Unpack[FormulaFitOptions]) -> BayesianFit
fit(formula: str | ResponseModel | MultivariateFormula | None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str] | None = None, entry: str | None = None, static: Mapping[str, int] | None = None, parameters: Mapping[str, str | NonlinearExpression] | None = None, response: str | None = None, family: str | Family = 'gaussian', weights: str | None = None, decision: str | None = None, data2: Mapping[str, AutocorMatrix] | None = None, distributional: Mapping[str, str | NonlinearExpression] | None = None, nonlinear: Mapping[str, str | NonlinearExpression] | None = None, fixed_parameters: Mapping[str, float] | None = None, method: FitMethod = 'nuts', num_warmup: int | None = None, num_samples: int | None = None, num_chains: int | None = None, num_steps: int | None = None, learning_rate: float = 0.01, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, priors: PriorInput | None = None, guide: type | None = None, initial_values: Mapping[str, Tensor | float] | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor: Module | None = None, predictor_data: Tensor | None = None, seed: int = 0, sample_prior: PriorMode = 'no', num_prior_samples: int = 100, prior_seed: int | None = None, snapshot_policy: SnapshotPolicy = 'clone', default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: Sequence[str] = (), control: SamplerControl | Mapping[str, float | int | str] | None = None, thin: int = 1, init: InitSpec | None = None, init_r: float = 2.0, algorithm: Algorithm | None = None, file: str | Path | None = None, file_refit: FileRefit = 'never', pathfinder: PathfinderOptions | Mapping[str, float | int | bool] | None = None, cores: int = 1, knots: Knots | None = None, drop_unused_levels: bool = True) -> BayesianFit | MultivariateFit

Compile a brms-style formula, fit it, and return the result.

See quivers.formulas for surface details. This entry point composes formula_from_data, FormulaToQVRModule, Compiler, and the inference layer in one call.

family="categorical" uses the sorted distinct integer labels or the declared factor levels and takes the first category as the default reference. An attached categorical predictor may return (N, K-1) reference logits or (N, K) full logits. For family="mixture", mixture_components selects any finite component count of at least two; the likelihood integrates assignments exactly.

PARAMETER DESCRIPTION
formula

brms/lme4-style response formula, or a joint formula built with bf (bf("mvbind(y1, y2) ~ x") or bf(...) + bf(...)), which returns a MultivariateFit. Response-level keywords then belong to each bf call. A single-response bf("y ~ x", "sigma ~ z") is fitted as the string formula with the response keywords it carries; a keyword given both there and here with different values raises. None for a program, given by program=.

TYPE: str or ResponseModel or MultivariateFormula or None DEFAULT: None

data

Pandas, Polars, or another Narwhals-compatible dataframe.

TYPE: IntoDataFrame

program

QVR source, or a source file path and a program name. With source text alone, the one program or the one exported program is selected. The program's observation of response is the likelihood, and its domain is the rows of the data. Every sample site and input that parameters names is replaced by a regression on the link scale its support requires; every other site keeps the program's own law. Data the program reads at each row are data columns of the same name; data on another axis and scalars come from data2.

TYPE: str or tuple[str or Path, str] or None DEFAULT: None

entry

The program name when it is given separately from the source text.

TYPE: str or None DEFAULT: None

static

Finite extents of the program, by binder name.

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

parameters

Formulas of the program's parameters, as {"noise": "~ 1 + (1 | g)"}. A NonlinearExpression gives a link-scale expression and can read additional parameter formulas in the mapping. Priors of the program's parameter formulas use dpar=<parameter>.

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

response

The site the program observes, a data column.

TYPE: str or None DEFAULT: None

family

Registered response family or a family value. Family.with_links selects location or auxiliary inverse links.

TYPE: str or Family DEFAULT: 'gaussian'

weights

Numeric column of finite nonnegative likelihood weights. Values multiply each response's log density, retain their original scale, and do not weight priors or posterior predictions.

TYPE: str or None DEFAULT: None

decision

Wiener boundary-choice column: numeric zero/lower or one/upper, or the labels lower and upper. Equivalent to response-side dec(column).

TYPE: str or None DEFAULT: None

nonlinear

Named additive parameter designs or deterministic QVR expressions. Supplying this mapping interprets the response RHS as a value expression. Defaults retain the same proper coefficient priors as ordinary QVR formulas; get_prior reports their exact site names.

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

data2

Named matrices referenced by autocorrelation terms, as in brms: the spatial weights of sar(M) and the fixed covariance of fcor(M), each over the included response rows. A group-level gr(g, cov = M) reads a labeled DataFrame covariance between the levels of g, and s(g, bs = "mrf", xt = list(penalty = M)) a penalty or neighbourhood matrix over them.

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

distributional

Auxiliary-parameter formulas, for instance {"sigma": "~ z + (1 | g)"}. The optional left-hand side must match the parameter name. Coefficient prior overrides use names such as dpar_sigma_intercept and dpar_sigma_beta_z.

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

fixed_parameters

Auxiliary parameters held constant on their natural scale, for instance {"quantile": 0.9}. A fixed parameter has no latent site or prior.

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

method

Inference algorithm.

TYPE: ('nuts', 'hmc', 'svi', 'fixed_param', 'pathfinder') DEFAULT: "nuts"

num_warmup

MCMC warmup iterations per chain (NUTS and HMC only); 500 when omitted.

TYPE: int or None DEFAULT: None

num_samples

MCMC draws kept per chain after warmup (NUTS and HMC only); 1000 when omitted.

TYPE: int or None DEFAULT: None

num_chains

MCMC chains (NUTS and HMC only), or Pathfinder paths as brms's chains; 4 when omitted.

TYPE: int or None DEFAULT: None

num_steps

SVI optimization steps (SVI only); 1000 when omitted.

TYPE: int or None DEFAULT: None

learning_rate

The Adam learning rate of the SVI optimizer (SVI only).

TYPE: float DEFAULT: 0.01

fixed_prior

Prior of every fixed-effect coefficient.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

random_scale_prior

Prior of every random-effect standard deviation.

TYPE: str DEFAULT: 'HalfNormal(1.0)'

correlation_prior

Default prior for correlated group blocks, in LKJ Cholesky form. Explicit shared IDs join coefficients across distributional formulas.

TYPE: str DEFAULT: 'LKJCholesky(1.0)'

group_covariances

Known covariance between labeled levels, keyed by grouping factor. The same declaration serves compilation, inspection, and prediction.

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

priors

Named overrides or typed selectors, including sampled shrinkage hierarchies. Unknown, unused, or ambiguous rules raise ValueError.

TYPE: PriorInput or None DEFAULT: None

guide

The SVI guide class; AutoNormalGuide when omitted.

TYPE: type or None DEFAULT: None

initial_values

Natural-scale starting values keyed by latent site, including coefficient names. Scalars broadcast to a site's declared shape. Values must lie strictly inside the prior support. MCMC applies these after its seeded initial strategy; SVI passes them to the guide constructor. A custom guide must accept this keyword when values are supplied. For a regressed shifted-lognormal or Wiener ndt with the log link and an intercept, default coefficient centers put the shift below the minimum observed response; explicit values override those centers. An unregressed learned Wiener delay starts at one quarter of the minimum reaction time, before explicit overrides.

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

reparameterize

Parameterization of the random effects.

TYPE: ('centered', 'noncentered') DEFAULT: "centered"

binomial_trials

Trials per row for binomial or beta-binomial responses: a constant or a column.

TYPE: int or str DEFAULT: None

thresholds_by

Column grouping the cutpoints of an ordinal family.

TYPE: str or None DEFAULT: None

mixture_components

Number of Gaussian components for the mixture family.

TYPE: int DEFAULT: 2

predictor

Optional differentiable contribution on the linear-predictor scale.

TYPE: Module or None DEFAULT: None

predictor_data

Input passed to predictor on each SVI step.

TYPE: Tensor or None DEFAULT: None

seed

Seed for compilation and inference. The caller's CPU random state is restored on return or failure.

TYPE: int DEFAULT: 0

sample_prior

Fit the posterior, additionally retain independent prior draws, or disable observation likelihoods during inference. Priors, their data dependencies, support constraints, and explicit potentials remain.

TYPE: ('no', 'yes', 'only') DEFAULT: "no"

num_prior_samples

Positive independent draw budget for mode "yes".

TYPE: int DEFAULT: 100

prior_seed

Isolated prior stream. None uses seed + 1 modulo 2**64. Retaining prior draws does not change fitted posterior draws or losses.

TYPE: int or None DEFAULT: None

snapshot_policy

Retain one independent original-data snapshot for update/refit by default. Reference mode shares caller data explicitly. Predictor initial states are copied before each refit, so fits do not share trained mutable parameters.

TYPE: ('clone', 'reference') DEFAULT: "clone"

default_priors

Default prior policy: the proper, autoscaled quivers defaults, or brms::default_prior (flat b; Student-t intercept, sd and sigma priors scaled by the response). Explicit priors win either way.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

center

brms bf(center = ): sample the intercept of the column-centered design and report b_Intercept = Intercept_c - mean(X) b. None centers under the brms policy only.

TYPE: bool or None DEFAULT: None

decomp

brms bf(decomp = "QR"): sample the location coefficients in scaled QR coordinates; class b priors act on those coordinates.

TYPE: ('none', 'QR') DEFAULT: "none"

cmc

brms cmc: with False, a formula without intercept keeps treatment coding (no cell-mean coding of its first factor).

TYPE: bool DEFAULT: True

sparse

brms sparse: the same model with centering disabled, as brms disables it for sparse designs; incompatible with decomp="QR".

TYPE: bool DEFAULT: False

unused

brms unused: further columns kept with the model rows, so rows missing them are excluded as for model variables.

TYPE: Sequence[str] DEFAULT: ()

control

brms control: adapt_delta (NUTS target acceptance), max_treedepth, initial stepsize, and metric (diag_e, dense_e, unit_e). MCMC only.

TYPE: SamplerControl or Mapping or None DEFAULT: None

thin

Keep every thin-th post-warmup transition; num_samples stays the retained draw count per chain. MCMC only.

TYPE: int DEFAULT: 1

init

brms init: "random" draws unconstrained starts uniformly from (-init_r, init_r), 0 or "0" starts at zero, a mapping gives named natural-scale starts, a list gives one mapping per chain, and a function of the one-based chain index returns one. None keeps the driver's seeded jitter. Formula starts and initial_values apply under every choice.

TYPE: str or float or Mapping or Sequence or Callable or None DEFAULT: None

init_r

Half-width of init = "random".

TYPE: float DEFAULT: 2.0

algorithm

brms algorithm: NUTS, SVI with a mean-field, full-rank, or Laplace guide, the fixed-parameter sampler, which keeps every draw at the initial values, or multi-path Pathfinder with num_chains paths.

TYPE: ('sampling', 'meanfield', 'fullrank', 'laplace', 'fixed_param', 'pathfinder') DEFAULT: "sampling"

file

brms file: load the fit saved there, or fit and save it there.

TYPE: str or Path or None DEFAULT: None

file_refit

brms file_refit: reuse a saved fit, always refit, or refit when the formula, data, priors, or settings differ from the saved recipe.

TYPE: ('never', 'always', 'on_change') DEFAULT: "never"

pathfinder

cmdstanr pathfinder arguments for algorithm="pathfinder" (draws, single_path_draws, history_size, max_lbfgs_iters, num_elbo_draws, psis_resample, calculate_lp, save_single_paths, init_alpha and the tol_* tolerances), which brms passes through its ....

TYPE: PathfinderOptions or Mapping or None DEFAULT: None

cores

brms cores: run the MCMC chains in up to this many worker processes. Each worker rebuilds the fit from the retained arguments and data and runs its share of the chains; the draws equal those of the serial run with the same seed. Every argument must be picklable.

TYPE: int DEFAULT: 1

knots

brms knots: knot values keyed by smooth covariate, passed to the cr, cs, cc, ps and bs constructors of s() as mgcv's smoothCon(knots = ) does.

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

drop_unused_levels

brms drop_unused_levels: with False, factor levels that no row uses keep their population columns (of zeros) and grouping-factor levels their group effects, as brms keeps them.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
BayesianFit or MultivariateFit

Parsed formula, compiled program, fitted posterior, and observations; a MultivariateFit for a joint formula.

RAISES DESCRIPTION
ValueError

If the family is unknown, a predictor and its data are not given together, a trainable predictor is used without SVI, or a count is given to a method it does not apply to (num_steps to NUTS or HMC; num_warmup, num_samples, or num_chains to SVI).

Source code in src/quivers/formulas/_fit.py
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
def fit(
    formula: str | ResponseModel | MultivariateFormula | None = None,
    *,
    data: IntoDataFrame,
    program: str | tuple[str | Path, str] | None = None,
    entry: str | None = None,
    static: Mapping[str, int] | None = None,
    parameters: Mapping[str, str | NonlinearExpression] | None = None,
    response: str | None = None,
    family: str | Family = "gaussian",
    weights: str | None = None,
    decision: str | None = None,
    data2: Mapping[str, AutocorMatrix] | None = None,
    distributional: Mapping[str, str | NonlinearExpression] | None = None,
    nonlinear: Mapping[str, str | NonlinearExpression] | None = None,
    fixed_parameters: Mapping[str, float] | None = None,
    method: FitMethod = "nuts",
    num_warmup: int | None = None,
    num_samples: int | None = None,
    num_chains: int | None = None,
    num_steps: int | None = None,
    learning_rate: float = 1e-2,
    fixed_prior: str = "Normal(0.0, 5.0)",
    random_scale_prior: str = "HalfNormal(1.0)",
    correlation_prior: str = "LKJCholesky(1.0)",
    group_covariances: Mapping[str, GroupCovariance] | None = None,
    priors: PriorInput | None = None,
    guide: type | None = None,
    initial_values: Mapping[str, torch.Tensor | float] | None = None,
    reparameterize: Literal["centered", "noncentered"] = "noncentered",
    binomial_trials: int | str | None = None,
    thresholds_by: str | None = None,
    mixture_components: int = 2,
    predictor: nn.Module | None = None,
    predictor_data: torch.Tensor | None = None,
    seed: int = 0,
    sample_prior: PriorMode = "no",
    num_prior_samples: int = 100,
    prior_seed: int | None = None,
    snapshot_policy: SnapshotPolicy = "clone",
    default_priors: DefaultPriorPolicy = "quivers",
    center: bool | None = None,
    decomp: Literal["none", "QR"] = "none",
    cmc: bool = True,
    sparse: bool = False,
    unused: Sequence[str] = (),
    control: SamplerControl | Mapping[str, float | int | str] | None = None,
    thin: int = 1,
    init: InitSpec | None = None,
    init_r: float = 2.0,
    algorithm: Algorithm | None = None,
    file: str | Path | None = None,
    file_refit: FileRefit = "never",
    pathfinder: PathfinderOptions | Mapping[str, float | int | bool] | None = None,
    cores: int = 1,
    knots: Knots | None = None,
    drop_unused_levels: bool = True,
) -> BayesianFit | _joint_fit.MultivariateFit:
    """Compile a brms-style formula, fit it, and return the result.

    See [`quivers.formulas`][quivers.formulas] for surface details.  This entry
    point composes `formula_from_data`, `FormulaToQVRModule`,
    `Compiler`, and the inference layer in one call.

    ``family="categorical"`` uses the sorted distinct integer labels or the
    declared factor levels and takes the first category as the default
    reference. An attached categorical predictor may return
    ``(N, K-1)`` reference logits or ``(N, K)`` full logits. For
    ``family="mixture"``, ``mixture_components`` selects any finite component
    count of at least two; the likelihood integrates assignments exactly.

    Parameters
    ----------
    formula : str or ResponseModel or MultivariateFormula or None
        brms/lme4-style response formula, or a joint formula built with
        `bf` (``bf("mvbind(y1, y2) ~ x")`` or ``bf(...) + bf(...)``), which
        returns a `MultivariateFit`. Response-level keywords then belong
        to each `bf` call. A single-response ``bf("y ~ x", "sigma ~ z")``
        is fitted as the string formula with the response keywords it
        carries; a keyword given both there and here with different values
        raises. None for a program, given by ``program=``.
    data : IntoDataFrame
        Pandas, Polars, or another Narwhals-compatible dataframe.
    program : str or tuple[str or Path, str] or None
        QVR source, or a source file path and a program name. With source
        text alone, the one program or the one exported program is selected.
        The program's observation of ``response`` is the likelihood, and its
        domain is the rows of the data. Every sample site and input that ``parameters``
        names is replaced by a regression on the link scale its support
        requires; every other site keeps the program's own law. Data the
        program reads at each row are data columns of the same name; data on
        another axis and scalars come from ``data2``.
    entry : str or None
        The program name when it is given separately from the source text.
    static : Mapping[str, int] or None
        Finite extents of the program, by binder name.
    parameters : Mapping[str, str or NonlinearExpression] or None
        Formulas of the program's parameters, as ``{"noise": "~ 1 + (1 | g)"}``.
        A `NonlinearExpression` gives a link-scale expression and can read
        additional parameter formulas in the mapping. Priors of the program's
        parameter formulas use ``dpar=<parameter>``.
    response : str or None
        The site the program observes, a data column.
    family : str or Family
        Registered response family or a family value. ``Family.with_links``
        selects location or auxiliary inverse links.
    weights : str or None
        Numeric column of finite nonnegative likelihood weights. Values
        multiply each response's log density, retain their original scale,
        and do not weight priors or posterior predictions.
    decision : str or None
        Wiener boundary-choice column: numeric zero/lower or one/upper, or
        the labels lower and upper. Equivalent to response-side dec(column).
    nonlinear : Mapping[str, str or NonlinearExpression] or None
        Named additive parameter designs or deterministic QVR expressions.
        Supplying this mapping interprets the response RHS as a value
        expression. Defaults retain the same proper coefficient priors as
        ordinary QVR formulas; get_prior reports their exact site names.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Named matrices referenced by autocorrelation terms, as in brms:
        the spatial weights of ``sar(M)`` and the fixed covariance of
        ``fcor(M)``, each over the included response rows. A group-level
        ``gr(g, cov = M)`` reads a labeled ``DataFrame`` covariance between
        the levels of ``g``, and ``s(g, bs = "mrf", xt = list(penalty = M))``
        a penalty or neighbourhood matrix over them.
    distributional : Mapping[str, str or NonlinearExpression] or None
        Auxiliary-parameter formulas, for instance
        ``{"sigma": "~ z + (1 | g)"}``. The optional left-hand side must
        match the parameter name. Coefficient prior overrides use names
        such as ``dpar_sigma_intercept`` and ``dpar_sigma_beta_z``.
    fixed_parameters : Mapping[str, float] or None
        Auxiliary parameters held constant on their natural scale, for instance
        ``{"quantile": 0.9}``. A fixed parameter has no latent site or prior.
    method : {"nuts", "hmc", "svi", "fixed_param", "pathfinder"}
        Inference algorithm.
    num_warmup : int or None
        MCMC warmup iterations per chain (NUTS and HMC only); 500 when
        omitted.
    num_samples : int or None
        MCMC draws kept per chain after warmup (NUTS and HMC only); 1000
        when omitted.
    num_chains : int or None
        MCMC chains (NUTS and HMC only), or Pathfinder paths as brms's
        ``chains``; 4 when omitted.
    num_steps : int or None
        SVI optimization steps (SVI only); 1000 when omitted.
    learning_rate : float
        The Adam learning rate of the SVI optimizer (SVI only).
    fixed_prior : str
        Prior of every fixed-effect coefficient.
    random_scale_prior : str
        Prior of every random-effect standard deviation.
    correlation_prior : str
        Default prior for correlated group blocks, in LKJ Cholesky form.
        Explicit shared IDs join coefficients across distributional formulas.
    group_covariances : Mapping[str, GroupCovariance] or None
        Known covariance between labeled levels, keyed by grouping factor.
        The same declaration serves compilation, inspection, and prediction.
    priors : PriorInput or None
        Named overrides or typed selectors, including sampled shrinkage
        hierarchies. Unknown, unused, or ambiguous rules raise ValueError.
    guide : type or None
        The SVI guide class; `AutoNormalGuide` when omitted.
    initial_values : Mapping[str, torch.Tensor or float] or None
        Natural-scale starting values keyed by latent site, including
        coefficient names. Scalars broadcast to a site's declared shape.
        Values must lie strictly inside the prior support. MCMC applies
        these after its seeded initial strategy; SVI passes them to the
        guide constructor. A custom guide must accept this keyword when
        values are supplied. For a regressed shifted-lognormal or Wiener ``ndt``
        with the log link and an intercept, default coefficient centers put the shift below
        the minimum observed response; explicit values override those centers.
        An unregressed learned Wiener delay starts at one quarter of the
        minimum reaction time, before explicit overrides.
    reparameterize : {"centered", "noncentered"}
        Parameterization of the random effects.
    binomial_trials : int or str
        Trials per row for binomial or beta-binomial responses: a constant or a column.
    thresholds_by : str or None
        Column grouping the cutpoints of an ordinal family.
    mixture_components : int
        Number of Gaussian components for the mixture family.
    predictor : nn.Module or None
        Optional differentiable contribution on the linear-predictor scale.
    predictor_data : torch.Tensor or None
        Input passed to ``predictor`` on each SVI step.
    seed : int
        Seed for compilation and inference. The caller's CPU random state
        is restored on return or failure.
    sample_prior : {"no", "yes", "only"}
        Fit the posterior, additionally retain independent prior draws, or
        disable observation likelihoods during inference. Priors, their data
        dependencies, support constraints, and explicit potentials remain.
    num_prior_samples : int
        Positive independent draw budget for mode "yes".
    prior_seed : int or None
        Isolated prior stream. None uses seed + 1 modulo 2**64. Retaining
        prior draws does not change fitted posterior draws or losses.

    snapshot_policy : {"clone", "reference"}
        Retain one independent original-data snapshot for update/refit by default.
        Reference mode shares caller data explicitly. Predictor initial states are
        copied before each refit, so fits do not share trained mutable parameters.
    default_priors : {"quivers", "brms"}
        Default prior policy: the proper, autoscaled quivers defaults, or
        ``brms::default_prior`` (flat ``b``; Student-t intercept, ``sd`` and
        ``sigma`` priors scaled by the response). Explicit priors win either way.
    center : bool or None
        brms ``bf(center = )``: sample the intercept of the column-centered
        design and report ``b_Intercept = Intercept_c - mean(X) b``. None
        centers under the brms policy only.
    decomp : {"none", "QR"}
        brms ``bf(decomp = "QR")``: sample the location coefficients in scaled
        QR coordinates; class ``b`` priors act on those coordinates.
    cmc : bool
        brms ``cmc``: with False, a formula without intercept keeps treatment
        coding (no cell-mean coding of its first factor).
    sparse : bool
        brms ``sparse``: the same model with centering disabled, as brms
        disables it for sparse designs; incompatible with ``decomp="QR"``.
    unused : Sequence[str]
        brms ``unused``: further columns kept with the model rows, so rows
        missing them are excluded as for model variables.
    control : SamplerControl or Mapping or None
        brms ``control``: ``adapt_delta`` (NUTS target acceptance),
        ``max_treedepth``, initial ``stepsize``, and ``metric`` (``diag_e``,
        ``dense_e``, ``unit_e``). MCMC only.
    thin : int
        Keep every ``thin``-th post-warmup transition; ``num_samples`` stays
        the retained draw count per chain. MCMC only.
    init : str or float or Mapping or Sequence or Callable or None
        brms ``init``: ``"random"`` draws unconstrained starts uniformly from
        ``(-init_r, init_r)``, ``0`` or ``"0"`` starts at zero, a mapping
        gives named natural-scale starts, a list gives one mapping per chain,
        and a function of the one-based chain index returns one. None keeps
        the driver's seeded jitter. Formula starts and ``initial_values``
        apply under every choice.
    init_r : float
        Half-width of ``init = "random"``.
    algorithm : {"sampling", "meanfield", "fullrank", "laplace", "fixed_param", "pathfinder"} or None
        brms ``algorithm``: NUTS, SVI with a mean-field, full-rank, or Laplace
        guide, the fixed-parameter sampler, which keeps every draw at the
        initial values, or multi-path Pathfinder with ``num_chains`` paths.
    file : str or Path or None
        brms ``file``: load the fit saved there, or fit and save it there.
    file_refit : {"never", "always", "on_change"}
        brms ``file_refit``: reuse a saved fit, always refit, or refit when the
        formula, data, priors, or settings differ from the saved recipe.
    pathfinder : PathfinderOptions or Mapping or None
        cmdstanr ``pathfinder`` arguments for ``algorithm="pathfinder"``
        (``draws``, ``single_path_draws``, ``history_size``,
        ``max_lbfgs_iters``, ``num_elbo_draws``, ``psis_resample``,
        ``calculate_lp``, ``save_single_paths``, ``init_alpha`` and the
        ``tol_*`` tolerances), which brms passes through its ``...``.
    cores : int
        brms ``cores``: run the MCMC chains in up to this many worker
        processes. Each worker rebuilds the fit from the retained arguments
        and data and runs its share of the chains; the draws equal those of
        the serial run with the same seed. Every argument must be picklable.
    knots : Mapping[str, Sequence[float]] or None
        brms ``knots``: knot values keyed by smooth covariate, passed to the
        ``cr``, ``cs``, ``cc``, ``ps`` and ``bs`` constructors of ``s()`` as
        mgcv's ``smoothCon(knots = )`` does.
    drop_unused_levels : bool
        brms ``drop_unused_levels``: with False, factor levels that no row
        uses keep their population columns (of zeros) and grouping-factor
        levels their group effects, as brms keeps them.

    Returns
    -------
    BayesianFit or MultivariateFit
        Parsed formula, compiled program, fitted posterior, and observations;
        a `MultivariateFit` for a joint formula.

    Raises
    ------
    ValueError
        If the family is unknown, a predictor and its data are not given
        together, a trainable predictor is used without SVI, or a count
        is given to a method it does not apply to (``num_steps`` to NUTS
        or HMC; ``num_warmup``, ``num_samples``, or ``num_chains`` to
        SVI).
    """
    from quivers.formulas._refit import capture_recipe

    # A single-response bf carries the response keywords of this call.
    if isinstance(formula, ResponseModel):
        authored = single_response(
            formula,
            family=family,
            distributional=distributional,
            nonlinear=nonlinear,
            fixed_parameters=fixed_parameters,
            weights=weights,
            decision=decision,
            binomial_trials=binomial_trials,
            thresholds_by=thresholds_by,
            mixture_components=mixture_components,
            center=center,
            decomp=decomp,
            cmc=cmc,
            sparse=sparse,
            unused=unused,
            caller="fit",
        )
        formula, family = authored["formula"], authored["family"]
        distributional = authored["distributional"]
        nonlinear = authored["nonlinear"]
        fixed_parameters = authored["fixed_parameters"]
        weights, decision = authored["weights"], authored["decision"]
        binomial_trials = authored["binomial_trials"]
        thresholds_by = authored["thresholds_by"]
        mixture_components = authored["mixture_components"]
        center, decomp = authored["center"], authored["decomp"]
        cmc, sparse = authored["cmc"], authored["sparse"]
        unused = authored["unused"]
    # An existing artifact with file_refit="never" needs no program file.
    if file is not None and file_refit == "never" and Path(file).exists():
        return cast(
            "BayesianFit | _joint_fit.MultivariateFit", artifact_store.load_fit(file)
        )
    if program is not None:
        program, entry = program_source(program, entry)
    # brms file / file_refit: reuse or refresh a fit in the artifact store.
    if file is not None:
        arguments = {
            name: value
            for name, value in locals().items()
            if name in _FIT_ARGUMENTS and name not in {"file", "file_refit"}
        }
        if not needs_refit(Path(file), file_refit, arguments):
            return cast(
                "BayesianFit | _joint_fit.MultivariateFit",
                artifact_store.load_fit(file),
            )
        result = fit(**arguments)
        artifact_store.save_fit(result, file)
        return result
    # brms algorithm selects the method and guide.
    method, guide = resolve_algorithm(algorithm, method, guide)
    controls = InferenceControls(
        control=sampler_control(control),
        thin=thin,
        init=init,
        init_r=init_r,
        pathfinder=pathfinder_options(pathfinder),
    )
    refit_recipe = capture_recipe(
        fit, data=data, arguments=locals(), snapshot_policy=snapshot_policy
    )
    # brms cores: workers rebuild the fit from the recipe.
    if checked_cores(cores) != 1:
        controls = controls.with_(
            cores=cores,
            chain_worker=FormulaChainWorker(
                arguments=dict(refit_recipe.method), data=refit_recipe._data
            ),
        )
    from quivers.modeling.refit import _snapshot

    preparation_data = (
        refit_recipe._data if snapshot_policy == "clone" else _snapshot(data)
    )
    with torch.random.fork_rng(devices=[]):
        torch.random.set_rng_state(torch.Generator().manual_seed(seed).get_state())
        # Joint (multivariate) formulas share the recipe and inference seam.
        if isinstance(formula, MultivariateFormula):
            return _joint_fit.fit_entry(
                formula, preparation_data, refit_recipe.method, refit_recipe
            )
        formula, family, distributional = program_arguments(
            formula,
            program=program,
            entry=entry,
            static=static,
            parameters=parameters,
            response=response,
            family=family,
            distributional=distributional,
            nonlinear=nonlinear,
            fixed_parameters=fixed_parameters,
            caller="fit",
        )
        _refuse_joint_syntax(formula, "fit")
        if method == "svi":
            given = [
                name
                for name, value in (
                    ("num_warmup", num_warmup),
                    ("num_samples", num_samples),
                    ("num_chains", num_chains),
                )
                if value is not None
            ]
            if given:
                raise ValueError(
                    f"fit: {', '.join(given)} count MCMC iterations, and "
                    "method='svi' runs none; give the optimization steps as "
                    "num_steps"
                )
        elif method != "pathfinder" and num_steps is not None:
            raise ValueError(
                f"fit: num_steps counts SVI optimization steps, and method={method!r} "
                "runs MCMC; give num_warmup, num_samples, and num_chains"
            )
        predictor_name = "neural_eta" if predictor is not None else None
        prepared = _prepare_formula(
            formula,
            data=preparation_data,
            family=family,
            weights=weights,
            decision=decision,
            data2=data2,
            distributional=distributional,
            nonlinear=nonlinear,
            fixed_parameters=fixed_parameters,
            fixed_prior=fixed_prior,
            random_scale_prior=random_scale_prior,
            correlation_prior=correlation_prior,
            group_covariances=group_covariances,
            priors=priors,
            reparameterize=reparameterize,
            binomial_trials=binomial_trials,
            thresholds_by=thresholds_by,
            mixture_components=mixture_components,
            predictor_name=predictor_name,
            caller="fit",
            allow_missing=True,
            default_priors=default_priors,
            center=center,
            decomp=decomp,
            cmc=cmc,
            sparse=sparse,
            unused=unused,
            knots=knots,
            drop_unused_levels=drop_unused_levels,
        )
        native = _prepare_fit(
            prepared,
            predictor=predictor,
            predictor_data=predictor_data,
            method=method,
            preparation_data=preparation_data,
        )
        # brms refuses prior sampling with improper flat priors.
        if sample_prior != "no":
            require_proper(native.module, f"sample_prior={sample_prior!r}")
        result = _run_inference(
            native.program,
            native.observations,
            method=method,
            num_steps=num_steps,
            num_warmup=num_warmup,
            num_samples=num_samples,
            num_chains=num_chains,
            learning_rate=learning_rate,
            seed=seed,
            guide=guide,
            sample_prior=sample_prior,
            num_prior_samples=num_prior_samples,
            prior_seed=prior_seed,
            predictor=native.predictor,
            predictor_data=native.predictor_data,
            predictor_name=native.predictor_name,
            predictor_categories=native.predictor_categories,
            predictor_reference=native.predictor_reference,
            initial_values=_initial_values(prepared, fixed_parameters, initial_values),
            controls=controls,
        )
        return _assemble_fit(
            native,
            result,
            refit_recipe=refit_recipe,
            reparameterize=reparameterize,
            thresholds_by=thresholds_by,
            mixture_components=mixture_components,
            fixed_prior=fixed_prior,
            random_scale_prior=random_scale_prior,
            correlation_prior=correlation_prior,
            group_covariances=group_covariances,
            priors=priors,
            fixed_parameters=fixed_parameters,
            default_priors=default_priors,
            center=center,
            decomp=decomp,
            cmc=cmc,
            sparse=sparse,
            unused=unused,
        )

formula_to_qvr

formula_to_qvr(formula: str | ResponseModel | MultivariateFormula | None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str] | None = None, entry: str | None = None, static: Mapping[str, int] | None = None, parameters: Mapping[str, str | NonlinearExpression] | None = None, response: str | None = None, family: str | Family = 'gaussian', weights: str | None = None, decision: str | None = None, data2: Mapping[str, AutocorMatrix] | None = None, distributional: Mapping[str, str | NonlinearExpression] | None = None, nonlinear: Mapping[str, str | NonlinearExpression] | None = None, fixed_parameters: Mapping[str, float] | None = None, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, priors: PriorInput | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor_name: str | None = None, default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: Sequence[str] = (), path: str | Path | None = None, knots: Knots | None = None, drop_unused_levels: bool = True) -> str

Emit .qvr source for a brms-style formula without fitting.

Builds the formula AST β†’ QVR Module via FormulaToQVRModule, then serialises the module via quivers.dsl.emit.module_to_source. Optionally writes the result to path. mixture_components selects any integer component count of at least two for family="mixture". distributional maps auxiliary names to formulas, for instance {"sigma": "~ z"}; the corresponding linked predictors are emitted in the same QVR program as the location formula. fixed_parameters instead binds auxiliary parameters to constants on their natural scale. weights="column" retains nonnegative likelihood weights and emits them only on the response observation; priors and predictions are unweighted. decision="column" or rt | dec(column) ~ predictors retains a Wiener boundary choice alongside positive reaction times. Emitted source visibly adapts raw times and Boolean choices to a lossless signed response.

PARAMETER DESCRIPTION
formula

Authored formula over original dataframe rows, a single-response bf carrying its response keywords, or a joint formula whose one composed program is emitted; None for a program.

TYPE: str or ResponseModel or MultivariateFormula or None DEFAULT: None

data

Original training columns, including response modifiers.

TYPE: IntoDataFrame

program

QVR source, or a source file path and a program name, as in fit.

TYPE: str or tuple[str or Path, str] or None DEFAULT: None

entry

The program name when it is given separately from the source text.

TYPE: str or None DEFAULT: None

static

Finite extents of the program, by binder name.

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

parameters

Formulas of the program's parameters, by name.

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

response

The site the program observes.

TYPE: str or None DEFAULT: None

family

Checked response law and retained link, threshold, and event choices.

TYPE: str or Family DEFAULT: 'gaussian'

weights

Optional existing response-role columns.

TYPE: str or None DEFAULT: None

decision

Optional existing response-role columns.

TYPE: str or None DEFAULT: None

data2

Named matrices referenced by autocorrelation terms, as in brms: the spatial weights of sar(M) and the fixed covariance of fcor(M), each over the included response rows. A group-level gr(g, cov = M) reads a labeled DataFrame covariance between the levels of g.

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

distributional

Auxiliary designs and checked derived predictor graph.

TYPE: Mapping or None DEFAULT: None

nonlinear

Auxiliary designs and checked derived predictor graph.

TYPE: Mapping or None DEFAULT: None

fixed_parameters

Bound auxiliary constants.

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

fixed_prior

Defaults consumed by the existing typed prior catalog.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

random_scale_prior

Defaults consumed by the existing typed prior catalog.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

correlation_prior

Defaults consumed by the existing typed prior catalog.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

group_covariances

Known group covariance structures.

TYPE: Mapping or None DEFAULT: None

priors

Typed selectors or existing exact-name overrides.

TYPE: PriorInput or None DEFAULT: None

reparameterize

Shared group coordinate policy.

TYPE: ('centered', 'noncentered') DEFAULT: "centered"

binomial_trials

Finite-trial count or retained column.

TYPE: int or str or None DEFAULT: None

thresholds_by

Group with an identified full threshold profile.

TYPE: str or None DEFAULT: None

mixture_components

Finite-mixture component count.

TYPE: int DEFAULT: 2

predictor_name

Checked external neural binding.

TYPE: str or None DEFAULT: None

default_priors

Default prior policy: the proper, autoscaled quivers defaults, or brms::default_prior (flat b; Student-t intercept, sd and sigma priors scaled by the response). Explicit priors win either way.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

center

brms bf(center = ): sample the intercept of the column-centered design and report b_Intercept = Intercept_c - mean(X) b. None centers under the brms policy only.

TYPE: bool or None DEFAULT: None

decomp

brms bf(decomp = "QR"): sample the location coefficients in scaled QR coordinates; class b priors act on those coordinates.

TYPE: ('none', 'QR') DEFAULT: "none"

cmc

brms cmc: with False, a formula without intercept keeps treatment coding (no cell-mean coding of its first factor).

TYPE: bool DEFAULT: True

sparse

brms sparse: the same model with centering disabled, as brms disables it for sparse designs; incompatible with decomp="QR".

TYPE: bool DEFAULT: False

unused

brms unused: further columns kept with the model rows, so rows missing them are excluded as for model variables.

TYPE: Sequence[str] DEFAULT: ()

knots

brms knots: knot values keyed by smooth covariate, passed to the cr, cs, cc, ps and bs constructors of s() as mgcv's smoothCon(knots = ) does.

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

drop_unused_levels

brms drop_unused_levels: with False, factor levels that no row uses keep their population columns (of zeros) and grouping-factor levels their group effects, as brms keeps them.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
str

Canonical checked source, without fitting a posterior.

Source code in src/quivers/formulas/_fit.py
def formula_to_qvr(
    formula: str | ResponseModel | MultivariateFormula | None = None,
    *,
    data: IntoDataFrame,
    program: str | tuple[str | Path, str] | None = None,
    entry: str | None = None,
    static: Mapping[str, int] | None = None,
    parameters: Mapping[str, str | NonlinearExpression] | None = None,
    response: str | None = None,
    family: str | Family = "gaussian",
    weights: str | None = None,
    decision: str | None = None,
    data2: Mapping[str, AutocorMatrix] | None = None,
    distributional: Mapping[str, str | NonlinearExpression] | None = None,
    nonlinear: Mapping[str, str | NonlinearExpression] | None = None,
    fixed_parameters: Mapping[str, float] | None = None,
    fixed_prior: str = "Normal(0.0, 5.0)",
    random_scale_prior: str = "HalfNormal(1.0)",
    correlation_prior: str = "LKJCholesky(1.0)",
    group_covariances: Mapping[str, GroupCovariance] | None = None,
    priors: PriorInput | None = None,
    reparameterize: Literal["centered", "noncentered"] = "noncentered",
    binomial_trials: int | str | None = None,
    thresholds_by: str | None = None,
    mixture_components: int = 2,
    predictor_name: str | None = None,
    default_priors: DefaultPriorPolicy = "quivers",
    center: bool | None = None,
    decomp: Literal["none", "QR"] = "none",
    cmc: bool = True,
    sparse: bool = False,
    unused: Sequence[str] = (),
    path: str | Path | None = None,
    knots: Knots | None = None,
    drop_unused_levels: bool = True,
) -> str:
    """Emit ``.qvr`` source for a brms-style formula without fitting.

    Builds the formula AST β†’ QVR Module via `FormulaToQVRModule`,
    then serialises the module via [`quivers.dsl.emit.module_to_source`][quivers.dsl.emit.module_to_source].
    Optionally writes the result to ``path``. ``mixture_components`` selects
    any integer component count of at least two for ``family="mixture"``.
    ``distributional`` maps auxiliary names to formulas, for instance
    ``{"sigma": "~ z"}``; the corresponding linked predictors are emitted
    in the same QVR program as the location formula. ``fixed_parameters``
    instead binds auxiliary parameters to constants on their natural scale.
    ``weights="column"`` retains nonnegative likelihood weights and emits
    them only on the response observation; priors and predictions are unweighted.
    ``decision="column"`` or ``rt | dec(column) ~ predictors`` retains a Wiener
    boundary choice alongside positive reaction times. Emitted source visibly
    adapts raw times and Boolean choices to a lossless signed response.

    Parameters
    ----------
    formula : str or ResponseModel or MultivariateFormula or None
        Authored formula over original dataframe rows, a single-response
        `bf` carrying its response keywords, or a joint formula whose one
        composed program is emitted; None for a program.
    data : IntoDataFrame
        Original training columns, including response modifiers.
    program : str or tuple[str or Path, str] or None
        QVR source, or a source file path and a program name, as in `fit`.
    entry : str or None
        The program name when it is given separately from the source text.
    static : Mapping[str, int] or None
        Finite extents of the program, by binder name.
    parameters : Mapping[str, str or NonlinearExpression] or None
        Formulas of the program's parameters, by name.
    response : str or None
        The site the program observes.
    family : str or Family
        Checked response law and retained link, threshold, and event choices.
    weights, decision : str or None
        Optional existing response-role columns.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Named matrices referenced by autocorrelation terms, as in brms:
        the spatial weights of ``sar(M)`` and the fixed covariance of
        ``fcor(M)``, each over the included response rows. A group-level
        ``gr(g, cov = M)`` reads a labeled ``DataFrame`` covariance between
        the levels of ``g``.
    distributional, nonlinear : Mapping or None
        Auxiliary designs and checked derived predictor graph.
    fixed_parameters : Mapping[str, float] or None
        Bound auxiliary constants.
    fixed_prior, random_scale_prior, correlation_prior : str
        Defaults consumed by the existing typed prior catalog.
    group_covariances : Mapping or None
        Known group covariance structures.
    priors : PriorInput or None
        Typed selectors or existing exact-name overrides.
    reparameterize : {"centered", "noncentered"}
        Shared group coordinate policy.
    binomial_trials : int or str or None
        Finite-trial count or retained column.
    thresholds_by : str or None
        Group with an identified full threshold profile.
    mixture_components : int
        Finite-mixture component count.
    predictor_name : str or None
        Checked external neural binding.

    default_priors : {"quivers", "brms"}
        Default prior policy: the proper, autoscaled quivers defaults, or
        ``brms::default_prior`` (flat ``b``; Student-t intercept, ``sd`` and
        ``sigma`` priors scaled by the response). Explicit priors win either way.
    center : bool or None
        brms ``bf(center = )``: sample the intercept of the column-centered
        design and report ``b_Intercept = Intercept_c - mean(X) b``. None
        centers under the brms policy only.
    decomp : {"none", "QR"}
        brms ``bf(decomp = "QR")``: sample the location coefficients in scaled
        QR coordinates; class ``b`` priors act on those coordinates.
    cmc : bool
        brms ``cmc``: with False, a formula without intercept keeps treatment
        coding (no cell-mean coding of its first factor).
    sparse : bool
        brms ``sparse``: the same model with centering disabled, as brms
        disables it for sparse designs; incompatible with ``decomp="QR"``.
    unused : Sequence[str]
        brms ``unused``: further columns kept with the model rows, so rows
        missing them are excluded as for model variables.
    knots : Mapping[str, Sequence[float]] or None
        brms ``knots``: knot values keyed by smooth covariate, passed to the
        ``cr``, ``cs``, ``cc``, ``ps`` and ``bs`` constructors of ``s()`` as
        mgcv's ``smoothCon(knots = )`` does.
    drop_unused_levels : bool
        brms ``drop_unused_levels``: with False, factor levels that no row
        uses keep their population columns (of zeros) and grouping-factor
        levels their group effects, as brms keeps them.
    Returns
    -------
    str
        Canonical checked source, without fitting a posterior.
    """
    # Joint (multivariate) formulas emit one composed program.
    if isinstance(formula, MultivariateFormula):
        with formula_data_options(knots, drop_unused_levels):
            module, _ = _joint_fit.joint_module(
                formula.with_default_priors(default_priors),
                data,
                fixed_prior=fixed_prior,
                random_scale_prior=random_scale_prior,
                correlation_prior=correlation_prior,
                group_covariances=group_covariances,
                priors=priors,
                reparameterize=reparameterize,
                data2=data2,
            )
        source = module_to_source(module)
        if path is not None:
            Path(path).write_text(source)
        return source
    formula, family, distributional = program_arguments(
        formula,
        program=program,
        entry=entry,
        static=static,
        parameters=parameters,
        response=response,
        family=family,
        distributional=distributional,
        nonlinear=nonlinear,
        fixed_parameters=fixed_parameters,
        caller="formula_to_qvr",
    )
    _refuse_joint_syntax(formula, "formula_to_qvr")
    prepared = _prepare_formula_entry(
        formula,
        data=data,
        family=family,
        weights=weights,
        decision=decision,
        data2=data2,
        distributional=distributional,
        nonlinear=nonlinear,
        fixed_parameters=fixed_parameters,
        fixed_prior=fixed_prior,
        random_scale_prior=random_scale_prior,
        correlation_prior=correlation_prior,
        group_covariances=group_covariances,
        priors=priors,
        reparameterize=reparameterize,
        binomial_trials=binomial_trials,
        thresholds_by=thresholds_by,
        mixture_components=mixture_components,
        predictor_name=predictor_name,
        default_priors=default_priors,
        center=center,
        decomp=decomp,
        cmc=cmc,
        sparse=sparse,
        unused=unused,
        knots=knots,
        drop_unused_levels=drop_unused_levels,
    )
    if prepared.missing is None:
        module, _ = prepared.lens.forward(prepared.formula)
    else:
        module = prepared.missing.emission.module
    source = module_to_source(module)
    if path is not None:
        Path(path).write_text(source)
    return source

get_prior

get_prior(formula: str | ResponseModel | MultivariateFormula | None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str] | None = None, entry: str | None = None, static: Mapping[str, int] | None = None, parameters: Mapping[str, str | NonlinearExpression] | None = None, response: str | None = None, family: str | Family = 'gaussian', weights: str | None = None, decision: str | None = None, data2: Mapping[str, AutocorMatrix] | None = None, distributional: Mapping[str, str | NonlinearExpression] | None = None, nonlinear: Mapping[str, str | NonlinearExpression] | None = None, fixed_parameters: Mapping[str, float] | None = None, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, priors: PriorInput | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor_name: str | None = None, default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: Sequence[str] = (), knots: Knots | None = None, drop_unused_levels: bool = True) -> dict[str, str]

Return effective named priors without running inference.

The arguments match formula_to_qvr, except for its output path. Priors reflect evaluated design columns, selected links, distributional formulas, group correlations, and explicit overrides. Default coefficient scales include column autoscaling; explicit overrides are emitted as given.

PARAMETER DESCRIPTION
formula

Response formula in brms/lme4 notation, a single-response bf carrying its response keywords, or a joint formula whose namespaced sites (response_<resp>__..., rescor) are listed; None for a program.

TYPE: str or ResponseModel or MultivariateFormula or None DEFAULT: None

data

Rows used to evaluate design matrices and autoscale default priors.

TYPE: IntoDataFrame

program

QVR source, or a source file path and a program name, as in fit.

TYPE: str or tuple[str or Path, str] or None DEFAULT: None

entry

The program name when it is given separately from the source text.

TYPE: str or None DEFAULT: None

static

Finite extents of the program, by binder name.

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

parameters

Formulas of the program's parameters, by name.

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

response

The site the program observes.

TYPE: str or None DEFAULT: None

family

Registered response family or a family value with selected links.

TYPE: str or Family DEFAULT: 'gaussian'

weights

Numeric column of finite nonnegative likelihood weights. Values multiply each response's log density, retain their original scale, and do not weight priors or posterior predictions.

TYPE: str or None DEFAULT: None

decision

Wiener boundary-choice column, equivalent to response-side dec(column). Numeric codes must be exactly zero/lower or one/upper.

TYPE: str or None DEFAULT: None

data2

Named matrices referenced by autocorrelation terms, as in brms: the spatial weights of sar(M) and the fixed covariance of fcor(M), each over the included response rows. A group-level gr(g, cov = M) reads a labeled DataFrame covariance between the levels of g.

TYPE: Mapping[str, ndarray or DataFrame] or None DEFAULT: None

distributional

Separate formulas for auxiliary parameters.

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

fixed_parameters

Auxiliary parameters held constant; these have no prior entries.

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

fixed_prior

Default coefficient, group-scale, and LKJ Cholesky priors.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

random_scale_prior

Default coefficient, group-scale, and LKJ Cholesky priors.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

correlation_prior

Default coefficient, group-scale, and LKJ Cholesky priors.

TYPE: str DEFAULT: 'Normal(0.0, 5.0)'

group_covariances

Known covariance between labeled levels, keyed by grouping factor. The same declaration serves compilation, inspection, and prediction.

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

priors

Named overrides or typed selectors, including sampled shrinkage hierarchies. Unknown, unused, or ambiguous rules raise ValueError.

TYPE: PriorInput or None DEFAULT: None

reparameterize

Group parameterization; its conditional draws are not overrideable.

TYPE: ('centered', 'noncentered') DEFAULT: "centered"

binomial_trials

Fixed trial count or a column of counts.

TYPE: int or str DEFAULT: None

thresholds_by

Grouping column for ordinal cutpoints.

TYPE: str or None DEFAULT: None

mixture_components

Number of Gaussian mixture components.

TYPE: int DEFAULT: 2

predictor_name

External contribution on the linear-predictor scale.

TYPE: str or None DEFAULT: None

default_priors

Default prior policy: the proper, autoscaled quivers defaults, or brms::default_prior (flat b; Student-t intercept, sd and sigma priors scaled by the response). Explicit priors win either way.

TYPE: ('quivers', 'brms') DEFAULT: "quivers"

center

brms bf(center = ): sample the intercept of the column-centered design and report b_Intercept = Intercept_c - mean(X) b. None centers under the brms policy only.

TYPE: bool or None DEFAULT: None

decomp

brms bf(decomp = "QR"): sample the location coefficients in scaled QR coordinates; class b priors act on those coordinates.

TYPE: ('none', 'QR') DEFAULT: "none"

cmc

brms cmc: with False, a formula without intercept keeps treatment coding (no cell-mean coding of its first factor).

TYPE: bool DEFAULT: True

sparse

brms sparse: the same model with centering disabled, as brms disables it for sparse designs; incompatible with decomp="QR".

TYPE: bool DEFAULT: False

unused

brms unused: further columns kept with the model rows, so rows missing them are excluded as for model variables.

TYPE: Sequence[str] DEFAULT: ()

knots

brms knots: knot values keyed by smooth covariate, passed to the cr, cs, cc, ps and bs constructors of s() as mgcv's smoothCon(knots = ) does.

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

drop_unused_levels

brms drop_unused_levels: with False, factor levels that no row uses keep their population columns (of zeros) and grouping-factor levels their group effects, as brms keeps them.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
dict[str, str]

Actual overrideable site names and canonical prior calls.

RAISES DESCRIPTION
ValueError

If a formula or family setting is invalid, or a prior is unused.

Source code in src/quivers/formulas/_fit.py
def get_prior(
    formula: str | ResponseModel | MultivariateFormula | None = None,
    *,
    data: IntoDataFrame,
    program: str | tuple[str | Path, str] | None = None,
    entry: str | None = None,
    static: Mapping[str, int] | None = None,
    parameters: Mapping[str, str | NonlinearExpression] | None = None,
    response: str | None = None,
    family: str | Family = "gaussian",
    weights: str | None = None,
    decision: str | None = None,
    data2: Mapping[str, AutocorMatrix] | None = None,
    distributional: Mapping[str, str | NonlinearExpression] | None = None,
    nonlinear: Mapping[str, str | NonlinearExpression] | None = None,
    fixed_parameters: Mapping[str, float] | None = None,
    fixed_prior: str = "Normal(0.0, 5.0)",
    random_scale_prior: str = "HalfNormal(1.0)",
    correlation_prior: str = "LKJCholesky(1.0)",
    group_covariances: Mapping[str, GroupCovariance] | None = None,
    priors: PriorInput | None = None,
    reparameterize: Literal["centered", "noncentered"] = "noncentered",
    binomial_trials: int | str | None = None,
    thresholds_by: str | None = None,
    mixture_components: int = 2,
    predictor_name: str | None = None,
    default_priors: DefaultPriorPolicy = "quivers",
    center: bool | None = None,
    decomp: Literal["none", "QR"] = "none",
    cmc: bool = True,
    sparse: bool = False,
    unused: Sequence[str] = (),
    knots: Knots | None = None,
    drop_unused_levels: bool = True,
) -> dict[str, str]:
    """Return effective named priors without running inference.

    The arguments match `formula_to_qvr`, except for its output path.
    Priors reflect evaluated design columns, selected links, distributional
    formulas, group correlations, and explicit overrides. Default coefficient
    scales include column autoscaling; explicit overrides are emitted as given.

    Parameters
    ----------
    formula : str or ResponseModel or MultivariateFormula or None
        Response formula in brms/lme4 notation, a single-response `bf`
        carrying its response keywords, or a joint formula whose
        namespaced sites (``response_<resp>__...``, ``rescor``) are listed;
        None for a program.
    data : IntoDataFrame
        Rows used to evaluate design matrices and autoscale default priors.
    program : str or tuple[str or Path, str] or None
        QVR source, or a source file path and a program name, as in `fit`.
    entry : str or None
        The program name when it is given separately from the source text.
    static : Mapping[str, int] or None
        Finite extents of the program, by binder name.
    parameters : Mapping[str, str or NonlinearExpression] or None
        Formulas of the program's parameters, by name.
    response : str or None
        The site the program observes.
    family : str or Family
        Registered response family or a family value with selected links.
    weights : str or None
        Numeric column of finite nonnegative likelihood weights. Values
        multiply each response's log density, retain their original scale,
        and do not weight priors or posterior predictions.
    decision : str or None
        Wiener boundary-choice column, equivalent to response-side dec(column).
        Numeric codes must be exactly zero/lower or one/upper.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Named matrices referenced by autocorrelation terms, as in brms:
        the spatial weights of ``sar(M)`` and the fixed covariance of
        ``fcor(M)``, each over the included response rows. A group-level
        ``gr(g, cov = M)`` reads a labeled ``DataFrame`` covariance between
        the levels of ``g``.
    distributional : Mapping[str, str] or None
        Separate formulas for auxiliary parameters.
    fixed_parameters : Mapping[str, float] or None
        Auxiliary parameters held constant; these have no prior entries.
    fixed_prior, random_scale_prior, correlation_prior : str
        Default coefficient, group-scale, and LKJ Cholesky priors.
    group_covariances : Mapping[str, GroupCovariance] or None
        Known covariance between labeled levels, keyed by grouping factor.
        The same declaration serves compilation, inspection, and prediction.
    priors : PriorInput or None
        Named overrides or typed selectors, including sampled shrinkage
        hierarchies. Unknown, unused, or ambiguous rules raise ValueError.
    reparameterize : {"centered", "noncentered"}
        Group parameterization; its conditional draws are not overrideable.
    binomial_trials : int or str
        Fixed trial count or a column of counts.
    thresholds_by : str or None
        Grouping column for ordinal cutpoints.
    mixture_components : int
        Number of Gaussian mixture components.
    predictor_name : str or None
        External contribution on the linear-predictor scale.

    default_priors : {"quivers", "brms"}
        Default prior policy: the proper, autoscaled quivers defaults, or
        ``brms::default_prior`` (flat ``b``; Student-t intercept, ``sd`` and
        ``sigma`` priors scaled by the response). Explicit priors win either way.
    center : bool or None
        brms ``bf(center = )``: sample the intercept of the column-centered
        design and report ``b_Intercept = Intercept_c - mean(X) b``. None
        centers under the brms policy only.
    decomp : {"none", "QR"}
        brms ``bf(decomp = "QR")``: sample the location coefficients in scaled
        QR coordinates; class ``b`` priors act on those coordinates.
    cmc : bool
        brms ``cmc``: with False, a formula without intercept keeps treatment
        coding (no cell-mean coding of its first factor).
    sparse : bool
        brms ``sparse``: the same model with centering disabled, as brms
        disables it for sparse designs; incompatible with ``decomp="QR"``.
    unused : Sequence[str]
        brms ``unused``: further columns kept with the model rows, so rows
        missing them are excluded as for model variables.
    knots : Mapping[str, Sequence[float]] or None
        brms ``knots``: knot values keyed by smooth covariate, passed to the
        ``cr``, ``cs``, ``cc``, ``ps`` and ``bs`` constructors of ``s()`` as
        mgcv's ``smoothCon(knots = )`` does.
    drop_unused_levels : bool
        brms ``drop_unused_levels``: with False, factor levels that no row
        uses keep their population columns (of zeros) and grouping-factor
        levels their group effects, as brms keeps them.
    Returns
    -------
    dict[str, str]
        Actual overrideable site names and canonical prior calls.

    Raises
    ------
    ValueError
        If a formula or family setting is invalid, or a prior is unused.
    """
    # Joint (multivariate) formulas read priors from the composed program.
    if isinstance(formula, MultivariateFormula):
        with formula_data_options(knots, drop_unused_levels):
            module, targets = _joint_fit.joint_module(
                formula.with_default_priors(default_priors),
                data,
                fixed_prior=fixed_prior,
                random_scale_prior=random_scale_prior,
                correlation_prior=correlation_prior,
                group_covariances=group_covariances,
                priors=priors,
                reparameterize=reparameterize,
                data2=data2,
                caller="get_prior",
            )
        return _joint_fit.joint_prior(module, targets)
    formula, family, distributional = program_arguments(
        formula,
        program=program,
        entry=entry,
        static=static,
        parameters=parameters,
        response=response,
        family=family,
        distributional=distributional,
        nonlinear=nonlinear,
        fixed_parameters=fixed_parameters,
        caller="get_prior",
    )
    _refuse_joint_syntax(formula, "get_prior")
    prepared = _prepare_formula_entry(
        formula,
        data=data,
        family=family,
        weights=weights,
        decision=decision,
        data2=data2,
        distributional=distributional,
        nonlinear=nonlinear,
        fixed_parameters=fixed_parameters,
        fixed_prior=fixed_prior,
        random_scale_prior=random_scale_prior,
        correlation_prior=correlation_prior,
        group_covariances=group_covariances,
        priors=priors,
        reparameterize=reparameterize,
        binomial_trials=binomial_trials,
        thresholds_by=thresholds_by,
        mixture_components=mixture_components,
        predictor_name=predictor_name,
        default_priors=default_priors,
        center=center,
        decomp=decomp,
        cmc=cmc,
        sparse=sparse,
        unused=unused,
        knots=knots,
        drop_unused_levels=drop_unused_levels,
    )
    if prepared.missing is not None:
        emission = prepared.missing.emission
        return prepared.lens._prior_calls(
            prepared.formula, emission.module, targets=emission.prior_targets
        )
    return prepared.lens.get_prior(prepared.formula)

conditional_smooths

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

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

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

PARAMETER DESCRIPTION
fitted

Fitted formula model.

TYPE: BayesianFit

term

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

TYPE: str

new_data

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

TYPE: IntoDataFrame

parameter

mu or a distributional or nonlinear parameter carrying the term.

TYPE: str DEFAULT: 'mu'

num_samples

Draw count under the convention of draws.

TYPE: int or None DEFAULT: None

seed

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

TYPE: int DEFAULT: 0

draws

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

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

site_prefix

Namespace of that response's sites within draws.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
Tensor

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

RAISES DESCRIPTION
ValueError

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

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

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

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

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

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

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

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

bf

bf(formula: str | None = None, *formulas: str, 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 | None = None, nl: bool = False, fixed_parameters: Mapping[str, float] | None = None, weights: str | None = None, decision: str | None = None, binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: tuple[str, ...] = ()) -> ResponseModel | MultivariateFormula

Build a response formula with brms bf() syntax.

PARAMETER DESCRIPTION
formula

Response formula. A left-hand side mvbind(y1, y2, ...) repeats the right-hand side and every other argument for each named response. None for a program, given by program=.

TYPE: str or None DEFAULT: None

*formulas

Formulas for distributional parameters ("sigma ~ x") or, with nl=True, for nonlinear parameters ("a ~ 1 + (1 | g)"). A left-hand side naming an auxiliary parameter of the family is distributional; any other name is nonlinear. Several parameters joined by + share one right-hand side ("b1 + b2 ~ 1").

TYPE: str DEFAULT: ()

program

QVR source, or a source file path and a program name, as in fit.

TYPE: str or tuple[str or Path, str] or None DEFAULT: None

entry

The program name when it is given separately from the source text.

TYPE: str or None DEFAULT: None

static

Finite extents of the program, by binder name.

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

parameters

Formulas of the program's parameters, by name.

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

response

The site the program observes.

TYPE: str or None DEFAULT: None

family

Response family of every response built by this call. None leaves the family to the entry point (fit(bf(...), family=...)), which then classifies the parameter formulas, and is Gaussian when the entry point states none.

TYPE: str or Family or None DEFAULT: None

nl

Read the main formula's right-hand side as a nonlinear expression: an R expression over Stan's functions, data columns, and the nonlinear parameters.

TYPE: bool DEFAULT: False

fixed_parameters

Auxiliary parameters fixed on their natural scale.

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

weights

Ordinary response-role shortcuts.

TYPE: str or int or None DEFAULT: None

decision

Ordinary response-role shortcuts.

TYPE: str or int or None DEFAULT: None

binomial_trials

Ordinary response-role shortcuts.

TYPE: str or int or None DEFAULT: None

thresholds_by

Ordinary response-role shortcuts.

TYPE: str or int or None DEFAULT: None

mixture_components

Component count of a finite mixture response.

TYPE: int DEFAULT: 2

center

brms center: sample the location intercept on the centered design; None centers under the brms default prior policy only.

TYPE: bool or None DEFAULT: None

decomp

brms decomp: sample the location coefficients in QR coordinates.

TYPE: ('none', 'QR') DEFAULT: "none"

cmc

brms cmc: False keeps treatment coding without an intercept.

TYPE: bool DEFAULT: True

sparse

brms sparse: the same model without centering.

TYPE: bool DEFAULT: False

unused

brms unused: further columns kept with the model rows.

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

RETURNS DESCRIPTION
ResponseModel or MultivariateFormula

One response; a joint formula for an mvbind left-hand side, whose residual-correlation setting follows the brms default; or a one-response joint formula when mi(), me(), or index() terms appear, since those compile through the joint program.

RAISES DESCRIPTION
ValueError

If a parameter formula lacks a left-hand side, names a nonlinear parameter without nl=True, or mvbind names fewer than two responses.

Source code in src/quivers/formulas/_multivariate.py
def bf(
    formula: str | None = None,
    *formulas: str,
    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 | None = None,
    nl: bool = False,
    fixed_parameters: Mapping[str, float] | None = None,
    weights: str | None = None,
    decision: str | None = None,
    binomial_trials: int | str | None = None,
    thresholds_by: str | None = None,
    mixture_components: int = 2,
    center: bool | None = None,
    decomp: Literal["none", "QR"] = "none",
    cmc: bool = True,
    sparse: bool = False,
    unused: tuple[str, ...] = (),
) -> ResponseModel | MultivariateFormula:
    """Build a response formula with brms ``bf()`` syntax.

    Parameters
    ----------
    formula : str or None
        Response formula. A left-hand side ``mvbind(y1, y2, ...)`` repeats
        the right-hand side and every other argument for each named response.
        None for a program, given by ``program=``.
    *formulas : str
        Formulas for distributional parameters (``"sigma ~ x"``) or, with
        ``nl=True``, for nonlinear parameters (``"a ~ 1 + (1 | g)"``).
        A left-hand side naming an auxiliary parameter of the family is
        distributional; any other name is nonlinear. Several parameters
        joined by ``+`` share one right-hand side (``"b1 + b2 ~ 1"``).
    program : str or tuple[str or Path, str] or None
        QVR source, or a source file path and a program name, as in `fit`.
    entry : str or None
        The program name when it is given separately from the source text.
    static : Mapping[str, int] or None
        Finite extents of the program, by binder name.
    parameters : Mapping[str, str or NonlinearExpression] or None
        Formulas of the program's parameters, by name.
    response : str or None
        The site the program observes.
    family : str or Family or None
        Response family of every response built by this call. None leaves
        the family to the entry point (``fit(bf(...), family=...)``), which
        then classifies the parameter formulas, and is Gaussian when the
        entry point states none.
    nl : bool
        Read the main formula's right-hand side as a nonlinear expression:
        an R expression over Stan's functions, data columns, and the
        nonlinear parameters.
    fixed_parameters : Mapping[str, float] or None
        Auxiliary parameters fixed on their natural scale.
    weights, decision, binomial_trials, thresholds_by : str or int or None
        Ordinary response-role shortcuts.
    mixture_components : int
        Component count of a finite mixture response.
    center : bool or None
        brms ``center``: sample the location intercept on the centered
        design; None centers under the brms default prior policy only.
    decomp : {"none", "QR"}
        brms ``decomp``: sample the location coefficients in QR coordinates.
    cmc : bool
        brms ``cmc``: False keeps treatment coding without an intercept.
    sparse : bool
        brms ``sparse``: the same model without centering.
    unused : tuple[str, ...]
        brms ``unused``: further columns kept with the model rows.

    Returns
    -------
    ResponseModel or MultivariateFormula
        One response; a joint formula for an ``mvbind`` left-hand side,
        whose residual-correlation setting follows the brms default; or a
        one-response joint formula when ``mi()``, ``me()``, or ``index()``
        terms appear, since those compile through the joint program.

    Raises
    ------
    ValueError
        If a parameter formula lacks a left-hand side, names a nonlinear
        parameter without ``nl=True``, or ``mvbind`` names fewer than two
        responses.
    """
    if program is not None:
        if formulas or nl:
            raise ValueError(
                "bf: the formulas of a program's parameters are given as "
                "parameters=, not as further formulas or nl=True"
            )
        text, kernel_family, given = program_arguments(
            formula,
            program=program,
            entry=entry,
            static=static,
            parameters=parameters,
            response=response,
            family="gaussian" if family is None else family,
            distributional=None,
            nonlinear=None,
            fixed_parameters=fixed_parameters,
            caller="bf",
        )
        return ResponseModel(
            formula=text,
            family=kernel_family,
            distributional=dict(given) if given else None,
            fixed_parameters=dict(fixed_parameters) if fixed_parameters else None,
            weights=weights,
            decision=decision,
            binomial_trials=binomial_trials,
            thresholds_by=thresholds_by,
            mixture_components=mixture_components,
            center=center,
            decomp=decomp,
            cmc=cmc,
            sparse=sparse,
            unused=tuple(unused),
        )
    if (
        formula is None
        or entry is not None
        or static is not None
        or parameters is not None
        or response is not None
    ):
        raise ValueError(
            "bf: give a response formula, or a program= with its response= and "
            "parameters="
        )
    stated = "gaussian" if family is None else family
    distributional, nonlinear = classify_parameters(
        stated,
        tuple(formulas),
        (),
        nl=nl,
        mixture_components=mixture_components,
        strict=family is not None,
    )

    def response_model(text: str) -> ResponseModel:
        """Build one response with this call's shared options.

        Parameters
        ----------
        text : str
            One response formula.

        Returns
        -------
        ResponseModel
            The response specification.
        """
        return ResponseModel(
            formula=text,
            family=stated,
            family_given=family is not None,
            parameter_formulas=tuple(formulas),
            nl=nl,
            distributional=distributional or None,
            nonlinear=nonlinear if nl else None,
            fixed_parameters=dict(fixed_parameters) if fixed_parameters else None,
            weights=weights,
            decision=decision,
            binomial_trials=binomial_trials,
            thresholds_by=thresholds_by,
            mixture_components=mixture_components,
            center=center,
            decomp=decomp,
            cmc=cmc,
            sparse=sparse,
            unused=tuple(unused),
        )

    bound = _MVBIND.match(formula)
    if bound is None:
        single = response_model(formula)
        # An explicit bf with missing terms retains its joint result and namespace.
        if uses_missing_syntax(formula, *formulas):
            return MultivariateFormula(responses={single.label: single})
        return single
    names = [name.strip() for name in bound.group("names").split(",") if name.strip()]
    if len(names) < 2:
        raise ValueError("mvbind() requires at least two response variables")
    return mvbf(*(response_model(name + " " + bound.group("rest")) for name in names))

lf

lf(*formulas: str) -> ParameterFormulas

Give additive parameter formulas to add to a response, as brms lf.

PARAMETER DESCRIPTION
*formulas

Formulas such as "sigma ~ 0 + sex" or "b1 + b2 ~ 1".

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION
ParameterFormulas

A value added to a bf response with +.

RAISES DESCRIPTION
ValueError

If a formula lacks a named left side.

Source code in src/quivers/formulas/_multivariate.py
def lf(*formulas: str) -> ParameterFormulas:
    """Give additive parameter formulas to add to a response, as brms ``lf``.

    Parameters
    ----------
    *formulas : str
        Formulas such as ``"sigma ~ 0 + sex"`` or ``"b1 + b2 ~ 1"``.

    Returns
    -------
    ParameterFormulas
        A value added to a `bf` response with ``+``.

    Raises
    ------
    ValueError
        If a formula lacks a named left side.
    """
    for text in formulas:
        parameter_names(text)
    return ParameterFormulas(formulas=tuple(formulas))

mvbf

mvbf(*parts: ResponseModel | MultivariateFormula, rescor: bool | None = None) -> MultivariateFormula

Combine responses into one joint formula, as brms mvbf does.

PARAMETER DESCRIPTION
*parts

Responses, or joint formulas whose responses are appended in order.

TYPE: ResponseModel or MultivariateFormula DEFAULT: ()

rescor

Residual-correlation setting. None keeps a setting carried by a joint part, and otherwise applies the brms default.

TYPE: bool or None DEFAULT: None

RETURNS DESCRIPTION
MultivariateFormula

Responses keyed by their brms names.

RAISES DESCRIPTION
ValueError

If two responses share a name.

TypeError

If a part is neither a response nor a joint formula.

Source code in src/quivers/formulas/_multivariate.py
def mvbf(
    *parts: ResponseModel | MultivariateFormula, rescor: bool | None = None
) -> MultivariateFormula:
    """Combine responses into one joint formula, as brms ``mvbf`` does.

    Parameters
    ----------
    *parts : ResponseModel or MultivariateFormula
        Responses, or joint formulas whose responses are appended in order.
    rescor : bool or None
        Residual-correlation setting. None keeps a setting carried by a
        joint part, and otherwise applies the brms default.

    Returns
    -------
    MultivariateFormula
        Responses keyed by their brms names.

    Raises
    ------
    ValueError
        If two responses share a name.
    TypeError
        If a part is neither a response nor a joint formula.
    """
    responses: dict[str, ResponseModel] = {}
    carried: bool | None = None
    for part in parts:
        if isinstance(part, MultivariateFormula):
            items = [(name, part.responses[name]) for name in part.response_names]
            if part.rescor_explicit and carried is None:
                carried = part.rescor
        elif isinstance(part, ResponseModel):
            items = [(part.label, part)]
        else:
            raise TypeError(
                "mvbf combines ResponseModel and MultivariateFormula values"
            )
        for name, response in items:
            if name in responses:
                raise ValueError(
                    f"response {name!r} appears twice; brms forbids using the same "
                    "response variable twice in one model"
                )
            responses[name] = response
    return MultivariateFormula(
        responses=responses, rescor=carried if rescor is None else rescor
    )

nlf

nlf(*formulas: str) -> ParameterFormulas

Give nonlinear parameter formulas to add to a response, as brms nlf.

PARAMETER DESCRIPTION
*formulas

Formulas such as "sigma ~ a * exp(b * x)". The right-hand side is an R expression over Stan's functions, data columns, and nonlinear parameters. For a distributional parameter it describes the link scale.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION
ParameterFormulas

A value added to a bf response with +.

RAISES DESCRIPTION
ValueError

If a formula lacks a named left side.

Source code in src/quivers/formulas/_multivariate.py
def nlf(*formulas: str) -> ParameterFormulas:
    """Give nonlinear parameter formulas to add to a response, as brms ``nlf``.

    Parameters
    ----------
    *formulas : str
        Formulas such as ``"sigma ~ a * exp(b * x)"``. The right-hand side is
        an R expression over Stan's functions, data columns, and nonlinear
        parameters. For a distributional parameter it describes the link
        scale.

    Returns
    -------
    ParameterFormulas
        A value added to a `bf` response with ``+``.

    Raises
    ------
    ValueError
        If a formula lacks a named left side.
    """
    for text in formulas:
        parameter_names(text)
    return ParameterFormulas(nonlinear=tuple(formulas))

set_mecor

set_mecor(mecor: bool = True) -> MecorSetting

Return the me() correlation setting, spelled as in brms.

PARAMETER DESCRIPTION
mecor

Correlate the latent values of a response's me() terms.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
MecorSetting

A value added to a response or joint formula with +.

Source code in src/quivers/formulas/_multivariate.py
def set_mecor(mecor: bool = True) -> MecorSetting:
    """Return the ``me()`` correlation setting, spelled as in brms.

    Parameters
    ----------
    mecor : bool
        Correlate the latent values of a response's ``me()`` terms.

    Returns
    -------
    MecorSetting
        A value added to a response or joint formula with ``+``.
    """
    return MecorSetting(mecor=mecor)

set_nl

set_nl(nl: bool = True) -> ParameterFormulas

Mark the main formula of a response as nonlinear, as brms set_nl.

PARAMETER DESCRIPTION
nl

Read the main formula's right-hand side as a nonlinear expression.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
ParameterFormulas

A value added to a bf response with +.

RAISES DESCRIPTION
TypeError

If nl is not Boolean.

Source code in src/quivers/formulas/_multivariate.py
def set_nl(nl: bool = True) -> ParameterFormulas:
    """Mark the main formula of a response as nonlinear, as brms ``set_nl``.

    Parameters
    ----------
    nl : bool
        Read the main formula's right-hand side as a nonlinear expression.

    Returns
    -------
    ParameterFormulas
        A value added to a `bf` response with ``+``.

    Raises
    ------
    TypeError
        If ``nl`` is not Boolean.
    """
    if type(nl) is not bool:
        raise TypeError("set_nl requires a Boolean")
    return ParameterFormulas(nl=nl)

set_rescor

set_rescor(rescor: bool = True) -> RescorSetting

Return the residual-correlation setting, spelled as in brms.

PARAMETER DESCRIPTION
rescor

Estimate residual correlations between Gaussian or Student responses.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
RescorSetting

A value added to a joint formula with +.

Source code in src/quivers/formulas/_multivariate.py
def set_rescor(rescor: bool = True) -> RescorSetting:
    """Return the residual-correlation setting, spelled as in brms.

    Parameters
    ----------
    rescor : bool
        Estimate residual correlations between Gaussian or Student responses.

    Returns
    -------
    RescorSetting
        A value added to a joint formula with ``+``.
    """
    return RescorSetting(rescor=rescor)

combine_models

combine_models(*fits: BayesianFit) -> BayesianFit
combine_models(*fits: MultivariateFit) -> MultivariateFit
combine_models(*fits: Pooled) -> Pooled

Pool the draws of fits of one model, as brms combine_models does.

Cost: one concatenation of every retained draw tensor.

PARAMETER DESCRIPTION
*fits

At least one fit of the same formula and settings, possibly to different datasets, each with recorded draws (MCMC or prior draws).

TYPE: BayesianFit or MultivariateFit DEFAULT: ()

RETURNS DESCRIPTION
BayesianFit or MultivariateFit

The first fit with the chains of every fit. Its data, designs, and prediction plan are the first fit's, as in brms.

RAISES DESCRIPTION
ValueError

If no fit is given or the fits differ in structure.

TypeError

If fits mix kinds or a posterior is a variational guide.

Source code in src/quivers/formulas/_multiple.py
def combine_models(*fits: Pooled) -> Pooled:
    """Pool the draws of fits of one model, as brms ``combine_models`` does.

    Cost: one concatenation of every retained draw tensor.

    Parameters
    ----------
    *fits : BayesianFit or MultivariateFit
        At least one fit of the same formula and settings, possibly to
        different datasets, each with recorded draws (MCMC or prior draws).

    Returns
    -------
    BayesianFit or MultivariateFit
        The first fit with the chains of every fit. Its data, designs, and
        prediction plan are the first fit's, as in brms.

    Raises
    ------
    ValueError
        If no fit is given or the fits differ in structure.
    TypeError
        If fits mix kinds or a posterior is a variational guide.
    """
    if not fits:
        raise ValueError("combine_models requires at least one fit")
    first = fits[0]
    if any(type(fitted) is not type(first) for fitted in fits):
        raise TypeError("combine_models requires fits of one kind")
    posteriors = []
    for fitted in fits:
        if not isinstance(fitted.posterior, MCMCResult | PriorDraws):
            raise TypeError(
                "combine_models pools recorded draws; a variational guide has none"
            )
        posteriors.append(fitted.posterior)
    structure = _structure(first)
    if any(_structure(fitted) != structure for fitted in fits[1:]):
        raise ValueError(
            "combine_models requires fits of the same model; their latent sites differ"
        )
    return first.with_(posterior=_concatenate(posteriors))

fit_multiple

fit_multiple(formula: MultivariateFormula, *, data: Sequence[IntoDataFrame], combine: Literal[True] = True, **options: Unpack[JointFitOptions]) -> MultipleFit
fit_multiple(formula: str | ResponseModel, *, data: Sequence[IntoDataFrame], combine: Literal[True] = True, **options: Unpack[FormulaFitOptions]) -> MultipleFit
fit_multiple(formula: MultivariateFormula, *, data: Sequence[IntoDataFrame], combine: Literal[False], **options: Unpack[JointFitOptions]) -> tuple[MultivariateFit, ...]
fit_multiple(formula: str | ResponseModel, *, data: Sequence[IntoDataFrame], combine: Literal[False], **options: Unpack[FormulaFitOptions]) -> tuple[BayesianFit, ...]
fit_multiple(formula: str | ResponseModel | MultivariateFormula, *, data: Sequence[IntoDataFrame], combine: bool = True, **options: Unpack[FormulaFitOptions]) -> MultipleFit | tuple[BayesianFit, ...] | tuple[MultivariateFit, ...]

Fit one formula to each imputed dataset, as brms brm_multiple does.

Every dataset is fitted by fit with the same options and seed, as brms passes one seed to every submodel, and the draws are pooled with combine_models.

PARAMETER DESCRIPTION
formula

Formula fitted to every dataset.

TYPE: str or ResponseModel or MultivariateFormula

data

Imputed datasets, for instance from a multiple-imputation package.

TYPE: Sequence[IntoDataFrame]

combine

brms combine: pool the fits into one MultipleFit. False returns the per-dataset fits, which may then use any method.

TYPE: bool DEFAULT: True

**options

Every other fit keyword. A combined fit requires a method that records draws (NUTS or HMC).

TYPE: FormulaFitOptions DEFAULT: {}

RETURNS DESCRIPTION
MultipleFit or tuple

Per-dataset fits and the pooled fit, or the per-dataset fits alone with combine=False.

RAISES DESCRIPTION
ValueError

If no dataset is given or a combined fit is requested with SVI.

TypeError

If combine is not Boolean.

Source code in src/quivers/formulas/_multiple.py
def fit_multiple(
    formula: str | ResponseModel | MultivariateFormula,
    *,
    data: Sequence[IntoDataFrame],
    combine: bool = True,
    **options: Unpack[FormulaFitOptions],
) -> MultipleFit | tuple[BayesianFit, ...] | tuple[MultivariateFit, ...]:
    """Fit one formula to each imputed dataset, as brms ``brm_multiple`` does.

    Every dataset is fitted by `fit` with the same options and seed, as
    brms passes one seed to every submodel, and the draws are pooled with
    `combine_models`.

    Parameters
    ----------
    formula : str or ResponseModel or MultivariateFormula
        Formula fitted to every dataset.
    data : Sequence[IntoDataFrame]
        Imputed datasets, for instance from a multiple-imputation package.
    combine : bool
        brms ``combine``: pool the fits into one `MultipleFit`. False
        returns the per-dataset fits, which may then use any method.
    **options : FormulaFitOptions
        Every other `fit` keyword. A combined fit requires a method that
        records draws (NUTS or HMC).

    Returns
    -------
    MultipleFit or tuple
        Per-dataset fits and the pooled fit, or the per-dataset fits alone
        with ``combine=False``.

    Raises
    ------
    ValueError
        If no dataset is given or a combined fit is requested with SVI.
    TypeError
        If ``combine`` is not Boolean.
    """
    if type(combine) is not bool:
        raise TypeError("combine must be True or False")
    datasets = list(data)
    if not datasets:
        raise ValueError("fit_multiple requires at least one dataset")
    if combine and options.get("method", "nuts") == "svi":
        raise ValueError(
            "fit_multiple pools recorded draws; use method='nuts' or 'hmc'"
        )
    if isinstance(formula, MultivariateFormula):
        settings = cast(JointFitOptions, options)
        joint = tuple(fit(formula, data=frame, **settings) for frame in datasets)
        if not combine:
            return joint
        return MultipleFit(pooled=combine_models(*joint), fits=joint)
    single = tuple(fit(formula, data=frame, **options) for frame in datasets)
    if not combine:
        return single
    return MultipleFit(pooled=combine_models(*single), fits=single)

kfold_predict

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

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

PARAMETER DESCRIPTION
result

A kfold result computed with save_fits=True.

TYPE: KFoldResult

method

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

TYPE: str DEFAULT: 'posterior_predict'

resp

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

TYPE: str or None DEFAULT: None

num_samples

Draws per chain of each refit.

TYPE: int or None DEFAULT: None

seed

Prediction seed.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
KFoldPrediction

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

RAISES DESCRIPTION
ValueError

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

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

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

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

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

loo_compare

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

Compare models by a stored criterion, as brms loo_compare.

PARAMETER DESCRIPTION
models

Named fits holding the criterion from add_criterion, or estimates.

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

criterion

Criterion to compare.

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

RETURNS DESCRIPTION
SummaryTable

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

RAISES DESCRIPTION
ValueError

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

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

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

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

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

loo_model_weights

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

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

PARAMETER DESCRIPTION
models

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

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

method

Weighting method.

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

bayesian_bootstrap

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

TYPE: bool DEFAULT: True

seed

Seed of the Bayesian bootstrap.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, float]

Weights summing to one.

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

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

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

model_weights

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

Return model weights, as brms model_weights.

PARAMETER DESCRIPTION
models

Named fits or estimates.

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

weights

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

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

seed

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

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, float]

Weights summing to one.

RAISES DESCRIPTION
ValueError

If the weighting method is unknown.

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

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

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

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

loo

loo(*models: ModelInput, model_names: Sequence[str] | None = None, compare: bool = True) -> CriterionList

Compute PSIS-LOO for one or more models and compare them, as brms loo.

PARAMETER DESCRIPTION
*models

Fitted models, or estimates. A fit with a stored loo criterion (add_criterion) is not evaluated again.

TYPE: BayesianFit or MultivariateFit or ELPDEstimate DEFAULT: ()

model_names

Names of the models; fit1, fit2, ... by default.

TYPE: Sequence[str] or None DEFAULT: None

compare

Compare several models, as loo_compare does.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
CriterionList

One estimate per model, and their comparison table for several models.

RAISES DESCRIPTION
ValueError

If no model is given, the names do not match, or the models score different observations.

Source code in src/quivers/formulas/_brms_loo.py
def loo(
    *models: ModelInput,
    model_names: Sequence[str] | None = None,
    compare: bool = True,
) -> CriterionList:
    """Compute PSIS-LOO for one or more models and compare them, as brms ``loo``.

    Parameters
    ----------
    *models : BayesianFit or MultivariateFit or ELPDEstimate
        Fitted models, or estimates. A fit with a stored ``loo`` criterion
        (`add_criterion`) is not evaluated again.
    model_names : Sequence[str] or None
        Names of the models; ``fit1``, ``fit2``, ... by default.
    compare : bool
        Compare several models, as ``loo_compare`` does.

    Returns
    -------
    CriterionList
        One estimate per model, and their comparison table for several
        models.

    Raises
    ------
    ValueError
        If no model is given, the names do not match, or the models score
        different observations.
    """
    return _criterion_list("loo", models, model_names, compare)

waic

waic(*models: ModelInput, model_names: Sequence[str] | None = None, compare: bool = True) -> CriterionList

Compute WAIC for one or more models and compare them, as brms waic.

PARAMETER DESCRIPTION
*models

Fitted models, or estimates.

TYPE: BayesianFit or MultivariateFit or ELPDEstimate DEFAULT: ()

model_names

Names of the models; fit1, fit2, ... by default.

TYPE: Sequence[str] or None DEFAULT: None

compare

Compare several models.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
CriterionList

One estimate per model, and their comparison table for several models.

RAISES DESCRIPTION
ValueError

If no model is given, the names do not match, or the models score different observations.

Source code in src/quivers/formulas/_brms_loo.py
def waic(
    *models: ModelInput,
    model_names: Sequence[str] | None = None,
    compare: bool = True,
) -> CriterionList:
    """Compute WAIC for one or more models and compare them, as brms ``waic``.

    Parameters
    ----------
    *models : BayesianFit or MultivariateFit or ELPDEstimate
        Fitted models, or estimates.
    model_names : Sequence[str] or None
        Names of the models; ``fit1``, ``fit2``, ... by default.
    compare : bool
        Compare several models.

    Returns
    -------
    CriterionList
        One estimate per model, and their comparison table for several
        models.

    Raises
    ------
    ValueError
        If no model is given, the names do not match, or the models score
        different observations.
    """
    return _criterion_list("waic", models, model_names, compare)

make_conditions

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

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

PARAMETER DESCRIPTION
data

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

TYPE: IntoDataFrame or BayesianFit or MultivariateFit

variables

Variables to condition on.

TYPE: str or Sequence[str]

**labels

rows2labels options (digits, sep, incl_vars).

TYPE: str or int or bool DEFAULT: {}

RETURNS DESCRIPTION
DataFrame

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

RAISES DESCRIPTION
ValueError

If a variable is not a column of the data.

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

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

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

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

bayes_factor

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

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

PARAMETER DESCRIPTION
x1

Numerator and denominator models, or their bridge estimates.

TYPE: BayesianFit or MultivariateFit or BridgeResult

x2

Numerator and denominator models, or their bridge estimates.

TYPE: BayesianFit or MultivariateFit or BridgeResult

log

Return the log Bayes factor.

TYPE: bool DEFAULT: False

model_names

Names of the two models.

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

method

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

repetitions

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

use_neff

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

maxiter

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

seed

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

RETURNS DESCRIPTION
BayesFactor

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

RAISES DESCRIPTION
ValueError

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

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

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

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

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

bridge_sampler

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

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

PARAMETER DESCRIPTION
fit

Fit with posterior MCMC draws and proper priors.

TYPE: BayesianFit or MultivariateFit

method

Proposal of the bridgesampling package.

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

repetitions

Independent proposal draws.

TYPE: int DEFAULT: 1

use_neff

Use the effective size of the iteration draws.

TYPE: bool DEFAULT: True

maxiter

Iteration bound of the fixed-point scheme.

TYPE: int DEFAULT: 1000

seed

Seed of the proposal draws.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
BridgeResult

The estimate, with the retained log densities.

RAISES DESCRIPTION
ValueError

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

RuntimeError

If the scheme does not converge.

Notes

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

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

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

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

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

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

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

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

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

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

post_prob

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

Return posterior model probabilities, as brms post_prob.

PARAMETER DESCRIPTION
models

At least two named models of the same response data.

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

prior_prob

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

TYPE: Sequence[float] or None DEFAULT: None

method

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

repetitions

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

use_neff

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

maxiter

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

seed

bridge_sampler settings for fits.

TYPE: BridgeMethod DEFAULT: 'normal'

RETURNS DESCRIPTION
dict[str, float]

Posterior probabilities summing to one.

RAISES DESCRIPTION
ValueError

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

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

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

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

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

mcmc_plot

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

Draw an MCMC diagnostic plot, as brms mcmc_plot.

PARAMETER DESCRIPTION
fit

Fitted model.

TYPE: BayesianFit or MultivariateFit

type

bayesplot mcmc_* type without prefix (MCMC_PLOTS).

TYPE: str DEFAULT: 'intervals'

variable

brms variable names or regular expressions; None for all.

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

regex

brms regex: search each expression anywhere in a name.

TYPE: bool DEFAULT: False

backend

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

TYPE: str

**kwargs

Further ArviZ keyword arguments.

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

RETURNS DESCRIPTION
PlotCollection or PlotMatrix

The plot.

RAISES DESCRIPTION
ValueError

If the type is unknown or has no ArviZ counterpart.

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

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

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

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

posterior_average

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

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

PARAMETER DESCRIPTION
models

Named fits.

TYPE: Mapping[str, BayesianFit or MultivariateFit]

variable

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

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

weights

Weighting method of averaging_weights, or explicit weights.

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

ndraws

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

TYPE: int or None DEFAULT: None

missing

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

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

seed

Seed of the draw selection and of the weights.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PosteriorAverage

Pooled draws, weights and draw counts.

RAISES DESCRIPTION
ValueError

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

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

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

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

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

pp_average

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

Mix the predictions of several fits, as brms pp_average.

PARAMETER DESCRIPTION
models

Named fits of the same response data.

TYPE: Mapping[str, BayesianFit or MultivariateFit]

weights

Weighting method of averaging_weights, or explicit weights.

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

method

Prediction method.

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

ndraws

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

TYPE: int or None DEFAULT: None

summary

Also summarize the pooled draws.

TYPE: bool DEFAULT: True

probs

Quantile probabilities of the summary.

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

robust

Median and MAD instead of mean and SD.

TYPE: bool DEFAULT: False

resp

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

TYPE: str or None DEFAULT: None

**options

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

TYPE: PredictionOptions DEFAULT: {}

RETURNS DESCRIPTION
PredictionAverage

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

RAISES DESCRIPTION
ValueError

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

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

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

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

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

pp_check

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

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

PARAMETER DESCRIPTION
fit

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

TYPE: BayesianFit or MultivariateFit

type

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

TYPE: str DEFAULT: 'dens_overlay'

ndraws

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

TYPE: int or None DEFAULT: None

prefix

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

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

group

Grouping variable; required by *_grouped types.

TYPE: str or None DEFAULT: None

x

Covariate of intervals, ribbon and error_scatter_avg_vs_x.

TYPE: str or None DEFAULT: None

newdata

Rows to predict, holding the response for ppc types.

TYPE: IntoDataFrame or None DEFAULT: None

resp

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

TYPE: str or None DEFAULT: None

draw_ids

Explicit 0-based draws.

TYPE: Sequence[int] or None DEFAULT: None

stat

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

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

prob

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

TYPE: float DEFAULT: 0.5

prob_outer

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

TYPE: float DEFAULT: 0.5

bins

Bins of error_binned.

TYPE: int or None DEFAULT: None

freq

Counts instead of proportions for bars.

TYPE: bool DEFAULT: True

style

Rootogram style.

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

seed

Seed of the draw selection and predictions.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PPCheck

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

RAISES DESCRIPTION
ValueError

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

Notes

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

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

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

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

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

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

default_prior

default_prior(formula: str | ResponseModel | MultivariateFormula, *, data: IntoDataFrame, **options: Unpack[PriorTableOptions]) -> PriorTable

Tabulate the default prior of every parameter, as brms::default_prior.

PARAMETER DESCRIPTION
formula

brms-style formula or joint specification.

TYPE: str or ResponseModel or MultivariateFormula

data

Rows that scale data-dependent defaults.

TYPE: IntoDataFrame

**options

Preparation keywords of get_prior, including default_priors, center, and decomp.

TYPE: PriorTableOptions DEFAULT: {}

RETURNS DESCRIPTION
PriorTable

brms's columns (prior, class, coef, group, resp, dpar, nlpar, lb, ub, tag, source) plus the generated site, every source default.

RAISES DESCRIPTION
ValueError

If the formula or a preparation keyword is invalid.

Source code in src/quivers/formulas/_prior_tables.py
def default_prior(
    formula: str | ResponseModel | MultivariateFormula,
    *,
    data: IntoDataFrame,
    **options: Unpack[PriorTableOptions],
) -> PriorTable:
    """Tabulate the default prior of every parameter, as ``brms::default_prior``.

    Parameters
    ----------
    formula : str or ResponseModel or MultivariateFormula
        brms-style formula or joint specification.
    data : IntoDataFrame
        Rows that scale data-dependent defaults.
    **options : PriorTableOptions
        Preparation keywords of `get_prior`, including ``default_priors``,
        ``center``, and ``decomp``.

    Returns
    -------
    PriorTable
        brms's columns (``prior, class, coef, group, resp, dpar, nlpar, lb,
        ub, tag, source``) plus the generated site, every source ``default``.

    Raises
    ------
    ValueError
        If the formula or a preparation keyword is invalid.
    """
    return _table(formula, data, None, options)

prior_summary

prior_summary(fit: BayesianFit | MultivariateFit) -> PriorTable

Tabulate the priors a fitted model used, as brms prior_summary.

PARAMETER DESCRIPTION
fit

Fitted single-response or joint model.

TYPE: BayesianFit or MultivariateFit

RETURNS DESCRIPTION
PriorTable

The effective prior of every site; rows set by a rule given to fit have source user.

RAISES DESCRIPTION
ValueError

If a single-response fit retains no emission.

Source code in src/quivers/formulas/_prior_tables.py
def prior_summary(fit: BayesianFit | MultivariateFit) -> PriorTable:
    """Tabulate the priors a fitted model used, as brms ``prior_summary``.

    Parameters
    ----------
    fit : BayesianFit or MultivariateFit
        Fitted single-response or joint model.

    Returns
    -------
    PriorTable
        The effective prior of every site; rows set by a rule given to
        `fit` have source ``user``.

    Raises
    ------
    ValueError
        If a single-response fit retains no emission.
    """
    if isinstance(fit, BayesianFit):
        return fit.prior_summary()
    targets = fit.emission.prior_targets
    policies = {
        response.default_priors for response in fit.specification.responses.values()
    }
    return prior_table(
        fit.emission.module,
        targets,
        user_selection(fit.priors, targets),
        policy="brms" if policies == {"brms"} else "quivers",
    )

validate_prior

validate_prior(priors: PriorInput, formula: str | ResponseModel | MultivariateFormula, *, data: IntoDataFrame, **options: Unpack[PriorTableOptions]) -> PriorTable

Check user priors against a model and return the complete prior table.

PARAMETER DESCRIPTION
priors

User rules: typed PriorSpec values or exact site names.

TYPE: PriorInput

formula

brms-style formula or joint specification.

TYPE: str or ResponseModel or MultivariateFormula

data

Training rows.

TYPE: IntoDataFrame

**options

Preparation keywords of get_prior.

TYPE: PriorTableOptions DEFAULT: {}

RETURNS DESCRIPTION
PriorTable

Every site with its effective prior; rows a user rule sets have source user and carry the rule's tag.

RAISES DESCRIPTION
ValueError

If a rule matches no parameter, is completely shadowed, conflicts with another rule, or is invalid for its target (bounds outside the domain, a shrinkage prior on an unsupported class, a constant of the wrong width).

Source code in src/quivers/formulas/_prior_tables.py
def validate_prior(
    priors: PriorInput,
    formula: str | ResponseModel | MultivariateFormula,
    *,
    data: IntoDataFrame,
    **options: Unpack[PriorTableOptions],
) -> PriorTable:
    """Check user priors against a model and return the complete prior table.

    Parameters
    ----------
    priors : PriorInput
        User rules: typed `PriorSpec` values or exact site names.
    formula : str or ResponseModel or MultivariateFormula
        brms-style formula or joint specification.
    data : IntoDataFrame
        Training rows.
    **options : PriorTableOptions
        Preparation keywords of `get_prior`.

    Returns
    -------
    PriorTable
        Every site with its effective prior; rows a user rule sets have
        source ``user`` and carry the rule's tag.

    Raises
    ------
    ValueError
        If a rule matches no parameter, is completely shadowed, conflicts
        with another rule, or is invalid for its target (bounds outside the
        domain, a shrinkage prior on an unsupported class, a constant of the
        wrong width).
    """
    return _table(formula, data, priors, options)

Cited sources

Paul-Christian BΓΌrkner. brms: An R Package for Bayesian Multilevel Models Using Stan. Journal of Statistical Software, 2017. doi:10.18637/jss.v080.i01.

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