quivers.formulas.formula¶
Parsing a formula separates the
ordinary predictor columns (FixedColumn) from the group terms (RandomTerm), and the Formula
record carries the design information from which compilation builds parameter sites and indexed
lookups. formula_from_data builds it over formulae.design_matrices, so its
design matrices
depend on the data and the category encoding as well as on the formula.
Formula.design_terms retains coupled Gaussian bases as GaussianDesignTerm
values. Their innovation coordinates and positive penalty scales are distinct
from ordinary fixed columns; FormulaData.source preserves the same
immutable records across source-lens round trips. The
structured predictor guide
describes the mgcv s() and t2() constructors and retained new-data
transforms. GaussianDesignTerm.scale_group names a smoothing scale shared
by smooths with one mgcv id.
GaussianDesignTerm.gp holds a
GaussianProcessBlock for an
approximate gp() term: its coordinate scales are the square roots of the
kernel's spectral density at the retained frequencies, as functions of the
sampled sdgp and lscale. For an exact gp() term (no k) the block
retains the distinct scaled training inputs, and its coordinates are the
latent function there, cholesky(K + 1e-12 I) times standard-Normal
innovations, written with the QVR builtin cholesky. Predictions at new
inputs draw from
GaussianProcessConditional,
brms's conditional Gaussian law given the training values.
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
Formula, FormulaData, and FixedColumn are immutable values that
compare by every field. Two formulas are equal only when their formula
strings, response names, fixed columns (labels and data), random
terms, offsets, response modifiers, response values, group levels, and group indices all agree, and
hashing agrees with equality. The arrays with one entry per row are stored as
read-only copies made at construction: writing into
formula.response_values or a column's data raises ValueError, and
changing the source data frame afterwards does not change the formula.
Copy a field (formula.response_values.copy()) to get a writable array.
Formula.response_layout retains response carrier and event shape, named
vector components, and scalar factor levels with their declared order.
cbind(a, b, c) contributes one vector event per row, whereas a factor
response contributes one integer code per row. FormulaData retains this
layout through the lens complement; neither serialization nor prediction
flattens the event into observation rows. FormulaData.group_layouts also
retains the matching immutable Gaussian coefficient layout. An interleaved
forward pass on another formula cannot change that complement's reconstruction.
Formula.offsets retains coefficient-free offset(expr) and exposure(expr)
columns as read-only FixedColumn values. Exposure contributes the logarithm of
positive finite values. The offset guide
shows how these terms affect fitting and posterior predictors.
formula_from_data(..., weights="column") retains a finite nonnegative
numeric column as Formula.modifiers.weights. Formula.modifiers.decision
retains a normalized binary decision column for a joint response model.
Both belong to ResponseModifiers; FormulaData.source preserves them
in the lens complement. The
likelihood-weight guide
explains the objective, row alignment, and prediction contract.
ResponseModifiers additionally retains CensoringSpec, TruncationSpec,
StandardErrorSpec, and RowSelection, together with trials, weight-scaling
policy, and the original column-or-constant role sources. Subsetting precedes
all design and role validation, and retained positions align auxiliary and
neural inputs. The response-modifier guide
states event endpoints, scale combination, supported families, and fresh-data
requirements. These records compare by value and retain read-only column data.
Exact observations must lie within their inclusive truncation bounds before
inference begins. Censoring endpoints may lie outside the sampling interval;
their recorded events are intersected with that interval when scored.
cs(expr) marks a transition-specific fixed or group column through
FixedColumn.category_specific. FormulaData.source retains those flags
and the authored column order. A cs() call may hold a s(), t2(),
gp(), or mo() call, which then has one set of coefficients per ordinal
transition. The
FormulaData.witnesses of a module list the binding that shows each element
of the formula, so reading a module back finds exactly the terms it states.
cs(1) uses an internally prepared ones column, with an explicit refusal
if the caller already uses its reserved name. The
ordinal guide
states supported constructions and prediction shapes.
Formula.monotonic_terms retains each brms mo() special-effects column as a
MonotonicTerm: one MonotonicFactor per mo() factor, holding the training
matrix of cumulative category indicators and the brms simo label, the
covariate of the term's other components, and the brms coefficient label.
FormulaData.source preserves them across source-lens round trips.
The mo() formulae transform retains the training coding, so fresh rows are
coded and validated the same way. The
structured predictor guide
states the model, priors, and prediction rules.
formula
¶
Parsed-formula IR: a typed didactic.api.Model wrapping
the raw formulae.matrices.DesignMatrices so the rest of
the formula frontend operates on typed values.
The Formula IR is the canonical source representation of the formula→QVR lens. Future versions can register it as a panproto protocol so the lens machinery applies; for now the compiler walks this IR directly.
Convention
Each fixed-effect term may produce one or more design-matrix
columns (a single column for x, two for poly(x, 2), K
for an unordered factor with K + 1 levels, etc.). R / brms
assign one coefficient per column; this IR follows the same
convention by exploding each term into a tuple of
FixedColumn records. Multi-column terms thus produce
multiple named scalar latents downstream, with deterministic naming
{term}_1, {term}_2, ... that mirrors R's
poly(x, 2)1 / poly(x, 2)2 display.
Polynomial default: formulae.design_matrices's poly
transform is orthogonal by default (matches R's
stats::poly). Raw monomials are available via
I(x^2) / I(x**2). Transforms log, exp, sqrt,
abs, sin, cos, tan, log10, log2,
log1p, expm1 are wired through the formulae evaluation
namespace so users coming from R get the expected base R behaviour.
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:
|
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 |
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:
|
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:
|
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:
|
ThresholdGroups
didactic-model
¶
ThresholdGroups(*, column: FixedColumn = field(opaque=True, extras=OPAQUE_BY_VALUE), levels: tuple[str, ...], counts: tuple[int, ...] = (), extra_category: bool = False)
Bases: ValueModel
Group-specific ordinal threshold vectors of brms thres(n, gr).
| PARAMETER | DESCRIPTION |
|---|---|
column
|
Zero-based code of each row's threshold group, an index into
TYPE:
|
levels
|
Group labels in brms's sorted factor order.
TYPE:
|
counts
|
Number of thresholds of each group, one fewer than its number of categories. Empty until resolved from the response when the formula declares no count.
TYPE:
|
extra_category
|
Whether response code zero is a category outside the thresholds (the
hurdle of
TYPE:
|
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
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. |
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
Witness
didactic-model
¶
Witness(*, part: FormulaPart = field(opaque=True, extras=OPAQUE_BY_VALUE), binding: str)
Bases: ValueModel
The program binding that shows one element of a formula.
| PARAMETER | DESCRIPTION |
|---|---|
part
|
Element of the formula.
TYPE:
|
binding
|
Name in the program.
TYPE:
|
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. |
RandomBlock
didactic-model
¶
RandomBlock(*, identity: str | None, shared: bool, position: int = 0, options: GroupOptions | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))
Bases: ValueModel
The bar a random coefficient is written in.
| PARAMETER | DESCRIPTION |
|---|---|
identity
|
Correlation identity; None for independent coefficients.
TYPE:
|
shared
|
Whether the identity was authored.
TYPE:
|
options
|
Options of the bar's grouping term.
TYPE:
|
position
|
Position of the bar in the formula.
TYPE:
|
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 | |
MonotonicTerm
didactic-model
¶
MonotonicTerm(*, term: str, name: str, coef: str, column: int = -1, category_specific: bool = False, factors: tuple[MonotonicFactor, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), covariate: ndarray = field(opaque=True, extras=opaque_by_value(_frozen)))
Bases: ValueModel
One evaluated brms special-effects column built from mo() factors.
Its contribution to the linear predictor is
bsp * prod_j (D_j * design_j @ simo_j) * covariate,
with one scalar bsp and one simplex per factor.
| ATTRIBUTE | DESCRIPTION |
|---|---|
term |
Authored formulae term, such as
TYPE:
|
name |
Column label: the term, or
TYPE:
|
coef |
brms coefficient label of
TYPE:
|
column |
Position of the covariate among the evaluated columns of the term's
other components, or
TYPE:
|
category_specific |
Whether the column has one coefficient and one simplex per ordinal transition.
TYPE:
|
factors |
The
TYPE:
|
covariate |
Training covariate (brms
TYPE:
|
linear_values
property
¶
Return the column the term equals when every simplex is uniform.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
The product of the category positions and the covariate; the column a default coefficient prior is scaled by. |
MonotonicFactor
didactic-model
¶
MonotonicFactor(*, call: str, simplex: str, shared: bool = False, design: ndarray = field(opaque=True, extras=opaque_by_value(_frozen)))
Bases: ValueModel
One mo() factor of a special-effects column.
| ATTRIBUTE | DESCRIPTION |
|---|---|
call |
Authored component, such as
TYPE:
|
simplex |
brms
TYPE:
|
shared |
Whether the simplex is named by an
TYPE:
|
design |
Training cumulative indicators, shape
TYPE:
|
width
property
¶
Return the simplex dimension D.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of columns of the indicator matrix. |
Formula.grouping retains brms's grouping-term syntax as a GroupingPlan.
Each GroupingSpec builds an interaction factor g1:g2 or a
multi-membership factor mm(g1, g2) from its source columns, for training
and fresh rows alike. A Membership holds the member codes and weights of a
multi-membership factor, and a MemberCovariate the member values of one of
its coefficients. The grouping guide
states the syntax and the model.
GroupingPlan
didactic-model
¶
GroupingPlan(*, specs: tuple[GroupingSpec, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), memberships: tuple[Membership, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), covariates: tuple[MemberCovariate, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), options: tuple[GroupLevelOptions, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))
Bases: ValueModel
Derived grouping factors, multi-membership codes, and member covariates.
| ATTRIBUTE | DESCRIPTION |
|---|---|
specs |
Interaction and multi-membership factors built from source columns.
TYPE:
|
memberships |
Training codes and weights of each
TYPE:
|
covariates |
Member covariates of every multi-membership coefficient.
TYPE:
|
options |
TYPE:
|
option
¶
option(options: GroupOptions | None) -> GroupLevelOptions | None
Find the coded options of a group-level term.
| PARAMETER | DESCRIPTION |
|---|---|
options
|
Authored options of the term.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
GroupLevelOptions or None
|
The options coded on the levels in use, or None when the term has none that depend on the levels. |
Source code in src/quivers/formulas/_grouping.py
spec
¶
spec(group: str) -> GroupingSpec | None
Find the construction of a derived grouping factor.
| PARAMETER | DESCRIPTION |
|---|---|
group
|
Grouping-factor name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
GroupingSpec or None
|
Its construction, or None for a data column. |
Source code in src/quivers/formulas/_grouping.py
membership
¶
membership(group: str) -> Membership | None
Find the retained membership of an mm() factor.
| PARAMETER | DESCRIPTION |
|---|---|
group
|
Grouping-factor name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Membership or None
|
Its codes and weights, or None for an ordinary factor. |
Source code in src/quivers/formulas/_grouping.py
covariate
¶
covariate(group: str, slope: str) -> MemberCovariate | None
Find the member covariate of one multi-membership coefficient.
| PARAMETER | DESCRIPTION |
|---|---|
group
|
Grouping-factor name.
TYPE:
|
slope
|
Coefficient label.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MemberCovariate or None
|
Its member values, or None for an ordinary coefficient. |
Source code in src/quivers/formulas/_grouping.py
GroupingSpec
didactic-model
¶
GroupingSpec(*, name: str, kind: Literal['interaction', 'membership'], sources: tuple[str, ...], weights: tuple[str, ...] = (), scale: bool = True)
Bases: ValueModel
A grouping factor built from several source columns.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
Grouping-factor name used by the formula, the brms group label:
TYPE:
|
kind |
Interaction of the sources, or multi-membership over them.
TYPE:
|
sources |
Source columns in authored order.
TYPE:
|
weights |
Multi-membership weight columns, one per member; empty for equal weights.
TYPE:
|
scale |
Whether multi-membership weights are normalized to sum to one per row.
TYPE:
|
labels
¶
Build the factor column the formula frontend evaluates.
An interaction pastes the source labels with _ as brms does. A
multi-membership factor carries its first member, which only fixes the
row set: the coefficient enters through every member.
| PARAMETER | DESCRIPTION |
|---|---|
frame
|
Rows holding the source columns.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Series
|
One label per row, missing where a source is missing. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a source column is absent. |
Source code in src/quivers/formulas/_grouping.py
Membership
didactic-model
¶
Membership(*, group: str, spec: GroupingSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), codes: tuple[tuple[int, ...], ...], weights: ndarray = field(opaque=True, extras=opaque_by_value(_frozen)))
Bases: ValueModel
Training codes, weights, and member covariates of one mm() factor.
| ATTRIBUTE | DESCRIPTION |
|---|---|
group |
Grouping-factor name.
TYPE:
|
spec |
Its construction from member and weight columns.
TYPE:
|
codes |
One code per row for each member, into the factor's sorted levels.
TYPE:
|
weights |
Membership weights, shape
TYPE:
|
MemberCovariate
didactic-model
¶
MemberCovariate(*, group: str, slope: str, term: str = '', per_member: bool = False, values: ndarray = field(opaque=True, extras=opaque_by_value(_frozen)))
Bases: ValueModel
The member-specific covariate of one multi-membership coefficient.
| ATTRIBUTE | DESCRIPTION |
|---|---|
group |
Grouping-factor name.
TYPE:
|
slope |
Group-level coefficient label,
TYPE:
|
term |
formulae term evaluating the covariate; empty for the intercept.
TYPE:
|
per_member |
Whether the term evaluates one column per member (
TYPE:
|
values |
Training values
TYPE:
|
GroupOptions
didactic-model
¶
GroupOptions(*, group: str, by: str | None = None, by_columns: tuple[str, ...] = (), student: bool = False, prior_weight: str | None = None, covariance: str | None = None)
Bases: ValueModel
The gr() or mm() options of one group-level term.
| ATTRIBUTE | DESCRIPTION |
|---|---|
group |
Grouping-factor name.
TYPE:
|
by |
Label of the variable whose levels each get their own group-level standard deviations and correlations; every level of the grouping factor must lie within one of its levels.
TYPE:
|
by_columns |
Columns of the
TYPE:
|
student |
Whether group-level effects follow a multivariate Student-t law
(brms
TYPE:
|
prior_weight |
Column of per-level weights on the standard-normal prior of the
group-level innovations (brms
TYPE:
|
covariance |
TYPE:
|
coded
property
¶
Return whether the options depend on the levels' data.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True with a |
GroupLevelOptions
didactic-model
¶
GroupLevelOptions(*, options: GroupOptions = field(opaque=True, extras=OPAQUE_BY_VALUE), by_levels: tuple[str, ...] = (), by_codes: tuple[int, ...] = (), prior_weights: tuple[float, ...] = ())
Bases: ValueModel
The gr() options of group-level terms, coded on the levels.
| ATTRIBUTE | DESCRIPTION |
|---|---|
options |
Authored options.
TYPE:
|
by_levels |
Sorted levels of the
TYPE:
|
by_codes |
The
TYPE:
|
prior_weights |
The prior weight of each grouping level; empty without
TYPE:
|
group
property
¶
Return the grouping-factor name.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Grouping-factor name. |
Formula parts¶
FormulaPart names one authored element of a formula: the Formula field
that holds it and its name there. Formula.without removes elements by
part, and each element of FormulaData records the part it comes from.
formula_parts
¶
Names of the authored elements of a formula.
A FormulaPart identifies one element of a quivers.formulas.Formula: the
field that holds it and its name within the field. The terms of a compiled
formula record the part they come from, so a program binding can be read
back to the element that wrote it.
FormulaField
¶
FormulaField = Literal['fixed_columns', 'design_terms', 'random_terms', 'latent_terms', 'monotonic_terms', 'offsets']
A field of Formula whose elements terms contribute.
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:
|