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 >> betaoverobserveddesign-matrix morphisms, - random-effect groups as plate-gather of per-level latent draws,
- responses as
observesites with the family-link kernel (Gaussian / Bernoulli / Binomial / Categorical / Poisson / NegativeBinomial / Cumulative / Beta / Gamma / Student-t / ZeroInflatedPoisson / HurdlePoisson / Mixture) registered inquivers.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
module-attribute
¶
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
¶
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.
TYPE:
|
name |
Per-column label, equal to
TYPE:
|
qvr_name |
QVR-legal identifier derived from
TYPE:
|
is_intercept |
TYPE:
|
category_specific |
Whether cs(expr) gives this column one coefficient per ordinal transition.
TYPE:
|
data |
The column's values, shape
TYPE:
|
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:
|
column_indices |
Columns of the retained formula evaluator carrying penalized coordinates.
TYPE:
|
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:
|
basis |
Retained structural basis state when generated from a spline.
TYPE:
|
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
TYPE:
|
constraint |
Original training-basis mean defining the identification constraint.
TYPE:
|
scale_group |
Name of a smoothing scale shared with other blocks (an mgcv
TYPE:
|
category_specific |
Whether the block has one coefficient vector per ordinal transition.
TYPE:
|
gp |
For an approximate
TYPE:
|
SplineBasis
didactic-model
¶
Bases: ValueModel
Immutable structural state of an evaluated B-spline basis.
| ATTRIBUTE | DESCRIPTION |
|---|---|
knots |
Complete nondecreasing knot sequence, including repeated boundaries.
TYPE:
|
degree |
Nonnegative polynomial degree. The source basis width is the knot count minus degree minus one.
TYPE:
|
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 |
TYPE:
|
group |
Grouping factor name.
TYPE:
|
correlation_id |
Correlation-block identity;
TYPE:
|
shared |
Whether the identity was explicitly named and can join blocks across location and auxiliary formulas.
TYPE:
|
column |
Evaluated slope column, including categorical contrasts and numeric transforms. The intercept uses a constant column.
TYPE:
|
specific |
Whether a slope the program computes has one coefficient per ordinal transition.
TYPE:
|
options |
TYPE:
|
covariance |
Known covariance between the levels that the options name.
TYPE:
|
bar |
Position of the term's bar in the formula.
TYPE:
|
category_specific
property
¶
Return whether the slope has one coefficient per transition.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True for a |
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:
|
response_name |
Name of the response column.
TYPE:
|
fixed_columns |
One entry per design-matrix column (matches R/brms's one-coefficient-per-column convention).
TYPE:
|
design_terms |
Coupled Gaussian basis contributions with separate penalty-scale priors.
TYPE:
|
random_terms |
Random-effect group specifications.
TYPE:
|
response_values |
Response values with shape
TYPE:
|
response_layout |
Event coordinates and evaluated numeric carrier.
TYPE:
|
group_levels |
Canonical level ordering per grouping factor, used to derive deterministic plate-index tensors.
TYPE:
|
modifiers |
Checked response-row weights and decision columns, independent of predictor coefficients.
TYPE:
|
offsets |
Evaluated
TYPE:
|
group_indices |
Per-group integer index array, shape
TYPE:
|
latent_terms |
Structured latent vectors added to the location predictor, such as
brms
TYPE:
|
monotonic_terms |
brms
TYPE:
|
grouping |
brms interaction (
TYPE:
|
category_specific
property
¶
Return whether a term has one coefficient per ordinal transition.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True for a formula with a |
without
¶
without(parts: Collection[FormulaPart]) -> Formula
Return the formula without some of its elements.
| PARAMETER | DESCRIPTION |
|---|---|
parts
|
Elements to leave out.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Formula
|
The formula with every other element, in authored order. |
Source code in src/quivers/formulas/formula.py
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:
|
witnesses
|
Binding of each element of the formula in the program.
TYPE:
|
group_laws
|
Laws of the group blocks of the program.
TYPE:
|
level_sites
|
Sites holding values for every level of a grouping factor.
TYPE:
|
prior_targets
|
Parameter roles, authored labels, and nominal coefficient axes of the program's sites.
TYPE:
|
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:
|
carrier
|
Numeric carrier of the evaluated response, before family validation.
TYPE:
|
category_levels
|
Scalar factor labels in their evaluated contrast order; distinct from vector event component names.
TYPE:
|
ordered
|
Whether the original factor declares an ordering.
TYPE:
|
category_values
|
Integer response value of each category, for a response whose
categories are integers read as brms reads them (ordinal codes
TYPE:
|
event_shape
property
¶
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:
|
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:
|
censoring |
Recorded exact or censored outcome events.
TYPE:
|
truncation |
Inclusive bounds on the response sampling law.
TYPE:
|
standard_error |
Known measurement errors and optional residual scale.
TYPE:
|
subset |
Structural row selection performed before evaluating the design: the
rows kept by
TYPE:
|
trials |
Exact finite trial counts supplied by a response modifier.
TYPE:
|
rate |
Positive response denominators of brms
TYPE:
|
thresholds |
Number of ordinal thresholds declared by brms
TYPE:
|
threshold_groups |
Row codes, labels, and threshold counts of brms
TYPE:
|
weights_scale |
Whether weights were normalized to the number of included rows.
TYPE:
|
sources |
Authored column references and scalar literals used to bind fresh sampling-law inputs without requiring recorded outcomes.
TYPE:
|
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
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:
|
upper
|
Interval upper endpoints with safe placeholders on inactive rows.
TYPE:
|
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:
|
upper
|
Constant or rowwise inclusive bounds; None leaves that side unbounded.
TYPE:
|
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:
|
sigma
|
Whether to include the estimated residual scale in quadrature. The default False matches brms: known errors alone scale the likelihood.
TYPE:
|
RowSelection
didactic-model
¶
Bases: ValueModel
Map included response rows to their original dataframe positions.
| PARAMETER | DESCRIPTION |
|---|---|
size
|
Original row count before selection.
TYPE:
|
positions
|
Included positions in original order.
TYPE:
|
FormulaPart
didactic-model
¶
FormulaPart(*, field: FormulaField, key: str)
Bases: ValueModel
One authored element of a formula.
| PARAMETER | DESCRIPTION |
|---|---|
field
|
Field of
TYPE:
|
key
|
Name of the element within the field.
TYPE:
|
Link
didactic-model
¶
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.
TYPE:
|
inverse_expr |
QVR expression giving the family parameter from the linear
predictor, written
TYPE:
|
intermediates |
Shared quantities bound, in order, before the inverse; each name
and expression may use
TYPE:
|
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:
|
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:
|
brms_response_expr |
The link applied to the response
TYPE:
|
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
TYPE:
|
prior |
Prior distribution expression (e.g.
TYPE:
|
link |
Link applied to a per-row linear predictor if the parameter
is itself distributionally regressed (
TYPE:
|
fixed_default |
Optional constant used unless the parameter is explicitly regressed, fixed, or given a prior. Ordinal discrimination defaults to one.
TYPE:
|
brms_class |
brms parameter class when it differs from
TYPE:
|
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:
|
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:
|
links |
Links
TYPE:
|
below_response |
Whether the parameter is a shift every response exceeds. A fixed
value is checked against the responses,
TYPE:
|
per_component |
Whether the parameter has one value per free component of the
family's
TYPE:
|
coordinates |
The axis of a parameter that takes one value per element of an axis of its own; None for a scalar parameter.
TYPE:
|
parameter_class
property
¶
The brms class of the parameter.
| RETURNS | DESCRIPTION |
|---|---|
str
|
The declared class, or the parameter's own name. |
admissible_links
property
¶
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
¶
Whether the default prior is bounded by the smallest response.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True when |
with_response_minimum
¶
Bind the smallest response in a prior of this parameter.
| PARAMETER | DESCRIPTION |
|---|---|
prior
|
Prior expression, possibly naming
TYPE:
|
response
|
Training responses.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The prior with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the prior names |
Source code in src/quivers/formulas/family.py
Binding
didactic-model
¶
Bases: Model
One named quantity defined by a QVR expression over earlier names.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
Name bound in the emitted program.
TYPE:
|
expr |
Deterministic QVR expression defining it.
TYPE:
|
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:
|
upper |
Upper endpoint, or None when unbounded above.
TYPE:
|
lower_closed |
Whether the lower endpoint belongs to the interval.
TYPE:
|
upper_closed |
Whether the upper endpoint belongs to the interval.
TYPE:
|
contains
¶
Test membership of one finite value.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
Candidate value.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True when the value lies in the interval. |
Source code in src/quivers/formulas/family.py
within
¶
within(other: Domain) -> bool
Test whether this interval is contained in another.
| PARAMETER | DESCRIPTION |
|---|---|
other
|
Candidate enclosing interval.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True when every value of this interval lies in |
Source code in src/quivers/formulas/family.py
requirement
¶
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
Elliptical
didactic-model
¶
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:
|
df |
Auxiliary parameter giving the Student degrees of freedom; None for the Normal law.
TYPE:
|
kernel
property
¶
The native law of a correlated residual vector.
| RETURNS | DESCRIPTION |
|---|---|
str
|
The multivariate Normal, or Student-t under degrees of freedom. |
parameterization
property
¶
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
TYPE:
|
observe_args |
Native constructor arguments of the accumulated count;
TYPE:
|
observe_family |
Native law of the accumulated count when it leaves the family's own.
TYPE:
|
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:
|
link |
Inverse link for cumulative or transition probabilities.
TYPE:
|
thresholds |
Flexible, equally spaced, or explicitly sum-centered thresholds.
TYPE:
|
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:
|
reference
|
Zero-predictor component by position or retained label. None gives every component its own predictor under proper coefficient priors.
TYPE:
|
reference_index
¶
Resolve a reference against retained component or factor labels.
| PARAMETER | DESCRIPTION |
|---|---|
labels
|
Complete component order.
TYPE:
|
| 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
coordinate_indices
¶
Return coefficient coordinates in retained component order.
| PARAMETER | DESCRIPTION |
|---|---|
labels
|
Complete component order.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[int, ...]
|
Component positions carrying free predictors. |
Source code in src/quivers/formulas/family.py
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:
|
degree
|
Polynomial degree when selecting knots.
TYPE:
|
boundary_knots
|
Explicit finite boundary span, starting at zero. None selects knots once from training events and follow-up times.
TYPE:
|
interior_knots
|
Explicit interior knots when boundary_knots is supplied.
TYPE:
|
by
|
Grouping factor for separate normalized profiles on this common basis.
TYPE:
|
resolve
¶
resolve(formula: Formula) -> MSplineBasis
Resolve the baseline once from retained training responses.
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
Evaluated positive scalar response and modifier columns.
TYPE:
|
| 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
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;
TYPE:
|
order
|
TYPE:
|
equal
|
Distributional parameters set equal to another parameter of the same
class, brms
TYPE:
|
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:
- The auxiliary-parameter latent draws (intercept-only by
default; one per parameter named in
aux_params). - A
let eta = <linear predictor>binding the location's linear predictor. - A
let mu = <link.inverse_expr>binding the natural parameter. - A single
observe y : Resp <- <observe_family>(mu, ...)step parameterised bymuand 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:
|
location_link
|
Location or mean inverse link.
TYPE:
|
observe_family
|
Checked native observation family.
TYPE:
|
observe_lets
|
Quantities derived from
TYPE:
|
observe_args
|
Native constructor arguments in schema order: names of formula
parameters or of
TYPE:
|
exposure
|
Law of the count over a
TYPE:
|
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:
|
circular
|
Whether the response is an angle, for which an expectation needs an angular convention and no arithmetic mean is defined.
TYPE:
|
log_response
|
Whether the location and scale parameterize the logarithm of the response, so default prior scales are taken on the log response.
TYPE:
|
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:
|
decision_event
|
Expression forming the scored event from
TYPE:
|
location_links
|
Links
TYPE:
|
recorded_events
|
Whether the family admits the
TYPE:
|
error_scale
|
Auxiliary parameter giving the residual scale that the known errors
of a
TYPE:
|
elliptical
|
Elliptical residual law, under which residuals may be correlated across rows or responses.
TYPE:
|
r_squared
|
Variance
TYPE:
|
factor_levels
|
Number of levels of a factor response the family codes
TYPE:
|
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:
|
aux_params
|
Auxiliary priors and distributional links.
TYPE:
|
trials_parameter
|
Native parameter receiving exact per-row trial counts.
TYPE:
|
ordinal
|
Retained ordinal thresholds and transition construction.
TYPE:
|
response
|
Joint component coordinate system and reference selection.
TYPE:
|
baseline
|
Retained normalized spline structure for proportional hazards.
TYPE:
|
custom
|
Checked custom constructor bindings and compilation-local native law.
TYPE:
|
mixture
|
Components and ordering of a finite mixture built by
TYPE:
|
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:
|
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
¶
native: DistributionFamily
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 |
retains_log_location
property
¶
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
¶
Whether one response event is a vector of components.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True for compositional and count-vector responses. |
coded_levels
property
¶
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
|
scores_cutpoints
property
¶
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 |
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
¶
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
|
reads_location
property
¶
Whether the family's kernel reads the location mu.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True for a native law; for a kernel law, whether |
kernel_columns
property
¶
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
¶
Whether the response is an unordered category code.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True for a scalar categorical response. |
category_response
property
¶
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
¶
Name the native constructor parameter that receives a quantity.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Formula parameter or derived binding passed to the constructor.
TYPE:
|
| 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
admissible_links
¶
List the links the family admits for one parameter.
| PARAMETER | DESCRIPTION |
|---|---|
parameter
|
TYPE:
|
| 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
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:
|
data2
|
Values that are not indexed by the rows.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Values by input name; empty for a native law. |
Source code in src/quivers/formulas/family.py
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:
|
families
|
Compilation-local laws of the model.
TYPE:
|
Source code in src/quivers/formulas/family.py
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:
|
df
|
Number of basis components for automatic selection.
TYPE:
|
degree
|
Polynomial degree for automatic selection.
TYPE:
|
by
|
Grouping factor with a separate normalized baseline simplex per level. Every group retains the same knot structure and endpoint tail policy.
TYPE:
|
| 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
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
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:
|
| 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
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:
|
| 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
with_links
¶
with_links(**parameters: str) -> Family
Return a family with selected parameter links.
| PARAMETER | DESCRIPTION |
|---|---|
**parameters
|
Link names keyed by
TYPE:
|
| 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
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 | |
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
TYPE:
|
fixed_prior
|
Default prior for fixed-effect coefficients, in the surface
form
TYPE:
|
random_scale_prior
|
Default prior for random-effect scale parameters.
TYPE:
|
correlation_prior
|
Default LKJ Cholesky prior for correlated coefficient blocks.
TYPE:
|
group_covariances
|
Known covariance between labeled levels of each grouping factor. Coefficient correlations retain their existing LKJ hierarchy.
TYPE:
|
user_priors
|
Exact-name overrides or typed role selectors. More specific selectors refine broader rules; ambiguous and unused rules raise an error.
TYPE:
|
reparameterize
|
Conditional Gaussian coordinates for scalar, category-specific and component-valued group effects, and grouped threshold log slacks.
TYPE:
|
binomial_trials
|
Nonnegative common trial count or a per-row trial-count column.
TYPE:
|
thresholds_by
|
Grouping factor whose levels receive partially pooled ordinal cutpoint spacings.
TYPE:
|
mixture_components
|
Number of components for
TYPE:
|
predictor_name
|
Host-data name for an external differentiable predictor.
TYPE:
|
distributional
|
Auxiliary-parameter formulas on the same response rows. Each
predictor receives its own coefficients, covariates, and group effects;
a
TYPE:
|
fixed_parameters
|
Auxiliary parameters bound to constants on their natural scale, without latent sites or priors. Cannot overlap distributional formulas.
TYPE:
|
default_priors
|
Default policy for sites no prior rule selects: the proper, autoscaled
quivers defaults, or
TYPE:
|
center
|
brms
TYPE:
|
decomp
|
brms
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an option is out of range or does not apply to |
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
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 | |
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 |
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
¶
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
¶
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
¶
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
¶
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
¶
Return the priors configured for exact sites.
| RETURNS | DESCRIPTION |
|---|---|
Mapping[str, str]
|
Prior source by site name. |
observation
property
¶
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
¶
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:
|
| RETURNS | DESCRIPTION |
|---|---|
FamilyCatalog or None
|
The response laws joined with those of the terms. |
Source code in src/quivers/formulas/compile.py
forward
¶
forward(formula: Formula) -> tuple[Module, FormulaData]
Compile one formula through the shared response emitter.
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
Evaluated response and design metadata.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Module, FormulaData]
|
Existing QVR program and its retained formula complement. |
Source code in src/quivers/formulas/compile.py
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:
|
| 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 |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a prior override does not name an available parameter. |
Source code in src/quivers/formulas/compile.py
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
TYPE:
|
complement
|
The complement
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Formula
|
The complement's formula without the elements whose bindings the module lacks. |
Source code in src/quivers/formulas/compile.py
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:
|
| 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
fixed_column_observations
¶
Bind retained covariates, offsets, and response likelihood weights.
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
The formula whose fixed-effect columns are bound.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Numeric predictor and offset columns as |
Source code in src/quivers/formulas/compile.py
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:
|
identity
|
Original grouping factor and correlation-block identity.
TYPE:
|
coordinate_axis
|
Joint finite coordinate axis, absent for one scalar coefficient.
TYPE:
|
parameterization
|
Whether raw sites contain coefficients or standard-normal innovations.
TYPE:
|
members
|
Ordered nonoverlapping coefficient slices.
TYPE:
|
correlation_site
|
Actual emitted Cholesky site; None denotes an independent block.
TYPE:
|
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:
|
width
property
¶
Return the joint coordinate count.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Sum of the retained member widths. |
raw_sites
property
¶
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:
|
slope
|
Predictor namespace and expanded slope label.
TYPE:
|
axis
|
Component axis; None denotes a scalar coefficient.
TYPE:
|
width
|
Component count and first coordinate in the joint block.
TYPE:
|
offset
|
Component count and first coordinate in the joint block.
TYPE:
|
coefficient
|
Retained deterministic coefficient binding.
TYPE:
|
raw_site
|
Sample site supplying this member's coordinates; None denotes a deterministic zero-rank deviation.
TYPE:
|
scale_site
|
Actual emitted conditional scale site for noncentered reconstruction.
TYPE:
|
mean_site
|
Optional affine hypermean, retained outside the supported deviation subspace for grouped threshold log-spacing profiles.
TYPE:
|
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:
|
matrix
|
Finite symmetric covariance, copied from nested numeric sequences or a fixed Tensor. Its scale is retained; it need not be a correlation.
TYPE:
|
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:
|
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
subset
¶
subset(levels: Sequence[str]) -> GroupCovariance
Retain a labeled principal submatrix in the requested order.
| PARAMETER | DESCRIPTION |
|---|---|
levels
|
Unique known grouping labels.
TYPE:
|
| 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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
GroupCovarianceBasis
|
Orthogonal support projection and exact positive coordinate law. |
Source code in src/quivers/formulas/_group_covariance.py
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:
|
new_levels
|
Disjoint known labels, in retained and requested order.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, GroupCovarianceBasis]
|
Mean map |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If labels overlap or the conditional covariance is not PSD. |
Source code in src/quivers/formulas/_group_covariance.py
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:
|
projection
|
Orthonormal columns mapping support coordinates to physical levels.
TYPE:
|
covariance
|
Positive-definite support covariance; an empty matrix denotes rank zero.
TYPE:
|
coordinate_factor
|
Cached Cholesky factor of the support covariance.
TYPE:
|
sampling_factor
|
Cached projection times coordinate_factor. Prediction materializes this factor without repeating an eigendecomposition or Cholesky.
TYPE:
|
rank
property
¶
Return the number of stochastic level coordinates.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Support dimension, including zero for a deterministic deviation. |
tensors
¶
Materialize projection, coordinate covariance, and sampling factor.
| PARAMETER | DESCRIPTION |
|---|---|
like
|
Optional floating dtype and device context.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor, Tensor]
|
|
Source code in src/quivers/formulas/_group_covariance.py
NonlinearExpression
didactic-model
¶
NonlinearExpression(*, expression: str | dict[str | int, str] = field(opaque=True, extras=OPAQUE_BY_VALUE), syntax: Literal['qvr', 'r'] = 'qvr')
Bases: ValueModel
A deterministic QVR value expression, rather than an additive design.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
Scalar expression or explicit component-label mapping using named nonlinear parameters and numeric data columns. Distributional expressions describe the family's link scale; inverse links are applied once, after evaluation. Intermediate nonlinear parameters have the identity link.
TYPE:
|
syntax
|
Language of the expression text.
TYPE:
|
ComponentExpression
didactic-model
¶
ComponentExpression(*, components: tuple[str, ...], values: tuple[LetExprNode, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: ValueModel
An explicitly labelled vector value whose coordinates keep nominal order.
| PARAMETER | DESCRIPTION |
|---|---|
components
|
Authored coordinate labels, never inferred from extent equality.
TYPE:
|
values
|
Scalar expressions aligned to those coordinate labels.
TYPE:
|
at
¶
at(component: str) -> LetExprNode
Return the expression of one coordinate.
| PARAMETER | DESCRIPTION |
|---|---|
component
|
Coordinate label.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LetExprNode
|
Scalar expression of the coordinate. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the value has no such coordinate. |
Source code in src/quivers/formulas/_predictor_graph.py
PredictorGraph
didactic-model
¶
PredictorGraph(*, leaves: dict[str, Formula] = field(opaque=True, extras=OPAQUE_BY_VALUE), expressions: dict[str, LetExprNode | ComponentExpression] = field(opaque=True, extras=OPAQUE_BY_VALUE), roots: dict[str, LetExprNode | ComponentExpression] = field(opaque=True, extras=OPAQUE_BY_VALUE), inputs: dict[str, FixedColumn] = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: ValueModel
Retain additive parameter designs and a checked deterministic dependency DAG.
| PARAMETER | DESCRIPTION |
|---|---|
leaves
|
Nonlinear parameters whose coefficients use ordinary formula emission.
TYPE:
|
expressions
|
Deterministic intermediate nodes in dependency order.
TYPE:
|
roots
|
Family link-scale outputs, keyed by distributional parameter.
TYPE:
|
inputs
|
Numeric raw columns with their exact fitted carriers and row axis.
TYPE:
|
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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
lower
|
Optional finite bounds, intersected with the target's domain.
TYPE:
|
upper
|
Optional finite bounds, intersected with the target's domain.
TYPE:
|
block
|
Shared shrinkage identity. Rules with the same block share global hyperparameters and allocations and must specify identical hierarchies.
TYPE:
|
tag
|
brms
TYPE:
|
selector
property
¶
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:
|
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:
|
class_
|
Generated binder and semantic parameter class.
TYPE:
|
coef
|
Authored coefficient, grouping, predictor, and joint-response labels.
TYPE:
|
group
|
Authored coefficient, grouping, predictor, and joint-response labels.
TYPE:
|
dpar
|
Authored coefficient, grouping, predictor, and joint-response labels.
TYPE:
|
nlpar
|
Authored coefficient, grouping, predictor, and joint-response labels.
TYPE:
|
response
|
Authored coefficient, grouping, predictor, and joint-response labels.
TYPE:
|
axes
|
Nominal independent coefficient axes in source order.
TYPE:
|
shape
|
Their declared cardinalities, distinct from native event dimensions.
TYPE:
|
lower
|
Admissible coefficient-domain bounds.
TYPE:
|
upper
|
Admissible coefficient-domain bounds.
TYPE:
|
event_rank
|
Native distribution event rank, separate from independent axes.
TYPE:
|
component_labels
|
Free response-component labels in the retained coefficient order.
TYPE:
|
parameters
|
Parameter of each component, when every component belongs to a
parameter of its own, as
TYPE:
|
partition_labels
|
Levels of the
TYPE:
|
partition_axis
|
Axis over those levels.
TYPE:
|
vector
|
Parameter
TYPE:
|
whole
|
Site the component is part of.
TYPE:
|
sites
property
¶
Return the target's site and the site it is part of.
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
One or two names. |
component_site
¶
Name the site of one component drawn on its own.
| PARAMETER | DESCRIPTION |
|---|---|
parameter
|
Parameter of the component.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Site name. |
Source code in src/quivers/formulas/_priors.py
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
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:
|
df_global
|
Positive degrees of freedom for local, global, and slab priors.
TYPE:
|
df_slab
|
Positive degrees of freedom for local, global, and slab priors.
TYPE:
|
scale_global
|
Positive global and slab scales.
TYPE:
|
scale_slab
|
Positive global and slab scales.
TYPE:
|
par_ratio
|
If supplied, replace scale_global by par_ratio/sqrt(training_rows).
TYPE:
|
autoscale
|
Multiply the global scale by a scalar residual sigma when available. Distributional-parameter coefficients are not autoscaled.
TYPE:
|
main
|
brms
TYPE:
|
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:
|
prec_R2
|
Positive Beta precision.
TYPE:
|
cons_D2
|
Positive Dirichlet concentration, shared or per selected coordinate.
TYPE:
|
autoscale
|
Multiply coefficient scales by a scalar residual sigma when available.
TYPE:
|
main
|
brms
TYPE:
|
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:
|
data
|
Deterministic distributional parameters paired with source data columns.
TYPE:
|
BayesianFit
didactic-model
¶
BayesianFit(*, program: MonadicProgram = field(opaque=True, extras=OPAQUE_BY_IDENTITY), posterior: MCMCResult | PriorDraws | Guide = field(opaque=True, extras=OPAQUE_BY_IDENTITY), observations: Mapping[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), sample_prior: PriorMode = 'no', prior: PriorDraws | MCMCResult | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), losses: tuple[float, ...] = (), reparameterize: Literal['centered', 'noncentered'] = 'noncentered', fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: dict[str, GroupCovariance] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), priors: PriorSet = field(default_factory=PriorSet, opaque=True, extras=OPAQUE_BY_VALUE), criteria: Mapping[str, ELPDEstimate | Tensor] = field(default=NO_CRITERIA, opaque=True, extras=OPAQUE_BY_IDENTITY), formula: Formula = field(opaque=True, extras=OPAQUE_BY_VALUE), family: Family = field(opaque=True, extras=OPAQUE_BY_VALUE), residual: ResidualLaw | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor: Module | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), predictor_data: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), predictor_name: str | None = None, fixed_parameters: dict[str, float] = field(default_factory=dict), distributional: Mapping[str, Formula] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), predictor_graph: PredictorGraph | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), prediction_plan: FormulaPredictionPlan | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), refit_recipe: RefitRecipe[IntoDataFrame, Mapping[str, object], BayesianFit] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none')
Bases: SinglePostprocess, EvidenceEffectsMethods, FormulaFit
A fitted Bayesian regression: the compiled program, the parsed formula, the family, the user-supplied data, and the posterior samples.
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
Parsed formula IR.
TYPE:
|
family
|
Response family used at compile time.
TYPE:
|
residual
|
Residual law of the response: natural residuals correlated across rows by an autocorrelation term; None for independent rows.
TYPE:
|
program
|
The compiled program.
TYPE:
|
posterior
|
TYPE:
|
sample_prior
|
Ordinary fitting, additionally retained independent priors, or observation-free inference with explicit score potentials retained.
TYPE:
|
prior
|
Independent prior samples, or explicitly factor-conditioned chains.
TYPE:
|
losses
|
Finite optimization losses for SVI; empty for recorded MCMC chains.
TYPE:
|
observations
|
Inference-time observations dict (response + per-column covariates + per-group plate indices).
TYPE:
|
group_covariances
|
Known labeled covariance between grouping levels, including any explicitly supplied future labels. Coefficient correlations remain separate.
TYPE:
|
fixed_parameters
|
Auxiliary parameters bound to constants rather than sampled or regressed.
TYPE:
|
distributional
|
Evaluated auxiliary-parameter design matrices, retained so source inspection emits the fitted model without re-evaluating transforms.
TYPE:
|
predictor_graph
|
Named nonlinear designs, typed expressions, and numeric input contracts.
TYPE:
|
refit_recipe
|
Retained original data and canonical fitting configuration, held by identity. Clone ownership is the default; explicit reference ownership observes mutations.
TYPE:
|
prediction_plan
|
Live fitted evaluators for new-data prediction. The versioned runtime plan is held by identity and explicitly refuses durable serialization.
TYPE:
|
criteria
|
Criteria stored by
TYPE:
|
default_priors
|
Default prior policy the model was compiled with.
TYPE:
|
center
|
brms intercept centering option.
TYPE:
|
decomp
|
brms population-coefficient decomposition.
TYPE:
|
Notes
Fits compare by value over the formula, family, and settings, and by identity over the live objects: the program, the posterior, the observations mapping, the predictor, its data, the prediction plan, and the refit recipe. Two fits are thus equal exactly when they share those objects and agree on everything else.
qvr_source
property
¶
Lazily emit the AST-equivalent .qvr source for display.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Canonical source emitted from the retained formula AST. |
included_rows
property
¶
Positions of the input data rows the model was fitted to.
Rows excluded by subset or by a missing value in any model
variable are absent. Pointwise likelihoods and predictions on the
training rows follow this order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[int, ...]
|
Zero-based positions in the data passed to |
category_labels
property
¶
Response-category labels in posterior probability-array order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[int or str, ...]
|
Factor levels, the integer values |
threshold_labels
property
¶
Adjacent category pairs identifying the ordinal transition axis.
| RETURNS | DESCRIPTION |
|---|---|
tuple of pair of int
|
Adjacent category labels, excluding the structural-zero boundary in a hurdle cumulative model; empty for nonordinal families. |
group_levels
property
¶
Retained group labels in each coefficient array's level-axis order.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, tuple[str, ...]]
|
Group names and the ordered labels used in coefficient arrays. |
coefficient_labels
property
¶
Label free component coefficients in their retained coordinate order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[int | str, ...]
|
Nonreference component labels, or all labels without a reference. |
update
¶
update(data: IntoDataFrame | None = None, **overrides: object) -> BayesianFit
Fit retained or replacement rows through the original fitting recipe.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Original-frame snapshot by default, or replacement unprepared rows.
TYPE:
|
**overrides
|
Explicit overrides of the canonical fit arguments, including formula, family, priors, inference method, budgets, or random seed. Changing methods resets inactive budgets unless explicitly overridden.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesianFit
|
A fresh fitted result; the retained posterior and predictor are unchanged. |
| RAISES | DESCRIPTION |
|---|---|
(ValueError, TypeError)
|
If no recipe was retained or an override fails canonical fit validation. |
Source code in src/quivers/formulas/_fit.py
refit_callback
¶
refit_callback(*, method_factory: Callable[[Mapping[str, object], int], Mapping[str, object]], partition: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame] | None = None, num_samples: int | None = None, **prediction: object) -> Callable[[FoldSplit], FoldPrediction]
Adapt retained included rows and neural inputs to explicit refits.
| PARAMETER | DESCRIPTION |
|---|---|
method_factory
|
Fold-specific canonical fit settings and seed. Retained row attachments are partitioned automatically and cannot be replaced.
TYPE:
|
partition
|
Optional nonmutating original-frame row selection. By default, Narwhals preserves the dataframe backend and authored columns.
TYPE:
|
num_samples
|
Per-chain draw budget for raw held-out likelihood scoring.
TYPE:
|
**prediction
|
Existing log_likelihood options, including re_formula and explicit new-group policies. The adapter owns rows, neural inputs, and seeds.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[FoldSplit], FoldPrediction]
|
Callback for cross_validate. Fold indices address fitted included rows; subset positions map them to the original raw frame once. Neural predictor_data follows the same train/test selection. |
| RAISES | DESCRIPTION |
|---|---|
(ValueError, TypeError)
|
If retained rows or attachments do not align, a partition has the wrong included-row count, or options fail canonical validation. |
Source code in src/quivers/formulas/_fit.py
evidence
¶
Estimate the retained formula target's normalizing constant with SMC.
| PARAMETER | DESCRIPTION |
|---|---|
sampler
|
Configured likelihood-tempered driver, including its particle budget, rejuvenation kernel, and random stream.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SMCResult
|
Independent particles and the estimated log normalizing constant. Ordinary data evidence requires a normalized prior and likelihood; response weights define a powered target's normalizer instead. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If SMC cannot partition the target, normalize its prior, or use an exact likelihood without observation subsampling. |
RuntimeError
|
If no temperature step meets the driver's ESS requirement. |
Notes
The compiled program, retained designs, fixed parameters, and observed tensors are reused without recompilation. The fitted posterior is neither sampled nor modified. Seeded drivers restore the caller's RNG.
Source code in src/quivers/formulas/_fit.py
prior_summary
¶
prior_summary() -> PriorTable
Tabulate the effective prior of every parameter, as brms prior_summary.
| RETURNS | DESCRIPTION |
|---|---|
PriorTable
|
brms's columns, with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fit retains no emission. |
Source code in src/quivers/formulas/_fit.py
conditional_effects
¶
conditional_effects(grid: PredictionGrid, *, method: EffectMethod = ..., parameter: str = ..., transform: bool = ..., **options: Unpack[ConditionalEffectsOptions]) -> ConditionalEffects
conditional_effects(grid: str | Sequence[str] | None = ..., *, method: EffectMethod = ..., parameter: str = ..., transform: bool = ..., **options: Unpack[ConditionalEffectsOptions]) -> BrmsConditionalEffects
conditional_effects(grid: PredictionGrid | str | Sequence[str] | None = None, *, method: EffectMethod = 'epred', parameter: str = 'mu', transform: bool = False, **options: Unpack[ConditionalEffectsOptions]) -> ConditionalEffects | BrmsConditionalEffects
Predict one joint grid and retain conditional or empirical effects.
Without a grid, or with brms effects such as "x" or
"x:z", this computes brms's automatic conditional effects
(quivers.formulas._brms_effects.brms_conditional_effects): default
effects and conditions, grids, and labeled summary frames.
| PARAMETER | DESCRIPTION |
|---|---|
grid
|
Explicit effect coordinates and conditioning/reference rows,
constructed with
TYPE:
|
method
|
TYPE:
|
parameter
|
Predictor selected only for linpred; other methods require mu.
TYPE:
|
transform
|
Apply the inverse link only for linpred.
TYPE:
|
**options
|
Existing prediction keywords, including varying-effect selectors,
new-level policies, trial/neural inputs, draw budget, and seed.
The grid supplies new_data; mc_samples applies only to epred.
Without a grid, brms's
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ConditionalEffects or BrmsConditionalEffects
|
Joint chain/draw/point/condition/event predictions, with reference rows averaged within each draw only for empirical grids. Retained draws support paired contrasts, covariance, and common summaries. Without a grid, brms's labeled effect frames. |
| RAISES | DESCRIPTION |
|---|---|
(ValueError, TypeError)
|
If the method/options or grid are invalid, or the existing fitted prediction contract rejects a predictor, group, or response law. |
Source code in src/quivers/formulas/_fit.py
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | |
prior_view
¶
prior_view(*, num_samples: int | None = None, seed: int = 0, method: Literal['ancestral'] | MCMC = 'ancestral') -> BayesianFit
Reuse prediction, likelihood, and analysis methods with prior draws.
| PARAMETER | DESCRIPTION |
|---|---|
num_samples
|
Fresh independent draw count. None reuses retained prior samples, or draws 100 if none were retained.
TYPE:
|
seed
|
Isolated CPU seed for fresh ancestral draws.
TYPE:
|
method
|
Conditional sampling or explicitly factor-conditioned inference.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesianFit
|
A new view sharing the fitted model, encodings, and data. |
Source code in src/quivers/formulas/_fit.py
dump_qvr
¶
Write the AST-equivalent .qvr source to path and
return the resulting Path.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Destination for canonical QVR source.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Path
|
Written source path. |
Source code in src/quivers/formulas/_fit.py
fixed_effects
¶
fixed_effects(*, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, Tensor]
Extract the population coefficients of one predictor.
| PARAMETER | DESCRIPTION |
|---|---|
parameter
|
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Original column labels and coefficient arrays, shape
|
Source code in src/quivers/formulas/_fit.py
random_effects
¶
random_effects(*, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, dict[str, Tensor]]
Extract native group adjustments, including correlations and scales.
| PARAMETER | DESCRIPTION |
|---|---|
parameter
|
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, Tensor]]
|
Group name, then original coefficient label, mapped to arrays
|
Source code in src/quivers/formulas/_fit.py
coefficients
¶
coefficients(*, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0) -> dict[str, dict[str, Tensor]]
Combine population coefficients and group adjustments by level.
| PARAMETER | DESCRIPTION |
|---|---|
parameter
|
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, Tensor]]
|
Arrays with the structure of |
Source code in src/quivers/formulas/_fit.py
posterior_thresholds
¶
posterior_thresholds(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0) -> Tensor
Replay complete ordinal threshold profiles at each requested row.
| PARAMETER | DESCRIPTION |
|---|---|
new_data
|
Fresh predictors evaluated with fitted encodings, or training rows.
TYPE:
|
predictor_data
|
Explicit neural input for fresh prediction rows when required.
TYPE:
|
re_formula
|
Varying-effect selector, with the same meaning as
TYPE:
|
allow_new_levels
|
Permit unseen grouping identities under the selected policy.
TYPE:
|
sample_new_levels
|
Joint donor or Gaussian policy. Explicit
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for separate posterior and group-effect random streams.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Effective thresholds with shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the family is not ordinal or a requested profile crosses. |
Source code in src/quivers/formulas/_fit.py
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 | |
posterior_linpred
¶
posterior_linpred(*, parameter: str = 'mu', transform: bool = False, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> Tensor
Replay a fitted linear predictor on training or fresh predictor rows.
| PARAMETER | DESCRIPTION |
|---|---|
parameter
|
TYPE:
|
transform
|
Return the native inverse-link binding instead of its linear
predictor. For binomial data this is a probability, not a count.
Ordinal probabilities are supplied by
TYPE:
|
new_data
|
Fresh predictor rows evaluated with fitted transforms, contrasts, and known group levels. None reuses the retained training rows. Response and likelihood-weight columns are not required.
TYPE:
|
predictor_data
|
Explicit input for a neural predictor on new rows. Required for neural fits with new_data; otherwise must be None.
TYPE:
|
trials
|
Response trial count or column for prediction rows. Vector count fits infer training totals; fresh rows require explicit totals unless a retained trial column supplies them. Linear predictors do not require totals.
TYPE:
|
re_formula
|
None includes all fitted varying effects;
TYPE:
|
allow_new_levels
|
Permit unseen or missing grouping identities in new_data. Repeated missing values share one new identity per group. Ordinary categorical predictors still require fitted levels.
TYPE:
|
sample_new_levels
|
For each new identity, uncertainty chooses one fitted donor jointly across slopes per posterior draw; old_levels retains one donor across all chains and draws; gaussian samples the fitted conditional zero-mean group law. Existing groups retain their posterior effects. Group and response noise use distinct random streams, and the caller's CPU RNG is restored. Explicit feasible_uncertainty and feasible_gaussian policies condition joint new-group proposals on cumulative row-order support; at most 1024 attempts are made per posterior draw, with an error on failure. Fitted draws and cutpoints are retained.
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
incl_autocor
|
Include an autocorrelation term (brms
TYPE:
|
data2
|
Matrices of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a parameter has no fitted predictor or an ordinal inverse link is requested without its thresholds. |
Source code in src/quivers/formulas/_fit.py
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 | |
posterior_epred
¶
posterior_epred(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, mc_samples: int | None = None, component: Literal['response', 'decision'] = 'response', seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> Tensor
Evaluate native expected responses on training or fresh rows.
| PARAMETER | DESCRIPTION |
|---|---|
new_data
|
Fresh predictor rows using fitted encodings and known levels, or None for training rows. No response or weight column is needed.
TYPE:
|
predictor_data
|
Explicit neural input for new_data, required for neural fits.
TYPE:
|
trials
|
Response trial count or column for prediction rows. Vector count fits infer training totals; fresh rows require explicit totals unless a retained trial column supplies them. Linear predictors do not require totals.
TYPE:
|
re_formula
|
None includes all fitted varying effects;
TYPE:
|
allow_new_levels
|
Permit unseen or missing grouping identities in new_data. Repeated missing values share one new identity per group. Ordinary categorical predictors still require fitted levels.
TYPE:
|
sample_new_levels
|
For each new identity, uncertainty chooses one fitted donor jointly across slopes per posterior draw; old_levels retains one donor across all chains and draws; gaussian samples the fitted conditional zero-mean group law. Existing groups retain their posterior effects. Group and response noise use distinct random streams, and the caller's CPU RNG is restored. Explicit feasible_uncertainty and feasible_gaussian policies condition joint new-group proposals on cumulative row-order support; at most 1024 attempts are made per posterior draw, with an error on failure. Fitted draws and cutpoints are retained.
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
mc_samples
|
Explicit Monte Carlo budget for bounded or certified finite-mean response laws without a closed mean. Sampling uses chunks of at most 64; None requires an analytic expectation. Logistic-normal and Cox response means require a budget.
TYPE:
|
component
|
Wiener response means are positive reaction times, including delay. Decision returns lower/upper probabilities for a decision response.
TYPE:
|
seed
|
Seed for variational draws, restored on exit.
TYPE:
|
incl_autocor
|
Include an autocorrelation term (brms
TYPE:
|
data2
|
Matrices of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Native response means, shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a draw has an undefined or nonfinite response mean. |
TypeError
|
If the native family exposes no expectation, or a circular response would require a specified angular convention. |
Source code in src/quivers/formulas/_fit.py
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 | |
bayes_r2
¶
bayes_r2(*, method: Literal['auto', 'model', 'residual'] = 'auto', observed: Tensor | None = None, **options: Unpack[ExpectationOptions]) -> Tensor
Compute per-draw explained variance on the response scale.
| PARAMETER | DESCRIPTION |
|---|---|
method
|
Model-variance ratios use native conditional means and variances; residual ratios use actual minus expected responses. Auto selects model variances for ordinary Gaussian and Bernoulli responses, and residual variances otherwise. Explicit observations select residual variances under auto.
TYPE:
|
observed
|
Explicit actual responses on row/event axes for the residual method. Otherwise use retained training responses or evaluate their fitted transform in new_data. Censoring bounds cannot stand in for actual responses.
TYPE:
|
**options
|
Shared posterior expectation options, including new_data, group policies, trials, draw counts, and seed. Model variances require analytic native moments; mc_samples applies to residual means.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Ratios on chain, draw, and event axes. Ordinal residual ratios use ordered integer scores. Unordered categories require a separately specified response metric. Zero total variance is NaN. |
Source code in src/quivers/formulas/_fit.py
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 | |
posterior_choice_probs
¶
posterior_choice_probs(**options: Unpack[ExpectationOptions]) -> Tensor
Return joint-model lower/upper decision probabilities.
| PARAMETER | DESCRIPTION |
|---|---|
**options
|
Shared posterior expectation options, including new_data, varying effect selection, draw count, and seed.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Probabilities shaped chain x draw x row x (lower, upper). |
Source code in src/quivers/formulas/_fit.py
pp_mixture
¶
pp_mixture(*, new_data: IntoDataFrame | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', log: bool = False, num_samples: int | None = None, seed: int = 0) -> Tensor
Posterior probabilities of mixture component membership, brms pp_mixture.
P(K = k | y_i) = theta_k p_k(y_i) / sum_j theta_j p_j(y_i) at each
posterior draw, scoring censored rows by their recorded event. Cost:
O(S n K) for S draws, n rows and K components.
| PARAMETER | DESCRIPTION |
|---|---|
new_data
|
Rows with recorded responses and any censoring columns; None scores the training rows.
TYPE:
|
re_formula
|
Varying-effect selector, as for prediction.
TYPE:
|
allow_new_levels
|
Permit unseen grouping levels in
TYPE:
|
sample_new_levels
|
Policy for unseen grouping levels.
TYPE:
|
log
|
Return log probabilities.
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws and new-level policies.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fit is not a mixture model. |
Source code in src/quivers/formulas/_fit.py
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 | |
posterior_response
¶
posterior_response(**options: Unpack[PredictionOptions]) -> ResponseDraws
Draw responses in original measurement coordinates in one replay.
| PARAMETER | DESCRIPTION |
|---|---|
**options
|
Shared posterior_predict options, including new_data, varying effect selection, draw count, and seed.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ResponseDraws
|
Positive reaction time and its joint binary decision for Wiener; ordinary response values with no decision for other families. |
Source code in src/quivers/formulas/_fit.py
hypothesis
¶
hypothesis(expression: str | ContrastExpression | Sequence[str] | Mapping[str, str], *, class_: str | None = 'b', parameter: str = 'mu', group: str | None = None, scope: Literal['standard', 'ranef', 'coef'] = 'standard', prior: bool = False, num_samples: int | None = None, num_prior_samples: int | None = None, seed: int = 0, null: float | int | Tensor = 0.0, probs: Sequence[float] = (0.025, 0.975), robust: bool = False, point: PointNullSpec | None = None, name: str = 'contrast', alpha: float = 0.05) -> HypothesisSummary | HypothesisTable
Test a brms hypothesis string, or evaluate a checked contrast.
A string of the form "left (= | < | >) right", or several such
strings, is a brms hypothesis: every name is prefixed with the
class ("x > 0" tests b_x, and with class_="sd" and
group="g" the name Intercept is sd_g__Intercept), the
sides are R expressions (^, exp), and the result is brms's
table. class_=None reads names as variables reports them.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
brms hypothesis strings (a mapping names them), or a QVR value expression over authored labels, with optional aliases.
TYPE:
|
class_
|
Parameter role such as b, Intercept, sd, cor, or an auxiliary name. The b role includes population intercepts. None selects exact constrained latent site names.
TYPE:
|
parameter
|
Distributional or nonlinear predictor for b, Intercept, and sd.
TYPE:
|
group
|
Grouping factor for scale/correlation filtering or per-level scopes.
TYPE:
|
scope
|
Named parameters, per-level random adjustments, or per-level population plus random coefficients. The latter two require b/group.
TYPE:
|
prior
|
Also evaluate the same contrast on the corresponding joint prior stream, yielding prior-corrected region evidence.
TYPE:
|
num_samples
|
Posterior and prior counts. None follows retained-draw conventions; retained prior samples are reused when available.
TYPE:
|
num_prior_samples
|
Posterior and prior counts. None follows retained-draw conventions; retained prior samples are reused when available.
TYPE:
|
seed
|
Isolated seed for guide or fresh prior draws.
TYPE:
|
null
|
Finite comparison value on event axes only.
TYPE:
|
probs
|
Quantile probabilities, in requested order.
TYPE:
|
robust
|
Return median/scaled MAD rather than mean/sample SD.
TYPE:
|
point
|
Optional marginal point-density comparison using these same joint contrast streams. Requires prior=True and a checked Real result.
TYPE:
|
name
|
Output contrast label.
TYPE:
|
alpha
|
brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HypothesisSummary or HypothesisTable
|
For a brms hypothesis string, brms's table ( |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a hypothesis string is malformed or names a parameter that is not in the model (the message lists the class's parameters), or the contrast selectors match nothing. |
Source code in src/quivers/formulas/_fit.py
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 | |
analysis
¶
analysis(*, num_samples: int | None = None, seed: int = 0) -> PosteriorAnalysis
Prepare reusable posterior summaries and predictive comparisons.
| PARAMETER | DESCRIPTION |
|---|---|
num_samples
|
Maximum MCMC draws per chain or fresh variational draw count.
TYPE:
|
seed
|
Variational seed; the caller's CPU RNG is preserved.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PosteriorAnalysis
|
Retained draws, raw training-row likelihoods, response data, and actual sampler statistics. Later analysis reuses these tensors. |
Source code in src/quivers/formulas/_fit.py
log_likelihood
¶
log_likelihood(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> dict[str, Tensor]
Evaluate raw response log likelihoods on fitted or recorded fresh rows.
| PARAMETER | DESCRIPTION |
|---|---|
new_data
|
Fresh predictors, outcomes, and authored observation-event columns. None scores the fitted rows. Fitting weight columns are not required.
TYPE:
|
predictor_data
|
Neural inputs aligned with fresh rows before any subset selection.
TYPE:
|
trials
|
Existing count-trial override. Fresh vector counts otherwise infer their totals from their recorded components.
TYPE:
|
re_formula
|
Existing varying-effect selector;
TYPE:
|
allow_new_levels
|
Permit fresh grouping identities under the selected prediction policy.
TYPE:
|
sample_new_levels
|
Existing joint donor or conditional Gaussian group-effect policy.
TYPE:
|
num_samples
|
Maximum retained draws per chain, or fresh variational draws.
TYPE:
|
seed
|
Seed for variational draws; the caller's CPU RNG is preserved.
TYPE:
|
incl_autocor
|
Include an autocorrelation term (brms
TYPE:
|
data2
|
Matrices of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Response name to raw scores with shape |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If a hidden response needs a marginal-likelihood observer. |
Source code in src/quivers/formulas/_fit.py
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 | |
posterior_predict
¶
posterior_predict(*, new_data: IntoDataFrame | None = None, predictor_data: Tensor | None = None, trials: int | str | None = None, re_formula: str | None = None, allow_new_levels: bool = False, sample_new_levels: Literal['uncertainty', 'old_levels', 'gaussian', 'feasible_uncertainty', 'feasible_gaussian'] = 'uncertainty', num_samples: int | None = None, seed: int = 0, incl_autocor: bool = True, data2: Mapping[str, AutocorMatrix] | None = None) -> Tensor
Sample native response distributions on training or fresh rows.
| PARAMETER | DESCRIPTION |
|---|---|
new_data
|
Fresh predictor rows using fitted encodings and known levels, or None for training rows. No response or weight column is needed.
TYPE:
|
predictor_data
|
Explicit neural input for new_data, required for neural fits.
TYPE:
|
trials
|
Response trial count or column for prediction rows. Vector count fits infer training totals; fresh rows require explicit totals unless a retained trial column supplies them. Linear predictors do not require totals.
TYPE:
|
re_formula
|
None includes all fitted varying effects;
TYPE:
|
allow_new_levels
|
Permit unseen or missing grouping identities in new_data. Repeated missing values share one new identity per group. Ordinary categorical predictors still require fitted levels.
TYPE:
|
sample_new_levels
|
For each new identity, uncertainty chooses one fitted donor jointly across slopes per posterior draw; old_levels retains one donor across all chains and draws; gaussian samples the fitted conditional zero-mean group law. Existing groups retain their posterior effects. Group and response noise use distinct random streams, and the caller's CPU RNG is restored. Explicit feasible_uncertainty and feasible_gaussian policies condition joint new-group proposals on cumulative row-order support; at most 1024 attempts are made per posterior draw, with an error on failure. Fitted draws and cutpoints are retained.
TYPE:
|
num_samples
|
Maximum draws per MCMC chain, or fresh guide draws, following
TYPE:
|
seed
|
Seed for separate latent and response random streams. The caller's CPU RNG state is restored on return or failure.
TYPE:
|
incl_autocor
|
Include an autocorrelation term (brms
TYPE:
|
data2
|
Matrices of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Predictive responses, shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the requested count or retained posterior layout is invalid. |
TypeError
|
If the response has no native sampling operation. |
Source code in src/quivers/formulas/_fit.py
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 | |
predictor_labels
¶
Label the last axis returned by posterior_linpred for one graph output.
| PARAMETER | DESCRIPTION |
|---|---|
parameter
|
Family parameter or named nonlinear intermediate.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[int or str, ...]
|
Output coordinate order; empty for scalar-row values. Family coordinates use fitted response order, with the ALR reference omitted. Intermediate vectors retain authored label order. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the parameter has no retained predictor or graph binding. |
Source code in src/quivers/formulas/_fit.py
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
TYPE:
|
estimate
|
Mean and standard deviation of the contrast draws, or median and scaled median absolute deviation when robust.
TYPE:
|
est_error
|
Mean and standard deviation of the contrast draws, or median and scaled median absolute deviation when robust.
TYPE:
|
ci_lower
|
Quantiles of the contrast:
TYPE:
|
ci_upper
|
Quantiles of the contrast:
TYPE:
|
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
TYPE:
|
post_prob
|
TYPE:
|
star
|
TYPE:
|
group
|
Level of the grouping factor for the
TYPE:
|
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:
|
samples
|
Contrast draws
TYPE:
|
prior_samples
|
Contrast draws under the prior, when prior draws were available for every row.
TYPE:
|
class_
|
Parameter class prefix without its trailing underscores.
TYPE:
|
alpha
|
The level of the intervals and stars.
TYPE:
|
to_frame
¶
Return the table with brms's column names.
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Columns |
Source code in src/quivers/formulas/_brms_hypothesis.py
__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
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
TYPE:
|
lscale_labels |
brms
TYPE:
|
kernel |
Covariance kernel.
TYPE:
|
frequencies |
TYPE:
|
lscale_priors |
Default prior of each length scale, in
TYPE:
|
inputs |
For an exact GP, the
TYPE:
|
gr |
Whether rows sharing an input share one latent value.
TYPE:
|
dmax |
Divisor applied to the covariates (one when
TYPE:
|
prediction_inputs |
For an exact GP specialized to prediction rows, their
TYPE:
|
exact
property
¶
Report whether the block is brms's exact GP.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True when the block retains its training inputs. |
dimension
property
¶
Count the GP's covariates.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Input dimension |
isotropic
property
¶
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
sites
¶
Name the block's sdgp and lscale latent sites.
| PARAMETER | DESCRIPTION |
|---|---|
prefix
|
Owning predictor namespace.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, tuple[str, ...]]
|
The |
Source code in src/quivers/formulas/_gp.py
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:
|
values
|
Latent function at the training inputs.
TYPE:
|
sdgp
|
Marginal standard deviation.
TYPE:
|
lscales
|
Length scales.
TYPE:
|
Source code in src/quivers/formulas/_gp.py
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
¶
Draw the latent function at the fresh inputs.
| PARAMETER | DESCRIPTION |
|---|---|
sample_shape
|
Leading sample shape. |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Draws with the sample, batch, and event shapes. |
Source code in src/quivers/formulas/_gp.py
log_prob
¶
Score latent values at the fresh inputs.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
Values at the fresh inputs.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Multivariate Normal log density. |
Source code in src/quivers/formulas/_gp.py
MecorSetting
didactic-model
¶
Bases: ValueModel
The me() latent-correlation setting added to a response formula.
| PARAMETER | DESCRIPTION |
|---|---|
mecor
|
Correlate the latent values of
TYPE:
|
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
TYPE:
|
rescor
|
Estimate residual correlation between aligned scalar Gaussian or
Student responses. None applies the brms default (
TYPE:
|
response_names
|
Explicit response coordinate order. None retains mapping insertion order. The order is part of equality, hashing, and serialization.
TYPE:
|
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
TYPE:
|
Retain the responses with an explicit coordinate order.
| PARAMETER | DESCRIPTION |
|---|---|
responses
|
Named responses, copied into a plain dictionary.
TYPE:
|
rescor
|
Estimate residual correlation between aligned responses, or None for the brms default.
TYPE:
|
response_names
|
Explicit response order, or None for the mapping's insertion order.
TYPE:
|
rescor_explicit
|
Whether the setting was given, or None to record whether
TYPE:
|
Source code in src/quivers/formulas/_multivariate.py
__add__
¶
__add__(other: ResponseModel | MultivariateFormula | RescorSetting | MecorSetting) -> MultivariateFormula
Add responses, the residual-correlation, or the me() setting.
| PARAMETER | DESCRIPTION |
|---|---|
other
|
Further responses,
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultivariateFormula
|
The extended specification. |
Source code in src/quivers/formulas/_multivariate.py
response
¶
response(name: str) -> ResponseModel
Return one named response.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Response label.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ResponseModel
|
The response specification. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no response has this label. |
Source code in src/quivers/formulas/_multivariate.py
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
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultivariateFormula
|
The same specification, each response under |
Source code in src/quivers/formulas/_multivariate.py
RescorSetting
didactic-model
¶
Bases: ValueModel
The residual-correlation setting added to a joint formula.
| PARAMETER | DESCRIPTION |
|---|---|
rescor
|
Estimate residual correlations between the responses.
TYPE:
|
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:
|
family
|
Registered family or a configured family value.
TYPE:
|
distributional
|
Existing distributional predictors and nonlinear dependency graph.
TYPE:
|
nonlinear
|
Existing distributional predictors and nonlinear dependency graph.
TYPE:
|
fixed_parameters
|
Auxiliary parameters fixed on their natural scale.
TYPE:
|
weights
|
Ordinary likelihood-weight and decision column shortcuts.
TYPE:
|
decision
|
Ordinary likelihood-weight and decision column shortcuts.
TYPE:
|
binomial_trials
|
Finite count total or trial column, following the ordinary family API.
TYPE:
|
thresholds_by
|
Retained grouping factor for ordinal thresholds.
TYPE:
|
mixture_components
|
Number of components for a finite mixture response.
TYPE:
|
mecor
|
Correlate the latent values of the response's
TYPE:
|
center
|
brms
TYPE:
|
decomp
|
brms
TYPE:
|
default_priors
|
Default prior policy of this response, set from
TYPE:
|
cmc
|
brms
TYPE:
|
sparse
|
brms
TYPE:
|
unused
|
brms
TYPE:
|
family_given
|
Whether the family was stated. A response built by
TYPE:
|
parameter_formulas
|
Authored additive (
TYPE:
|
nonlinear_formulas
|
Authored additive (
TYPE:
|
nl
|
Whether the main formula is a nonlinear expression.
TYPE:
|
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
¶
Return the brms response name derived from the left-hand side.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Left-hand-side variable with non-alphanumeric characters removed. |
__add__
¶
__add__(other: ResponseModel | MultivariateFormula | RescorSetting | MecorSetting | Family | ParameterFormulas) -> MultivariateFormula | ResponseModel
Combine this response with another response, a family, or a setting.
| PARAMETER | DESCRIPTION |
|---|---|
other
|
Further responses, the residual-correlation setting, the
TYPE:
|
| 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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
ResponseModel
|
The response with its authored parameter formulas classified as
distributional or nonlinear under |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an authored parameter formula names neither an auxiliary
parameter of |
Source code in src/quivers/formulas/_multivariate.py
with_parameters
¶
with_parameters(added: ParameterFormulas) -> ResponseModel
Return this response with further parameter formulas.
| PARAMETER | DESCRIPTION |
|---|---|
added
|
The value of
TYPE:
|
| 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 |
Source code in src/quivers/formulas/_multivariate.py
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
TYPE:
|
nonlinear
|
Formulas whose right-hand side is a nonlinear expression, the
arguments of brms
TYPE:
|
nl
|
brms
TYPE:
|
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:
|
program
|
The single compiled joint program.
TYPE:
|
posterior
|
Retained posterior representation.
TYPE:
|
observations
|
Runtime inputs and observations bound to the program.
TYPE:
|
emission
|
The composed emission with its response namespaces.
TYPE:
|
prepared
|
Ordinary preparation of each response, retaining design evaluators.
TYPE:
|
losses
|
SVI losses, empty for MCMC.
TYPE:
|
prior
|
Retained prior result, if one was requested.
TYPE:
|
sample_prior
|
Prior/likelihood scoring policy of the fit.
TYPE:
|
priors
|
Joint prior rules, including response selectors.
TYPE:
|
fixed_prior
|
Default priors of every response preparation.
TYPE:
|
random_scale_prior
|
Default priors of every response preparation.
TYPE:
|
correlation_prior
|
Default priors of every response preparation.
TYPE:
|
group_covariances
|
Known group covariances, keyed by grouping factor.
TYPE:
|
reparameterize
|
Group coordinate policy.
TYPE:
|
preparation_data
|
Original-row snapshot used to rebuild designs.
TYPE:
|
refit_recipe
|
Retained original data and canonical fitting configuration.
TYPE:
|
response_fits
|
Lazily built response views used by row preparation.
TYPE:
|
missing
|
TYPE:
|
missing_specs
|
Recorded and latent coordinates of each
TYPE:
|
data2
|
Named matrices given to
TYPE:
|
criteria
|
Criteria stored by
TYPE:
|
Notes
Equality follows BayesianFit: by value over the specification and
settings, by identity over live objects.
response_names
property
¶
Return the response labels in authored order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
Response labels. |
rescor
property
¶
Report whether residual correlations were estimated.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
The fitted residual-correlation setting. |
qvr_source
property
¶
Return the canonical QVR source of the fitted joint program.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Source emitted from the retained joint module. |
group_levels
property
¶
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
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
brms-named draws on chain and draw axes. |
Source code in src/quivers/formulas/_joint_fit.py
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:
|
parameter
|
TYPE:
|
num_samples
|
Draws per chain under the convention of
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| 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
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:
|
parameter
|
TYPE:
|
num_samples
|
Draws per chain under the convention of
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, Tensor]]
|
Group, then coefficient label, mapped to |
Source code in src/quivers/formulas/_joint_fit.py
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:
|
parameter
|
TYPE:
|
num_samples
|
Draws per chain under the convention of
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, Tensor]]
|
Arrays with the structure of |
Source code in src/quivers/formulas/_joint_fit.py
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:
|
parameter
|
TYPE:
|
transform
|
Return the inverse-link binding instead of the linear predictor.
TYPE:
|
new_data
|
Fresh rows holding every response's predictors, or None.
TYPE:
|
re_formula
|
Varying-effect selector applied to every response.
TYPE:
|
allow_new_levels
|
Permit new grouping identities.
TYPE:
|
sample_new_levels
|
Existing new-level policy, drawn once per shared grouping axis.
TYPE:
|
num_samples
|
Draws per chain under the convention of
TYPE:
|
seed
|
Seed for posterior and group-effect streams.
TYPE:
|
data2
|
Matrices of
TYPE:
|
incl_autocor
|
Include the dependence of residual laws and latent residual
terms (brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Response label mapped to |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a selection, predictor, or row is invalid. |
Source code in src/quivers/formulas/_joint_fit.py
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 | |
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:
|
new_data
|
Fresh rows holding every response's predictors, or None.
TYPE:
|
re_formula
|
Varying-effect selector applied to every response.
TYPE:
|
allow_new_levels
|
Permit new grouping identities.
TYPE:
|
sample_new_levels
|
Existing new-level policy, drawn once per shared grouping axis.
TYPE:
|
num_samples
|
Draws per chain under the convention of
TYPE:
|
mc_samples
|
Monte Carlo budget for responses without a closed mean.
TYPE:
|
seed
|
Seed for posterior, group-effect, and Monte Carlo streams.
TYPE:
|
data2
|
Matrices of
TYPE:
|
incl_autocor
|
Include the dependence of residual laws and latent residual
terms (brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Response label mapped to |
Source code in src/quivers/formulas/_joint_fit.py
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 | |
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:
|
new_data
|
Fresh rows holding every response's predictors, or None.
TYPE:
|
re_formula
|
Varying-effect selector applied to every response.
TYPE:
|
allow_new_levels
|
Permit new grouping identities.
TYPE:
|
sample_new_levels
|
Existing new-level policy, drawn once per shared grouping axis.
TYPE:
|
num_samples
|
Draws per chain under the convention of
TYPE:
|
seed
|
Seed for posterior, group-effect, and response streams.
TYPE:
|
data2
|
Matrices of
TYPE:
|
incl_autocor
|
Include the dependence of residual laws and latent residual
terms (brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Response label mapped to |
Source code in src/quivers/formulas/_joint_fit.py
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 | |
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:
|
new_data
|
Fresh predictors and recorded outcomes of the selected responses, or None for the training rows.
TYPE:
|
re_formula
|
Varying-effect selector applied to every response.
TYPE:
|
allow_new_levels
|
Permit new grouping identities.
TYPE:
|
sample_new_levels
|
Existing new-level policy, drawn once per shared grouping axis.
TYPE:
|
num_samples
|
Draws per chain under the convention of
TYPE:
|
seed
|
Seed for posterior and group-effect streams.
TYPE:
|
data2
|
Matrices of
TYPE:
|
incl_autocor
|
Include the dependence of residual laws and latent residual
terms (brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
One entry keyed by the selected labels joined by |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If summed responses have different row counts. |
Source code in src/quivers/formulas/_joint_fit.py
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 | |
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:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Native response carriers keyed by response. |
Source code in src/quivers/formulas/_joint_fit.py
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
TYPE:
|
num_samples
|
Draws per chain under the convention of
TYPE:
|
seed
|
Seed for variational draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PosteriorAnalysis
|
Native draws, pointwise scores, outcomes, and sampler statistics. |
Source code in src/quivers/formulas/_joint_fit.py
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
TYPE:
|
resp
|
Selected responses, or None for every response.
TYPE:
|
method
|
TYPE:
|
mc_samples
|
Monte Carlo budget of expectations without a closed mean.
TYPE:
|
**options
|
Varying-effect selection, new-level policy, draw count, and seed;
without a grid, brms's
TYPE:
|
| 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
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 | |
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:
|
seed
|
Isolated seed of fresh draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultivariateFit
|
A view sharing the fitted model with the prior as its posterior. |
Source code in src/quivers/formulas/_joint_fit.py
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
TYPE:
|
prior
|
Also evaluate the contrast on joint prior draws.
TYPE:
|
num_samples
|
Posterior and prior draw counts.
TYPE:
|
num_prior_samples
|
Posterior and prior draw counts.
TYPE:
|
seed
|
Isolated seed.
TYPE:
|
null
|
Comparison value.
TYPE:
|
probs
|
Quantile probabilities.
TYPE:
|
robust
|
Use median and scaled MAD.
TYPE:
|
point
|
Optional point-density comparison; requires prior=True.
TYPE:
|
name
|
Output contrast label.
TYPE:
|
class_
|
Class prefix of the names in a brms hypothesis string; None
reads them as
TYPE:
|
group
|
Grouping factor of a brms hypothesis string.
TYPE:
|
scope
|
Scope of a brms hypothesis string.
TYPE:
|
alpha
|
brms
TYPE:
|
| 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
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 | |
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:
|
**overrides
|
Overrides of the canonical
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultivariateFit
|
A fresh fit. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no recipe was retained. |
Source code in src/quivers/formulas/_joint_fit.py
refit_callback
¶
refit_callback(*, method_factory: Callable[[Mapping[str, object], int], Mapping[str, object]], partition: Callable[[IntoDataFrame, tuple[int, ...]], IntoDataFrame] | None = None, num_samples: int | None = None, **prediction: object) -> Callable[[FoldSplit], FoldPrediction]
Adapt 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:
|
partition
|
Optional nonmutating row selection.
TYPE:
|
num_samples
|
Draws per chain for held-out scoring.
TYPE:
|
**prediction
|
Further
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[FoldSplit], FoldPrediction]
|
Callback for |
| 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 |
Source code in src/quivers/formulas/_joint_fit.py
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 | |
dump_qvr
¶
Write the canonical joint QVR source.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Destination.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Path
|
Written path. |
Source code in src/quivers/formulas/_joint_fit.py
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 (
TYPE:
|
fits
|
The per-dataset fits, in dataset order.
TYPE:
|
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__
¶
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:
|
| 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
__dir__
¶
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
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
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
TYPE:
|
data2
|
One mapping of named matrices per dataset; None keeps the template's matrices for every dataset.
TYPE:
|
**overrides
|
Overrides of the canonical
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultipleFit
|
Fresh per-dataset fits and their pooled fit. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the datasets are missing or empty, |
Source code in src/quivers/formulas/_multiple.py
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | |
ResponseDraws
didactic-model
¶
ResponseDraws(*, value: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), decision: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), decision_labels: tuple[str, ...] = ())
Bases: ValueModel
Posterior responses decoded into their original measurement coordinates.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
Response draws preserving chain, draw, row, and event dimensions. Wiener responses are positive reaction times, including nondecision delay.
TYPE:
|
decision
|
Joint binary decisions on the same sample axes, zero lower and one upper; None for a response without a decision modifier.
TYPE:
|
decision_labels
|
Semantic labels of the binary codes, or an empty tuple.
TYPE:
|
PredictionOptions
¶
Bases: TypedDict
Optional prediction keywords shared by native and decoded response draws.
Each key follows BayesianFit.posterior_predict: retained predictor
encodings, group policies, trial counts, draw count, and random seed.
Omitted keys retain that method's defaults.
ExpectationOptions
¶
Bases: PredictionOptions
Optional expectation keywords shared by response and decision means.
Prediction keys follow BayesianFit.posterior_epred. The additional
mc_samples key requests Monte Carlo moments when no closed mean exists.
Decision probabilities always use their closed joint-model probabilities.
KFoldPrediction
didactic-model
¶
KFoldPrediction(*, observed: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), predicted: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), positions: tuple[int, ...])
Bases: ValueModel
Held-out observations and predictions of k-fold refits, as kfold_predict.
| PARAMETER | DESCRIPTION |
|---|---|
observed
|
Observed responses of the predicted units, in original row order.
TYPE:
|
predicted
|
Draws
TYPE:
|
positions
|
Original row position of each predicted unit.
TYPE:
|
KFoldResult
didactic-model
¶
KFoldResult(*, estimate: ELPDEstimate = field(opaque=True, extras=OPAQUE_BY_VALUE), cross_validation: CrossValidationResult = field(opaque=True, extras=OPAQUE_BY_IDENTITY), data: IntoDataFrame = field(opaque=True, extras=OPAQUE_BY_IDENTITY), positions: tuple[int, ...], fold_type: str, joint_fit: bool, resp: str | tuple[str, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))
Bases: ValueModel
A brms kfold result: the criterion, its refits and its partition.
| PARAMETER | DESCRIPTION |
|---|---|
estimate
|
The k-fold criterion.
TYPE:
|
cross_validation
|
Held-out scores, the partition, and the refits when saved.
TYPE:
|
data
|
Original rows of the fitted model.
TYPE:
|
positions
|
Original row position of every partitioned unit.
TYPE:
|
fold_type
|
TYPE:
|
joint_fit
|
Whether the refits are joint fits.
TYPE:
|
resp
|
Joint response selection of the scores.
TYPE:
|
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:
|
family
|
Family description.
TYPE:
|
nobs
|
Number of observations used in fitting.
TYPE:
|
ngrps
|
Number of levels of each grouping factor.
TYPE:
|
algorithm
|
TYPE:
|
chains
|
Chains, retained draws per chain, and warmup iterations per chain.
TYPE:
|
iterations
|
Chains, retained draws per chain, and warmup iterations per chain.
TYPE:
|
warmup
|
Chains, retained draws per chain, and warmup iterations per chain.
TYPE:
|
total_ndraws
|
Retained draws pooled over chains.
TYPE:
|
fixed
|
Population coefficients, named without their
TYPE:
|
spec_pars
|
Unregressed family parameters (
TYPE:
|
random
|
Per grouping factor,
TYPE:
|
splines
|
Smoothing standard deviations of
TYPE:
|
rescor
|
Residual correlations of a joint fit,
TYPE:
|
other
|
Native QVR sites without a brms counterpart.
TYPE:
|
divergences
|
Divergent transitions after warmup, zero without recorded chains.
TYPE:
|
VarCorrBlock
didactic-model
¶
VarCorrBlock(*, labels: tuple[str, ...], sd: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), cor: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), cov: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), sd_draws: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), cor_draws: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), cov_draws: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
Standard deviations, correlations and covariances of one block.
| PARAMETER | DESCRIPTION |
|---|---|
sd
|
Summary of the standard deviations, one row per coefficient.
TYPE:
|
cor
|
Three-way summaries
TYPE:
|
cov
|
Three-way summaries
TYPE:
|
sd_draws
|
Draws
TYPE:
|
cor_draws
|
Draws
TYPE:
|
cov_draws
|
Draws
TYPE:
|
labels
|
Coefficient labels.
TYPE:
|
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
TYPE:
|
diffs
|
The comparison table, best model first (brms's
TYPE:
|
BrmsConditionalEffects
didactic-model
¶
BrmsConditionalEffects(*, effects: tuple[EffectFrame, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), smooths_only: bool = False)
Bases: ValueModel
Conditional effects of one call, as a brms_conditional_effects list.
| PARAMETER | DESCRIPTION |
|---|---|
effects
|
Effects in brms's order.
TYPE:
|
smooths_only
|
Whether the effects are smooth contributions (
TYPE:
|
names
¶
Return the effect names in order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
brms's list names. |
__getitem__
¶
__getitem__(name: str) -> EffectFrame
Return one effect by name.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
brms's list name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectFrame
|
The effect. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If no effect has the name. |
Source code in src/quivers/formulas/_brms_effects.py
frames
¶
Return every effect's data frame by name.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, DataFrame]
|
brms's data frames. |
Source code in src/quivers/formulas/_brms_effects.py
EffectFrame
didactic-model
¶
EffectFrame(*, name: str, effects: tuple[str, ...], response: str, frame: DataFrame = field(opaque=True, extras=OPAQUE_BY_IDENTITY), draws: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), surface: bool = False, categorical: bool = False, spaghetti: DataFrame | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), points: DataFrame | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
One conditional effect, as an element of brms_conditional_effects.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
brms's list name: the effects joined by
TYPE:
|
effects
|
Plotted variables in plotting order;
TYPE:
|
response
|
Response, distributional parameter, or nonlinear parameter predicted.
TYPE:
|
frame
|
Grid and condition columns,
TYPE:
|
draws
|
Prediction draws
TYPE:
|
surface
|
Whether both effects are numeric and plotted as a surface.
TYPE:
|
categorical
|
Whether rows are per category.
TYPE:
|
spaghetti
|
One row per draw and grid row with
TYPE:
|
points
|
Observed data assigned to conditions, with
TYPE:
|
BayesFactor
didactic-model
¶
Bases: ValueModel
A Bayes factor of two models, as a bf_bridge object.
| PARAMETER | DESCRIPTION |
|---|---|
bf
|
:math:
TYPE:
|
log
|
Whether
TYPE:
|
numerator
|
Names of the numerator and denominator models.
TYPE:
|
denominator
|
Names of the numerator and denominator models.
TYPE:
|
PosteriorAverage
didactic-model
¶
PosteriorAverage(*, draws: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), weights: dict[str, float], ndraws: dict[str, int])
Bases: ValueModel
Model-averaged posterior draws, as brms posterior_average.
| PARAMETER | DESCRIPTION |
|---|---|
draws
|
Pooled draws
TYPE:
|
weights
|
Normalized model weights.
TYPE:
|
ndraws
|
Draws contributed by each model.
TYPE:
|
to_frame
¶
Return the draws as brms's data frame, one column per variable.
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
One row per pooled draw. |
Source code in src/quivers/formulas/_model_averaging.py
PredictionAverage
didactic-model
¶
PredictionAverage(*, draws: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), weights: dict[str, float], ndraws: dict[str, int], summary: SummaryTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
Model-averaged predictions, as brms pp_average.
| PARAMETER | DESCRIPTION |
|---|---|
draws
|
Pooled prediction draws
TYPE:
|
weights
|
Normalized model weights.
TYPE:
|
ndraws
|
Draws contributed by each model.
TYPE:
|
summary
|
brms's summary of the pooled draws, when requested.
TYPE:
|
PPCheck
didactic-model
¶
PPCheck(*, type: str, prefix: Prefix, data: DataFrame = field(opaque=True, extras=OPAQUE_BY_IDENTITY), y: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), yrep: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), draw_ids: tuple[int, ...] = (), group: tuple[str | int | float | bool, ...] | None = None, x: tuple[str | int | float | bool, ...] | None = None, status: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), log_weights: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), log_likelihood: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), pit: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
The data behind one predictive check, as brms pp_check prepares it.
| PARAMETER | DESCRIPTION |
|---|---|
type
|
bayesplot type without its prefix.
TYPE:
|
prefix
|
Posterior predictive check or predictive distribution.
TYPE:
|
data
|
bayesplot's table for the type (see the
TYPE:
|
y
|
Observed responses
TYPE:
|
yrep
|
Predictive draws
TYPE:
|
draw_ids
|
Pooled 0-based draws used.
TYPE:
|
group
|
Group label per observation.
TYPE:
|
x
|
Covariate per observation.
TYPE:
|
status
|
Event indicator of censored responses (
TYPE:
|
log_weights
|
Normalized PSIS log weights
TYPE:
|
log_likelihood
|
Pointwise log-likelihoods
TYPE:
|
pit
|
PIT or LOO-PIT values per observation.
TYPE:
|
to_datatree
¶
Return an ArviZ data tree of the check.
| RETURNS | DESCRIPTION |
|---|---|
DataTree
|
|
Source code in src/quivers/formulas/_pp_check.py
plot
¶
Draw the check with its ArviZ counterpart.
| PARAMETER | DESCRIPTION |
|---|---|
backend
|
ArviZ plotting backend (
TYPE:
|
**kwargs
|
Further keyword arguments of the ArviZ function.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PlotCollection
|
The plot. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If ArviZ has no counterpart of the type; its data remain in |
Source code in src/quivers/formulas/_pp_check.py
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:
|
prior
|
Effective prior: a canonical QVR distribution call,
TYPE:
|
class_
|
Parameter class.
TYPE:
|
coef
|
brms
TYPE:
|
group
|
brms
TYPE:
|
response
|
brms
TYPE:
|
dpar
|
brms
TYPE:
|
nlpar
|
brms
TYPE:
|
lower
|
brms
TYPE:
|
upper
|
brms
TYPE:
|
tag
|
brms
TYPE:
|
source
|
Whether a user rule or the default policy set the prior.
TYPE:
|
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:
|
policy
|
Default policy that filled sites no user rule selects.
TYPE:
|
to_pandas
¶
Return the table with brms's column names.
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Columns |
Source code in src/quivers/formulas/_brms_priors.py
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
TYPE:
|
single_path_draws
|
Draws per path (cmdstanr
TYPE:
|
history_size
|
L-BFGS history size.
TYPE:
|
max_lbfgs_iters
|
Maximum L-BFGS iterations per path.
TYPE:
|
num_elbo_draws
|
Draws per ELBO estimate.
TYPE:
|
psis_resample
|
Whether to importance resample across paths.
TYPE:
|
calculate_lp
|
Whether to evaluate the log density at the returned draws; without it, no resampling takes place.
TYPE:
|
save_single_paths
|
Whether to keep each path's draws.
TYPE:
|
init_alpha
|
L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.
TYPE:
|
tol_obj
|
L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.
TYPE:
|
tol_rel_obj
|
L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.
TYPE:
|
tol_grad
|
L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.
TYPE:
|
tol_rel_grad
|
L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.
TYPE:
|
tol_param
|
L-BFGS first step length and convergence tolerances, as CmdStan's optimizer.
TYPE:
|
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
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:
|
max_treedepth
|
Maximum NUTS tree depth (at most
TYPE:
|
stepsize
|
Initial step size before adaptation; None keeps the kernel default.
TYPE:
|
metric
|
Diagonal, dense, or unit Euclidean metric (mass matrix).
TYPE:
|
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:
|
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:
|
ImproperFlat
didactic-model
¶
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:
|
data
|
Pandas, polars, or any other Narwhals-compatible dataframe.
TYPE:
|
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:
|
decision
|
Binary decision column, numeric 0/1 or lower/upper labels. Equivalent
to
TYPE:
|
groups
|
Additional grouping columns retained for structural parameters without adding varying coefficients to the predictor.
TYPE:
|
extra_namespace
|
Additional names visible inside the formula's expression evaluation, merged on top of the R-style transforms.
TYPE:
|
data2
|
Named matrices the formula reads, such as the
TYPE:
|
| 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 |
Source code in src/quivers/formulas/formula.py
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 | |
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:
TYPE:
|
link
|
Link of the location parameter. None keeps the family's default.
TYPE:
|
threshold
|
Threshold structure of an ordinal family.
TYPE:
|
refcat
|
Reference category of a categorical or vector family.
TYPE:
|
**links
|
Links of auxiliary parameters, keyed
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Family
|
The configured family, for |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the family is unknown, an option does not apply to it, a keyword
is not |
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
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
TYPE:
|
nmix
|
Number of repetitions of each component, brms
TYPE:
|
order
|
Identification by ordered location intercepts.
TYPE:
|
equal
|
Parameters set equal to another parameter of the same class, brms
TYPE:
|
| 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, |
Source code in src/quivers/formulas/_mixture.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
update_adterms
¶
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
TYPE:
|
adform
|
The new terms as a one-sided formula,
TYPE:
|
action
|
Keep unrelated existing terms, or drop them all.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str or ResponseModel
|
The edited formula, of the same kind as |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/formulas/_addition_terms.py
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:
|
| 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
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:
|
catalog
|
Immutable semantic contracts and native distribution factories.
TYPE:
|
location
|
Native parameter receiving the linked main predictor named
TYPE:
|
link
|
Existing inverse link for that predictor.
TYPE:
|
auxiliary
|
Other native parameters, with ordinary priors and distributional links.
A mapping separates native names from formula names, for instance
native
TYPE:
|
data
|
Native parameters supplied by typed numeric data columns. These enter the existing predictor graph as deterministic identity-linked roots.
TYPE:
|
| 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
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | |
fit
¶
fit(formula: MultivariateFormula, *, data: IntoDataFrame, **options: Unpack[JointFitOptions]) -> MultivariateFit
fit(formula: str | ResponseModel, *, data: IntoDataFrame, **options: Unpack[FormulaFitOptions]) -> BayesianFit
fit(formula: None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str], response: str, entry: str | None = None, static: Mapping[str, int] | None = None, **options: Unpack[FormulaFitOptions]) -> BayesianFit
fit(formula: str | ResponseModel | MultivariateFormula | None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str] | None = None, entry: str | None = None, static: Mapping[str, int] | None = None, parameters: Mapping[str, str | NonlinearExpression] | None = None, response: str | None = None, family: str | Family = 'gaussian', weights: str | None = None, decision: str | None = None, data2: Mapping[str, AutocorMatrix] | None = None, distributional: Mapping[str, str | NonlinearExpression] | None = None, nonlinear: Mapping[str, str | NonlinearExpression] | None = None, fixed_parameters: Mapping[str, float] | None = None, method: FitMethod = 'nuts', num_warmup: int | None = None, num_samples: int | None = None, num_chains: int | None = None, num_steps: int | None = None, learning_rate: float = 0.01, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, priors: PriorInput | None = None, guide: type | None = None, initial_values: Mapping[str, Tensor | float] | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor: Module | None = None, predictor_data: Tensor | None = None, seed: int = 0, sample_prior: PriorMode = 'no', num_prior_samples: int = 100, prior_seed: int | None = None, snapshot_policy: SnapshotPolicy = 'clone', default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: Sequence[str] = (), control: SamplerControl | Mapping[str, float | int | str] | None = None, thin: int = 1, init: InitSpec | None = None, init_r: float = 2.0, algorithm: Algorithm | None = None, file: str | Path | None = None, file_refit: FileRefit = 'never', pathfinder: PathfinderOptions | Mapping[str, float | int | bool] | None = None, cores: int = 1, knots: Knots | None = None, drop_unused_levels: bool = True) -> BayesianFit | MultivariateFit
Compile a brms-style formula, fit it, and return the result.
See quivers.formulas for surface details. This entry
point composes formula_from_data, FormulaToQVRModule,
Compiler, and the inference layer in one call.
family="categorical" uses the sorted distinct integer labels or the
declared factor levels and takes the first category as the default
reference. An attached categorical predictor may return
(N, K-1) reference logits or (N, K) full logits. For
family="mixture", mixture_components selects any finite component
count of at least two; the likelihood integrates assignments exactly.
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
brms/lme4-style response formula, or a joint formula built with
TYPE:
|
data
|
Pandas, Polars, or another Narwhals-compatible dataframe.
TYPE:
|
program
|
QVR source, or a source file path and a program name. With source
text alone, the one program or the one exported program is selected.
The program's observation of
TYPE:
|
entry
|
The program name when it is given separately from the source text.
TYPE:
|
static
|
Finite extents of the program, by binder name.
TYPE:
|
parameters
|
Formulas of the program's parameters, as
TYPE:
|
response
|
The site the program observes, a data column.
TYPE:
|
family
|
Registered response family or a family value.
TYPE:
|
weights
|
Numeric column of finite nonnegative likelihood weights. Values multiply each response's log density, retain their original scale, and do not weight priors or posterior predictions.
TYPE:
|
decision
|
Wiener boundary-choice column: numeric zero/lower or one/upper, or the labels lower and upper. Equivalent to response-side dec(column).
TYPE:
|
nonlinear
|
Named additive parameter designs or deterministic QVR expressions. Supplying this mapping interprets the response RHS as a value expression. Defaults retain the same proper coefficient priors as ordinary QVR formulas; get_prior reports their exact site names.
TYPE:
|
data2
|
Named matrices referenced by autocorrelation terms, as in brms:
the spatial weights of
TYPE:
|
distributional
|
Auxiliary-parameter formulas, for instance
TYPE:
|
fixed_parameters
|
Auxiliary parameters held constant on their natural scale, for instance
TYPE:
|
method
|
Inference algorithm.
TYPE:
|
num_warmup
|
MCMC warmup iterations per chain (NUTS and HMC only); 500 when omitted.
TYPE:
|
num_samples
|
MCMC draws kept per chain after warmup (NUTS and HMC only); 1000 when omitted.
TYPE:
|
num_chains
|
MCMC chains (NUTS and HMC only), or Pathfinder paths as brms's
TYPE:
|
num_steps
|
SVI optimization steps (SVI only); 1000 when omitted.
TYPE:
|
learning_rate
|
The Adam learning rate of the SVI optimizer (SVI only).
TYPE:
|
fixed_prior
|
Prior of every fixed-effect coefficient.
TYPE:
|
random_scale_prior
|
Prior of every random-effect standard deviation.
TYPE:
|
correlation_prior
|
Default prior for correlated group blocks, in LKJ Cholesky form. Explicit shared IDs join coefficients across distributional formulas.
TYPE:
|
group_covariances
|
Known covariance between labeled levels, keyed by grouping factor. The same declaration serves compilation, inspection, and prediction.
TYPE:
|
priors
|
Named overrides or typed selectors, including sampled shrinkage hierarchies. Unknown, unused, or ambiguous rules raise ValueError.
TYPE:
|
guide
|
The SVI guide class;
TYPE:
|
initial_values
|
Natural-scale starting values keyed by latent site, including
coefficient names. Scalars broadcast to a site's declared shape.
Values must lie strictly inside the prior support. MCMC applies
these after its seeded initial strategy; SVI passes them to the
guide constructor. A custom guide must accept this keyword when
values are supplied. For a regressed shifted-lognormal or Wiener
TYPE:
|
reparameterize
|
Parameterization of the random effects.
TYPE:
|
binomial_trials
|
Trials per row for binomial or beta-binomial responses: a constant or a column.
TYPE:
|
thresholds_by
|
Column grouping the cutpoints of an ordinal family.
TYPE:
|
mixture_components
|
Number of Gaussian components for the mixture family.
TYPE:
|
predictor
|
Optional differentiable contribution on the linear-predictor scale.
TYPE:
|
predictor_data
|
Input passed to
TYPE:
|
seed
|
Seed for compilation and inference. The caller's CPU random state is restored on return or failure.
TYPE:
|
sample_prior
|
Fit the posterior, additionally retain independent prior draws, or disable observation likelihoods during inference. Priors, their data dependencies, support constraints, and explicit potentials remain.
TYPE:
|
num_prior_samples
|
Positive independent draw budget for mode "yes".
TYPE:
|
prior_seed
|
Isolated prior stream. None uses seed + 1 modulo 2**64. Retaining prior draws does not change fitted posterior draws or losses.
TYPE:
|
snapshot_policy
|
Retain one independent original-data snapshot for update/refit by default. Reference mode shares caller data explicitly. Predictor initial states are copied before each refit, so fits do not share trained mutable parameters.
TYPE:
|
default_priors
|
Default prior policy: the proper, autoscaled quivers defaults, or
TYPE:
|
center
|
brms
TYPE:
|
decomp
|
brms
TYPE:
|
cmc
|
brms
TYPE:
|
sparse
|
brms
TYPE:
|
unused
|
brms
TYPE:
|
control
|
brms
TYPE:
|
thin
|
Keep every
TYPE:
|
init
|
brms
TYPE:
|
init_r
|
Half-width of
TYPE:
|
algorithm
|
brms
TYPE:
|
file
|
brms
TYPE:
|
file_refit
|
brms
TYPE:
|
pathfinder
|
cmdstanr
TYPE:
|
cores
|
brms
TYPE:
|
knots
|
brms
TYPE:
|
drop_unused_levels
|
brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesianFit or MultivariateFit
|
Parsed formula, compiled program, fitted posterior, and observations;
a |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the family is unknown, a predictor and its data are not given
together, a trainable predictor is used without SVI, or a count
is given to a method it does not apply to ( |
Source code in src/quivers/formulas/_fit.py
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 | |
formula_to_qvr
¶
formula_to_qvr(formula: str | ResponseModel | MultivariateFormula | None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str] | None = None, entry: str | None = None, static: Mapping[str, int] | None = None, parameters: Mapping[str, str | NonlinearExpression] | None = None, response: str | None = None, family: str | Family = 'gaussian', weights: str | None = None, decision: str | None = None, data2: Mapping[str, AutocorMatrix] | None = None, distributional: Mapping[str, str | NonlinearExpression] | None = None, nonlinear: Mapping[str, str | NonlinearExpression] | None = None, fixed_parameters: Mapping[str, float] | None = None, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, priors: PriorInput | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor_name: str | None = None, default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: Sequence[str] = (), path: str | Path | None = None, knots: Knots | None = None, drop_unused_levels: bool = True) -> str
Emit .qvr source for a brms-style formula without fitting.
Builds the formula AST β QVR Module via FormulaToQVRModule,
then serialises the module via quivers.dsl.emit.module_to_source.
Optionally writes the result to path. mixture_components selects
any integer component count of at least two for family="mixture".
distributional maps auxiliary names to formulas, for instance
{"sigma": "~ z"}; the corresponding linked predictors are emitted
in the same QVR program as the location formula. fixed_parameters
instead binds auxiliary parameters to constants on their natural scale.
weights="column" retains nonnegative likelihood weights and emits
them only on the response observation; priors and predictions are unweighted.
decision="column" or rt | dec(column) ~ predictors retains a Wiener
boundary choice alongside positive reaction times. Emitted source visibly
adapts raw times and Boolean choices to a lossless signed response.
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
Authored formula over original dataframe rows, a single-response
TYPE:
|
data
|
Original training columns, including response modifiers.
TYPE:
|
program
|
QVR source, or a source file path and a program name, as in
TYPE:
|
entry
|
The program name when it is given separately from the source text.
TYPE:
|
static
|
Finite extents of the program, by binder name.
TYPE:
|
parameters
|
Formulas of the program's parameters, by name.
TYPE:
|
response
|
The site the program observes.
TYPE:
|
family
|
Checked response law and retained link, threshold, and event choices.
TYPE:
|
weights
|
Optional existing response-role columns.
TYPE:
|
decision
|
Optional existing response-role columns.
TYPE:
|
data2
|
Named matrices referenced by autocorrelation terms, as in brms:
the spatial weights of
TYPE:
|
distributional
|
Auxiliary designs and checked derived predictor graph.
TYPE:
|
nonlinear
|
Auxiliary designs and checked derived predictor graph.
TYPE:
|
fixed_parameters
|
Bound auxiliary constants.
TYPE:
|
fixed_prior
|
Defaults consumed by the existing typed prior catalog.
TYPE:
|
random_scale_prior
|
Defaults consumed by the existing typed prior catalog.
TYPE:
|
correlation_prior
|
Defaults consumed by the existing typed prior catalog.
TYPE:
|
group_covariances
|
Known group covariance structures.
TYPE:
|
priors
|
Typed selectors or existing exact-name overrides.
TYPE:
|
reparameterize
|
Shared group coordinate policy.
TYPE:
|
binomial_trials
|
Finite-trial count or retained column.
TYPE:
|
thresholds_by
|
Group with an identified full threshold profile.
TYPE:
|
mixture_components
|
Finite-mixture component count.
TYPE:
|
predictor_name
|
Checked external neural binding.
TYPE:
|
default_priors
|
Default prior policy: the proper, autoscaled quivers defaults, or
TYPE:
|
center
|
brms
TYPE:
|
decomp
|
brms
TYPE:
|
cmc
|
brms
TYPE:
|
sparse
|
brms
TYPE:
|
unused
|
brms
TYPE:
|
knots
|
brms
TYPE:
|
drop_unused_levels
|
brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Canonical checked source, without fitting a posterior. |
Source code in src/quivers/formulas/_fit.py
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 | |
get_prior
¶
get_prior(formula: str | ResponseModel | MultivariateFormula | None = None, *, data: IntoDataFrame, program: str | tuple[str | Path, str] | None = None, entry: str | None = None, static: Mapping[str, int] | None = None, parameters: Mapping[str, str | NonlinearExpression] | None = None, response: str | None = None, family: str | Family = 'gaussian', weights: str | None = None, decision: str | None = None, data2: Mapping[str, AutocorMatrix] | None = None, distributional: Mapping[str, str | NonlinearExpression] | None = None, nonlinear: Mapping[str, str | NonlinearExpression] | None = None, fixed_parameters: Mapping[str, float] | None = None, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, priors: PriorInput | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor_name: str | None = None, default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none', cmc: bool = True, sparse: bool = False, unused: Sequence[str] = (), knots: Knots | None = None, drop_unused_levels: bool = True) -> dict[str, str]
Return effective named priors without running inference.
The arguments match formula_to_qvr, except for its output path.
Priors reflect evaluated design columns, selected links, distributional
formulas, group correlations, and explicit overrides. Default coefficient
scales include column autoscaling; explicit overrides are emitted as given.
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
Response formula in brms/lme4 notation, a single-response
TYPE:
|
data
|
Rows used to evaluate design matrices and autoscale default priors.
TYPE:
|
program
|
QVR source, or a source file path and a program name, as in
TYPE:
|
entry
|
The program name when it is given separately from the source text.
TYPE:
|
static
|
Finite extents of the program, by binder name.
TYPE:
|
parameters
|
Formulas of the program's parameters, by name.
TYPE:
|
response
|
The site the program observes.
TYPE:
|
family
|
Registered response family or a family value with selected links.
TYPE:
|
weights
|
Numeric column of finite nonnegative likelihood weights. Values multiply each response's log density, retain their original scale, and do not weight priors or posterior predictions.
TYPE:
|
decision
|
Wiener boundary-choice column, equivalent to response-side dec(column). Numeric codes must be exactly zero/lower or one/upper.
TYPE:
|
data2
|
Named matrices referenced by autocorrelation terms, as in brms:
the spatial weights of
TYPE:
|
distributional
|
Separate formulas for auxiliary parameters.
TYPE:
|
fixed_parameters
|
Auxiliary parameters held constant; these have no prior entries.
TYPE:
|
fixed_prior
|
Default coefficient, group-scale, and LKJ Cholesky priors.
TYPE:
|
random_scale_prior
|
Default coefficient, group-scale, and LKJ Cholesky priors.
TYPE:
|
correlation_prior
|
Default coefficient, group-scale, and LKJ Cholesky priors.
TYPE:
|
group_covariances
|
Known covariance between labeled levels, keyed by grouping factor. The same declaration serves compilation, inspection, and prediction.
TYPE:
|
priors
|
Named overrides or typed selectors, including sampled shrinkage hierarchies. Unknown, unused, or ambiguous rules raise ValueError.
TYPE:
|
reparameterize
|
Group parameterization; its conditional draws are not overrideable.
TYPE:
|
binomial_trials
|
Fixed trial count or a column of counts.
TYPE:
|
thresholds_by
|
Grouping column for ordinal cutpoints.
TYPE:
|
mixture_components
|
Number of Gaussian mixture components.
TYPE:
|
predictor_name
|
External contribution on the linear-predictor scale.
TYPE:
|
default_priors
|
Default prior policy: the proper, autoscaled quivers defaults, or
TYPE:
|
center
|
brms
TYPE:
|
decomp
|
brms
TYPE:
|
cmc
|
brms
TYPE:
|
sparse
|
brms
TYPE:
|
unused
|
brms
TYPE:
|
knots
|
brms
TYPE:
|
drop_unused_levels
|
brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, str]
|
Actual overrideable site names and canonical prior calls. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a formula or family setting is invalid, or a prior is unused. |
Source code in src/quivers/formulas/_fit.py
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 | |
conditional_smooths
¶
conditional_smooths(fitted: SingleFit, term: str, new_data: IntoDataFrame, *, parameter: str = 'mu', num_samples: int | None = None, seed: int = 0, draws: Mapping[str, Tensor] | None = None, site_prefix: str = '') -> Tensor
Evaluate one smooth's posterior contribution to its linear predictor.
The contribution is the smooth's unpenalized columns times their
population coefficients plus each penalized block times its scale and
innovations, evaluated through the retained training basis, as brms's
conditional_smooths reports. For an approximate gp() term it is
the retained eigenfunction basis times sqrt(spd) * zgp of every
sub-GP, which brms reports through conditional_effects. For an exact
gp() term each draw's latent function is drawn at the rows' distinct
inputs given its training values, as brms's .predictor_gp_new does,
at O(u^3 + u^2 m + u m^2 + m^3) per draw for u training and m
fresh inputs. Other terms, the intercept, and the
inverse link are excluded. Costs O(draws times rows times basis width).
| PARAMETER | DESCRIPTION |
|---|---|
fitted
|
Fitted formula model.
TYPE:
|
term
|
Smooth or GP term exactly as the fitted formula's evaluator names
it, for instance
TYPE:
|
new_data
|
Rows holding the smooth's covariates and any
TYPE:
|
parameter
|
TYPE:
|
num_samples
|
Draw count under the convention of
TYPE:
|
seed
|
Seed for variational draws and for the latent function of an exact
TYPE:
|
draws
|
Explicit constrained draws to read in place of the fit's own.
TYPE:
|
site_prefix
|
Namespace of that response's sites within
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Contributions with shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fit is joint, the term is not a fitted smooth of the predictor, or the rows are invalid for its retained basis. |
Source code in src/quivers/formulas/_smooth_effects.py
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
TYPE:
|
*formulas
|
Formulas for distributional parameters (
TYPE:
|
program
|
QVR source, or a source file path and a program name, as in
TYPE:
|
entry
|
The program name when it is given separately from the source text.
TYPE:
|
static
|
Finite extents of the program, by binder name.
TYPE:
|
parameters
|
Formulas of the program's parameters, by name.
TYPE:
|
response
|
The site the program observes.
TYPE:
|
family
|
Response family of every response built by this call. None leaves
the family to the entry point (
TYPE:
|
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:
|
fixed_parameters
|
Auxiliary parameters fixed on their natural scale.
TYPE:
|
weights
|
Ordinary response-role shortcuts.
TYPE:
|
decision
|
Ordinary response-role shortcuts.
TYPE:
|
binomial_trials
|
Ordinary response-role shortcuts.
TYPE:
|
thresholds_by
|
Ordinary response-role shortcuts.
TYPE:
|
mixture_components
|
Component count of a finite mixture response.
TYPE:
|
center
|
brms
TYPE:
|
decomp
|
brms
TYPE:
|
cmc
|
brms
TYPE:
|
sparse
|
brms
TYPE:
|
unused
|
brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ResponseModel or MultivariateFormula
|
One response; a joint formula for an |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a parameter formula lacks a left-hand side, names a nonlinear
parameter without |
Source code in src/quivers/formulas/_multivariate.py
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 | |
lf
¶
lf(*formulas: str) -> ParameterFormulas
Give additive parameter formulas to add to a response, as brms lf.
| PARAMETER | DESCRIPTION |
|---|---|
*formulas
|
Formulas such as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ParameterFormulas
|
A value added to a |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a formula lacks a named left side. |
Source code in src/quivers/formulas/_multivariate.py
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:
|
rescor
|
Residual-correlation setting. None keeps a setting carried by a joint part, and otherwise applies the brms default.
TYPE:
|
| 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
nlf
¶
nlf(*formulas: str) -> ParameterFormulas
Give nonlinear parameter formulas to add to a response, as brms nlf.
| PARAMETER | DESCRIPTION |
|---|---|
*formulas
|
Formulas such as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ParameterFormulas
|
A value added to a |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a formula lacks a named left side. |
Source code in src/quivers/formulas/_multivariate.py
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
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MecorSetting
|
A value added to a response or joint formula with |
Source code in src/quivers/formulas/_multivariate.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
ParameterFormulas
|
A value added to a |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
Source code in src/quivers/formulas/_multivariate.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
RescorSetting
|
A value added to a joint formula with |
Source code in src/quivers/formulas/_multivariate.py
combine_models
¶
combine_models(*fits: BayesianFit) -> BayesianFit
combine_models(*fits: MultivariateFit) -> MultivariateFit
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:
|
| 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
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:
|
data
|
Imputed datasets, for instance from a multiple-imputation package.
TYPE:
|
combine
|
brms
TYPE:
|
**options
|
Every other
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultipleFit or tuple
|
Per-dataset fits and the pooled fit, or the per-dataset fits alone
with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no dataset is given or a combined fit is requested with SVI. |
TypeError
|
If |
Source code in src/quivers/formulas/_multiple.py
kfold_predict
¶
kfold_predict(result: KFoldResult, *, method: str = 'posterior_predict', resp: str | None = None, num_samples: int | None = None, seed: int = 0) -> KFoldPrediction
Predict held-out rows from their own k-fold refits, as brms kfold_predict.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
A
TYPE:
|
method
|
TYPE:
|
resp
|
Response of a joint fit; None for a single response.
TYPE:
|
num_samples
|
Draws per chain of each refit.
TYPE:
|
seed
|
Prediction seed.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KFoldPrediction
|
Observed responses and predictions of every held-out row, ordered by original row; new group levels are sampled from the fitted Gaussian group law, as brms. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the refits were not saved or draw counts differ between folds. |
Source code in src/quivers/formulas/_postprocess_methods.py
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 | |
loo_compare
¶
loo_compare(models: Mapping[str, ModelInput], *, criterion: Literal['loo', 'waic', 'kfold'] = 'loo') -> SummaryTable
Compare models by a stored criterion, as brms loo_compare.
| PARAMETER | DESCRIPTION |
|---|---|
models
|
Named fits holding the criterion from
TYPE:
|
criterion
|
Criterion to compare.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SummaryTable
|
The loo package's comparison table, best model first. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a fit has no stored criterion, or the models score different data. |
Source code in src/quivers/formulas/_postprocess_methods.py
loo_model_weights
¶
loo_model_weights(models: Mapping[str, ModelInput], *, method: Literal['stacking', 'pseudobma'] = 'stacking', bayesian_bootstrap: bool = True, seed: int = 0) -> dict[str, float]
Return stacking or pseudo-BMA weights, as brms loo_model_weights.
| PARAMETER | DESCRIPTION |
|---|---|
models
|
Named fits or PSIS-LOO estimates; fits without a stored
TYPE:
|
method
|
Weighting method.
TYPE:
|
bayesian_bootstrap
|
Bayesian-bootstrap regularization of pseudo-BMA weights (loo's
TYPE:
|
seed
|
Seed of the Bayesian bootstrap.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float]
|
Weights summing to one. |
Source code in src/quivers/formulas/_postprocess_methods.py
model_weights
¶
model_weights(models: Mapping[str, ModelInput], *, weights: Literal['stacking', 'pseudobma', 'loo', 'waic', 'kfold', 'bma'] = 'stacking', seed: int = 0) -> dict[str, float]
Return model weights, as brms model_weights.
| PARAMETER | DESCRIPTION |
|---|---|
models
|
Named fits or estimates.
TYPE:
|
weights
|
Stacking or pseudo-BMA weights of PSIS-LOO, or Akaike-type weights
TYPE:
|
seed
|
Seed of the pseudo-BMA Bayesian bootstrap and of bridge sampling.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float]
|
Weights summing to one. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the weighting method is unknown. |
Source code in src/quivers/formulas/_postprocess_methods.py
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
TYPE:
|
model_names
|
Names of the models;
TYPE:
|
compare
|
Compare several models, as
TYPE:
|
| 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
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:
|
model_names
|
Names of the models;
TYPE:
|
compare
|
Compare several models.
TYPE:
|
| 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
make_conditions
¶
make_conditions(data: IntoDataFrame | Fit, variables: str | Sequence[str], **labels: str | int | bool) -> DataFrame
Build conditions from variables of the data, as brms make_conditions.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
A data frame, or a fit whose retained training data is used.
TYPE:
|
variables
|
Variables to condition on.
TYPE:
|
**labels
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Every combination of the levels of factor variables and of the mean
and mean plus and minus one standard deviation of numeric variables,
the last variable varying fastest, with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a variable is not a column of the data. |
Source code in src/quivers/formulas/_brms_effects.py
bayes_factor
¶
bayes_factor(x1: EvidenceInput, x2: EvidenceInput, *, log: bool = False, model_names: tuple[str, str] = ('x1', 'x2'), method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> BayesFactor
Return the Bayes factor of two models, as brms bayes_factor.
| PARAMETER | DESCRIPTION |
|---|---|
x1
|
Numerator and denominator models, or their bridge estimates.
TYPE:
|
x2
|
Numerator and denominator models, or their bridge estimates.
TYPE:
|
log
|
Return the log Bayes factor.
TYPE:
|
model_names
|
Names of the two models.
TYPE:
|
method
|
TYPE:
|
repetitions
|
TYPE:
|
use_neff
|
TYPE:
|
maxiter
|
TYPE:
|
seed
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesFactor
|
:math: |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fits model different response data or are refused by
|
Source code in src/quivers/formulas/_evidence.py
bridge_sampler
¶
bridge_sampler(fit: Fit, *, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> BridgeResult
Estimate a fit's log marginal likelihood by bridge sampling.
| PARAMETER | DESCRIPTION |
|---|---|
fit
|
Fit with posterior MCMC draws and proper priors.
TYPE:
|
method
|
Proposal of the
TYPE:
|
repetitions
|
Independent proposal draws.
TYPE:
|
use_neff
|
Use the effective size of the iteration draws.
TYPE:
|
maxiter
|
Iteration bound of the fixed-point scheme.
TYPE:
|
seed
|
Seed of the proposal draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BridgeResult
|
The estimate, with the retained log densities. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fit is refused by |
RuntimeError
|
If the scheme does not converge. |
Notes
Cost is S / 2 (1 + R) program evaluations for S draws and R
repetitions (twice that for "warp3"), each O(C) for one log-joint
evaluation of the fit's program.
Source code in src/quivers/formulas/_evidence.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
post_prob
¶
post_prob(models: Mapping[str, EvidenceInput], *, prior_prob: Sequence[float] | None = None, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> dict[str, float]
Return posterior model probabilities, as brms post_prob.
| PARAMETER | DESCRIPTION |
|---|---|
models
|
At least two named models of the same response data.
TYPE:
|
prior_prob
|
Prior model probabilities in the order of
TYPE:
|
method
|
TYPE:
|
repetitions
|
TYPE:
|
use_neff
|
TYPE:
|
maxiter
|
TYPE:
|
seed
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float]
|
Posterior probabilities summing to one. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If fewer than two models are given, the fits model different data, or the prior probabilities are invalid. |
Source code in src/quivers/formulas/_evidence.py
mcmc_plot
¶
mcmc_plot(fit: Fit, type: str = 'intervals', *, variable: str | Sequence[str] | None = None, regex: bool = False, backend: str, **kwargs: str | int | float | bool) -> PlotResult
Draw an MCMC diagnostic plot, as brms mcmc_plot.
| PARAMETER | DESCRIPTION |
|---|---|
fit
|
Fitted model.
TYPE:
|
type
|
bayesplot
TYPE:
|
variable
|
brms variable names or regular expressions; None for all.
TYPE:
|
regex
|
brms
TYPE:
|
backend
|
ArviZ plotting backend (
TYPE:
|
**kwargs
|
Further ArviZ keyword arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PlotCollection or PlotMatrix
|
The plot. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the type is unknown or has no ArviZ counterpart. |
Source code in src/quivers/formulas/_mcmc_plot.py
posterior_average
¶
posterior_average(models: Mapping[str, Fit], *, variable: str | Sequence[str] | None = None, weights: WeightMethod | Sequence[float] = 'stacking', ndraws: int | None = None, missing: float | Mapping[str, float] | None = None, seed: int = 0) -> PosteriorAverage
Mix the posterior draws of several fits, as brms posterior_average.
| PARAMETER | DESCRIPTION |
|---|---|
models
|
Named fits.
TYPE:
|
variable
|
brms variable names (see
TYPE:
|
weights
|
Weighting method of
TYPE:
|
ndraws
|
Total draws; the first model's draw count by default.
TYPE:
|
missing
|
Value of a variable in models that lack it; None requires every variable in every model.
TYPE:
|
seed
|
Seed of the draw selection and of the weights.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PosteriorAverage
|
Pooled draws, weights and draw counts. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a variable is absent from the required models, |
Source code in src/quivers/formulas/_model_averaging.py
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
pp_average
¶
pp_average(models: Mapping[str, Fit], *, weights: WeightMethod | Sequence[float] = 'stacking', method: PredictionMethod = 'posterior_predict', ndraws: int | None = None, summary: bool = True, probs: Sequence[float] = (0.025, 0.975), robust: bool = False, resp: str | None = None, **options: Unpack[PredictionOptions]) -> PredictionAverage
Mix the predictions of several fits, as brms pp_average.
| PARAMETER | DESCRIPTION |
|---|---|
models
|
Named fits of the same response data.
TYPE:
|
weights
|
Weighting method of
TYPE:
|
method
|
Prediction method.
TYPE:
|
ndraws
|
Total draws; the first model's draw count by default.
TYPE:
|
summary
|
Also summarize the pooled draws.
TYPE:
|
probs
|
Quantile probabilities of the summary.
TYPE:
|
robust
|
Median and MAD instead of mean and SD.
TYPE:
|
resp
|
Response of joint fits; required when a joint fit has several.
TYPE:
|
**options
|
Prediction keywords such as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PredictionAverage
|
Pooled draws, weights, draw counts and the optional summary. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the fits model different responses, |
Source code in src/quivers/formulas/_model_averaging.py
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | |
pp_check
¶
pp_check(fit: Fit, type: str = 'dens_overlay', *, ndraws: int | None = None, prefix: Prefix = 'ppc', group: str | None = None, x: str | None = None, newdata: IntoDataFrame | None = None, resp: str | None = None, draw_ids: Sequence[int] | None = None, stat: StatisticSpec | None = None, prob: float = 0.5, prob_outer: float = 0.9, bins: int | None = None, freq: bool = True, style: Literal['standing', 'hanging', 'suspended'] = 'standing', seed: int = 0) -> PPCheck
Prepare a posterior or prior predictive check, as brms pp_check.
| PARAMETER | DESCRIPTION |
|---|---|
fit
|
Fitted model; a prior view (
TYPE:
|
type
|
bayesplot type without prefix (
TYPE:
|
ndraws
|
Random draws; every draw for summary types and ten otherwise.
TYPE:
|
prefix
|
Compare with observed data, or show the predictive distribution only.
TYPE:
|
group
|
Grouping variable; required by
TYPE:
|
x
|
Covariate of
TYPE:
|
newdata
|
Rows to predict, holding the response for
TYPE:
|
resp
|
Response of a joint fit; required when it has several.
TYPE:
|
draw_ids
|
Explicit 0-based draws.
TYPE:
|
stat
|
Test statistic;
TYPE:
|
prob
|
Interval probabilities of interval types;
TYPE:
|
prob_outer
|
Interval probabilities of interval types;
TYPE:
|
bins
|
Bins of
TYPE:
|
freq
|
Counts instead of proportions for
TYPE:
|
style
|
Rootogram style.
TYPE:
|
seed
|
Seed of the draw selection and predictions.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PPCheck
|
The table behind the plot with the inputs it was computed from. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the type is unknown for the prefix, a required |
Notes
Cost is one prediction at S draws over N rows, plus one
log-likelihood evaluation and PSIS smoothing, O(S N log S), for
leave-one-out types.
Source code in src/quivers/formulas/_pp_check.py
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | |
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:
|
data
|
Rows that scale data-dependent defaults.
TYPE:
|
**options
|
Preparation keywords of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PriorTable
|
brms's columns ( |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the formula or a preparation keyword is invalid. |
Source code in src/quivers/formulas/_prior_tables.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
PriorTable
|
The effective prior of every site; rows set by a rule given to
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a single-response fit retains no emission. |
Source code in src/quivers/formulas/_prior_tables.py
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
TYPE:
|
formula
|
brms-style formula or joint specification.
TYPE:
|
data
|
Training rows.
TYPE:
|
**options
|
Preparation keywords of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PriorTable
|
Every site with its effective prior; rows a user rule sets have
source |
| 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
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.