quivers.formulas¶
A brms-style formula frontend over the QVR DSL. It compiles a
regression formula to .qvr source and fits the resulting Bayesian
model.
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}
The built-in inverse links, keyed by link name.
families
module-attribute
¶
families: Mapping[str, Family] = {'gaussian': Family(name='gaussian', location_link=_IDENTITY, observe_family='Normal', extra_observe_args=('sigma',), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG),)), 'bernoulli': Family(name='bernoulli', location_link=_LOGIT, observe_family='Bernoulli'), 'binomial': Family(name='binomial', location_link=_LOGIT, observe_family='Binomial'), 'categorical': Family(name='categorical', location_link=_SOFTMAX, observe_family='Categorical'), 'poisson': Family(name='poisson', location_link=_LOG, observe_family='Poisson'), 'negative_binomial': Family(name='negative_binomial', location_link=_LOG, observe_family='NegativeBinomial', extra_observe_args=('disp',), aux_params=(AuxParam(name='disp', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'gamma': Family(name='gamma', location_link=_LOG, observe_family='Gamma', extra_observe_args=('shape',), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'beta': Family(name='beta', location_link=_LOGIT, observe_family='Beta', extra_observe_args=('phi',), aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG),)), 'student_t': Family(name='student_t', location_link=_IDENTITY, observe_family='StudentT', extra_observe_args=('nu', 'sigma'), aux_params=(AuxParam(name='nu', prior='Gamma(2.0, 0.1)', link=_LOG), AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG))), 'cumulative': Family(name='cumulative', location_link=_IDENTITY, observe_family='OrderedLogistic'), 'zero_inflated_poisson': Family(name='zero_inflated_poisson', location_link=_LOG, observe_family='ZeroInflatedPoisson', extra_observe_args=('zi',), aux_params=(AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT),)), 'hurdle_poisson': Family(name='hurdle_poisson', location_link=_LOG, observe_family='HurdlePoisson', extra_observe_args=('zi',), aux_params=(AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT),)), 'zero_one_inflated_beta': Family(name='zero_one_inflated_beta', location_link=_LOGIT, observe_family='ZeroOneInflatedBeta', extra_observe_args=('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), AuxParam(name='coi', prior='Beta(2.0, 2.0)', link=_LOGIT))), 'mixture': Family(name='mixture', location_link=_IDENTITY, observe_family='MixtureNormal')}
The built-in response families, keyed by brms-style family name.
The compiler dispatches on the family name and slots each family's
observe step and link into the emitted .qvr source.
FixedColumn
didactic-model
¶
FixedColumn(*, term: str, name: str, qvr_name: str, is_intercept: bool = False, data: ndarray = field(opaque=True))
Bases: Model
One column of the fixed-effects design matrix.
| 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:
|
RandomTerm
didactic-model
¶
Bases: Model
One random-effect group, e.g. (1 | g) or (x | g).
| ATTRIBUTE | DESCRIPTION |
|---|---|
slope |
TYPE:
|
group |
Grouping factor name.
TYPE:
|
Formula
didactic-model
¶
Formula(*, formula: str, response_name: str, fixed_columns: tuple[FixedColumn, ...] = field(default_factory=tuple, opaque=True), random_terms: tuple[RandomTerm, ...] = (), response_values: ndarray = field(opaque=True), group_levels: Mapping[str, tuple[str, ...]] = field(default_factory=dict, opaque=True), group_indices: Mapping[str, tuple[int, ...]] = field(default_factory=dict, opaque=True))
Bases: Model
A parsed regression formula plus the data it was parsed against.
| 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:
|
random_terms |
Random-effect group specifications.
TYPE:
|
response_values |
Response column values, shape
TYPE:
|
group_levels |
Canonical level ordering per grouping factor, used to derive deterministic plate-index tensors.
TYPE:
|
group_indices |
Per-group integer index array, shape
TYPE:
|
FormulaData
didactic-model
¶
FormulaData(*, formula: str = '', response_name: str = '', response_values: ndarray = field(opaque=True), fixed_column_names: Mapping[str, tuple[str, str]] = field(default_factory=dict, opaque=True), fixed_column_data: Mapping[str, ndarray] = field(default_factory=dict, opaque=True), group_original_names: Mapping[str, str] = field(default_factory=dict, opaque=True), group_levels: Mapping[str, tuple[str, ...]] = field(default_factory=dict, opaque=True), group_indices: Mapping[str, tuple[int, ...]] = field(default_factory=dict, opaque=True))
Bases: Model
Store the nonstructural complement of a Formula lens mapping.
The emitted QVR module records formula structure under normalized
identifiers. This complement retains the source formula, original names,
presentation labels, per-row arrays, group levels, and group indices so
backward(module, complement) can reconstruct the original Formula.
| ATTRIBUTE | DESCRIPTION |
|---|---|
formula |
Original formula string.
TYPE:
|
response_name |
Original response column name.
TYPE:
|
response_values |
Response values with shape
TYPE:
|
fixed_column_names |
TYPE:
|
fixed_column_data |
Predictor values keyed by normalized fixed-column name.
TYPE:
|
group_original_names |
Original group names keyed by normalized group name.
TYPE:
|
group_levels |
Canonical level order for each group.
TYPE:
|
group_indices |
Per-row integer codes for each group.
TYPE:
|
Link
didactic-model
¶
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 let-expression template applied to a linear predictor
TYPE:
|
AuxParam
didactic-model
¶
AuxParam(*, name: str, prior: str, link: Link)
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:
|
Family
didactic-model
¶
Family(*, name: str, location_link: Link, observe_family: str, extra_observe_args: tuple[str, ...] = (), aux_params: tuple[AuxParam, ...] = ())
Bases: Model
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.
FormulaToQVRModule
¶
FormulaToQVRModule(family: Family, *, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', user_priors: Mapping[str, str] | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str = 1, thresholds_by: str | None = None, mixture_components: int = 2, predictor_name: str | None = None)
Bases: Lens[Formula, Module, FormulaData]
Translate a Formula to a QVR Module AST.
A typed didactic.api.Lens whose complement is a
FormulaData carrier containing the fields of the source
Formula that are not recoverable from the emitted
Module. The per-row data arrays, the original (pre-
_qvr_name) identifiers, the per-column term / name
presentation labels, and the original formula string travel in
the complement; everything else (which columns there are, the
intercept / random-term structure, the family choice) is decoded
back out of the Module by _decode_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:
|
user_priors
|
Per-name prior overrides keyed by the latent's variable name in the emitted module.
TYPE:
|
reparameterize
|
Random-effect parameterization. Categorical random effects use the non-centered form.
TYPE:
|
binomial_trials
|
Common trial count or the name of 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:
|
| 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
forward
¶
forward(formula: Formula) -> tuple[Module, FormulaData]
Compile a formula to a QVR module and its complement.
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
The parsed formula with its design data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Module, FormulaData]
|
The emitted QVR module AST, and the fields of |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the response is incompatible with the family (for
instance non-integer or non-contiguous category labels
for a categorical or cumulative family), or a prior does
not parse as |
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 column, intercept, and random-term structure is decoded
from target; the data arrays and presentation labels come
from complement.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
A QVR module in the image of
TYPE:
|
complement
|
The complement
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Formula
|
The reconstructed formula. |
Source code in src/quivers/formulas/compile.py
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 | |
fixed_column_observations
¶
Per-column free-variable bindings for the host-data
channel. One entry per non-intercept fixed column, shape
(N,).
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
The formula whose fixed-effect columns are bound.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Each non-intercept column's |
Source code in src/quivers/formulas/compile.py
BayesianFit
didactic-model
¶
BayesianFit(*, formula: Formula = field(opaque=True), family: Family, program: MonadicProgram = field(opaque=True), posterior: MCMCResult | Guide = field(opaque=True), observations: Mapping[str, Tensor] = field(default_factory=dict, opaque=True), reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str = 1, thresholds_by: str | None = None, mixture_components: int = 2, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', priors: Mapping[str, str] = field(default_factory=dict, opaque=True), predictor: Module | None = field(default=None, opaque=True), predictor_data: Tensor | None = field(default=None, opaque=True), predictor_name: str | None = None)
Bases: Model
A fitted Bayesian regression: the compiled program, the parsed formula, the family, the user-supplied data, and the posterior samples.
| ATTRIBUTE | DESCRIPTION |
|---|---|
formula |
Parsed formula IR.
TYPE:
|
family |
Response family used at compile time.
TYPE:
|
program |
The compiled program.
TYPE:
|
posterior |
TYPE:
|
observations |
Inference-time observations dict (response + per-column covariates + per-group plate indices).
TYPE:
|
dump_qvr
¶
Write the AST-equivalent .qvr source to path and
return the resulting Path.
formula_from_data
¶
formula_from_data(formula: str, data: IntoDataFrame, *, extra_namespace: Mapping[str, object] | 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. Polynomial terms via
poly(x, k) are orthogonal by default, matching R's
stats::poly.
| PARAMETER | DESCRIPTION |
|---|---|
formula
|
Formula string in brms / lme4 syntax.
TYPE:
|
data
|
Pandas, polars, or any other Narwhals-compatible dataframe.
TYPE:
|
extra_namespace
|
Additional names visible inside the formula's expression evaluation, merged on top of the R-style transforms.
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
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
fit
¶
fit(formula: str, *, data: IntoDataFrame, family: str | Family = 'gaussian', method: Literal['nuts', 'hmc', 'svi'] = 'nuts', num_warmup: int = 500, num_samples: int = 1000, num_chains: int = 4, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', priors: Mapping[str, str] | None = None, guide: type | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str = 1, thresholds_by: str | None = None, mixture_components: int = 2, predictor: Module | None = None, predictor_data: Tensor | None = None, seed: int = 0) -> BayesianFit
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" infers contiguous labels 0..K-1 and uses
label zero as the 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.
TYPE:
|
data
|
Pandas, Polars, or another Narwhals-compatible dataframe.
TYPE:
|
family
|
Registered response family or a family value.
TYPE:
|
method
|
Inference algorithm.
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:
|
| RETURNS | DESCRIPTION |
|---|---|
BayesianFit
|
Parsed formula, compiled program, fitted posterior, and observations. |
Source code in src/quivers/formulas/_fit.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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 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 | |
formula_to_qvr
¶
formula_to_qvr(formula: str, *, data: IntoDataFrame, family: str | Family = 'gaussian', fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', priors: Mapping[str, str] | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str = 1, thresholds_by: str | None = None, mixture_components: int = 2, predictor_name: str | None = None, path: str | Path | None = None) -> 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".