Skip to content

quivers.formulas.compile

The FormulaToQVRModule lens turns a Formula into a quivers.dsl.ast_nodes.Module, expanding formula terms into explicit QVR declarations and program steps (inspect the generated QVR). A group intercept becomes a set of group effects and a lookup of each observation's group. The generated module shows exactly which priors, axes, and likelihood the formula produced. Its optional distributional mapping takes parsed Formula values for auxiliary parameters, giving each predictor its own coefficient namespace while sharing group coding. The lens complement still reconstructs the primary location formula; auxiliary formulas are retained in the configured lens. Offset and exposure columns enter native predictor bindings without coefficient draws; their arrays are retained by FormulaData.source and returned by fixed_column_observations.

A retained Formula.modifiers.weights column becomes an explicitly typed row input and an observation-only [weights=formula_weights] option. The lens binds its data without coefficient or prior sites and preserves the column through backward. A decision modifier additionally provides a typed binary row input; the generated program visibly combines it with the raw response before scoring the joint law. Modifier declarations describe inputs and do not add effects.

Censoring and truncation become typed row inputs and explicit observation event metadata. Censoring selects the recorded event; truncation normalizes the sampling law before that event is scored. Standard-error roles modify the family scale, and sigma=False removes the residual-scale site. The same role record provides retained columns for fresh prediction; the compiler does not create a second response-data schema.

reparameterize selects coordinates for all Gaussian group blocks, including scalar, category-specific, and component-valued members of one shared correlation. A correlated centered block emits one MultivariateNormal draw; independent coefficients use their scalar or indexed Normal laws. Noncentered blocks retain their standard Normal innovation sites. The lens's immutable group_layouts records the coefficient slices used by posterior replay. FormulaData.group_layouts retains the matching tuple for formula reconstruction, so reusing the lens for a second forward pass does not alter an earlier module's complement.

Grouped cumulative thresholds use the same hierarchical log-slack law under both choices. Flexible and sum-to-zero policies have one shape coordinate per gap; equidistant profiles have one shared gap per group. The one varying group location is reused or added once, including for binary responses. The existing named prior catalog accepts cutpoint_log_spacing_mean and cutpoint_log_spacing_scale overrides; scale priors are conditioned on nonnegative values. See the identified construction.

The optional predictor_graph retains named nonlinear additive designs, deterministic intermediates, and family-output expressions. The compiler emits their dependency order through the existing QVR value AST and applies the family link at each output once. Shared group blocks collect members across these leaves through the same layout as ordinary distributional regression; nonlinear compilation does not introduce a second group emitter.

compile

Bidirectional didactic.api.Lens from Formula to a QVR quivers.dsl.ast_nodes.Module AST.

The compilation from a formula to a QVR program is a panproto-style lens. The forward direction produces (module, formula_data): the module states which terms the model has, and FormulaData holds what a program cannot state (the data, the authored names, the original formula string) with the binding by which each authored element is recognized. The backward direction reads the terms from the module and their content from the complement.

The lens target is a Module that the existing quivers.dsl.compiler.Compiler consumes directly, identical in shape to one produced by quivers.dsl.parser.parse. Authored prior strings enter through that parser once per distinct expression within a forward preparation; emission and specialization retain their source AST.

Emitted structure (one named scalar coefficient per design-matrix column, matching the brms / lme4 canonical layout in which poly(x, 2) produces two coefficients poly(x, 2)_1 and poly(x, 2)_2):

  • One object Resp : N declaration per response plate.
  • One object G : K declaration per random-effect grouping factor (with K levels).
  • For each fixed-design column c: one scalar latent draw inside the program body, beta_c <- Normal(0, fixed_prior), whose scale is autoscaled by 1 / rms(c) so the nominal value reads in contribution space and means the same thing on a raw predictor and on an orthonormal poly column. An explicit per-name prior is emitted as written. The per-row covariate values for c flow in as a free variable via the host-data channel (observations[c]).
  • For each random-effect group (slope | g): a HalfNormal scale latent plus a per-level plate draw, with the per-row contribution as a plate-gather alpha_g[g_idx] (or beta_g_slope[g_idx] * slope for a random slope). Single-bar blocks couple coefficients through an LKJ Cholesky factor; double bars retain independent effects. Explicit shared IDs can couple location and auxiliary coefficients.
  • One observe step closes the program with the family's observation kernel applied to the inverse-link of the linear predictor.
  • Categorical responses use category zero as an identified reference and lift every fixed and random term over the remaining K - 1 logits before applying softmax.
  • Finite mixtures emit each component as a nested response block and observe the components' laws under one native Mixture (quivers.formulas._mixture).

GetPut holds for every Formula f: backward(*forward(f)) == f.

FormulaToQVRModule

FormulaToQVRModule(family: Family, *, fixed_prior: str = 'Normal(0.0, 5.0)', random_scale_prior: str = 'HalfNormal(1.0)', user_priors: PriorInput | None = None, reparameterize: Literal['centered', 'noncentered'] = 'noncentered', binomial_trials: int | str | None = None, thresholds_by: str | None = None, mixture_components: int = 2, predictor_name: str | None = None, distributional: Mapping[str, Formula] | None = None, predictor_graph: PredictorGraph | None = None, correlation_prior: str = 'LKJCholesky(1.0)', group_covariances: Mapping[str, GroupCovariance] | None = None, fixed_parameters: Mapping[str, float] | None = None, default_priors: DefaultPriorPolicy = 'quivers', center: bool | None = None, decomp: Literal['none', 'QR'] = 'none')

Bases: Lens[Formula, Module, FormulaData]

Translate a Formula to a QVR Module AST.

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

PARAMETER DESCRIPTION
family

Response family from quivers.formulas.families.

TYPE: Family

fixed_prior

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

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

random_scale_prior

Default prior for random-effect scale parameters.

TYPE: str DEFAULT: 'HalfNormal(1.0)'

correlation_prior

Default LKJ Cholesky prior for correlated coefficient blocks.

TYPE: str DEFAULT: 'LKJCholesky(1.0)'

group_covariances

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

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

user_priors

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

TYPE: PriorInput or None DEFAULT: None

reparameterize

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

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

binomial_trials

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

TYPE: int or str DEFAULT: None

thresholds_by

Grouping factor whose levels receive partially pooled ordinal cutpoint spacings.

TYPE: str or None DEFAULT: None

mixture_components

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

TYPE: int DEFAULT: 2

predictor_name

Host-data name for an external differentiable predictor.

TYPE: str or None DEFAULT: None

distributional

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

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

fixed_parameters

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

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

default_priors

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

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

center

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

TYPE: bool or None DEFAULT: None

decomp

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

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

RAISES DESCRIPTION
ValueError

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

Notes

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

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

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

group_covariances property

group_covariances: dict[str, GroupCovariance]

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

RETURNS DESCRIPTION
dict[str, GroupCovariance]

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

group_layouts property

group_layouts: tuple[GroupBlockLayout, ...]

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

RETURNS DESCRIPTION
tuple[GroupBlockLayout, ...]

Immutable group blocks shared with retained prediction plans.

level_sites property

level_sites: tuple[LevelSite, ...]

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

RETURNS DESCRIPTION
tuple[LevelSite, ...]

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

predictors property

predictors: tuple[Predictor, ...]

Return the linear predictors of the latest forward pass.

RETURNS DESCRIPTION
tuple[Predictor, ...]

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

group_laws property

group_laws: tuple[GroupBlockLaw, ...]

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

RETURNS DESCRIPTION
tuple[GroupBlockLaw, ...]

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

rows property

rows: RowSource | None

Return the rows the latest forward pass covers.

RETURNS DESCRIPTION
RowSource or None

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

site_priors property

site_priors: Mapping[str, str]

Return the priors configured for exact sites.

RETURNS DESCRIPTION
Mapping[str, str]

Prior source by site name.

observation property

observation: Observation | None

Return the observation of the latest forward pass.

RETURNS DESCRIPTION
Observation or None

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

names property

names: ProgramNames

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

RETURNS DESCRIPTION
ProgramNames

The names that differ from the terms' own.

term_laws property

term_laws: FamilyCatalog | None

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

RETURNS DESCRIPTION
FamilyCatalog or None

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

prior_targets property

prior_targets: tuple[PriorTarget, ...]

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

prior_set property

prior_set: PriorSet

Read the canonical authored prior rules retained for replay.

response_laws property

response_laws: FamilyCatalog | None

Return the compilation-local laws of the response.

RETURNS DESCRIPTION
FamilyCatalog or None

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

families

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

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

PARAMETER DESCRIPTION
response

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

TYPE: FamilyCatalog or None DEFAULT: None

RETURNS DESCRIPTION
FamilyCatalog or None

The response laws joined with those of the terms.

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

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

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

forward

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

Compile one formula through the shared response emitter.

PARAMETER DESCRIPTION
formula

Evaluated response and design metadata.

TYPE: Formula

RETURNS DESCRIPTION
tuple[Module, FormulaData]

Existing QVR program and its retained formula complement.

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

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

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

get_prior

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

Inspect the effective priors without compiling or fitting a model.

PARAMETER DESCRIPTION
formula

Evaluated response and predictor columns.

TYPE: Formula

RETURNS DESCRIPTION
dict[str, str]

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

RAISES DESCRIPTION
ValueError

If a prior override does not name an available parameter.

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

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

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

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

backward

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

Recover a formula from a QVR module and its complement.

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

PARAMETER DESCRIPTION
target

A QVR module in the image of forward.

TYPE: Module

complement

The complement forward returned with that module.

TYPE: FormulaData

RETURNS DESCRIPTION
Formula

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

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

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

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

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

symbolic_column_expressions

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

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

PARAMETER DESCRIPTION
formula

Primary predictor, together with configured auxiliary and graph leaves.

TYPE: Formula

RETURNS DESCRIPTION
dict[str, LetExprNode]

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

RAISES DESCRIPTION
ValueError

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

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

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

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

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

fixed_column_observations

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

Bind retained covariates, offsets, and response likelihood weights.

PARAMETER DESCRIPTION
formula

The formula whose fixed-effect columns are bound.

TYPE: Formula

RETURNS DESCRIPTION
dict[str, Tensor]

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

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

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

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

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

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

GroupMemberLayout didactic-model

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

Bases: ValueModel

Locate one named coefficient within its joint Gaussian block.

PARAMETER DESCRIPTION
prefix

Predictor namespace and expanded slope label.

TYPE: str

slope

Predictor namespace and expanded slope label.

TYPE: str

axis

Component axis; None denotes a scalar coefficient.

TYPE: str or None

width

Component count and first coordinate in the joint block.

TYPE: int

offset

Component count and first coordinate in the joint block.

TYPE: int

coefficient

Retained deterministic coefficient binding.

TYPE: str

raw_site

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

TYPE: str or None

scale_site

Actual emitted conditional scale site for noncentered reconstruction.

TYPE: str or None DEFAULT: None

mean_site

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

TYPE: str or None DEFAULT: None

GroupBlockLayout didactic-model

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

Bases: ValueModel

Share Gaussian coefficient slices between compilation and prediction.

PARAMETER DESCRIPTION
group

Original grouping factor and correlation-block identity.

TYPE: str

identity

Original grouping factor and correlation-block identity.

TYPE: str

coordinate_axis

Joint finite coordinate axis, absent for one scalar coefficient.

TYPE: str or None

parameterization

Whether raw sites contain coefficients or standard-normal innovations.

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

members

Ordered nonoverlapping coefficient slices.

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

correlation_site

Actual emitted Cholesky site; None denotes an independent block.

TYPE: str or None DEFAULT: None

level_covariance

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

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

width property

width: int

Return the joint coordinate count.

RETURNS DESCRIPTION
int

Sum of the retained member widths.

raw_sites property

raw_sites: dict[str, int]

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

RETURNS DESCRIPTION
dict[str, int]

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

group_covariances retains labeled known level covariance independently of coefficient correlations. Gaussian blocks use the existing MatrixNormal law on explicit support coordinates; positive-semidefinite rank declarations keep only genuine stochastic dimensions. Prediction shares the same layout and conditions new levels through the retained covariance. See the known-covariance workflow.

GroupCovariance didactic-model

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

Bases: ValueModel

A known covariance between explicitly labeled grouping levels.

PARAMETER DESCRIPTION
levels

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

TYPE: tuple[str, ...]

matrix

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

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

rank

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

TYPE: int or None DEFAULT: None

tensor

tensor() -> Tensor

Read a fresh Double-precision covariance matrix.

RETURNS DESCRIPTION
Tensor

Independent CPU storage; modifying it cannot change this value.

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

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

subset

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

Retain a labeled principal submatrix in the requested order.

PARAMETER DESCRIPTION
levels

Unique known grouping labels.

TYPE: Sequence[str]

RETURNS DESCRIPTION
GroupCovariance

Reordered covariance, retaining explicit PSD support when declared.

RAISES DESCRIPTION
ValueError

If a requested label is unknown or repeated.

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

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

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

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

basis

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

Factor a principal covariance without adding artificial dimensions.

PARAMETER DESCRIPTION
levels

Ordered labels used by one emitted Gaussian block.

TYPE: Sequence[str]

RETURNS DESCRIPTION
GroupCovarianceBasis

Orthogonal support projection and exact positive coordinate law.

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

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

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

conditional

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

Condition new Gaussian levels on the complete fitted level vector.

PARAMETER DESCRIPTION
fitted_levels

Disjoint known labels, in retained and requested order.

TYPE: Sequence[str]

new_levels

Disjoint known labels, in retained and requested order.

TYPE: Sequence[str]

RETURNS DESCRIPTION
tuple[Tensor, GroupCovarianceBasis]

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

RAISES DESCRIPTION
ValueError

If labels overlap or the conditional covariance is not PSD.

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

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

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

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

GroupCovarianceBasis didactic-model

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

Bases: ValueModel

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

PARAMETER DESCRIPTION
levels

Physical grouping labels.

TYPE: tuple[str, ...]

projection

Orthonormal columns mapping support coordinates to physical levels.

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

covariance

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

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

coordinate_factor

Cached Cholesky factor of the support covariance.

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

sampling_factor

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

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

rank property

rank: int

Return the number of stochastic level coordinates.

RETURNS DESCRIPTION
int

Support dimension, including zero for a deterministic deviation.

tensors

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

Materialize projection, coordinate covariance, and sampling factor.

PARAMETER DESCRIPTION
like

Optional floating dtype and device context.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
tuple[Tensor, Tensor, Tensor]

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

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

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

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

Typed prior plans

user_priors accepts an exact-name mapping, PriorSpec, PriorSet, or a sequence of specs. The compiler resolves selectors against one immutable PriorTarget catalogue built from the same design and group layouts as the model. prior_targets and FormulaData.prior_targets expose that catalogue; prior_set retains the authored specification. Ordinary priors use the existing compositional distribution parser, including normalized restrictions. Sampled horseshoe and R2D2 hierarchies add hyperprior sites while preserving coefficient binders and conditional group geometry. See the prior workflow.

PriorSpec didactic-model

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

Bases: ValueModel

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

PARAMETER DESCRIPTION
distribution

A compositional QVR distribution or a sampled shrinkage hierarchy.

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

class_

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

TYPE: str or None DEFAULT: 'b'

coef

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

TYPE: str or None DEFAULT: None

group

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

TYPE: str or None DEFAULT: None

dpar

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

TYPE: str or None DEFAULT: None

nlpar

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

TYPE: str or None DEFAULT: None

site

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

TYPE: str or None DEFAULT: None

response

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

TYPE: str or None DEFAULT: None

lower

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

TYPE: float or None DEFAULT: None

upper

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

TYPE: float or None DEFAULT: None

block

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

TYPE: str or None DEFAULT: None

tag

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

TYPE: str or None DEFAULT: None

selector property

selector: dict[str, str]

Return exactly the explicitly selected role coordinates.

PriorSet didactic-model

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

Bases: ValueModel

An immutable collection of prior rules with explicit override semantics.

PARAMETER DESCRIPTION
rules

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

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

PriorTarget didactic-model

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

Bases: ValueModel

One overrideable site with semantic labels and nominal component axes.

PARAMETER DESCRIPTION
site

Generated binder and semantic parameter class.

TYPE: str

class_

Generated binder and semantic parameter class.

TYPE: str

coef

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

TYPE: str or None DEFAULT: None

group

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

TYPE: str or None DEFAULT: None

dpar

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

TYPE: str or None DEFAULT: None

nlpar

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

TYPE: str or None DEFAULT: None

response

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

TYPE: str or None DEFAULT: None

axes

Nominal independent coefficient axes in source order.

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

shape

Their declared cardinalities, distinct from native event dimensions.

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

lower

Admissible coefficient-domain bounds.

TYPE: float or None DEFAULT: None

upper

Admissible coefficient-domain bounds.

TYPE: float or None DEFAULT: None

event_rank

Native distribution event rank, separate from independent axes.

TYPE: int DEFAULT: 0

component_labels

Free response-component labels in the retained coefficient order.

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

parameters

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

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

partition_labels

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

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

partition_axis

Axis over those levels.

TYPE: str or None DEFAULT: None

vector

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

TYPE: str or None DEFAULT: None

whole

Site the component is part of.

TYPE: str or None DEFAULT: None

width property

width: int

Return the number of independent selected coordinates.

sites property

sites: tuple[str, ...]

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

RETURNS DESCRIPTION
tuple[str, ...]

One or two names.

component_site

component_site(parameter: str) -> str

Name the site of one component drawn on its own.

PARAMETER DESCRIPTION
parameter

Parameter of the component.

TYPE: str

RETURNS DESCRIPTION
str

Site name.

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

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

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

components

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

Return the target of each component drawn on its own.

RETURNS DESCRIPTION
tuple[PriorTarget, ...]

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

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

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

RegularizedHorseshoe didactic-model

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

Bases: ValueModel

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

PARAMETER DESCRIPTION
df

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

TYPE: float DEFAULT: 1.0

df_global

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

TYPE: float DEFAULT: 1.0

df_slab

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

TYPE: float DEFAULT: 1.0

scale_global

Positive global and slab scales.

TYPE: float DEFAULT: 1.0

scale_slab

Positive global and slab scales.

TYPE: float DEFAULT: 1.0

par_ratio

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

TYPE: float or None DEFAULT: None

autoscale

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

TYPE: bool DEFAULT: True

main

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

TYPE: bool DEFAULT: False

R2D2 didactic-model

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

Bases: ValueModel

A Gaussian-kernel R2D2 variance-allocation hierarchy.

PARAMETER DESCRIPTION
mean_R2

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

TYPE: float DEFAULT: 0.5

prec_R2

Positive Beta precision.

TYPE: float DEFAULT: 2.0

cons_D2

Positive Dirichlet concentration, shared or per selected coordinate.

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

autoscale

Multiply coefficient scales by a scalar residual sigma when available.

TYPE: bool DEFAULT: True

main

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

TYPE: bool DEFAULT: False

normalize_priors

normalize_priors(value: PriorInput | None) -> PriorSet

Adapt legacy named priors and typed rules into one immutable representation.

PARAMETER DESCRIPTION
value

Exact-name mapping, one rule, or a collection of typed rules.

TYPE: PriorInput or None

RETURNS DESCRIPTION
PriorSet

The canonical representation retained for compilation and replay.

RAISES DESCRIPTION
TypeError

If values are neither named distribution strings nor typed rules.

Source code in src/quivers/formulas/_priors.py
def normalize_priors(value: PriorInput | None) -> PriorSet:
    """Adapt legacy named priors and typed rules into one immutable representation.

    Parameters
    ----------
    value : PriorInput or None
        Exact-name mapping, one rule, or a collection of typed rules.

    Returns
    -------
    PriorSet
        The canonical representation retained for compilation and replay.

    Raises
    ------
    TypeError
        If values are neither named distribution strings nor typed rules.
    """
    if value is None:
        return PriorSet()
    if isinstance(value, PriorSet):
        return value
    if isinstance(value, PriorSpec):
        return PriorSet(rules=(value,))
    if isinstance(value, Mapping):
        if not all(isinstance(k, str) and isinstance(v, str) for k, v in value.items()):
            raise TypeError("named priors must map site names to distribution strings")
        return PriorSet(
            rules=tuple(
                PriorSpec(distribution=v, class_=None, site=k) for k, v in value.items()
            )
        )
    if (
        not isinstance(value, Sequence)
        or isinstance(value, (str, bytes))
        or not all(isinstance(v, PriorSpec) for v in value)
    ):
        raise TypeError("priors require a named mapping or typed PriorSpec collection")
    return PriorSet(rules=tuple(value))

PriorInput

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

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

PriorDistribution

PriorDistribution = str | RegularizedHorseshoe | R2D2 | ImproperFlat | ConstantPrior

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