Skip to content

quivers.formulas.family

A response family is the distribution of the observations, and its link function connects the linear predictor to a parameter of that distribution (Nelder and Wedderburn, 1972). In Bernoulli regression, the inverse logit maps an unconstrained predictor to a probability. The module gives Family, Link, AuxParam, OrdinalSpec, and ResponseSpec, and the families and links registries. Family.with_links(mu="probit") selects a location link, while Family.with_links(sigma="softplus") changes a distributional scale link; link selection gives the supported names and parameterizations.

squareplus gives the positive inverse link (eta + sqrt(eta**2 + 4)) / 2; softit gives the probability inverse link softplus(eta) / (1 + softplus(eta)). The compiler uses stable equivalent forms and stages shared intermediates. The link guide distinguishes a distributional predictor's link from a scalar auxiliary prior, and the formal definition states their value-map semantics.

What a family declares

A Family states everything the compiler needs to emit it, so a new family is a new value and not a new branch in the compiler.

  • Native parameterization. Family.observe_lets binds quantities derived from mu and the auxiliary parameters, and Family.observe_args lists the native constructor arguments in order. families["gamma"], for instance, binds gamma_rate = shape / mu and passes (shape, gamma_rate).
  • Links. A Link carries its inverse as a QVR expression in Link.inverse_expr, with any shared Link.intermediates; the emitted program contains exactly that expression. Link.image is the interval the inverse maps onto.
  • Admissible links. Family.location_links and AuxParam.links list the links with_links admits. An auxiliary parameter on the positive half-line or the unit interval takes brms's links for that interval when it lists none. Family.admissible_links reads either list, and a parameter without one refuses with_links.
  • Parameter ranges. Each AuxParam has a Domain. A fixed value outside it is refused. A lower endpoint above zero also restricts the prior, and the link must map into it: the nu of frechet, for instance, must exceed one, so its link is logm1.
  • Shifts. AuxParam.below_response marks a shift every response exceeds, such as the ndt of shifted_lognormal. A fixed value is checked against the responses, a prior may name the smallest one as response_min, and inference starts below it.
  • Response support. Family.response_interval is the interval a continuous scalar response must lie in. It comes from the support and atoms of the native distribution, reached through Family.native, unless Family.response_domain states it. Every such family checks its response before inference.
  • Exposure. Family.exposure gives the distribution of a count over a rate() denominator. A family without one refuses rate().
  • Log-scale location. Family.log_location_argument names a native parameter that takes the location on the log scale; under a log link the linear predictor is passed to it without exponentiation.
  • Known errors. Family.error_scale names the residual scale that the errors of a se() term replace, or join in quadrature under sigma = TRUE. A family without one refuses se().
  • Correlated residuals. Family.elliptical is an Elliptical value naming the scale and the degrees of freedom of a Normal or Student-t residual law. Autocorrelation terms and set_rescor read the multivariate law from it. Responses are correlated only under one common value.
  • Recorded events. Family.recorded_events admits cens() and trunc(). A mixture admits them when all its components do.
  • Missing responses. A family admits mi() when a missing response can be a latent coordinate of its law: a continuous scalar law without point masses, decision, baseline or shift below the responses. Family.latent_response_obstacle gives the property that rules it out.
  • Factor responses. A factor is coded 0, ..., n - 1 when the native support is that set, or when Family.factor_levels states the number of levels (Family.coded_levels).
  • Explained variance. Family.r_squared selects the variance bayes_r2 reads by default.
  • Mixture law. Family.mixture_law names a native law for a mixture of copies of the family, such as MixtureNormal for gaussian.
  • Component scales. AuxParam.per_component gives a parameter one value per free component of the response, as the sigma of logistic_normal.

Every declaration is open to a new family. A family built with Family, or with custom_family and then with_, takes part in a feature by declaring its property:

from quivers.formulas import Elliptical, families

heavy = families["student_t"]
heavy.error_scale   # "sigma"
heavy.elliptical    # Elliptical(scale="sigma", df="nu")
heavy.with_(error_scale=None)   # refuses se(), naming Family.error_scale

Ordinal configuration

Family.ordinal retains an OrdinalSpec for cumulative, adjacent-category, stopping-ratio, continuation-ratio, or hurdle-cumulative probabilities. families["acat"].with_links(mu="probit").with_thresholds("equidistant") returns a configured value. Discrimination defaults to the constant one; explicit scalar or distributional estimates must be finite and positive. cs(expr) adds transition-specific effects. Cumulative and hurdle-cumulative effects use training-domain spacing bounds plus positive slack to keep effective row cutpoints ordered. Their proper conditional slack priors differ from independent brms threshold priors. thresholds_by combines centered group shape with exactly one reused or automatic varying location; centered and noncentered category-specific slopes may coexist with it. A fixed cs(1) with free cumulative/hurdle thresholds and a proportional intercept is redundant and fails explicitly, as do duplicate same-factor category-specific intercept/profile coordinates. The ordinal guide gives links, threshold support, generated priors, and prediction shapes.

Joint response coordinates

Family.response retains a ResponseSpec for scalar categorical responses and joint vector families. with_reference(index_or_label) selects a retained component and returns a configured family value. The default reference is the first component; dirichlet2 instead estimates every concentration and permits only None. Additive log-ratio logistic_normal requires a reference and uses identity-linked Normal coordinates, with coordinate-specific scales and an LKJ response correlation. The native AdditiveLogRatioNormal constructor retains its own final-component default.

multinomial and dirichlet_multinomial use count events; dirichlet, dirichlet2, and logistic_normal use open-simplex events. ResponseLayout retains the distinction between factor levels and named vector components. The vector guide gives component labels, inferred training totals, new-row trial counts, and explicit Monte Carlo expectations for additive log-ratio responses.

Finite mixtures

Family.mixture retains a MixtureSpec for families built by mixture: the component families after nmix repetition, the order identification, and equated parameters. The mixture's auxiliary parameters are the component parameters with the component number appended (mu1, sigma1, nu2) and the proportions theta1, ..., thetaK. Links belong to the components, so with_links refuses a mixture. The mixture guide gives the brms correspondence and the identification by ordered intercepts.

Retained proportional-hazards baselines

Family.baseline retains a BaselineSpec for cox regressions. families["cox"].with_baseline(df=5, degree=3) selects knots from training responses; with_baseline(basis) accepts an immutable MSplineBasis. The specification stores typed knot tuples and dimensions and preserves its value through link selection and serialization. The generated program retains the actual coefficient table for prediction on fresh rows.

with_baseline(..., by="site") retains separate normalized simplex profiles for a grouping column on the same basis. Fitting retains its level coding without inserting a varying intercept. Direct lens users pass the column through formula_from_data(..., groups=("site",)). New-data group policies share donor identities across baseline and coefficient sites; gaussian draws a new baseline from the actual Dirichlet law. Baseline conditioning remains active under re_formula="~0".

The location parameter is a hazard multiplier, with default log link; it is not response mean. Baseline weights have a unit-sum simplex prior sbhaz ~ Dirichlet(1), separating shape from rate. A finite positive constant tail makes response moments finite at each fixed parameter draw, but no closed mean is exposed. Use an explicit posterior_epred(mc_samples=...) budget. The regression example distinguishes rate, event draws, and expected time.

BaselineSpec didactic-model

BaselineSpec(*, df: int = 5, degree: int = 3, boundary_knots: tuple[float, ...] | None = None, interior_knots: tuple[float, ...] = (), by: str | None = None)

Bases: Model

Retain spline structure independently of fitted baseline weights.

PARAMETER DESCRIPTION
df

Number of normalized M-spline components when selecting knots.

TYPE: int DEFAULT: 5

degree

Polynomial degree when selecting knots.

TYPE: int DEFAULT: 3

boundary_knots

Explicit finite boundary span, starting at zero. None selects knots once from training events and follow-up times.

TYPE: tuple[float, float] or None DEFAULT: None

interior_knots

Explicit interior knots when boundary_knots is supplied.

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

by

Grouping factor for separate normalized profiles on this common basis.

TYPE: str or None DEFAULT: None

resolve

resolve(formula: Formula) -> MSplineBasis

Resolve the baseline once from retained training responses.

PARAMETER DESCRIPTION
formula

Evaluated positive scalar response and modifier columns.

TYPE: Formula

RETURNS DESCRIPTION
MSplineBasis

Explicit basis or event-quantile training basis.

RAISES DESCRIPTION
ValueError

If responses are not positive finite scalar event times or the requested automatic knot structure is not identified by the data.

Source code in src/quivers/formulas/_survival.py
def resolve(self, formula: Formula) -> MSplineBasis:
    """Resolve the baseline once from retained training responses.

    Parameters
    ----------
    formula : Formula
        Evaluated positive scalar response and modifier columns.

    Returns
    -------
    MSplineBasis
        Explicit basis or event-quantile training basis.

    Raises
    ------
    ValueError
        If responses are not positive finite scalar event times or the
        requested automatic knot structure is not identified by the data.
    """
    values = np.asarray(formula.response_values)
    if values.ndim != 1 or not np.isfinite(values).all() or np.any(values <= 0):
        raise ValueError(
            "cox responses require finite strictly positive event times"
        )
    if self.boundary_knots is not None:
        if len(self.boundary_knots) != 2:
            raise ValueError("cox baseline requires two boundary knots")
        if self.boundary_knots[0] != 0:
            raise ValueError("cox baseline must start at zero")
        return MSplineBasis(
            (self.boundary_knots[0], self.boundary_knots[1]),
            self.interior_knots,
            self.degree,
        )
    if self.interior_knots:
        raise ValueError("explicit interior knots require boundary knots")
    censoring = formula.modifiers.censoring
    events = values if censoring is None else values[censoring.status.data == 0]
    followup = values
    if censoring is not None and censoring.upper is not None:
        followup = np.concatenate(
            (followup, censoring.upper.data[censoring.status.data == 2])
        )
    return cox_spline_basis(
        events.tolist(), followup.tolist(), df=self.df, degree=self.degree
    )

COM-Poisson parameters

com_poisson uses log-linked rate mu=lambda and log-linked dispersion shape=nu, with scalar default Gamma(0.01, 0.01). Rate is not generally response mean. The compiler passes log_rate directly to the native kernel; transformed predictors return rate, while response expectations use its certified normalized moment. The rate guide distinguishes the pinned released Stan law from its R helper's mode parameterization and states resource and capability limits.

Count and zero-atom parameterizations

discrete_weibull uses a logit-linked survival probability, called mu in the formula interface, and a log-linked positive shape. Its scalar shape default is HalfCauchy(2). The transformed predictor gives a probability; the expected response requires a bounded numerical tail sum.

negbinomial2 reuses native NegativeBinomial with reciprocal shape 1/sigma, mean mu, and variance mu + sigma*mu**2. Its positive sigma has scalar default Gamma(0.4, 0.3) and a log link when regressed. It is a dispersion coefficient, rather than a standard deviation or the original negative_binomial family's disp.

zero_inflated_asym_laplace uses identity-linked component quantile location, log-linked scale sigma, and logit-linked quantile and zi. Their scalar defaults are HalfCauchy(2), Beta(2, 2), and Beta(2, 2), respectively. The response mean and whole-response quantiles include the zero atom. The regression guide gives scoring conventions, parameter maps, and fixed or distributional parameter examples.

Skew, shifted, and extreme-value parameters

skew_normal uses response mean and standard deviation, converting them to native skew-normal location and scale. shifted_lognormal predicts the log-location of the component above ndt; its response expectation adds ndt after exponentiating the lognormal mean correction. frechet predicts response mean and restricts its nu to exceed one. gen_extreme_value predicts location and uses a direct real shape xi. The parameter guide gives conversions, moment domains, and the GEV shape-policy distinction from the pinned brms release.

A regressed Fréchet nu requires logm1. Its scalar default conditions Gamma(2, 0.1) on nu > 1; custom scalar priors retain that restriction. The shifted-lognormal scalar ndt default is bounded by the smallest observed response, while a regressed ndt uses its declared link without hidden response-dependent rescaling. GEV uses identity-linked xi with scalar Normal(0, 0.3), rather than the pinned brms shape-prior policy.

Other response parameters

xbeta uses logit-linked underlying Beta mean mu, log-linked precision phi, and log-linked extension kappa. Its native ExtendedBeta law creates boundary atoms by censoring an affine Beta component; it does not add independent inflation parameters. Fixed kappa=0 recovers ordinary Beta responses. Expected responses use the censored law's full mean, whereas transformed linear predictions retain the component mean. Scalar auxiliary defaults are HalfCauchy(2) for precision and Gamma(0.01, 0.01) for extension; distributional coefficient priors use the shared QVR coefficient policy.

zero_inflated_beta uses logit mean and zero-probability links plus a log precision link. It lowers to native ZeroOneInflatedBeta with coi=0, retaining only the phi and zi auxiliaries. Its response mean includes the zero-atom weight; see the regression example.

hurdle_gamma uses positive-component mean/shape parameters; hurdle_lognormal uses log-location/log-scale parameters. Both have a hu auxiliary with a logit link and exact zero-atom semantics. Their response expectations include the positive-component probability, as shown in the hurdle guide.

The count variants zero_inflated_negbinomial, zero_inflated_binomial, zero_inflated_beta_binomial, and hurdle_negbinomial retain the native component's count support. zi denotes a structural-zero probability; hu denotes the hurdle's full zero probability. The negative-binomial variants use shape, and the beta-binomial variant uses precision phi. The count guide gives their component and response means.

Family.trials_parameter names the native parameter for a known trial count. Fitting and prediction use this metadata for binomial, beta-binomial, and their zero-inflated variants. binomial_trials accepts a common count or a column of nonnegative integer counts no greater than 2**53; zero trials imply a zero response. The bound preserves exact integer representation in native float64 count arithmetic. The language's Int carrier remains signed 64-bit. The trial count is data, not a fitted auxiliary parameter.

family

Response families and link functions for the formula frontend.

Each Family knows how to emit a QVR observe step plus the inverse-link expression that wraps a linear predictor. The registry maps brms-style family names to a typed family record. The record declares every property the frontend reads: the compiler, the posterior methods and the response terms consult those declarations and never the family name, so a new family opts in to whatever it declares.

Each family declares location and auxiliary links separately. The compiler converts regression parameters to QVR constructor parameters, for instance Weibull mean/shape to scale/shape. Categorical and finite-mixture families add compiler-owned component axes because their likelihood parameters are vectors rather than scalar auxiliaries.

RESPONSE_MIN module-attribute

RESPONSE_MIN = 'response_min'

Name of the smallest response in the prior of a shift below it.

LOCATION module-attribute

LOCATION = 'mu'

The parameter whose formula is the main formula of the model.

links: Mapping[str, Link] = {'identity': _IDENTITY, 'logit': _LOGIT, 'log': _LOG, 'softmax': _SOFTMAX, 'inverse': _INVERSE, 'probit': Link(name='probit', inverse_expr='0.5 * (1.0 + erf({eta} / 1.4142135623730951))', image=_UNIT_OPEN), 'probit_approx': Link(name='probit_approx', inverse_expr='sigmoid(0.07056 * ({eta} * ({eta} * {eta})) + 1.5976 * {eta})', image=_UNIT_OPEN), 'log1p': Link(name='log1p', inverse_expr='expm1({eta})', image=Domain(lower=-1.0)), 'cloglog': Link(name='cloglog', inverse_expr='-1.0 * expm1(-1.0 * exp({eta}))', image=_UNIT_OPEN), 'cauchit': Link(name='cauchit', inverse_expr='0.5 + atan({eta}) / 3.141592653589793', image=_UNIT_OPEN), 'sqrt': Link(name='sqrt', inverse_expr='{eta} * {eta}', image=_NONNEGATIVE, brms_response_expr='sqrt({y})'), 'inverse_square': Link(name='inverse_square', inverse_expr='1.0 / sqrt({eta})', image=Domain(), brms_response_expr='1.0 / ({y} * {y})'), 'logm1': Link(name='logm1', inverse_expr='1.0 + exp({eta})', image=Domain(lower=1.0)), 'softplus': Link(name='softplus', inverse_expr=_SOFTPLUS_EXPR, image=Domain()), 'squareplus': Link(name='squareplus', image=Domain(), intermediates=(Binding(name='{name}_link_half', expr='0.5 * {eta}'), Binding(name='{name}_link_scale', expr='max(1.0, abs({name}_link_half))'), Binding(name='{name}_link_root', expr='{name}_link_scale * sqrt({name}_link_half / {name}_link_scale * ({name}_link_half / {name}_link_scale) + 1.0 / {name}_link_scale * (1.0 / {name}_link_scale))'), Binding(name='{name}_link_magnitude', expr='{name}_link_root + select({name}_link_half >= 0.0, {name}_link_half, -1.0 * {name}_link_half)')), inverse_expr='select({name}_link_half >= 0.0, {name}_link_magnitude, 1.0 / {name}_link_magnitude)'), 'softit': Link(name='softit', image=_UNIT_OPEN, intermediates=(Binding(name='{name}_link_positive', expr=_SOFTPLUS_EXPR),), inverse_expr='{name}_link_positive / (1.0 + {name}_link_positive)'), 'tan_half': Link(name='tan_half', inverse_expr='2.0 * atan({eta})', image=Domain(lower=-math.pi, upper=math.pi), brms_intercept_prior='StudentT(1.0, 0.0, 1.0)')}

The built-in inverse links, keyed by link name.

families module-attribute

families: Mapping[str, Family] = FamilyRegistry({'wiener': Family(name='wiener', location_link=_IDENTITY, location_links=('identity', 'log', 'softplus', 'squareplus'), observe_family='Wiener', response_domain=Domain(), decision_event='formula_response * (2.0 * real(formula_decision) - 1.0)', observe_args=('bs', 'ndt', 'bias', 'mu'), aux_params=(AuxParam(name='bs', prior='Gamma(1.0, 1.0)', link=_LOG), AuxParam(name='ndt', prior='LogNormal(-2.0, 0.5)', link=_LOG, domain=_NONNEGATIVE, below_response=True, brms_prior='Uniform(0.0, response_min)'), AuxParam(name='bias', prior='Beta(1.0, 1.0)', link=_LOGIT, domain=_UNIT_OPEN))), 'com_poisson': Family(name='com_poisson', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='COMPoisson', recorded_events=True, log_location_argument='log_rate', observe_args=('mu', 'shape'), aux_params=(AuxParam(name='shape', prior='Gamma(0.01, 0.01)', link=_LOG),)), 'discrete_weibull': Family(name='discrete_weibull', location_link=_LOGIT, location_links=_UNIT_LINKS[:-1], observe_family='DiscreteWeibull', recorded_events=True, observe_args=('mu', 'shape'), aux_params=(AuxParam(name='shape', prior='HalfCauchy(2.0)', link=_LOG),)), 'zero_inflated_asym_laplace': Family(name='zero_inflated_asym_laplace', location_link=_IDENTITY, location_links=_SHIFTED_LINKS, observe_family='ZeroInflatedAsymmetricLaplace', recorded_events=True, observe_args=('zi', 'mu', 'sigma', 'quantile'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='quantile', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_OPEN), AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'negbinomial2': Family(name='negbinomial2', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='NegativeBinomial', recorded_events=True, exposure=Exposure(observe_lets=(Binding(name='rate_shape', expr='negative_binomial_shape * exposure'),), observe_args=('rate_shape', 'negative_binomial_probs')), observe_lets=(Binding(name='negative_binomial_shape', expr='1.0 / sigma'), Binding(name='negative_binomial_probs', expr='mu / (mu + negative_binomial_shape)')), observe_args=('negative_binomial_shape', 'negative_binomial_probs'), aux_params=(AuxParam(name='sigma', prior='Gamma(0.4, 0.3)', link=_LOG, brms_prior='Gamma(0.4, 0.3)'),)), 'skew_normal': Family(name='skew_normal', location_link=_IDENTITY, location_links=_REAL_LINKS + _REAL_EXTENSIONS, observe_family='SkewNormal', recorded_events=True, error_scale='sigma', observe_lets=(Binding(name='skew_delta', expr='sin(atan(alpha))'), Binding(name='skew_center', expr='skew_delta * 0.7978845608028654'), Binding(name='skew_scale', expr='sigma / sqrt(1.0 - skew_center * skew_center)'), Binding(name='skew_location', expr='mu - skew_scale * skew_center')), observe_args=('skew_location', 'skew_scale', 'alpha'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='alpha', prior='Normal(0.0, 4.0)', link=_IDENTITY, domain=_REAL, links=('identity', 'log', 'softplus', 'squareplus')))), 'shifted_lognormal': Family(name='shifted_lognormal', location_link=_IDENTITY, location_links=_LOG_LOCATION_LINKS, observe_family='ShiftedLogNormal', recorded_events=True, log_response=True, response_domain=Domain(), observe_args=('mu', 'sigma', 'ndt'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='ndt', prior='Uniform(0.0, response_min)', link=_LOG, domain=_NONNEGATIVE, below_response=True, brms_prior='Uniform(0.0, response_min)'))), 'frechet': Family(name='frechet', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='Frechet', recorded_events=True, observe_lets=(Binding(name='frechet_scale', expr='mu * exp(-1.0 * lgamma(1.0 - 1.0 / nu))'),), observe_args=('frechet_scale', 'nu'), aux_params=(AuxParam(name='nu', prior='Restrict(base=Gamma(concentration=2.0, rate=0.1), low=1.0)', link=links['logm1'], domain=Domain(lower=1.0), links=('logm1',)),)), 'gen_extreme_value': Family(name='gen_extreme_value', location_link=_IDENTITY, location_links=_SHIFTED_LINKS, observe_family='GeneralizedExtremeValue', recorded_events=True, observe_args=('mu', 'sigma', 'xi'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='xi', prior='Normal(0.0, 0.3)', link=_IDENTITY, domain=_REAL, links=('log1p', 'identity')))), 'gaussian': _GAUSSIAN, 'bernoulli': Family(name='bernoulli', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='Bernoulli', r_squared='model'), 'binomial': Family(name='binomial', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='Binomial', recorded_events=True, factor_levels=2, observe_args=('trials', 'mu'), trials_parameter='total_count'), 'beta_binomial': Family(name='beta_binomial', location_link=_LOGIT, location_links=_UNIT_LINKS[:-1], observe_family='BetaBinomial', recorded_events=True, observe_lets=(Binding(name='beta_binomial_concentration1', expr='mu * phi'), Binding(name='beta_binomial_concentration0', expr='(1.0 - mu) * phi')), observe_args=('trials', 'beta_binomial_concentration1', 'beta_binomial_concentration0'), trials_parameter='total_count', aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG),)), 'categorical': Family(name='categorical', location_link=_SOFTMAX, location_links=_COMPOSITIONAL_LINKS, observe_family='Categorical', response=ResponseSpec(kind='categorical')), 'multinomial': Family(name='multinomial', location_link=_SOFTMAX, location_links=_COMPOSITIONAL_LINKS, observe_family='Multinomial', observe_args=('trials', 'mu'), trials_parameter='total_count', response=ResponseSpec(kind='multinomial')), 'dirichlet_multinomial': Family(name='dirichlet_multinomial', location_link=_SOFTMAX, location_links=_COMPOSITIONAL_LINKS, observe_family='DirichletMultinomial', observe_args=('trials', 'mu'), trials_parameter='total_count', aux_params=(AuxParam(name='phi', prior='Gamma(2.0, 0.1)', link=_LOG),), response=ResponseSpec(kind='dirichlet_multinomial')), 'dirichlet': Family(name='dirichlet', location_link=_SOFTMAX, location_links=_COMPOSITIONAL_LINKS, observe_family='Dirichlet', aux_params=(AuxParam(name='phi', prior='Gamma(2.0, 0.1)', link=_LOG),), response=ResponseSpec(kind='dirichlet')), 'dirichlet2': Family(name='dirichlet2', location_link=_LOG, location_links=('log', 'softplus', 'squareplus', 'identity', 'logm1'), observe_family='Dirichlet', response=ResponseSpec(kind='dirichlet2', reference=None)), 'logistic_normal': Family(name='logistic_normal', location_link=_IDENTITY, location_links=('identity',), observe_family='AdditiveLogRatioNormal', aux_params=(AuxParam(name='sigma', prior='HalfNormal(1.0)', link=_LOG, per_component=True),), response=ResponseSpec(kind='logistic_normal')), 'poisson': Family(name='poisson', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='Poisson', recorded_events=True, exposure=Exposure(observe_lets=(Binding(name='rate_mu', expr='mu * exposure'),), observe_args=('rate_mu',))), 'negative_binomial': Family(name='negative_binomial', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='NegativeBinomial', recorded_events=True, exposure=Exposure(observe_lets=(Binding(name='rate_shape', expr='disp * exposure'),), observe_args=('rate_shape', 'negative_binomial_probs')), observe_lets=(Binding(name='negative_binomial_probs', expr='mu / (mu + disp)'),), observe_args=('disp', 'negative_binomial_probs'), aux_params=(AuxParam(name='disp', prior='Gamma(2.0, 2.0)', link=_LOG, brms_class='shape', brms_prior='InverseGamma(0.4, 0.3)'),)), 'gamma': Family(name='gamma', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='Gamma', recorded_events=True, observe_lets=(Binding(name='gamma_rate', expr='shape / mu'),), observe_args=('shape', 'gamma_rate'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'beta': Family(name='beta', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='Beta', recorded_events=True, observe_lets=(Binding(name='beta_concentration1', expr='mu * phi'), Binding(name='beta_concentration0', expr='(1.0 - mu) * phi')), observe_args=('beta_concentration1', 'beta_concentration0'), aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG),)), 'student_t': Family(name='student_t', location_link=_IDENTITY, location_links=_REAL_LINKS + _REAL_EXTENSIONS, observe_family='StudentT', recorded_events=True, error_scale='sigma', elliptical=Elliptical(scale='sigma', df='nu'), observe_args=('nu', 'mu', 'sigma'), aux_params=(AuxParam(name='nu', prior='Gamma(2.0, 0.1)', link=links['logm1'], links=('logm1', 'identity')), AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG))), 'cumulative': Family(name='cumulative', location_link=_IDENTITY, location_links=_ORDINAL_LINKS, observe_family='OrderedLogistic', ordinal=OrdinalSpec(kind='cumulative'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0),)), 'hurdle_cumulative': Family(name='hurdle_cumulative', location_link=_LOGIT, location_links=_ORDINAL_LINKS, observe_family='Categorical', ordinal=OrdinalSpec(kind='hurdle_cumulative'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0), AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'acat': Family(name='acat', location_link=_LOGIT, location_links=_ORDINAL_LINKS, observe_family='Categorical', ordinal=OrdinalSpec(kind='acat'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0),)), 'sratio': Family(name='sratio', location_link=_LOGIT, location_links=_RATIO_LINKS, observe_family='Categorical', ordinal=OrdinalSpec(kind='sratio'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0),)), 'cratio': Family(name='cratio', location_link=_LOGIT, location_links=_RATIO_LINKS, observe_family='Categorical', ordinal=OrdinalSpec(kind='cratio'), aux_params=(AuxParam(name='disc', prior='LogNormal(0.0, 1.0)', link=_LOG, fixed_default=1.0),)), 'zero_inflated_poisson': Family(name='zero_inflated_poisson', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='ZeroInflatedPoisson', recorded_events=True, observe_args=('zi', 'mu'), aux_params=(AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED),)), 'hurdle_poisson': Family(name='hurdle_poisson', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='HurdlePoisson', recorded_events=True, observe_args=('hu', 'mu'), aux_params=(AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED),)), 'zero_inflated_negbinomial': Family(name='zero_inflated_negbinomial', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='ZeroInflatedNegativeBinomial', recorded_events=True, observe_lets=(Binding(name='negative_binomial_probs', expr='mu / (mu + shape)'),), observe_args=('zi', 'shape', 'negative_binomial_probs'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG, brms_prior='InverseGamma(0.4, 0.3)'), AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'zero_inflated_binomial': Family(name='zero_inflated_binomial', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ZeroInflatedBinomial', recorded_events=True, observe_args=('zi', 'trials', 'mu'), trials_parameter='total_count', aux_params=(AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED),)), 'zero_inflated_beta_binomial': Family(name='zero_inflated_beta_binomial', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ZeroInflatedBetaBinomial', recorded_events=True, observe_lets=(Binding(name='beta_binomial_concentration1', expr='mu * phi'), Binding(name='beta_binomial_concentration0', expr='(1.0 - mu) * phi')), observe_args=('zi', 'trials', 'beta_binomial_concentration1', 'beta_binomial_concentration0'), trials_parameter='total_count', aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'hurdle_negbinomial': Family(name='hurdle_negbinomial', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='HurdleNegativeBinomial', recorded_events=True, observe_lets=(Binding(name='negative_binomial_probs', expr='mu / (mu + shape)'),), observe_args=('hu', 'shape', 'negative_binomial_probs'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG, brms_prior='InverseGamma(0.4, 0.3)'), AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'hurdle_gamma': Family(name='hurdle_gamma', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='HurdleGamma', recorded_events=True, observe_lets=(Binding(name='hurdle_gamma_rate', expr='shape / mu'),), observe_args=('hu', 'shape', 'hurdle_gamma_rate'), aux_params=(AuxParam(name='shape', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'hurdle_lognormal': Family(name='hurdle_lognormal', location_link=_IDENTITY, location_links=_LOG_LOCATION_LINKS, observe_family='HurdleLogNormal', recorded_events=True, log_response=True, observe_args=('hu', 'mu', 'sigma'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='hu', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'zero_inflated_beta': Family(name='zero_inflated_beta', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ZeroOneInflatedBeta', recorded_events=True, response_domain=Domain(upper=1.0, lower_closed=True), observe_args=('mu', 'phi', 'zi', 0.0), aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='zi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'xbeta': Family(name='xbeta', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ExtendedBeta', observe_args=('mu', 'phi', 'kappa'), aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='kappa', prior='Gamma(0.01, 0.01)', link=_LOG, brms_prior='Gamma(0.01, 0.01)'))), 'zero_one_inflated_beta': Family(name='zero_one_inflated_beta', location_link=_LOGIT, location_links=_UNIT_LINKS, observe_family='ZeroOneInflatedBeta', observe_args=('mu', 'phi', 'zoi', 'coi'), aux_params=(AuxParam(name='phi', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='zoi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED), AuxParam(name='coi', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_CLOSED))), 'lognormal': Family(name='lognormal', location_link=_IDENTITY, location_links=_LOG_LOCATION_LINKS, observe_family='LogNormal', recorded_events=True, log_response=True, observe_args=('mu', 'sigma'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG),)), 'asym_laplace': Family(name='asym_laplace', location_link=_IDENTITY, location_links=_SHIFTED_LINKS, observe_family='AsymmetricLaplace', recorded_events=True, observe_args=('mu', 'sigma', 'quantile'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='quantile', prior='Beta(2.0, 2.0)', link=_LOGIT, domain=_UNIT_OPEN))), 'exgaussian': Family(name='exgaussian', location_link=_IDENTITY, location_links=_SHIFTED_LINKS, observe_family='ExGaussian', recorded_events=True, observe_lets=(Binding(name='exgaussian_location', expr='mu - beta'), Binding(name='exgaussian_rate', expr='1.0 / beta')), observe_args=('exgaussian_location', 'sigma', 'exgaussian_rate'), aux_params=(AuxParam(name='sigma', prior='HalfCauchy(2.0)', link=_LOG), AuxParam(name='beta', prior='HalfNormal(1.0)', link=_LOG))), 'inverse_gaussian': Family(name='inverse_gaussian', location_link=_LOG, location_links=('inverse_square', 'inverse', 'identity', 'log', 'softplus', 'squareplus'), observe_family='InverseGaussian', recorded_events=True, observe_args=('mu', 'shape'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'exponential': Family(name='exponential', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='Exponential', recorded_events=True, observe_lets=(Binding(name='exponential_rate', expr='1.0 / mu'),), observe_args=('exponential_rate',)), 'geometric': Family(name='geometric', location_link=_LOG, location_links=_COUNT_LINKS, observe_family='Geometric', recorded_events=True, exposure=Exposure(observe_family='NegativeBinomial', observe_lets=(Binding(name='rate_probs', expr='mu / (1.0 + mu)'),), observe_args=('exposure', 'rate_probs')), observe_lets=(Binding(name='geometric_probs', expr='1.0 / (1.0 + mu)'),), observe_args=('geometric_probs',)), 'weibull': Family(name='weibull', location_link=_LOG, location_links=_POSITIVE_LINKS, observe_family='Weibull', recorded_events=True, observe_lets=(Binding(name='weibull_scale', expr='mu * exp(-1.0 * lgamma(1.0 + 1.0 / shape))'),), observe_args=('weibull_scale', 'shape'), aux_params=(AuxParam(name='shape', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'von_mises': Family(name='von_mises', location_link=links['tan_half'], location_links=('tan_half', 'identity'), observe_family='VonMises', recorded_events=True, circular=True, observe_args=('mu', 'kappa'), aux_params=(AuxParam(name='kappa', prior='Gamma(2.0, 2.0)', link=_LOG),)), 'cox': Family(name='cox', location_link=_LOG, location_links=('log', 'identity', 'softplus', 'squareplus'), observe_family='BernsteinHazard', recorded_events=True, observe_args=('baseline_breaks', 'baseline_controls', 'mu'), log_location_argument='log_rate', baseline=BaselineSpec()), 'mixture': Family(name='mixture', location_link=_IDENTITY, observe_family='Mixture', recorded_events=True, mixture=MixtureSpec(components=(_GAUSSIAN,)))})

The built-in response families, keyed by brms-style family name.

Each family states its link and its map to the native constructor; the compiler emits them without consulting the family name. Lookup also accepts the brms spellings of a name (negbinomial, student, Gamma, inverse.gaussian, zi_poisson), each resolving to the one registered family.

BaselineSpec didactic-model

BaselineSpec(*, df: int = 5, degree: int = 3, boundary_knots: tuple[float, ...] | None = None, interior_knots: tuple[float, ...] = (), by: str | None = None)

Bases: Model

Retain spline structure independently of fitted baseline weights.

PARAMETER DESCRIPTION
df

Number of normalized M-spline components when selecting knots.

TYPE: int DEFAULT: 5

degree

Polynomial degree when selecting knots.

TYPE: int DEFAULT: 3

boundary_knots

Explicit finite boundary span, starting at zero. None selects knots once from training events and follow-up times.

TYPE: tuple[float, float] or None DEFAULT: None

interior_knots

Explicit interior knots when boundary_knots is supplied.

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

by

Grouping factor for separate normalized profiles on this common basis.

TYPE: str or None DEFAULT: None

resolve

resolve(formula: Formula) -> MSplineBasis

Resolve the baseline once from retained training responses.

PARAMETER DESCRIPTION
formula

Evaluated positive scalar response and modifier columns.

TYPE: Formula

RETURNS DESCRIPTION
MSplineBasis

Explicit basis or event-quantile training basis.

RAISES DESCRIPTION
ValueError

If responses are not positive finite scalar event times or the requested automatic knot structure is not identified by the data.

Source code in src/quivers/formulas/_survival.py
def resolve(self, formula: Formula) -> MSplineBasis:
    """Resolve the baseline once from retained training responses.

    Parameters
    ----------
    formula : Formula
        Evaluated positive scalar response and modifier columns.

    Returns
    -------
    MSplineBasis
        Explicit basis or event-quantile training basis.

    Raises
    ------
    ValueError
        If responses are not positive finite scalar event times or the
        requested automatic knot structure is not identified by the data.
    """
    values = np.asarray(formula.response_values)
    if values.ndim != 1 or not np.isfinite(values).all() or np.any(values <= 0):
        raise ValueError(
            "cox responses require finite strictly positive event times"
        )
    if self.boundary_knots is not None:
        if len(self.boundary_knots) != 2:
            raise ValueError("cox baseline requires two boundary knots")
        if self.boundary_knots[0] != 0:
            raise ValueError("cox baseline must start at zero")
        return MSplineBasis(
            (self.boundary_knots[0], self.boundary_knots[1]),
            self.interior_knots,
            self.degree,
        )
    if self.interior_knots:
        raise ValueError("explicit interior knots require boundary knots")
    censoring = formula.modifiers.censoring
    events = values if censoring is None else values[censoring.status.data == 0]
    followup = values
    if censoring is not None and censoring.upper is not None:
        followup = np.concatenate(
            (followup, censoring.upper.data[censoring.status.data == 2])
        )
    return cox_spline_basis(
        events.tolist(), followup.tolist(), df=self.df, degree=self.degree
    )

Binding didactic-model

Binding(*, name: str, expr: str)

Bases: Model

One named quantity defined by a QVR expression over earlier names.

ATTRIBUTE DESCRIPTION
name

Name bound in the emitted program.

TYPE: str

expr

Deterministic QVR expression defining it.

TYPE: str

Exposure didactic-model

Exposure(*, observe_lets: tuple[Binding, ...] = (), observe_args: tuple[str | float, ...], observe_family: str | None = None)

Bases: Model

The law of a count accumulated over exposure unit denominators.

A family carrying one is closed under summing independent unit-exposure counts, which is what a rate() response term requires.

ATTRIBUTE DESCRIPTION
observe_lets

Quantities bound after the family's own, written over the formula parameters, the family's bindings and exposure.

TYPE: tuple[Binding, ...]

observe_args

Native constructor arguments of the accumulated count; "exposure" names the denominator itself.

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

observe_family

Native law of the accumulated count when it leaves the family's own.

TYPE: str or None

Domain didactic-model

Domain(*, lower: float | None = 0.0, upper: float | None = None, lower_closed: bool = False, upper_closed: bool = False)

Bases: Model

The interval of values a family parameter or response may take.

ATTRIBUTE DESCRIPTION
lower

Lower endpoint, or None when unbounded below.

TYPE: float or None

upper

Upper endpoint, or None when unbounded above.

TYPE: float or None

lower_closed

Whether the lower endpoint belongs to the interval.

TYPE: bool

upper_closed

Whether the upper endpoint belongs to the interval.

TYPE: bool

contains

contains(value: float) -> bool

Test membership of one finite value.

PARAMETER DESCRIPTION
value

Candidate value.

TYPE: float

RETURNS DESCRIPTION
bool

True when the value lies in the interval.

Source code in src/quivers/formulas/family.py
def contains(self, value: float) -> bool:
    """Test membership of one finite value.

    Parameters
    ----------
    value : float
        Candidate value.

    Returns
    -------
    bool
        True when the value lies in the interval.
    """
    above = self.lower is None or (
        value >= self.lower if self.lower_closed else value > self.lower
    )
    below = self.upper is None or (
        value <= self.upper if self.upper_closed else value < self.upper
    )
    return above and below

within

within(other: Domain) -> bool

Test whether this interval is contained in another.

PARAMETER DESCRIPTION
other

Candidate enclosing interval.

TYPE: Domain

RETURNS DESCRIPTION
bool

True when every value of this interval lies in other.

Source code in src/quivers/formulas/family.py
def within(self, other: Domain) -> bool:
    """Test whether this interval is contained in another.

    Parameters
    ----------
    other : Domain
        Candidate enclosing interval.

    Returns
    -------
    bool
        True when every value of this interval lies in ``other``.
    """
    above = other.lower is None or (
        self.lower is not None
        and (
            self.lower > other.lower
            or self.lower == other.lower
            and (other.lower_closed or not self.lower_closed)
        )
    )
    below = other.upper is None or (
        self.upper is not None
        and (
            self.upper < other.upper
            or self.upper == other.upper
            and (other.upper_closed or not self.upper_closed)
        )
    )
    return above and below

requirement

requirement() -> str

Describe the interval as the completion of "must ...".

RETURNS DESCRIPTION
str

A verb phrase stating the constraint.

Source code in src/quivers/formulas/family.py
def requirement(self) -> str:
    """Describe the interval as the completion of "must ...".

    Returns
    -------
    str
        A verb phrase stating the constraint.
    """
    if self.lower is None and self.upper is None:
        return "be a real number"
    if self.upper is None:
        if self.lower == 0:
            return "be nonnegative" if self.lower_closed else "be strictly positive"
        return (
            f"be at least {self.lower:g}"
            if self.lower_closed
            else f"exceed {self.lower:g}"
        )
    if self.lower is None:
        return (
            f"be at most {self.upper:g}"
            if self.upper_closed
            else f"be below {self.upper:g}"
        )
    if not self.lower_closed and not self.upper_closed:
        return f"be strictly between {self.lower:g} and {self.upper:g}"
    left = "[" if self.lower_closed else "("
    right = "]" if self.upper_closed else ")"
    return f"be in {left}{self.lower:g}, {self.upper:g}{right}"
Link(*, name: str, inverse_expr: str, intermediates: tuple[Binding, ...] = (), image: Domain | None = None, brms_intercept_prior: str | None = None, brms_response_expr: str | None = None)

Bases: Model

Inverse-link function bridging a linear predictor on :math:\mathbb{R} to the family's natural parameter space.

ATTRIBUTE DESCRIPTION
name

Canonical name (e.g. "identity", "logit", "log", "probit", "cloglog").

TYPE: str

inverse_expr

QVR expression giving the family parameter from the linear predictor, written {eta}. The compiler emits exactly this expression. {name} is the parameter being defined, for referring to intermediates.

TYPE: str

intermediates

Shared quantities bound, in order, before the inverse; each name and expression may use {eta} and {name}.

TYPE: tuple[Binding, ...]

image

Interval the inverse maps the real line onto, coordinate by coordinate for a vector link. None when it is not declared, which a parameter whose domain has a lower endpoint above zero refuses.

TYPE: Domain or None

brms_intercept_prior

brms's default prior of a centered location intercept under this link, where it is not the response-scaled Student-t.

TYPE: str or None

brms_response_expr

The link applied to the response {y}, where brms reads the scales of its default priors from the linked response; None where brms keeps its fixed scale.

TYPE: str or None

is_identity property

is_identity: bool

Whether the parameter is its linear predictor.

RETURNS DESCRIPTION
bool

True when the inverse is the identity.

is_log property

is_log: bool

Whether the linear predictor is the logarithm of the parameter.

RETURNS DESCRIPTION
bool

True when the inverse is the exponential.

OrdinalSpec didactic-model

OrdinalSpec(*, kind: Literal['cumulative', 'acat', 'sratio', 'cratio', 'hurdle_cumulative'], link: Literal['logit', 'probit', 'probit_approx', 'cloglog', 'cauchit', 'softit'] = 'logit', thresholds: Literal['flexible', 'equidistant', 'sum_to_zero'] = 'flexible')

Bases: Model

Static ordinal likelihood and threshold configuration.

ATTRIBUTE DESCRIPTION
kind

Cumulative, adjacent-category, stopping-ratio, or continuation-ratio construction. The hurdle variant adds a separate lowest category zero.

TYPE: str

link

Inverse link for cumulative or transition probabilities.

TYPE: str

thresholds

Flexible, equally spaced, or explicitly sum-centered thresholds.

TYPE: str

ParameterCoordinates didactic-model

ParameterCoordinates(*, axis: str, size: int, reference: int | None = None)

Bases: Model

The coordinates of a parameter that takes one value per element of an axis.

ATTRIBUTE DESCRIPTION
axis

Finite axis of the parameter's value.

TYPE: str

size

Number of elements of the axis.

TYPE: int

reference

Coordinate fixed at zero on the link scale, so that a predictor has one coefficient vector per other coordinate; None when every coordinate is free.

TYPE: int or None

free property

free: tuple[int, ...]

The coordinates a predictor gives a value.

RETURNS DESCRIPTION
tuple[int, ...]

Every coordinate but the reference, in axis order.

AuxParam didactic-model

AuxParam(*, name: str, prior: str, link: Link, fixed_default: float | None = None, domain: Domain = Domain(), brms_class: str | None = None, brms_prior: str | None = None, links: tuple[str, ...] | None = None, below_response: bool = False, per_component: bool = False, coordinates: ParameterCoordinates | None = None)

Bases: Model

An auxiliary family parameter (scale, dispersion, etc.).

ATTRIBUTE DESCRIPTION
name

Variable name to emit in the .qvr source.

TYPE: str

prior

Prior distribution expression (e.g. "HalfCauchy(2.0)").

TYPE: str

link

Link applied to a per-row linear predictor if the parameter is itself distributionally regressed (y ~ x, sigma ~ x, etc.); otherwise unused.

TYPE: Link

fixed_default

Optional constant used unless the parameter is explicitly regressed, fixed, or given a prior. Ordinal discrimination defaults to one.

TYPE: float or None

brms_class

brms parameter class when it differs from name.

TYPE: str or None

brms_prior

brms's default prior where it is specific to this family's parameter; otherwise the default of the parameter's brms class applies.

TYPE: str or None

domain

Values the parameter may take; the positive half-line by default. A fixed value is checked against it. A lower endpoint above zero is narrower than the native constraint, so a prior is restricted to it and a link must map into it.

TYPE: Domain

links

Links Family.with_links admits for the parameter, where they are not those brms gives every parameter of the domain (admissible_links).

TYPE: tuple[str, ...] or None

below_response

Whether the parameter is a shift every response exceeds. A fixed value is checked against the responses, prior and brms_prior may name the smallest response as response_min, and inference starts at a quarter of it unless the prior is already bounded by it.

TYPE: bool

per_component

Whether the parameter has one value per free component of the family's ResponseSpec.

TYPE: bool

coordinates

The axis of a parameter that takes one value per element of an axis of its own; None for a scalar parameter.

TYPE: ParameterCoordinates or None

parameter_class property

parameter_class: str

The brms class of the parameter.

RETURNS DESCRIPTION
str

The declared class, or the parameter's own name.

admissible_links: tuple[str, ...] | None

The links brms admits for the parameter.

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

The declared links, or those brms gives every parameter on the positive half-line or the unit interval. None for a parameter on another interval that declares no links.

bounded_by_response property

bounded_by_response: bool

Whether the default prior is bounded by the smallest response.

RETURNS DESCRIPTION
bool

True when prior names response_min.

with_response_minimum

with_response_minimum(prior: str, response: ndarray) -> str

Bind the smallest response in a prior of this parameter.

PARAMETER DESCRIPTION
prior

Prior expression, possibly naming response_min.

TYPE: str

response

Training responses.

TYPE: ndarray

RETURNS DESCRIPTION
str

The prior with response_min replaced by its value.

RAISES DESCRIPTION
ValueError

If the prior names response_min for a parameter that does not declare below_response.

Source code in src/quivers/formulas/family.py
def with_response_minimum(self, prior: str, response: np.ndarray) -> str:
    """Bind the smallest response in a prior of this parameter.

    Parameters
    ----------
    prior : str
        Prior expression, possibly naming ``response_min``.
    response : np.ndarray
        Training responses.

    Returns
    -------
    str
        The prior with ``response_min`` replaced by its value.

    Raises
    ------
    ValueError
        If the prior names ``response_min`` for a parameter that does
        not declare `below_response`.
    """
    if RESPONSE_MIN not in prior:
        return prior
    if not self.below_response:
        raise ValueError(
            f"the prior of {self.name!r} names {RESPONSE_MIN}, which only a "
            "parameter declaring AuxParam.below_response may"
        )
    return prior.replace(RESPONSE_MIN, repr(float(np.min(response))))

ResponseSpec didactic-model

ResponseSpec(*, kind: Literal['categorical', 'multinomial', 'dirichlet_multinomial', 'dirichlet', 'dirichlet2', 'logistic_normal'], reference: int | str | None = 0)

Bases: Model

Retain the component coordinate system of a categorical or vector law.

PARAMETER DESCRIPTION
kind

Native response construction using the shared component predictor.

TYPE: str

reference

Zero-predictor component by position or retained label. None gives every component its own predictor under proper coefficient priors.

TYPE: int or str or None DEFAULT: 0

reference_index

reference_index(labels: tuple[str, ...]) -> int | None

Resolve a reference against retained component or factor labels.

PARAMETER DESCRIPTION
labels

Complete component order.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
int or None

Reference position, or None for all-component predictors.

RAISES DESCRIPTION
ValueError

If the reference is missing, invalid, or incompatible with ALR.

Source code in src/quivers/formulas/family.py
def reference_index(self, labels: tuple[str, ...]) -> int | None:
    """Resolve a reference against retained component or factor labels.

    Parameters
    ----------
    labels : tuple[str, ...]
        Complete component order.

    Returns
    -------
    int or None
        Reference position, or None for all-component predictors.

    Raises
    ------
    ValueError
        If the reference is missing, invalid, or incompatible with ALR.
    """
    reference = self.reference
    if reference is None:
        if self.kind == "logistic_normal":
            raise ValueError(
                "logistic_normal requires an explicit reference component"
            )
        return None
    if isinstance(reference, str):
        if reference not in labels:
            raise ValueError(
                f"unknown reference component {reference!r}; choices are {labels}"
            )
        return labels.index(reference)
    if (
        isinstance(reference, bool)
        or not isinstance(reference, int)
        or not 0 <= reference < len(labels)
    ):
        raise ValueError("reference component must identify a retained component")
    return reference

coordinate_indices

coordinate_indices(labels: tuple[str, ...]) -> tuple[int, ...]

Return coefficient coordinates in retained component order.

PARAMETER DESCRIPTION
labels

Complete component order.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
tuple[int, ...]

Component positions carrying free predictors.

Source code in src/quivers/formulas/family.py
def coordinate_indices(self, labels: tuple[str, ...]) -> tuple[int, ...]:
    """Return coefficient coordinates in retained component order.

    Parameters
    ----------
    labels : tuple[str, ...]
        Complete component order.

    Returns
    -------
    tuple[int, ...]
        Component positions carrying free predictors.
    """
    reference = self.reference_index(labels)
    return tuple(index for index in range(len(labels)) if index != reference)

Elliptical didactic-model

Elliptical(*, scale: str, df: str | None = None)

Bases: Model

The elliptical residual law of a location-scale family.

A family declaring one has the density of a multivariate Normal or Student-t in one coordinate, so residuals may be correlated across rows (autocorrelation terms) or across responses (set_rescor) under the multivariate law with the same scale and degrees of freedom.

ATTRIBUTE DESCRIPTION
scale

Auxiliary parameter scaling the residual.

TYPE: str

df

Auxiliary parameter giving the Student degrees of freedom; None for the Normal law.

TYPE: str or None

kernel property

kernel: str

The native law of a correlated residual vector.

RETURNS DESCRIPTION
str

The multivariate Normal, or Student-t under degrees of freedom.

parameterization property

parameterization: tuple[str, ...]

The constructor parameters of kernel in schema order.

RETURNS DESCRIPTION
tuple[str, ...]

Location and Cholesky scale factor, after the degrees of freedom of a Student-t.

MixtureSpec didactic-model

MixtureSpec(*, components: tuple[Family, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), order: Literal['mu', 'none'] = 'none', equal: tuple[tuple[str, str], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Retain the components and identification of a finite mixture family.

PARAMETER DESCRIPTION
components

Component families in brms order; nmix repetitions are expanded. One component is a template, repeated mixture_components times.

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

order

"mu" orders the component location intercepts; "none" applies no ordering constraint.

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

equal

Distributional parameters set equal to another parameter of the same class, brms sigma2 = "sigma1", as (target, source) pairs.

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

Family didactic-model

Family(*, name: str, location_link: Link, observe_family: str, observe_lets: tuple[Binding, ...] = (), observe_args: tuple[str | float, ...] = ('mu',), exposure: Exposure | None = None, log_location_argument: str | None = None, circular: bool = False, log_response: bool = False, response_domain: Domain | None = None, decision_event: str | None = None, location_links: tuple[str, ...] | None = None, recorded_events: bool = False, error_scale: str | None = None, elliptical: Elliptical | None = None, r_squared: Literal['model', 'residual'] = 'residual', factor_levels: int | None = None, mixture_law: str | None = None, aux_params: tuple[AuxParam, ...] = (), trials_parameter: str | None = None, ordinal: OrdinalSpec | None = None, response: ResponseSpec | None = None, baseline: BaselineSpec | None = None, custom: CustomFamilySpec | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), mixture: MixtureSpec | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), kernel_law: KernelLaw | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Response family: observation kernel plus its link and any auxiliary parameters.

The compiler emits, for each family-keyed regression:

  1. The auxiliary-parameter latent draws (intercept-only by default; one per parameter named in aux_params).
  2. A let eta = <linear predictor> binding the location's linear predictor.
  3. A let mu = <link.inverse_expr> binding the natural parameter.
  4. A single observe y : Resp <- <observe_family>(mu, ...) step parameterised by mu and the auxiliary parameters.

The native constructor rarely shares the formula parameterization (a mean and a shape against a concentration and a rate). observe_lets and observe_args state that map as data, so the compiler emits any family the same way.

trials_parameter identifies families that require a constant or per-row number of trials. It names the native constructor parameter; fitting and prediction use the same metadata to validate trial counts. ordinal retains static likelihood, inverse-link, and threshold choices; ordinary QVR expressions lower these choices to checked category logits. response retains joint component predictors, reference coordinates, and the distinction between scalar categorical and vector response events.

PARAMETER DESCRIPTION
name

Formula registry key.

TYPE: str

location_link

Location or mean inverse link.

TYPE: Link

observe_family

Checked native observation family.

TYPE: str

observe_lets

Quantities derived from mu and the auxiliary parameters, bound in order before the observation: the map from the formula parameterization to the native constructor's.

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

observe_args

Native constructor arguments in schema order: names of formula parameters or of observe_lets, literal constants, or "trials" for the per-row trial counts of a family with trials_parameter.

TYPE: tuple[str or float, ...] DEFAULT: ('mu',)

exposure

Law of the count over a rate() denominator; None when the family is not closed under summing unit-exposure counts.

TYPE: Exposure or None DEFAULT: None

log_location_argument

Native constructor parameter that accepts the location on the log scale. Under a log location link the linear predictor is passed to it directly, so a rate too large to exponentiate still scores.

TYPE: str or None DEFAULT: None

circular

Whether the response is an angle, for which an expectation needs an angular convention and no arithmetic mean is defined.

TYPE: bool DEFAULT: False

log_response

Whether the location and scale parameterize the logarithm of the response, so default prior scales are taken on the log response.

TYPE: bool DEFAULT: False

response_domain

Interval every observed response must lie in, stated only where the native support depends on parameters or the family narrows it; otherwise the native support and its atoms give it.

TYPE: Domain or None DEFAULT: None

decision_event

Expression forming the scored event from formula_response and the binary formula_decision of a dec() term. None for a family whose event is its response.

TYPE: str or None DEFAULT: None

location_links

Links with_links admits for the location; None declares no decision, and with_links refuses a location link.

TYPE: tuple[str, ...] or None DEFAULT: None

recorded_events

Whether the family admits the cens() and trunc() terms.

TYPE: bool DEFAULT: False

error_scale

Auxiliary parameter giving the residual scale that the known errors of a se() term replace, or join in quadrature; None when the family admits no se().

TYPE: str or None DEFAULT: None

elliptical

Elliptical residual law, under which residuals may be correlated across rows or responses.

TYPE: Elliptical or None DEFAULT: None

r_squared

Variance bayes_r2 reads by default: the law's own conditional variance or that of the residuals.

TYPE: ('model', 'residual') DEFAULT: "model"

factor_levels

Number of levels of a factor response the family codes 0, ..., n - 1, stated only where the native support depends on parameters (coded_levels).

TYPE: int or None DEFAULT: None

mixture_law

Native law of a finite mixture whose components all have this family, over the stacked native arguments of the components. The law must truncate each component itself. None mixes the component laws.

TYPE: str or None DEFAULT: None

aux_params

Auxiliary priors and distributional links.

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

trials_parameter

Native parameter receiving exact per-row trial counts.

TYPE: str or None DEFAULT: None

ordinal

Retained ordinal thresholds and transition construction.

TYPE: OrdinalSpec or None DEFAULT: None

response

Joint component coordinate system and reference selection.

TYPE: ResponseSpec or None DEFAULT: None

baseline

Retained normalized spline structure for proportional hazards.

TYPE: BaselineSpec or None DEFAULT: None

custom

Checked custom constructor bindings and compilation-local native law.

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

mixture

Components and ordering of a finite mixture built by quivers.formulas.mixture.

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

kernel_law

A law that builds the family's kernel itself, such as a named QVR program; None for a family observed through its native law.

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

response_interval property

response_interval: Domain | None

The interval a scalar continuous response must lie in.

An atom of the native law at an endpoint of its support closes that endpoint.

RETURNS DESCRIPTION
Domain or None

The declared or native interval, or None for a discrete, vector or composite response, whose values are checked by their coding.

native property

The semantic record of the observed native law.

Support, element type, discreteness, atoms and event rank are read from it; the family does not restate them.

RETURNS DESCRIPTION
DistributionFamily

The record registered under observe_family, from the custom catalog of a custom family.

retains_log_location property

retains_log_location: bool

Whether the observation takes the linear predictor on the log scale.

RETURNS DESCRIPTION
bool

True when the native law accepts a log-scale location and the location link is the logarithm.

vector_response property

vector_response: bool

Whether one response event is a vector of components.

RETURNS DESCRIPTION
bool

True for compositional and count-vector responses.

coded_levels property

coded_levels: int | None

Number of levels of a factor the family reads as integer codes.

RETURNS DESCRIPTION
int or None

The declared number, or the size of a native support 0, ..., n - 1. None for a family without such codes; a category_response takes any number of levels.

scores_cutpoints property

scores_cutpoints: bool

Whether the native law of an ordinal family takes its cutpoints.

RETURNS DESCRIPTION
bool

True for a law over a predictor and cutpoints, False for a law over category logits.

component_scale property

component_scale: AuxParam | None

The auxiliary parameter with one value per free component.

RETURNS DESCRIPTION
AuxParam or None

The parameter declaring AuxParam.per_component, if any.

residual_scale property

residual_scale: AuxParam | None

The residual scale, the parameter of brms class sigma.

RETURNS DESCRIPTION
AuxParam or None

The parameter of that class, or None.

latent_response_obstacle property

latent_response_obstacle: str | None

Why a missing response cannot be a latent coordinate.

A missing mi() response is a latent coordinate drawn from the response law, so the law needs a density on an interval and nothing fixed by the recorded responses.

RETURNS DESCRIPTION
str or None

The property that rules it out, or None when the family admits mi() responses.

reads_location property

reads_location: bool

Whether the family's kernel reads the location mu.

RETURNS DESCRIPTION
bool

True for a native law; for a kernel law, whether mu is one of the parameters it replaces.

kernel_columns property

kernel_columns: tuple[str, ...]

The data columns the family's kernel reads at each row by name.

RETURNS DESCRIPTION
tuple[str, ...]

The columns of a kernel law; empty for a native law, which reads only the formulas' columns.

unordered_categories property

unordered_categories: bool

Whether the response is an unordered category code.

RETURNS DESCRIPTION
bool

True for a scalar categorical response.

category_response property

category_response: bool

Whether the response is a category code with class probabilities.

RETURNS DESCRIPTION
bool

True for ordinal and unordered categorical responses, and for a mixture of ordinal components.

native_parameter

native_parameter(name: str) -> str

Name the native constructor parameter that receives a quantity.

PARAMETER DESCRIPTION
name

Formula parameter or derived binding passed to the constructor.

TYPE: str

RETURNS DESCRIPTION
str

The constructor parameter in the native schema.

RAISES DESCRIPTION
ValueError

If the quantity is not itself a native constructor argument.

Source code in src/quivers/formulas/family.py
def native_parameter(self, name: str) -> str:
    """Name the native constructor parameter that receives a quantity.

    Parameters
    ----------
    name : str
        Formula parameter or derived binding passed to the constructor.

    Returns
    -------
    str
        The constructor parameter in the native schema.

    Raises
    ------
    ValueError
        If the quantity is not itself a native constructor argument.
    """
    arguments = {
        argument: native
        for argument, native in zip(
            self.observe_args, self.native.parameter_names, strict=False
        )
        if isinstance(argument, str)
    }
    if name not in arguments:
        raise ValueError(
            f"family {self.name!r} does not pass {name!r} to its native "
            "constructor (Family.observe_args)"
        )
    return arguments[name]
admissible_links(parameter: str) -> tuple[str, ...]

List the links the family admits for one parameter.

PARAMETER DESCRIPTION
parameter

mu for the location or an auxiliary parameter name.

TYPE: str

RETURNS DESCRIPTION
tuple[str, ...]

Admissible link names; those of its component for a mixture template.

RAISES DESCRIPTION
ValueError

If the parameter is unknown or declares no links.

Source code in src/quivers/formulas/family.py
def admissible_links(self, parameter: str) -> tuple[str, ...]:
    """List the links the family admits for one parameter.

    Parameters
    ----------
    parameter : str
        ``mu`` for the location or an auxiliary parameter name.

    Returns
    -------
    tuple[str, ...]
        Admissible link names; those of its component for a mixture
        template.

    Raises
    ------
    ValueError
        If the parameter is unknown or declares no links.
    """
    if self.mixture is not None and len(self.mixture.components) == 1:
        return self.mixture.components[0].admissible_links(parameter)
    if parameter == "mu":
        declared, field = self.location_links, "Family.location_links"
    else:
        aux = next((aux for aux in self.aux_params if aux.name == parameter), None)
        if aux is None:
            raise ValueError(
                f"unknown family parameter {parameter!r} of {self.name!r}"
            )
        declared, field = aux.admissible_links, "AuxParam.links"
    if declared is None:
        raise ValueError(
            f"family {self.name!r} declares no admissible links for parameter "
            f"{parameter!r} ({field})"
        )
    return declared

kernel_bindings

kernel_bindings(frame: DataFrame, data2: Mapping[str, ndarray | DataFrame | Tensor | float | int] | None) -> dict[str, Tensor]

Bind the data the family's kernel reads by name.

PARAMETER DESCRIPTION
frame

The rows of the response, in row order.

TYPE: DataFrame

data2

Values that are not indexed by the rows.

TYPE: Mapping[str, ndarray or DataFrame or Tensor or float or int] or None

RETURNS DESCRIPTION
dict[str, Tensor]

Values by input name; empty for a native law.

Source code in src/quivers/formulas/family.py
def kernel_bindings(
    self,
    frame: pd.DataFrame,
    data2: Mapping[str, np.ndarray | pd.DataFrame | torch.Tensor | float | int]
    | None,
) -> dict[str, torch.Tensor]:
    """Bind the data the family's kernel reads by name.

    Parameters
    ----------
    frame : pandas.DataFrame
        The rows of the response, in row order.
    data2 : Mapping[str, numpy.ndarray or pandas.DataFrame or torch.Tensor or float or int] or None
        Values that are not indexed by the rows.

    Returns
    -------
    dict[str, torch.Tensor]
        Values by input name; empty for a native law.
    """
    return {} if self.kernel_law is None else self.kernel_law.bindings(frame, data2)

check_kernel

check_kernel(module: Module, families: FamilyCatalog | None) -> None

Check a model emitted with the family's kernel law.

A native law's model is correct by its construction; a kernel law states a body the formulas change, so its model is checked.

PARAMETER DESCRIPTION
module

The emitted model.

TYPE: Module

families

Compilation-local laws of the model.

TYPE: FamilyCatalog or None

Source code in src/quivers/formulas/family.py
def check_kernel(self, module: Module, families: FamilyCatalog | None) -> None:
    """Check a model emitted with the family's kernel law.

    A native law's model is correct by its construction; a kernel law
    states a body the formulas change, so its model is checked.

    Parameters
    ----------
    module : Module
        The emitted model.
    families : FamilyCatalog or None
        Compilation-local laws of the model.
    """
    if self.kernel_law is not None:
        self.kernel_law.check(module, families)

with_baseline

with_baseline(basis: MSplineBasis | None = None, *, df: int = 5, degree: int = 3, by: str | None = None) -> Family

Configure a retained normalized baseline for proportional hazards.

PARAMETER DESCRIPTION
basis

Explicit immutable knots and tail policy, or automatic training knots.

TYPE: MSplineBasis or None DEFAULT: None

df

Number of basis components for automatic selection.

TYPE: int DEFAULT: 5

degree

Polynomial degree for automatic selection.

TYPE: int DEFAULT: 3

by

Grouping factor with a separate normalized baseline simplex per level. Every group retains the same knot structure and endpoint tail policy.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
Family

Independent family retaining the selected baseline structure.

RAISES DESCRIPTION
ValueError

If this is not a baseline-hazard family or automatic dimensions are invalid.

Source code in src/quivers/formulas/family.py
def with_baseline(
    self,
    basis: MSplineBasis | None = None,
    *,
    df: int = 5,
    degree: int = 3,
    by: str | None = None,
) -> Family:
    """Configure a retained normalized baseline for proportional hazards.

    Parameters
    ----------
    basis : MSplineBasis or None
        Explicit immutable knots and tail policy, or automatic training knots.
    df : int
        Number of basis components for automatic selection.
    degree : int
        Polynomial degree for automatic selection.
    by : str or None
        Grouping factor with a separate normalized baseline simplex per level.
        Every group retains the same knot structure and endpoint tail policy.

    Returns
    -------
    Family
        Independent family retaining the selected baseline structure.

    Raises
    ------
    ValueError
        If this is not a baseline-hazard family or automatic dimensions are invalid.
    """
    if self.baseline is None:
        raise ValueError(
            "baseline configuration requires a proportional-hazards family"
        )
    if basis is not None and not isinstance(basis, MSplineBasis):
        raise ValueError("basis must be an immutable MSplineBasis")
    if isinstance(degree, bool) or not isinstance(degree, int) or degree < 0:
        raise ValueError("baseline degree must be a nonnegative integer")
    if isinstance(df, bool) or not isinstance(df, int) or df < degree + 1:
        raise ValueError("baseline df must be an integer at least degree + 1")
    if by is not None and (not isinstance(by, str) or not by):
        raise ValueError("baseline by must be a nonempty grouping column name")
    return self.with_(
        baseline=BaselineSpec(
            df=basis.size if basis is not None else df,
            degree=basis.degree if basis is not None else degree,
            boundary_knots=basis.boundary_knots if basis is not None else None,
            interior_knots=basis.interior_knots if basis is not None else (),
            by=by,
        )
    )

response_ordinal

response_ordinal() -> OrdinalSpec | None

Read the ordinal construction that codes the response categories.

RETURNS DESCRIPTION
OrdinalSpec or None

The family's own ordinal specification, that of the first component for a mixture of ordinal families, or None for a response without ordered categories.

Source code in src/quivers/formulas/family.py
def response_ordinal(self) -> OrdinalSpec | None:
    """Read the ordinal construction that codes the response categories.

    Returns
    -------
    OrdinalSpec or None
        The family's own ordinal specification, that of the first
        component for a mixture of ordinal families, or None for a
        response without ordered categories.
    """
    if self.mixture is not None:
        return self.mixture.components[0].ordinal
    return self.ordinal

with_reference

with_reference(reference: int | str | None) -> Family

Select the reference component of a joint categorical predictor.

PARAMETER DESCRIPTION
reference

Component position or label; None estimates every component.

TYPE: int or str or None

RETURNS DESCRIPTION
Family

Independent family retaining the selected coordinate system.

RAISES DESCRIPTION
ValueError

If this family has no component predictor or forbids references.

Source code in src/quivers/formulas/family.py
def with_reference(self, reference: int | str | None) -> Family:
    """Select the reference component of a joint categorical predictor.

    Parameters
    ----------
    reference : int or str or None
        Component position or label; None estimates every component.

    Returns
    -------
    Family
        Independent family retaining the selected coordinate system.

    Raises
    ------
    ValueError
        If this family has no component predictor or forbids references.
    """
    if self.response is None:
        raise ValueError(
            "reference components require a categorical or vector family"
        )
    if self.response.kind == "dirichlet2" and reference is not None:
        raise ValueError(
            "dirichlet2 estimates every concentration and has no reference"
        )
    if self.response.kind == "logistic_normal" and reference is None:
        raise ValueError("logistic_normal requires an explicit reference component")
    return self.with_(response=self.response.with_(reference=reference))

with_thresholds

with_thresholds(thresholds: Literal['flexible', 'equidistant', 'sum_to_zero']) -> Family

Return an ordinal family with the requested threshold structure.

PARAMETER DESCRIPTION
thresholds

Threshold configuration; ordering applies only to cumulative models.

TYPE: ('flexible', 'equidistant', 'sum_to_zero') DEFAULT: "flexible"

RETURNS DESCRIPTION
Family

Independent family value preserving links and auxiliary parameters.

RAISES DESCRIPTION
ValueError

If the family is not ordinal or the threshold option is unknown.

Source code in src/quivers/formulas/family.py
def with_thresholds(
    self, thresholds: Literal["flexible", "equidistant", "sum_to_zero"]
) -> Family:
    """Return an ordinal family with the requested threshold structure.

    Parameters
    ----------
    thresholds : {"flexible", "equidistant", "sum_to_zero"}
        Threshold configuration; ordering applies only to cumulative models.

    Returns
    -------
    Family
        Independent family value preserving links and auxiliary parameters.

    Raises
    ------
    ValueError
        If the family is not ordinal or the threshold option is unknown.
    """
    if self.ordinal is None:
        raise ValueError("threshold configuration requires an ordinal family")
    if thresholds not in {"flexible", "equidistant", "sum_to_zero"}:
        raise ValueError(f"unknown ordinal threshold configuration {thresholds!r}")
    return self.with_(ordinal=self.ordinal.with_(thresholds=thresholds))
with_links(**parameters: str) -> Family

Return a family with selected parameter links.

PARAMETER DESCRIPTION
**parameters

Link names keyed by mu for the location or an auxiliary parameter name, for instance sigma="softplus". The links of a mixture template are those of its one component.

TYPE: str DEFAULT: {}

RETURNS DESCRIPTION
Family

An independent family value with the requested links.

RAISES DESCRIPTION
ValueError

If a parameter or link is unknown, or if brms does not admit the link for that family parameter; the error lists the admissible links. Categorical models require their multinomial softmax location link.

Source code in src/quivers/formulas/family.py
def with_links(self, **parameters: str) -> Family:
    """Return a family with selected parameter links.

    Parameters
    ----------
    **parameters : str
        Link names keyed by ``mu`` for the location or an auxiliary
        parameter name, for instance ``sigma="softplus"``. The links of
        a mixture template are those of its one component.

    Returns
    -------
    Family
        An independent family value with the requested links.

    Raises
    ------
    ValueError
        If a parameter or link is unknown, or if brms does not admit the
        link for that family parameter; the error lists the admissible
        links. Categorical models require their multinomial softmax
        location link.
    """
    if self.mixture is not None:
        if len(self.mixture.components) > 1:
            raise ValueError(
                "mixture links belong to the components; set them before mixture()"
            )
        template = self.mixture.components[0].with_links(**parameters)
        return self.with_(
            location_link=template.location_link,
            mixture=self.mixture.with_(components=(template,)),
        )
    known = {"mu", *(aux.name for aux in self.aux_params)}
    unknown = parameters.keys() - known
    if unknown:
        raise ValueError(
            f"unknown family parameters {sorted(unknown)}; choices are {sorted(known)}"
        )
    if self.response is not None and self.response.kind in {
        "categorical",
        "multinomial",
        "dirichlet_multinomial",
        "dirichlet",
    }:
        if parameters.get("mu") == "logit":
            parameters["mu"] = "softmax"
        if parameters.get("mu", "softmax") != "softmax":
            raise ValueError(
                "compositional means require the softmax location link"
            )
    if (
        self.response is not None
        and self.response.kind == "logistic_normal"
        and parameters.get("mu", "identity") != "identity"
    ):
        raise ValueError(
            "logistic_normal log ratios require the identity location link"
        )
    invalid = set(parameters.values()) - links.keys()
    if invalid:
        raise ValueError(
            f"unknown links {sorted(invalid)}; choices are {sorted(links)}"
        )
    ordinal = self.ordinal
    observe_family = self.observe_family
    requested = dict(parameters)
    if ordinal is not None and "mu" in parameters:
        # The location of a cumulative family is its own linear predictor;
        # the identity keeps it, with thresholds on the logit scale.
        if parameters["mu"] == "identity" and ordinal.kind == "cumulative":
            requested["mu"] = "logit"
    for parameter, link in requested.items():
        allowed = self.admissible_links(parameter)
        if link not in allowed:
            raise ValueError(
                f"link {link!r} is not supported for parameter {parameter!r} of "
                f"family {self.name!r}; admissible links are {list(allowed)}"
            )
    if ordinal is not None and "mu" in requested:
        ordinal = ordinal.with_(link=requested["mu"])
        observe_family = (
            _CUTPOINT_LAWS.get(ordinal.link, "Categorical")
            if ordinal.kind == "cumulative"
            else "Categorical"
        )
    return self.with_(
        location_link=links[parameters["mu"]]
        if "mu" in parameters
        else self.location_link,
        observe_family=observe_family,
        ordinal=ordinal,
        aux_params=tuple(
            aux.with_(link=links[parameters[aux.name]])
            if aux.name in parameters
            else aux
            for aux in self.aux_params
        ),
    )

parameter_prefix

parameter_prefix(name: str) -> str

Return the namespace of the predictor of a parameter.

PARAMETER DESCRIPTION
name

Parameter name.

TYPE: str

RETURNS DESCRIPTION
str

Empty for the location mu, whose formula is the main formula; dpar_<name>_ for any other parameter.

Source code in src/quivers/formulas/family.py
def parameter_prefix(name: str) -> str:
    """Return the namespace of the predictor of a parameter.

    Parameters
    ----------
    name : str
        Parameter name.

    Returns
    -------
    str
        Empty for the location ``mu``, whose formula is the main formula;
        ``dpar_<name>_`` for any other parameter.
    """
    return "" if name == LOCATION else f"dpar_{name}_"

Cited sources

J. A. Nelder and R. W. M. Wedderburn. Generalized Linear Models. Journal of the Royal Statistical Society. Series A (General), 135(3):370–384, 1972. URL: https://academic.oup.com/jrsssa/article/135/3/370/7110572, doi:10.2307/2344614.