Skip to content

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 sdgp coefficient label, for instance gpx or gpxga.

TYPE: str

lscale_labels

brms lscale coefficient labels: one for an isotropic GP, one per covariate otherwise.

TYPE: tuple[str, ...]

kernel

Covariance kernel.

TYPE: GpKernel

frequencies

(m, D) square roots of the Laplacian eigenvalues, brms's slambda, read-only.

TYPE: ndarray

lscale_priors

Default prior of each length scale, in lscale_labels order.

TYPE: tuple[str, ...]

inputs

For an exact GP, the (u, D) distinct scaled training inputs, brms's Xgp, in order of first appearance (every active row when gr is false); None for the approximation, whose frequencies then hold the basis.

TYPE: ndarray or None

gr

Whether rows sharing an input share one latent value.

TYPE: bool

dmax

Divisor applied to the covariates (one when scale = FALSE).

TYPE: float

prediction_inputs

For an exact GP specialized to prediction rows, their (m, D) distinct scaled inputs, at which the latent function is drawn given its training values.

TYPE: ndarray or None

exact property

exact: bool

Report whether the block is brms's exact GP.

RETURNS DESCRIPTION
bool

True when the block retains its training inputs.

dimension property

dimension: int

Count the GP's covariates.

RETURNS DESCRIPTION
int

Input dimension D.

isotropic property

isotropic: bool

Report whether one length scale serves every covariate.

RETURNS DESCRIPTION
bool

True for a single length scale.

specific

specific() -> GaussianProcessBlock

Return the block of one process per ordinal transition.

RETURNS DESCRIPTION
GaussianProcessBlock

The same block, with labels distinct from those of a block shared by the transitions.

Source code in src/quivers/formulas/_gp.py
def specific(self) -> GaussianProcessBlock:
    """Return the block of one process per ordinal transition.

    Returns
    -------
    GaussianProcessBlock
        The same block, with labels distinct from those of a block
        shared by the transitions.
    """
    return self.with_(
        label="cs" + self.label,
        lscale_labels=tuple("cs" + label for label in self.lscale_labels),
    )

sites

sites(prefix: str) -> tuple[str, tuple[str, ...]]

Name the block's sdgp and lscale latent sites.

PARAMETER DESCRIPTION
prefix

Owning predictor namespace.

TYPE: str

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

The sdgp site and the lscale sites.

Source code in src/quivers/formulas/_gp.py
def sites(self, prefix: str) -> tuple[str, tuple[str, ...]]:
    """Name the block's ``sdgp`` and ``lscale`` latent sites.

    Parameters
    ----------
    prefix : str
        Owning predictor namespace.

    Returns
    -------
    tuple[str, tuple[str, ...]]
        The ``sdgp`` site and the ``lscale`` sites.
    """
    return (
        f"{prefix}sdgp_{_qvr(self.label)}",
        tuple(f"{prefix}lscale_{_qvr(label)}" for label in self.lscale_labels),
    )

GaussianProcessConditional

GaussianProcessConditional(block: GaussianProcessBlock, values: Tensor, sdgp: Tensor, lscales: tuple[Tensor, ...])

Bases: Distribution

The latent function of an exact GP at fresh inputs given its training values.

PARAMETER DESCRIPTION
block

Exact block specialized to prediction rows.

TYPE: GaussianProcessBlock

values

Latent function at the training inputs.

TYPE: Tensor

sdgp

Marginal standard deviation.

TYPE: Tensor

lscales

Length scales.

TYPE: tuple[Tensor, ...]

Source code in src/quivers/formulas/_gp.py
def __init__(
    self,
    block: GaussianProcessBlock,
    values: torch.Tensor,
    sdgp: torch.Tensor,
    lscales: tuple[torch.Tensor, ...],
) -> None:
    assert block.prediction_inputs is not None
    batch = torch.broadcast_shapes(
        values.shape[:-1], sdgp.shape, *(lscale.shape for lscale in lscales)
    )
    self._loc, self._scale_tril = conditional_moments(
        block,
        values.expand(*batch, values.shape[-1]),
        sdgp.expand(batch),
        tuple(lscale.expand(batch) for lscale in lscales),
        np.asarray(block.prediction_inputs),
    )
    super().__init__(
        batch,
        torch.Size((len(block.prediction_inputs),)),
        validate_args=False,
    )

arg_constraints property

arg_constraints: dict[str, Constraint]

Declare no torch-validated arguments.

RETURNS DESCRIPTION
dict[str, Constraint]

An empty mapping.

support property

support: Constraint

Give the real vectors.

RETURNS DESCRIPTION
Constraint

Support of the law.

mean property

mean: Tensor

Give the conditional mean.

RETURNS DESCRIPTION
Tensor

Mean at the fresh inputs.

rsample

rsample(sample_shape: _size = Size()) -> Tensor

Draw the latent function at the fresh inputs.

PARAMETER DESCRIPTION
sample_shape

Leading sample shape.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws with the sample, batch, and event shapes.

Source code in src/quivers/formulas/_gp.py
def rsample(self, sample_shape: _size = torch.Size()) -> torch.Tensor:
    """Draw the latent function at the fresh inputs.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading sample shape.

    Returns
    -------
    torch.Tensor
        Draws with the sample, batch, and event shapes.
    """
    shape = self._extended_shape(sample_shape)
    noise = torch.randn(shape, dtype=self._loc.dtype)
    return self._loc + (self._scale_tril @ noise[..., None])[..., 0]

log_prob

log_prob(value: Tensor) -> Tensor

Score latent values at the fresh inputs.

PARAMETER DESCRIPTION
value

Values at the fresh inputs.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Multivariate Normal log density.

Source code in src/quivers/formulas/_gp.py
def log_prob(self, value: torch.Tensor) -> torch.Tensor:
    """Score latent values at the fresh inputs.

    Parameters
    ----------
    value : torch.Tensor
        Values at the fresh inputs.

    Returns
    -------
    torch.Tensor
        Multivariate Normal log density.
    """
    return MultivariateNormal(self._loc, scale_tril=self._scale_tril).log_prob(
        value.double()
    )

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. "poly(x, 2)" or "x").

TYPE: str

name

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

TYPE: str

qvr_name

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

TYPE: str

is_intercept

True for the constant-1 proportional predictor column.

TYPE: bool

category_specific

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

TYPE: bool

data

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

TYPE: ndarray

RandomTerm didactic-model

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

Bases: ValueModel

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

ATTRIBUTE DESCRIPTION
slope

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

TYPE: str

group

Grouping factor name.

TYPE: str

correlation_id

Correlation-block identity; None requests independent effects.

TYPE: str or None

shared

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

TYPE: bool

column

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

TYPE: FixedColumn or None

specific

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

TYPE: bool

options

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

TYPE: GroupOptions or None

covariance

Known covariance between the levels that the options name.

TYPE: GroupCovariance or None

bar

Position of the term's bar in the formula.

TYPE: int

category_specific property

category_specific: bool

Return whether the slope has one coefficient per transition.

RETURNS DESCRIPTION
bool

True for a cs() slope.

SplineBasis didactic-model

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

Bases: ValueModel

Immutable structural state of an evaluated B-spline basis.

ATTRIBUTE DESCRIPTION
knots

Complete nondecreasing knot sequence, including repeated boundaries.

TYPE: tuple[float, ...]

degree

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

TYPE: int

GaussianDesignTerm didactic-model

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

Bases: ValueModel

One coupled Gaussian coefficient block evaluated on response rows.

ATTRIBUTE DESCRIPTION
term, qvr_name

Authored term label and normalized runtime design identifier.

TYPE: str

column_indices

Columns of the retained formula evaluator carrying penalized coordinates.

TYPE: tuple[int, ...]

data

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

TYPE: ndarray

basis

Retained structural basis state when generated from a spline.

TYPE: SplineBasis or None

coefficient_map

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

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

constraint

Original training-basis mean defining the identification constraint.

TYPE: tuple[float, ...]

scale_group

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

TYPE: str

category_specific

Whether the block has one coefficient vector per ordinal transition.

TYPE: bool

gp

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

TYPE: GaussianProcessBlock or None

CensoringSpec didactic-model

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

Bases: ValueModel

Retain recorded event codes and interval endpoints on response rows.

PARAMETER DESCRIPTION
status

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

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

upper

Interval upper endpoints with safe placeholders on inactive rows.

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

TruncationSpec didactic-model

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

Bases: ValueModel

Retain inclusive sampling bounds without changing predictor columns.

PARAMETER DESCRIPTION
lower

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

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

upper

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

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

StandardErrorSpec didactic-model

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

Bases: ValueModel

Retain known measurement errors and the residual-scale policy.

PARAMETER DESCRIPTION
column

Finite nonnegative standard errors in response units.

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

sigma

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

TYPE: bool DEFAULT: False

RowSelection didactic-model

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

Bases: ValueModel

Map included response rows to their original dataframe positions.

PARAMETER DESCRIPTION
size

Original row count before selection.

TYPE: int

positions

Included positions in original order.

TYPE: tuple[int, ...]

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 levels.

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

levels

Group labels in brms's sorted factor order.

TYPE: tuple[str, ...]

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: tuple[int, ...] DEFAULT: ()

extra_category

Whether response code zero is a category outside the thresholds (the hurdle of hurdle_cumulative), so that a group with n thresholds has the codes 0, ..., n + 1.

TYPE: bool DEFAULT: False

ResponseModifiers didactic-model

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

Bases: ValueModel

Retain typed response-row inputs independently of predictor coefficients.

ATTRIBUTE DESCRIPTION
weights

Finite nonnegative observation weights, optionally scaled after selection.

TYPE: FixedColumn or None

decision

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

TYPE: FixedColumn or None

censoring

Recorded exact or censored outcome events.

TYPE: CensoringSpec or None

truncation

Inclusive bounds on the response sampling law.

TYPE: TruncationSpec or None

standard_error

Known measurement errors and optional residual scale.

TYPE: StandardErrorSpec or None

subset

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

TYPE: RowSelection or None

trials

Exact finite trial counts supplied by a response modifier.

TYPE: FixedColumn or None

rate

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

TYPE: FixedColumn or None

thresholds

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

TYPE: int or None

threshold_groups

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

TYPE: ThresholdGroups or None

weights_scale

Whether weights were normalized to the number of included rows.

TYPE: bool

sources

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

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

columns

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

Return supplied role-column pairs in canonical input order.

RETURNS DESCRIPTION
tuple of role and FixedColumn

Checked modifier inputs with no fitted coefficient.

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

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

ResponseLayout didactic-model

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

Bases: ValueModel

Retain event coordinates independently of the observation-row axis.

PARAMETER DESCRIPTION
component_names

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

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

carrier

Numeric carrier of the evaluated response, before family validation.

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

category_levels

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

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

ordered

Whether the original factor declares an ordering.

TYPE: bool DEFAULT: False

category_values

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

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

event_shape property

event_shape: tuple[int, ...]

Return event dimensions, excluding observation rows.

RETURNS DESCRIPTION
tuple[int, ...]

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

Formula didactic-model

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

Bases: ValueModel

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

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

ATTRIBUTE DESCRIPTION
formula

Original formula string.

TYPE: str

response_name

Name of the response column.

TYPE: str

fixed_columns

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

TYPE: tuple[FixedColumn, ...]

design_terms

Coupled Gaussian basis contributions with separate penalty-scale priors.

TYPE: tuple[GaussianDesignTerm, ...]

random_terms

Random-effect group specifications.

TYPE: tuple[RandomTerm, ...]

response_values

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

TYPE: ndarray

response_layout

Event coordinates and evaluated numeric carrier.

TYPE: ResponseLayout

group_levels

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

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

modifiers

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

TYPE: ResponseModifiers

offsets

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

TYPE: tuple[FixedColumn, ...]

group_indices

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

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

latent_terms

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

TYPE: tuple[LatentTerm, ...]

monotonic_terms

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

TYPE: tuple[MonotonicTerm, ...]

grouping

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

TYPE: GroupingPlan

category_specific property

category_specific: bool

Return whether a term has one coefficient per ordinal transition.

RETURNS DESCRIPTION
bool

True for a formula with a cs() term.

without

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

Return the formula without some of its elements.

PARAMETER DESCRIPTION
parts

Elements to leave out.

TYPE: Collection[FormulaPart]

RETURNS DESCRIPTION
Formula

The formula with every other element, in authored order.

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

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

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

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

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

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: FormulaPart DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

binding

Name in the program.

TYPE: str

FormulaData didactic-model

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

Bases: ValueModel

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

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

PARAMETER DESCRIPTION
source

The translated formula.

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

witnesses

Binding of each element of the formula in the program.

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

group_laws

Laws of the group blocks of the program.

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

level_sites

Sites holding values for every level of a grouping factor.

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

prior_targets

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

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

group_layouts property

group_layouts: tuple[GroupBlockLayout, ...]

Return the coordinate layout of each group block.

RETURNS DESCRIPTION
tuple[GroupBlockLayout, ...]

Raw sites and coefficient slices derived from the block laws.

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: str or None

shared

Whether the identity was authored.

TYPE: bool

options

Options of the bar's grouping term.

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

position

Position of the bar in the formula.

TYPE: int DEFAULT: 0

formula_from_data

formula_from_data(formula: str, data: IntoDataFrame, *, weights: str | None = None, decision: str | None = None, groups: tuple[str, ...] = (), extra_namespace: Mapping[str, object] | None = None, data2: Mapping[str, Data2Object] | None = None) -> Formula

Build a typed Formula IR by lifting formulae.design_matrices over a dataframe.

This is an adapter, not a parser: the brms-style formula syntax is parsed by the formulae library; we lift its formulae.matrices.DesignMatrices result into a typed didactic record, augmented with deterministic per-group level orderings and integer-code arrays derived from the dataframe.

The R-style numeric transforms (log, exp, sqrt, abs, sin, cos, tan, log10, log2, log1p, expm1, asin, acos, atan, sinh, cosh, tanh) are pre-loaded into the formulae evaluation namespace so users coming from R / brms get the expected base R behaviour without explicit registration. offset(expr) adds an evaluated expression with coefficient one; exposure(expr) adds its logarithm and requires positive finite values. These terms work in location and auxiliary formulas. Ordinal cs(expr) terms retain a category-specific transition axis; cs(1) uses an internal constant column so fresh-data evaluation preserves its row axis. Polynomial terms via poly(x, k) are orthogonal by default, matching R's stats::poly. As brms's na_omit, a row with a missing value in any variable the formula uses (response, predictors, grouping factors, and role columns) is removed with a warning before anything is evaluated, and modifiers.subset records the original positions of the rows kept.

PARAMETER DESCRIPTION
formula

Formula string in brms / lme4 syntax.

TYPE: str

data

Pandas, polars, or any other Narwhals-compatible dataframe.

TYPE: IntoDataFrame

weights

Name of a numeric, finite, nonnegative likelihood-weight column. Its values are retained without normalization and must align with every response row after formula evaluation.

TYPE: str or None DEFAULT: None

decision

Binary decision column, numeric 0/1 or lower/upper labels. Equivalent to response | dec(column); repeated declarations must agree.

TYPE: str or None DEFAULT: None

groups

Additional grouping columns retained for structural parameters without adding varying coefficients to the predictor.

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

extra_namespace

Additional names visible inside the formula's expression evaluation, merged on top of the R-style transforms.

TYPE: Mapping[str, object] DEFAULT: None

data2

Named matrices the formula reads, such as the cov matrix of a gr() term.

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

RETURNS DESCRIPTION
Formula

The formula IR: response values, one fixed column per design column, the random terms, and each grouping factor's levels and per-row level indices.

RAISES DESCRIPTION
ValueError

If the formula has no response on the left of ~, or a random term is invalid, an offset modifier is used inside an interaction or group, or weights are nonnumeric, negative, nonfinite, or misaligned with the evaluated response rows.

Source code in src/quivers/formulas/formula.py
def formula_from_data(
    formula: str,
    data: IntoDataFrame,
    *,
    weights: str | None = None,
    decision: str | None = None,
    groups: tuple[str, ...] = (),
    extra_namespace: Mapping[str, object] | None = None,
    data2: Mapping[str, Data2Object] | None = None,
) -> Formula:
    """Build a typed `Formula` IR by lifting
    `formulae.design_matrices` over a dataframe.

    This is an adapter, not a parser: the brms-style formula syntax
    is parsed by the [`formulae`](https://bambinos.github.io/formulae/)
    library; we lift its `formulae.matrices.DesignMatrices`
    result into a typed didactic record, augmented with deterministic
    per-group level orderings and integer-code arrays derived from
    the dataframe.

    The R-style numeric transforms (``log``, ``exp``, ``sqrt``,
    ``abs``, ``sin``, ``cos``, ``tan``, ``log10``, ``log2``,
    ``log1p``, ``expm1``, ``asin``, ``acos``, ``atan``, ``sinh``,
    ``cosh``, ``tanh``) are pre-loaded into the formulae evaluation
    namespace so users coming from R / brms get the expected base
    R behaviour without explicit registration.
    ``offset(expr)`` adds an evaluated expression with coefficient one;
    ``exposure(expr)`` adds its logarithm and requires positive finite values.
    These terms work in location and auxiliary formulas. Ordinal ``cs(expr)``
    terms retain a category-specific transition axis; ``cs(1)`` uses an internal
    constant column so fresh-data evaluation preserves its row axis.
    Polynomial terms via
    ``poly(x, k)`` are orthogonal by default, matching R's
    ``stats::poly``.
    As brms's ``na_omit``, a row with a missing value in any variable the
    formula uses (response, predictors, grouping factors, and role columns)
    is removed with a warning before anything is evaluated, and
    ``modifiers.subset`` records the original positions of the rows kept.

    Parameters
    ----------
    formula : str
        Formula string in brms / lme4 syntax.
    data : IntoDataFrame
        Pandas, polars, or any other Narwhals-compatible dataframe.
    weights : str or None
        Name of a numeric, finite, nonnegative likelihood-weight column.
        Its values are retained without normalization and must align with
        every response row after formula evaluation.
    decision : str or None
        Binary decision column, numeric 0/1 or lower/upper labels. Equivalent
        to ``response | dec(column)``; repeated declarations must agree.
    groups : tuple[str, ...]
        Additional grouping columns retained for structural parameters without
        adding varying coefficients to the predictor.
    extra_namespace : Mapping[str, object], optional
        Additional names visible inside the formula's expression
        evaluation, merged on top of the R-style transforms.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame] or None
        Named matrices the formula reads, such as the ``cov`` matrix of a
        ``gr()`` term.

    Returns
    -------
    Formula
        The formula IR: response values, one fixed column per design
        column, the random terms, and each grouping factor's levels
        and per-row level indices.

    Raises
    ------
    ValueError
        If the formula has no response on the left of ``~``, or a
        random term is invalid, an offset modifier is used inside an
        interaction or group, or weights are nonnumeric, negative, nonfinite,
        or misaligned with the evaluated response rows.
    """
    with formula_data_options(data2=data2):
        return _formula_and_design(
            formula,
            data,
            weights=weights,
            decision=decision,
            groups=groups,
            extra_namespace=extra_namespace,
        )[0]

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 mo(x):z.

TYPE: str

name

Column label: the term, or {term}_{k} for the k-th column of a term whose other components evaluate to several columns.

TYPE: str

coef

brms coefficient label of bsp, such as mox:z.

TYPE: str

column

Position of the covariate among the evaluated columns of the term's other components, or -1 when the term has none.

TYPE: int

category_specific

Whether the column has one coefficient and one simplex per ordinal transition.

TYPE: bool

factors

The mo() factors in term order.

TYPE: tuple[MonotonicFactor, ...]

covariate

Training covariate (brms Csp), shape (rows,), or shape (0,) when the term has no other components; read-only.

TYPE: ndarray

linear_values property

linear_values: NDArray[float64]

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 mo(x).

TYPE: str

simplex

brms simo coefficient label: the id, or the column's coefficient label followed by the factor's position in the term.

TYPE: str

shared

Whether the simplex is named by an id and may be shared.

TYPE: bool

design

Training cumulative indicators, shape (rows, D); read-only.

TYPE: ndarray

width property

width: int

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: tuple[GroupingSpec, ...]

memberships

Training codes and weights of each mm() factor.

TYPE: tuple[Membership, ...]

covariates

Member covariates of every multi-membership coefficient.

TYPE: tuple[MemberCovariate, ...]

options

gr(by, dist, pw) options coded on the training levels.

TYPE: tuple[GroupLevelOptions, ...]

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: GroupOptions or None

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
def option(self, options: GroupOptions | None) -> GroupLevelOptions | None:
    """Find the coded options of a group-level term.

    Parameters
    ----------
    options : GroupOptions or None
        Authored options of the term.

    Returns
    -------
    GroupLevelOptions or None
        The options coded on the levels in use, or None when the term
        has none that depend on the levels.
    """
    return next(
        (option for option in self.options if option.options == options), None
    )

spec

spec(group: str) -> GroupingSpec | None

Find the construction of a derived grouping factor.

PARAMETER DESCRIPTION
group

Grouping-factor name.

TYPE: str

RETURNS DESCRIPTION
GroupingSpec or None

Its construction, or None for a data column.

Source code in src/quivers/formulas/_grouping.py
def spec(self, group: str) -> GroupingSpec | None:
    """Find the construction of a derived grouping factor.

    Parameters
    ----------
    group : str
        Grouping-factor name.

    Returns
    -------
    GroupingSpec or None
        Its construction, or None for a data column.
    """
    return next((spec for spec in self.specs if spec.name == group), None)

membership

membership(group: str) -> Membership | None

Find the retained membership of an mm() factor.

PARAMETER DESCRIPTION
group

Grouping-factor name.

TYPE: str

RETURNS DESCRIPTION
Membership or None

Its codes and weights, or None for an ordinary factor.

Source code in src/quivers/formulas/_grouping.py
def membership(self, group: str) -> Membership | None:
    """Find the retained membership of an ``mm()`` factor.

    Parameters
    ----------
    group : str
        Grouping-factor name.

    Returns
    -------
    Membership or None
        Its codes and weights, or None for an ordinary factor.
    """
    return next(
        (
            membership
            for membership in self.memberships
            if membership.group == group
        ),
        None,
    )

covariate

covariate(group: str, slope: str) -> MemberCovariate | None

Find the member covariate of one multi-membership coefficient.

PARAMETER DESCRIPTION
group

Grouping-factor name.

TYPE: str

slope

Coefficient label.

TYPE: str

RETURNS DESCRIPTION
MemberCovariate or None

Its member values, or None for an ordinary coefficient.

Source code in src/quivers/formulas/_grouping.py
def covariate(self, group: str, slope: str) -> MemberCovariate | None:
    """Find the member covariate of one multi-membership coefficient.

    Parameters
    ----------
    group : str
        Grouping-factor name.
    slope : str
        Coefficient label.

    Returns
    -------
    MemberCovariate or None
        Its member values, or None for an ordinary coefficient.
    """
    return next(
        (
            covariate
            for covariate in self.covariates
            if covariate.group == group and covariate.slope == slope
        ),
        None,
    )

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: g1:g2 for an interaction and mmg1g2 for mm(g1, g2).

TYPE: str

kind

Interaction of the sources, or multi-membership over them.

TYPE: {'interaction', 'membership'}

sources

Source columns in authored order.

TYPE: tuple[str, ...]

weights

Multi-membership weight columns, one per member; empty for equal weights.

TYPE: tuple[str, ...]

scale

Whether multi-membership weights are normalized to sum to one per row.

TYPE: bool

labels

labels(frame: DataFrame) -> Series

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: DataFrame

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
def labels(self, frame: pd.DataFrame) -> pd.Series:
    """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.

    Parameters
    ----------
    frame : pandas.DataFrame
        Rows holding the source columns.

    Returns
    -------
    pandas.Series
        One label per row, missing where a source is missing.

    Raises
    ------
    ValueError
        If a source column is absent.
    """
    missing = [column for column in self.sources if column not in frame.columns]
    if missing:
        raise ValueError(
            f"grouping term {self.name!r} names absent columns {missing!r}"
        )
    if self.kind == "membership":
        return pd.Series(
            frame[self.sources[0]].to_numpy(dtype=object),
            index=frame.index,
            dtype=object,
        )
    parts = [frame[column] for column in self.sources]
    absent = np.zeros(len(frame), dtype=bool)
    for part in parts:
        absent |= np.asarray(part.isna())
    labels = [
        None if absent[row] else "_".join(str(part.iloc[row]) for part in parts)
        for row in range(len(frame))
    ]
    return pd.Series(labels, index=frame.index, dtype=object)

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: str

spec

Its construction from member and weight columns.

TYPE: GroupingSpec

codes

One code per row for each member, into the factor's sorted levels.

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

weights

Membership weights, shape (rows, members); read-only.

TYPE: ndarray

size property

size: int

Return the number of members.

RETURNS DESCRIPTION
int

Member count.

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: str

slope

Group-level coefficient label, Intercept for the intercept.

TYPE: str

term

formulae term evaluating the covariate; empty for the intercept.

TYPE: str

per_member

Whether the term evaluates one column per member (mmc()).

TYPE: bool

values

Training values Z_k, shape (rows, members); read-only.

TYPE: ndarray

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: str

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: str or None

by_columns

Columns of the by variable, one per source column of the factor: the by level of the level that source names in a row.

TYPE: tuple[str, ...]

student

Whether group-level effects follow a multivariate Student-t law (brms dist = "student").

TYPE: bool

prior_weight

Column of per-level weights on the standard-normal prior of the group-level innovations (brms pw).

TYPE: str or None

covariance

data2 name of the known covariance between the levels (brms cov).

TYPE: str or None

coded property

coded: bool

Return whether the options depend on the levels' data.

RETURNS DESCRIPTION
bool

True with a by variable, prior weights, or Student-t effects.

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: GroupOptions

by_levels

Sorted levels of the by factor; empty without by.

TYPE: tuple[str, ...]

by_codes

The by level of each grouping level, in level order.

TYPE: tuple[int, ...]

prior_weights

The prior weight of each grouping level; empty without pw.

TYPE: tuple[float, ...]

group property

group: str

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 Formula that holds the element.

TYPE: str

key

Name of the element within the field.

TYPE: str