Skip to content

_priors

Classes

PriorSpec dataclass

Python representation of a brms prior specification.

This dataclass provides a typed interface to brms::prior_string() arguments, allowing Python developers to specify priors with IDE autocomplete and type checking. Use the prior() factory function to create instances.

Attributes:

Name Type Description
prior str

Prior distribution as string (e.g., "normal(0, 1)", "exponential(2)").

class_ (str, optional)

Parameter class: "b" (fixed effects), "sd" (group SD), "Intercept", "sigma", "cor", etc.

coef (str, optional)

Specific coefficient name for class-level priors.

group (str, optional)

Grouping variable for hierarchical effects.

dpar (str, optional)

Distributional parameter (e.g., "sigma", "phi", "zi").

resp (str, optional)

Response variable for multivariate models.

nlpar (str, optional)

Non-linear parameter name.

lb (float, optional)

Lower bound for truncated priors.

ub (float, optional)

Upper bound for truncated priors.

See Also

prior : Factory function to create PriorSpec instances. brms::prior_string : R documentation

Examples:

Create prior specifications (prefer using prior()):

from brmspy.types import PriorSpec

# Fixed effect prior
p1 = PriorSpec(prior="normal(0, 1)", class_="b")

# Group-level SD prior
p2 = PriorSpec(prior="exponential(2)", class_="sd", group="patient")

# Coefficient-specific prior with bounds
p3 = PriorSpec(prior="normal(0, 1)", class_="b", coef="age", lb=0)
Source code in brmspy/types/brms_results.py
@dataclass(frozen=True)
class PriorSpec:
    """
    Python representation of a brms prior specification.

    This dataclass provides a typed interface to `brms::prior_string()` arguments,
    allowing Python developers to specify priors with IDE autocomplete and type
    checking. Use the [`prior()`][brmspy.brms.prior] factory function to create
    instances.

    Attributes
    ----------
    prior : str
        Prior distribution as string (e.g., ``"normal(0, 1)"``, ``"exponential(2)"``).
    class_ : str, optional
        Parameter class: ``"b"`` (fixed effects), ``"sd"`` (group SD),
        ``"Intercept"``, ``"sigma"``, ``"cor"``, etc.
    coef : str, optional
        Specific coefficient name for class-level priors.
    group : str, optional
        Grouping variable for hierarchical effects.
    dpar : str, optional
        Distributional parameter (e.g., ``"sigma"``, ``"phi"``, ``"zi"``).
    resp : str, optional
        Response variable for multivariate models.
    nlpar : str, optional
        Non-linear parameter name.
    lb : float, optional
        Lower bound for truncated priors.
    ub : float, optional
        Upper bound for truncated priors.

    See Also
    --------
    prior : Factory function to create `PriorSpec` instances.
    brms::prior_string : [R documentation](https://paulbuerkner.com/brms/reference/prior_string.html)

    Examples
    --------
    Create prior specifications (prefer using [`prior()`][brmspy.brms.prior]):

    ```python
    from brmspy.types import PriorSpec

    # Fixed effect prior
    p1 = PriorSpec(prior="normal(0, 1)", class_="b")

    # Group-level SD prior
    p2 = PriorSpec(prior="exponential(2)", class_="sd", group="patient")

    # Coefficient-specific prior with bounds
    p3 = PriorSpec(prior="normal(0, 1)", class_="b", coef="age", lb=0)
    ```
    """

    prior: str
    class_: str | None = None
    coef: str | None = None
    group: str | None = None
    dpar: str | None = None
    resp: str | None = None
    nlpar: str | None = None
    lb: float | None = None
    ub: float | None = None

    def to_brms_kwargs(self) -> dict[str, Any]:
        """
        Convert PriorSpec to keyword arguments for brms::prior_string().

        Maps Python dataclass fields to R function arguments, handling
        the `class_` -> `class` parameter name conversion.

        Returns
        -------
        dict
            Keyword arguments ready for brms::prior_string()

        Examples
        --------
        ```python
        from brmspy import prior
        p = prior("normal(0, 1)", class_="b", coef="age")
        kwargs = p.to_brms_kwargs()
        print(kwargs)
        # {'prior': 'normal(0, 1)', 'class': 'b', 'coef': 'age'}
        ```
        """
        out: dict[str, Any] = {"prior": self.prior}
        if self.class_ is not None:
            out["class"] = self.class_
        if self.coef is not None:
            out["coef"] = self.coef
        if self.group is not None:
            out["group"] = self.group
        if self.dpar is not None:
            out["dpar"] = self.dpar
        if self.resp is not None:
            out["resp"] = self.resp
        if self.nlpar is not None:
            out["nlpar"] = self.nlpar
        if self.lb is not None:
            out["lb"] = self.lb
        if self.ub is not None:
            out["ub"] = self.ub
        return out

Attributes

prior instance-attribute
class_ = None class-attribute instance-attribute
coef = None class-attribute instance-attribute
group = None class-attribute instance-attribute
dpar = None class-attribute instance-attribute
resp = None class-attribute instance-attribute
nlpar = None class-attribute instance-attribute
lb = None class-attribute instance-attribute
ub = None class-attribute instance-attribute

Functions

to_brms_kwargs()

Convert PriorSpec to keyword arguments for brms::prior_string().

Maps Python dataclass fields to R function arguments, handling the class_ -> class parameter name conversion.

Returns:

Type Description
dict

Keyword arguments ready for brms::prior_string()

Examples:

from brmspy import prior
p = prior("normal(0, 1)", class_="b", coef="age")
kwargs = p.to_brms_kwargs()
print(kwargs)
# {'prior': 'normal(0, 1)', 'class': 'b', 'coef': 'age'}
Source code in brmspy/types/brms_results.py
def to_brms_kwargs(self) -> dict[str, Any]:
    """
    Convert PriorSpec to keyword arguments for brms::prior_string().

    Maps Python dataclass fields to R function arguments, handling
    the `class_` -> `class` parameter name conversion.

    Returns
    -------
    dict
        Keyword arguments ready for brms::prior_string()

    Examples
    --------
    ```python
    from brmspy import prior
    p = prior("normal(0, 1)", class_="b", coef="age")
    kwargs = p.to_brms_kwargs()
    print(kwargs)
    # {'prior': 'normal(0, 1)', 'class': 'b', 'coef': 'age'}
    ```
    """
    out: dict[str, Any] = {"prior": self.prior}
    if self.class_ is not None:
        out["class"] = self.class_
    if self.coef is not None:
        out["coef"] = self.coef
    if self.group is not None:
        out["group"] = self.group
    if self.dpar is not None:
        out["dpar"] = self.dpar
    if self.resp is not None:
        out["resp"] = self.resp
    if self.nlpar is not None:
        out["nlpar"] = self.nlpar
    if self.lb is not None:
        out["lb"] = self.lb
    if self.ub is not None:
        out["ub"] = self.ub
    return out
__init__(prior, class_=None, coef=None, group=None, dpar=None, resp=None, nlpar=None, lb=None, ub=None)

Functions

_build_priors(priors=None)

Build R brms prior object from Python PriorSpec specifications.

Converts a sequence of PriorSpec objects to a single combined R brms prior object by calling brms::prior_string() for each spec and combining with +. Used internally by fit() to translate Python prior specifications to R.

Parameters:

Name Type Description Default
priors sequence of PriorSpec

List of prior specifications. Each PriorSpec contains: - prior: Prior distribution string (e.g., "normal(0, 1)") - class_: Parameter class (e.g., "b", "Intercept", "sigma") - coef: Specific coefficient name (optional) - group: Group-level effects (optional)

If None or empty, returns empty list (brms uses default priors)

None

Returns:

Type Description
R brmsprior object or list

Combined R brms prior object if priors provided, empty list otherwise

Raises:

Type Description
AssertionError

If combined result is not a valid brmsprior object

Notes

Prior Combination:

Multiple priors are combined using R's + operator:

prior1 + prior2 + prior3

This creates a single brmsprior object containing all specifications.

brms Prior Classes:

Common parameter classes: - b: Population-level effects (regression coefficients) - Intercept: Model intercept - sigma: Residual standard deviation (for gaussian family) - sd: Standard deviation of group-level effects - cor: Correlation of group-level effects

Prior String Format:

brms uses Stan-style prior specifications: - Normal: "normal(mean, sd)" - Student-t: "student_t(df, location, scale)" - Cauchy: "cauchy(location, scale)" - Exponential: "exponential(rate)" - Uniform: "uniform(lower, upper)"

Examples:

from brmspy.types import PriorSpec
from brmspy.helpers.priors import _build_priors

# Single prior for regression coefficients
priors = [
    PriorSpec(
        prior="normal(0, 1)",
        class_="b"
    )
]
brms_prior = _build_priors(priors)
See Also

brmspy.types.PriorSpec : Prior specification class brmspy.brms.fit : Uses this to convert priors for model fitting brms::prior : R brms prior specification brms::set_prior : R function for setting priors

References

.. [1] brms prior documentation: https://paul-buerkner.github.io/brms/reference/set_prior.html .. [2] Stan prior choice recommendations: https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations

Source code in brmspy/helpers/_rpy2/_priors.py
def _build_priors(
    priors: None | Sequence[PriorSpec] = None,
) -> list[Sexp]:
    """
    Build R brms prior object from Python PriorSpec specifications.

    Converts a sequence of PriorSpec objects to a single combined R brms prior
    object by calling brms::prior_string() for each spec and combining with `+`.
    Used internally by fit() to translate Python prior specifications to R.

    Parameters
    ----------
    priors : sequence of PriorSpec, optional
        List of prior specifications. Each PriorSpec contains:
        - prior: Prior distribution string (e.g., "normal(0, 1)")
        - class_: Parameter class (e.g., "b", "Intercept", "sigma")
        - coef: Specific coefficient name (optional)
        - group: Group-level effects (optional)

        If None or empty, returns empty list (brms uses default priors)

    Returns
    -------
    R brmsprior object or list
        Combined R brms prior object if priors provided, empty list otherwise

    Raises
    ------
    AssertionError
        If combined result is not a valid brmsprior object

    Notes
    -----
    **Prior Combination:**

    Multiple priors are combined using R's `+` operator:
    ```R
    prior1 + prior2 + prior3
    ```

    This creates a single brmsprior object containing all specifications.

    **brms Prior Classes:**

    Common parameter classes:
    - **b**: Population-level effects (regression coefficients)
    - **Intercept**: Model intercept
    - **sigma**: Residual standard deviation (for gaussian family)
    - **sd**: Standard deviation of group-level effects
    - **cor**: Correlation of group-level effects

    **Prior String Format:**

    brms uses Stan-style prior specifications:
    - Normal: "normal(mean, sd)"
    - Student-t: "student_t(df, location, scale)"
    - Cauchy: "cauchy(location, scale)"
    - Exponential: "exponential(rate)"
    - Uniform: "uniform(lower, upper)"

    Examples
    --------

    ```python
    from brmspy.types import PriorSpec
    from brmspy.helpers.priors import _build_priors

    # Single prior for regression coefficients
    priors = [
        PriorSpec(
            prior="normal(0, 1)",
            class_="b"
        )
    ]
    brms_prior = _build_priors(priors)
    ```

    See Also
    --------
    brmspy.types.PriorSpec : Prior specification class
    brmspy.brms.fit : Uses this to convert priors for model fitting
    brms::prior : R brms prior specification
    brms::set_prior : R function for setting priors

    References
    ----------
    .. [1] brms prior documentation: https://paul-buerkner.github.io/brms/reference/set_prior.html
    .. [2] Stan prior choice recommendations: https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations
    """
    if not priors:
        return []
    import rpy2.robjects as ro

    from brmspy.helpers._rpy2._converters import r_to_py

    fun_prior_string = cast(Callable, ro.r("brms::prior_string"))

    prior_objs = []
    for p in priors:
        kwargs = p.to_brms_kwargs()
        # first argument is the prior string
        prior_str = kwargs.pop("prior")
        prior_obj = fun_prior_string(prior_str, **kwargs)
        prior_objs.append(prior_obj)

    brms_prior = prior_objs[0]
    for p in prior_objs[1:]:
        brms_prior = brms_prior + p

    return brms_prior