Skip to content

_brms_module

Main brms module with Pythonic API.

Attributes

FitResult = IDResult[IDBrm] module-attribute

Classes

IDResult dataclass

Bases: Generic[T_idata], RListVectorExtension

Generic result container with arviz and R objects.

Attributes:

Name Type Description
idata InferenceData

arviz InferenceData object

r ListVector

R object from brms

Source code in brmspy/types/brms_results.py
@dataclass
class IDResult(Generic[T_idata], RListVectorExtension):
    """Generic result container with arviz and R objects.

    Attributes
    ----------
    idata : arviz.InferenceData
        arviz InferenceData object
    r : robjects.ListVector
        R object from brms
    """

    idata: T_idata

    def __repr__(self) -> str:
        return repr(self.idata)

Attributes

idata instance-attribute

Functions

__repr__()
Source code in brmspy/types/brms_results.py
def __repr__(self) -> str:
    return repr(self.idata)
__init__(r, idata)

LooResult dataclass

Bases: RListVectorExtension

Parsed brms::loo() result.

Attributes:

Name Type Description
estimates, pointwise, diagnostics DataFrame

LOO tables.

psis_object Any or None

PSIS object (if present). May be an R-handle wrapper depending on conversion.

elpd_loo, p_loo, looic float

Key scalar metrics.

se_elpd_loo, se_p_loo, se_looic float

Standard errors for the corresponding scalars.

Source code in brmspy/types/brms_results.py
@dataclass
class LooResult(RListVectorExtension):
    """
    Parsed `brms::loo()` result.

    Attributes
    ----------
    estimates, pointwise, diagnostics : pandas.DataFrame
        LOO tables.
    psis_object : Any or None
        PSIS object (if present). May be an R-handle wrapper depending on conversion.
    elpd_loo, p_loo, looic : float
        Key scalar metrics.
    se_elpd_loo, se_p_loo, se_looic : float
        Standard errors for the corresponding scalars.
    """

    estimates: pd.DataFrame
    pointwise: pd.DataFrame
    diagnostics: pd.DataFrame
    psis_object: Any | None
    elpd_loo: float
    p_loo: float
    looic: float
    se_elpd_loo: float
    se_p_loo: float
    se_looic: float

    def __repr__(self) -> str:
        """Pretty print LOO-CV results."""
        lines = []
        lines.append("LOO-CV Results")
        lines.append("=" * 50)
        lines.append(f"ELPD LOO:  {self.elpd_loo:>10.2f}  (SE: {self.se_elpd_loo:.2f})")
        lines.append(f"p_loo:     {self.p_loo:>10.2f}  (SE: {self.se_p_loo:.2f})")
        lines.append(f"LOOIC:     {self.looic:>10.2f}  (SE: {self.se_looic:.2f})")
        lines.append("")

        # Show Pareto k diagnostic summary if available
        if isinstance(self.diagnostics, pd.DataFrame) and not self.diagnostics.empty:
            if "pareto_k" in self.diagnostics.columns:
                k_vals = self.diagnostics["pareto_k"]
                lines.append("Pareto k Diagnostics:")
                lines.append(
                    f"  Good (k < 0.5):       {(k_vals < 0.5).sum():>5} observations"
                )
                lines.append(
                    f"  OK (0.5 ≤ k < 0.7):   {((k_vals >= 0.5) & (k_vals < 0.7)).sum():>5} observations"
                )
                lines.append(
                    f"  Bad (0.7 ≤ k < 1):    {((k_vals >= 0.7) & (k_vals < 1)).sum():>5} observations"
                )
                lines.append(
                    f"  Very bad (k ≥ 1):     {(k_vals >= 1).sum():>5} observations"
                )

        return "\n".join(lines)

Attributes

estimates instance-attribute
pointwise instance-attribute
diagnostics instance-attribute
psis_object instance-attribute
elpd_loo instance-attribute
p_loo instance-attribute
looic instance-attribute
se_elpd_loo instance-attribute
se_p_loo instance-attribute
se_looic instance-attribute

Functions

__repr__()

Pretty print LOO-CV results.

Source code in brmspy/types/brms_results.py
def __repr__(self) -> str:
    """Pretty print LOO-CV results."""
    lines = []
    lines.append("LOO-CV Results")
    lines.append("=" * 50)
    lines.append(f"ELPD LOO:  {self.elpd_loo:>10.2f}  (SE: {self.se_elpd_loo:.2f})")
    lines.append(f"p_loo:     {self.p_loo:>10.2f}  (SE: {self.se_p_loo:.2f})")
    lines.append(f"LOOIC:     {self.looic:>10.2f}  (SE: {self.se_looic:.2f})")
    lines.append("")

    # Show Pareto k diagnostic summary if available
    if isinstance(self.diagnostics, pd.DataFrame) and not self.diagnostics.empty:
        if "pareto_k" in self.diagnostics.columns:
            k_vals = self.diagnostics["pareto_k"]
            lines.append("Pareto k Diagnostics:")
            lines.append(
                f"  Good (k < 0.5):       {(k_vals < 0.5).sum():>5} observations"
            )
            lines.append(
                f"  OK (0.5 ≤ k < 0.7):   {((k_vals >= 0.5) & (k_vals < 0.7)).sum():>5} observations"
            )
            lines.append(
                f"  Bad (0.7 ≤ k < 1):    {((k_vals >= 0.7) & (k_vals < 1)).sum():>5} observations"
            )
            lines.append(
                f"  Very bad (k ≥ 1):     {(k_vals >= 1).sum():>5} observations"
            )

    return "\n".join(lines)
__init__(r, estimates, pointwise, diagnostics, psis_object, elpd_loo, p_loo, looic, se_elpd_loo, se_p_loo, se_looic)

LooCompareResult dataclass

Bases: RListVectorExtension

Result of comparing models by a LOO-style criterion.

Attributes:

Name Type Description
table DataFrame

Comparison table.

criterion str

Criterion name (e.g. "loo").

Source code in brmspy/types/brms_results.py
@dataclass
class LooCompareResult(RListVectorExtension):
    """
    Result of comparing models by a LOO-style criterion.

    Attributes
    ----------
    table : pandas.DataFrame
        Comparison table.
    criterion : str
        Criterion name (e.g. ``"loo"``).
    """

    table: pd.DataFrame
    criterion: str

    def __repr__(self) -> str:
        header = f"Model comparison ({self.criterion.upper()})"
        lines = [header, "=" * len(header)]
        lines.append(self.table.to_string())
        return "\n".join(lines)

Attributes

table instance-attribute
criterion instance-attribute

Functions

__repr__()
Source code in brmspy/types/brms_results.py
def __repr__(self) -> str:
    header = f"Model comparison ({self.criterion.upper()})"
    lines = [header, "=" * len(header)]
    lines.append(self.table.to_string())
    return "\n".join(lines)
__init__(r, table, criterion)

IDPosterior

Bases: IDConstantData

Typed .posterior extension to idata

Source code in brmspy/types/brms_results.py
class IDPosterior(IDConstantData):
    """Typed .posterior extension to idata"""

    posterior: xr.Dataset

Attributes

posterior instance-attribute

IDPosteriorPredictive

Bases: IDConstantData

Typed .posterior_predictive extension to idata

Source code in brmspy/types/brms_results.py
class IDPosteriorPredictive(IDConstantData):
    """Typed .posterior_predictive extension to idata"""

    posterior_predictive: xr.Dataset

Attributes

posterior_predictive instance-attribute

IDPredictions

Bases: IDPredictionsConstantData

Typed .predictions extension to idata

Source code in brmspy/types/brms_results.py
class IDPredictions(IDPredictionsConstantData):
    """Typed .predictions extension to idata"""

    predictions: xr.Dataset

Attributes

predictions instance-attribute

IDLogLikelihoodInsample

Bases: IDConstantData

Typed .log_likelihood extension to idata

Source code in brmspy/types/brms_results.py
class IDLogLikelihoodInsample(IDConstantData):
    """Typed .log_likelihood extension to idata"""

    log_likelihood: xr.Dataset

Attributes

log_likelihood instance-attribute

IDLogLikelihoodOutsample

Bases: IDPredictionsConstantData

Typed .log_likelihood extension to idata

Source code in brmspy/types/brms_results.py
class IDLogLikelihoodOutsample(IDPredictionsConstantData):
    """Typed .log_likelihood extension to idata"""

    log_likelihood: xr.Dataset

Attributes

log_likelihood instance-attribute

IDObservedData

Bases: IDConstantData

Typed .posterior extension to idata

Source code in brmspy/types/brms_results.py
class IDObservedData(IDConstantData):
    """Typed .posterior extension to idata"""

    observed_data: xr.Dataset

Attributes

observed_data instance-attribute

IDConstantData

Bases: InferenceData

Typed .constant_data extension to idata

Source code in brmspy/types/brms_results.py
class IDConstantData(az.InferenceData):
    """Typed .constant_data extension to idata"""

    constant_data: xr.Dataset

Attributes

constant_data instance-attribute

IDPredictionsConstantData

Bases: InferenceData

Typed .predictions_constant_data extension to idata

Source code in brmspy/types/brms_results.py
class IDPredictionsConstantData(az.InferenceData):
    """Typed .predictions_constant_data extension to idata"""

    predictions_constant_data: xr.Dataset

Attributes

predictions_constant_data instance-attribute

RListVectorExtension dataclass

Generic result container with R objects.

Attributes:

Name Type Description
r ListVector

R object from brms

Source code in brmspy/types/brms_results.py
@dataclass
class RListVectorExtension:
    """Generic result container with R objects.

    Attributes
    ----------
    r : robjects.ListVector
        R object from brms
    """

    r: ProxyListSexpVector

Attributes

r instance-attribute

Functions

__init__(r)

IDBrm

Bases: IDConstantData

Typed arviz.InferenceData for fitted brms models.

Extends arviz.InferenceData with type hints for IDE autocomplete. In brmspy, the fitted model result typically exposes an .idata attribute of this type.

Attributes:

Name Type Description
posterior Dataset

Posterior samples of model parameters.

posterior_predictive Dataset

Posterior predictive samples (with observation noise).

log_likelihood Dataset

Log-likelihood values for each observation.

observed_data Dataset

Original observed response data.

coords dict

Coordinate mappings for dimensions (inherited from arviz.InferenceData).

dims dict

Dimension specifications for variables (inherited from arviz.InferenceData).

See Also

brmspy.brms.brm : Creates fitted model results (alias: brmspy.brms.fit). arviz.InferenceData : Base class documentation.

Examples:

from brmspy import brms

model = brms.brm("y ~ x", data=df, chains=4)

# Type checking and autocomplete
assert isinstance(model.idata, IDFit)
print(model.idata.posterior)
Source code in brmspy/types/brms_results.py
class IDBrm(IDConstantData):
    """
    Typed `arviz.InferenceData` for fitted brms models.

    Extends `arviz.InferenceData` with type hints for IDE autocomplete. In brmspy,
    the fitted model result typically exposes an `.idata` attribute of this type.

    Attributes
    ----------
    posterior : xr.Dataset
        Posterior samples of model parameters.
    posterior_predictive : xr.Dataset
        Posterior predictive samples (with observation noise).
    log_likelihood : xr.Dataset
        Log-likelihood values for each observation.
    observed_data : xr.Dataset
        Original observed response data.
    coords : dict
        Coordinate mappings for dimensions (inherited from `arviz.InferenceData`).
    dims : dict
        Dimension specifications for variables (inherited from `arviz.InferenceData`).

    See Also
    --------
    brmspy.brms.brm : Creates fitted model results (alias: `brmspy.brms.fit`).
    arviz.InferenceData : Base class documentation.

    Examples
    --------
    ```python
    from brmspy import brms

    model = brms.brm("y ~ x", data=df, chains=4)

    # Type checking and autocomplete
    assert isinstance(model.idata, IDFit)
    print(model.idata.posterior)
    ```
    """

    posterior: xr.Dataset
    posterior_predictive: xr.Dataset
    log_likelihood: xr.Dataset
    observed_data: xr.Dataset
    coords: xr.Dataset
    dims: xr.Dataset

Attributes

posterior instance-attribute
posterior_predictive instance-attribute
log_likelihood instance-attribute
observed_data instance-attribute
coords instance-attribute
dims instance-attribute

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)

FormulaConstruct dataclass

A composite formula expression built from parts.

FormulaConstruct stores a tree of nodes (FormulaPart and/or R objects) representing expressions combined with +. It is primarily created by calling the public formula helpers exposed by brmspy.brms.

Notes

The + operator supports grouping:

  • a + b + c becomes a single summand (one “group”)
  • (a + b) + (a + b) becomes two summands (two “groups”)

Use iter_summands() to iterate over these groups in a deterministic way.

Source code in brmspy/types/formula_dsl.py
@dataclass
class FormulaConstruct:
    """
    A composite formula expression built from parts.

    `FormulaConstruct` stores a tree of nodes (`FormulaPart` and/or R objects)
    representing expressions combined with `+`. It is primarily created by
    calling the public formula helpers exposed by [`brmspy.brms`][brmspy.brms].

    Notes
    -----
    The `+` operator supports grouping:

    - `a + b + c` becomes a single summand (one “group”)
    - `(a + b) + (a + b)` becomes two summands (two “groups”)

    Use [`iter_summands()`][brmspy.types.formula_dsl.FormulaConstruct.iter_summands]
    to iterate over these groups in a deterministic way.
    """

    _parts: list[Node]

    @classmethod
    def _formula_parse(cls, obj: Other) -> "FormulaConstruct":
        """
        Convert a supported value into a `FormulaConstruct`.

        Parameters
        ----------
        obj
            One of: `FormulaConstruct`, `FormulaPart`, string (interpreted as `bf(<string>)`),
            or `ProxyListSexpVector`.

        Returns
        -------
        FormulaConstruct
        """
        if isinstance(obj, FormulaConstruct):
            return obj
        if isinstance(obj, ProxyListSexpVector):
            return FormulaConstruct(_parts=[obj])
        if isinstance(obj, FormulaPart):
            return FormulaConstruct(_parts=[obj])
        if isinstance(obj, str):
            part = FormulaPart(_fun="bf", _args=[obj], _kwargs={})
            return FormulaConstruct(_parts=[part])
        raise TypeError(
            f"Cannot parse object of type {type(obj)!r} into FormulaConstruct"
        )

    def __add__(self, other: Other):
        """
        Combine two formula expressions with `+`.

        Parameters
        ----------
        other
            Value to add. Strings are treated as `bf(<string>)`.

        Returns
        -------
        FormulaConstruct
            New combined expression.
        """
        if isinstance(other, (FormulaPart, str, ProxyListSexpVector)):
            other = FormulaConstruct._formula_parse(other)

        if not isinstance(other, FormulaConstruct):
            raise ArithmeticError(
                "When adding values to formula, they must be FormulaConstruct or parseable to FormulaConstruct"
            )

        if len(other._parts) <= 1:
            return FormulaConstruct(_parts=self._parts + other._parts)
        else:
            return FormulaConstruct(_parts=[self._parts, other._parts])

    def __radd__(self, other: Other) -> "FormulaConstruct":
        """Support `"y ~ x" + bf("z ~ 1")` by coercing the left operand."""
        return self._formula_parse(other) + self

    def iter_summands(self) -> Iterator[Summand]:
        """
        Iterate over arithmetic groups (summands).

        Returns
        -------
        Iterator[tuple[FormulaPart | ProxyListSexpVector, ...]]
            Each yielded tuple represents one summand/group.

        Examples
        --------
        ```python
        from brmspy.brms import bf, gaussian, set_rescor

        f = bf("y ~ x") + gaussian() + set_rescor(True)
        for summand in f.iter_summands():
            print(summand)
        ```
        """

        def _groups(node: Node) -> Iterator[list[FormulaPart | ProxyListSexpVector]]:
            # Leaf node: single bf/family/etc
            if isinstance(node, (FormulaPart, ProxyListSexpVector)):
                return ([node],)  # one group with one element

            if isinstance(node, list):
                # If any child is a list, this node represents a "+"
                # between sub-expressions, so recurse into each child.
                if any(isinstance(child, list) for child in node):
                    for child in node:
                        yield from _groups(child)
                else:
                    # All children are leaves -> one summand
                    out: list[FormulaPart | ProxyListSexpVector] = []
                    for child in node:
                        if isinstance(child, (FormulaPart, ProxyListSexpVector, Sexp)):
                            child = cast(FormulaPart | ProxyListSexpVector, child)
                            out.append(child)
                        else:
                            raise TypeError(
                                f"Unexpected leaf node type in FormulaConstruct: {type(child)!r}"
                            )
                    yield out
                return

            raise TypeError(f"Unexpected node type in FormulaConstruct: {type(node)!r}")

        # self._parts is always a list[Node]
        for group in _groups(self._parts):
            yield tuple(group)

    # Make __iter__ return summands by default
    def __iter__(self) -> Iterator[Summand]:
        """Alias for [`iter_summands()`][brmspy.types.formula_dsl.FormulaConstruct.iter_summands]."""
        return self.iter_summands()

    def iterate(self) -> Iterator[FormulaPart | ProxyListSexpVector]:
        """
        Iterate over all leaf nodes in left-to-right order.

        This flattens the expression tree, unlike
        [`iter_summands()`][brmspy.types.formula_dsl.FormulaConstruct.iter_summands], which
        respects grouping.

        Returns
        -------
        Iterator[FormulaPart | ProxyListSexpVector]
        """

        def _walk(node: Node) -> Iterator[FormulaPart | ProxyListSexpVector]:
            if isinstance(node, FormulaPart):
                yield node
            elif isinstance(node, ProxyListSexpVector):
                yield node
            elif isinstance(node, list):
                for child in node:
                    yield from _walk(child)
            else:
                raise TypeError(
                    f"Unexpected node type in FormulaConstruct: {type(node)!r}"
                )

        for root in self._parts:
            yield from _walk(root)

    def __str__(self) -> str:
        return self._pretty(self._parts)

    def _pretty(self, node, _outer=True) -> str:
        if isinstance(node, FormulaPart):
            return str(node)

        if isinstance(node, (ProxyListSexpVector, Sexp)):
            return _sexp_to_str(node)

        if isinstance(node, list):
            # Pretty-print each child
            rendered = [self._pretty(child, _outer=False) for child in node]

            # If only one child, no parentheses needed
            if len(rendered) == 1:
                return rendered[0]

            # Multiple children → join with " + "
            inner = " + ".join(rendered)
            if _outer:
                return inner
            else:
                return f"({inner})"

        raise TypeError(f"Unexpected node type {type(node)!r} in pretty-printer")

    def __repr__(self) -> str:
        return self.__str__()

Attributes

_parts instance-attribute

Functions

_formula_parse(obj) classmethod

Convert a supported value into a FormulaConstruct.

Parameters:

Name Type Description Default
obj Other

One of: FormulaConstruct, FormulaPart, string (interpreted as bf(<string>)), or ProxyListSexpVector.

required

Returns:

Type Description
FormulaConstruct
Source code in brmspy/types/formula_dsl.py
@classmethod
def _formula_parse(cls, obj: Other) -> "FormulaConstruct":
    """
    Convert a supported value into a `FormulaConstruct`.

    Parameters
    ----------
    obj
        One of: `FormulaConstruct`, `FormulaPart`, string (interpreted as `bf(<string>)`),
        or `ProxyListSexpVector`.

    Returns
    -------
    FormulaConstruct
    """
    if isinstance(obj, FormulaConstruct):
        return obj
    if isinstance(obj, ProxyListSexpVector):
        return FormulaConstruct(_parts=[obj])
    if isinstance(obj, FormulaPart):
        return FormulaConstruct(_parts=[obj])
    if isinstance(obj, str):
        part = FormulaPart(_fun="bf", _args=[obj], _kwargs={})
        return FormulaConstruct(_parts=[part])
    raise TypeError(
        f"Cannot parse object of type {type(obj)!r} into FormulaConstruct"
    )
__add__(other)

Combine two formula expressions with +.

Parameters:

Name Type Description Default
other Other

Value to add. Strings are treated as bf(<string>).

required

Returns:

Type Description
FormulaConstruct

New combined expression.

Source code in brmspy/types/formula_dsl.py
def __add__(self, other: Other):
    """
    Combine two formula expressions with `+`.

    Parameters
    ----------
    other
        Value to add. Strings are treated as `bf(<string>)`.

    Returns
    -------
    FormulaConstruct
        New combined expression.
    """
    if isinstance(other, (FormulaPart, str, ProxyListSexpVector)):
        other = FormulaConstruct._formula_parse(other)

    if not isinstance(other, FormulaConstruct):
        raise ArithmeticError(
            "When adding values to formula, they must be FormulaConstruct or parseable to FormulaConstruct"
        )

    if len(other._parts) <= 1:
        return FormulaConstruct(_parts=self._parts + other._parts)
    else:
        return FormulaConstruct(_parts=[self._parts, other._parts])
__radd__(other)

Support "y ~ x" + bf("z ~ 1") by coercing the left operand.

Source code in brmspy/types/formula_dsl.py
def __radd__(self, other: Other) -> "FormulaConstruct":
    """Support `"y ~ x" + bf("z ~ 1")` by coercing the left operand."""
    return self._formula_parse(other) + self
iter_summands()

Iterate over arithmetic groups (summands).

Returns:

Type Description
Iterator[tuple[FormulaPart | ProxyListSexpVector, ...]]

Each yielded tuple represents one summand/group.

Examples:

from brmspy.brms import bf, gaussian, set_rescor

f = bf("y ~ x") + gaussian() + set_rescor(True)
for summand in f.iter_summands():
    print(summand)
Source code in brmspy/types/formula_dsl.py
def iter_summands(self) -> Iterator[Summand]:
    """
    Iterate over arithmetic groups (summands).

    Returns
    -------
    Iterator[tuple[FormulaPart | ProxyListSexpVector, ...]]
        Each yielded tuple represents one summand/group.

    Examples
    --------
    ```python
    from brmspy.brms import bf, gaussian, set_rescor

    f = bf("y ~ x") + gaussian() + set_rescor(True)
    for summand in f.iter_summands():
        print(summand)
    ```
    """

    def _groups(node: Node) -> Iterator[list[FormulaPart | ProxyListSexpVector]]:
        # Leaf node: single bf/family/etc
        if isinstance(node, (FormulaPart, ProxyListSexpVector)):
            return ([node],)  # one group with one element

        if isinstance(node, list):
            # If any child is a list, this node represents a "+"
            # between sub-expressions, so recurse into each child.
            if any(isinstance(child, list) for child in node):
                for child in node:
                    yield from _groups(child)
            else:
                # All children are leaves -> one summand
                out: list[FormulaPart | ProxyListSexpVector] = []
                for child in node:
                    if isinstance(child, (FormulaPart, ProxyListSexpVector, Sexp)):
                        child = cast(FormulaPart | ProxyListSexpVector, child)
                        out.append(child)
                    else:
                        raise TypeError(
                            f"Unexpected leaf node type in FormulaConstruct: {type(child)!r}"
                        )
                yield out
            return

        raise TypeError(f"Unexpected node type in FormulaConstruct: {type(node)!r}")

    # self._parts is always a list[Node]
    for group in _groups(self._parts):
        yield tuple(group)
__iter__()

Alias for iter_summands().

Source code in brmspy/types/formula_dsl.py
def __iter__(self) -> Iterator[Summand]:
    """Alias for [`iter_summands()`][brmspy.types.formula_dsl.FormulaConstruct.iter_summands]."""
    return self.iter_summands()
iterate()

Iterate over all leaf nodes in left-to-right order.

This flattens the expression tree, unlike iter_summands(), which respects grouping.

Returns:

Type Description
Iterator[FormulaPart | ProxyListSexpVector]
Source code in brmspy/types/formula_dsl.py
def iterate(self) -> Iterator[FormulaPart | ProxyListSexpVector]:
    """
    Iterate over all leaf nodes in left-to-right order.

    This flattens the expression tree, unlike
    [`iter_summands()`][brmspy.types.formula_dsl.FormulaConstruct.iter_summands], which
    respects grouping.

    Returns
    -------
    Iterator[FormulaPart | ProxyListSexpVector]
    """

    def _walk(node: Node) -> Iterator[FormulaPart | ProxyListSexpVector]:
        if isinstance(node, FormulaPart):
            yield node
        elif isinstance(node, ProxyListSexpVector):
            yield node
        elif isinstance(node, list):
            for child in node:
                yield from _walk(child)
        else:
            raise TypeError(
                f"Unexpected node type in FormulaConstruct: {type(node)!r}"
            )

    for root in self._parts:
        yield from _walk(root)
__str__()
Source code in brmspy/types/formula_dsl.py
def __str__(self) -> str:
    return self._pretty(self._parts)
_pretty(node, _outer=True)
Source code in brmspy/types/formula_dsl.py
def _pretty(self, node, _outer=True) -> str:
    if isinstance(node, FormulaPart):
        return str(node)

    if isinstance(node, (ProxyListSexpVector, Sexp)):
        return _sexp_to_str(node)

    if isinstance(node, list):
        # Pretty-print each child
        rendered = [self._pretty(child, _outer=False) for child in node]

        # If only one child, no parentheses needed
        if len(rendered) == 1:
            return rendered[0]

        # Multiple children → join with " + "
        inner = " + ".join(rendered)
        if _outer:
            return inner
        else:
            return f"({inner})"

    raise TypeError(f"Unexpected node type {type(node)!r} in pretty-printer")
__repr__()
Source code in brmspy/types/formula_dsl.py
def __repr__(self) -> str:
    return self.__str__()
__init__(_parts)

FormulaPart dataclass

A single formula helper invocation.

Instances of this type represent a call like bf("y ~ x") or set_rescor(True) without executing anything. They are primarily used as nodes inside a FormulaConstruct.

Parameters:

Name Type Description Default
_fun Literal[...]

Whitelisted formula helper name.

required
_args Sequence[Primitive]

Positional arguments for the helper.

required
_kwargs Mapping[str, Primitive]

Keyword arguments for the helper.

required
Notes

This is a low-level type. Most users should construct these via the public helper functions in brmspy.brms.

Source code in brmspy/types/formula_dsl.py
@dataclass
class FormulaPart:
    """
    A single formula helper invocation.

    Instances of this type represent a call like `bf("y ~ x")` or `set_rescor(True)`
    without executing anything. They are primarily used as nodes inside a
    [`FormulaConstruct`][brmspy.types.formula_dsl.FormulaConstruct].

    Parameters
    ----------
    _fun : Literal[...]
        Whitelisted formula helper name.
    _args : Sequence[Primitive]
        Positional arguments for the helper.
    _kwargs : Mapping[str, Primitive]
        Keyword arguments for the helper.

    Notes
    -----
    This is a low-level type. Most users should construct these via the public
    helper functions in [`brmspy.brms`][brmspy.brms].
    """

    _fun: _FORMULA_FUNCTION_WHITELIST
    _args: Sequence[Primitive]
    _kwargs: Mapping[str, Primitive]

    def __post_init__(self):
        """Validate `_fun`, `_args`, and `_kwargs` types after construction."""
        # Validate function name first
        if self._fun not in get_args(_FORMULA_FUNCTION_WHITELIST):
            raise ValueError(
                f"FormulaPart._fun must be one of {_FORMULA_FUNCTION_WHITELIST!r}, "
                f"got {self._fun!r}"
            )

        # Enforce _args is a list
        if not isinstance(self._args, Sequence):
            raise TypeError(
                f"FormulaPart._args must be a Sequence, got {type(self._args).__name__}"
            )

        # Enforce _kwargs is a dict
        if not isinstance(self._kwargs, Mapping):
            raise TypeError(
                f"FormulaPart._kwargs must be a Mapping, got {type(self._kwargs).__name__}"
            )

    def __str__(self) -> str:
        """Render a readable `fun(arg1, ..., kw=...)` representation."""
        args = ", ".join(repr(a) for a in self._args)
        kwargs = ", ".join(f"{k}={v!r}" for k, v in self._kwargs.items())
        inner = ", ".join(x for x in (args, kwargs) if x)
        return f"{self._fun}({inner})"

    def __repr__(self) -> str:
        return self.__str__()

Attributes

_fun instance-attribute
_args instance-attribute
_kwargs instance-attribute

Functions

__post_init__()

Validate _fun, _args, and _kwargs types after construction.

Source code in brmspy/types/formula_dsl.py
def __post_init__(self):
    """Validate `_fun`, `_args`, and `_kwargs` types after construction."""
    # Validate function name first
    if self._fun not in get_args(_FORMULA_FUNCTION_WHITELIST):
        raise ValueError(
            f"FormulaPart._fun must be one of {_FORMULA_FUNCTION_WHITELIST!r}, "
            f"got {self._fun!r}"
        )

    # Enforce _args is a list
    if not isinstance(self._args, Sequence):
        raise TypeError(
            f"FormulaPart._args must be a Sequence, got {type(self._args).__name__}"
        )

    # Enforce _kwargs is a dict
    if not isinstance(self._kwargs, Mapping):
        raise TypeError(
            f"FormulaPart._kwargs must be a Mapping, got {type(self._kwargs).__name__}"
        )
__str__()

Render a readable fun(arg1, ..., kw=...) representation.

Source code in brmspy/types/formula_dsl.py
def __str__(self) -> str:
    """Render a readable `fun(arg1, ..., kw=...)` representation."""
    args = ", ".join(repr(a) for a in self._args)
    kwargs = ", ".join(f"{k}={v!r}" for k, v in self._kwargs.items())
    inner = ", ".join(x for x in (args, kwargs) if x)
    return f"{self._fun}({inner})"
__repr__()
Source code in brmspy/types/formula_dsl.py
def __repr__(self) -> str:
    return self.__str__()
__init__(_fun, _args, _kwargs)

Functions

log(*msg, method_name=None, level=logging.INFO)

Log a message with automatic method name detection.

Parameters:

Name Type Description Default
msg str

The message to log

()
method_name str

The name of the method/function. If None, will auto-detect from call stack.

None
level int

Logging level (default: logging.INFO)

INFO
Source code in brmspy/helpers/log.py
def log(*msg: str, method_name: str | None = None, level: int = logging.INFO):
    """
    Log a message with automatic method name detection.

    Parameters
    ----------
    msg : str
        The message to log
    method_name : str, optional
        The name of the method/function. If None, will auto-detect from call stack.
    level : int, optional
        Logging level (default: logging.INFO)
    """
    if method_name is None:
        method_name = _get_caller_name()

    msg_str = " ".join(str(v) for v in msg)

    logger = get_logger()
    logger.log(level, msg_str, extra={"method_name": method_name})

log_warning(msg, method_name=None)

Log a warning message.

Parameters:

Name Type Description Default
msg str

The warning message to log

required
method_name str

The name of the method/function. If None, will auto-detect from call stack.

None
Source code in brmspy/helpers/log.py
def log_warning(msg: str, method_name: str | None = None):
    """
    Log a warning message.

    Parameters
    ----------
    msg : str
        The warning message to log
    method_name : str, optional
        The name of the method/function. If None, will auto-detect from call stack.

    """
    log(msg, method_name=method_name, level=logging.WARNING)

_get_brms()

Get brms R package, importing on first access.

Source code in brmspy/_runtime/_state.py
def get_brms() -> Any:
    """Get brms R package, importing on first access."""
    global _brms
    if _brms is None:
        try:
            from rpy2.robjects.packages import importr
            import rpy2.robjects as ro

            _brms = importr("brms")
            ro.r("library(brms)")
        except Exception as e:
            raise ImportError(
                "brms R package not found. Install it using:\n\n"
                "  import brmspy\n"
                "  brmspy.install_brms(use_prebuilt=True)  # for prebuilt binaries\n\n"
                "Or install from source:\n"
                "  brmspy.install_brms()\n"
            ) from e
    return _brms

get_brms_data(dataset_name, **kwargs)

Load an example dataset from the R brms package.

Parameters:

Name Type Description Default
dataset_name str

Dataset name (for example "epilepsy" or "kidney").

required
**kwargs

Forwarded to R utils::data() via get_data().

{}

Returns:

Type Description
DataFrame

Dataset converted to a DataFrame.

Examples:

from brmspy import brms

epilepsy = brms.get_brms_data("epilepsy")
assert epilepsy.shape[0] > 0
Source code in brmspy/_brms_functions/io.py
def get_brms_data(dataset_name: str, **kwargs) -> pd.DataFrame:
    """
    Load an example dataset from the R ``brms`` package.

    Parameters
    ----------
    dataset_name : str
        Dataset name (for example ``"epilepsy"`` or ``"kidney"``).
    **kwargs
        Forwarded to R ``utils::data()`` via `get_data()`.

    Returns
    -------
    pandas.DataFrame
        Dataset converted to a DataFrame.

    Examples
    --------
    ```python
    from brmspy import brms

    epilepsy = brms.get_brms_data("epilepsy")
    assert epilepsy.shape[0] > 0
    ```
    """
    return get_data(dataset_name, package="brms", **kwargs)

read_rds_fit(file, **kwargs)

Load a saved brms model from an .rds file.

Parameters:

Name Type Description Default
file str

Input path containing a saved brmsfit.

required
**kwargs

Forwarded to R readRDS().

{}

Returns:

Type Description
FitResult

FitResult containing ArviZ InferenceData and an underlying R handle.

Examples:

from brmspy import brms

fit = brms.read_rds_fit("model.rds")
fit.idata.posterior
Source code in brmspy/_brms_functions/io.py
def read_rds_fit(file: str, **kwargs) -> FitResult:
    """
    Load a saved brms model from an ``.rds`` file.

    Parameters
    ----------
    file : str
        Input path containing a saved brmsfit.
    **kwargs
        Forwarded to R ``readRDS()``.

    Returns
    -------
    FitResult
        `FitResult` containing ArviZ `InferenceData` and an underlying R handle.

    Examples
    --------
    ```python
    from brmspy import brms

    fit = brms.read_rds_fit("model.rds")
    fit.idata.posterior
    ```
    """
    brmsfit = read_rds_raw(file, **kwargs)
    idata = brmsfit_to_idata(brmsfit)

    return FitResult(idata=idata, r=brmsfit)

read_rds_raw(file, **kwargs)

Load an R object from an .rds file via R readRDS().

This returns the raw R object handle.

Parameters:

Name Type Description Default
file str

Input path.

required
**kwargs

Forwarded to R readRDS().

{}

Returns:

Type Description
ListSexpVector

Raw R object.

Examples:

from brmspy import brms

obj = brms.read_rds_raw("model.rds")
Source code in brmspy/_brms_functions/io.py
def read_rds_raw(file: str, **kwargs) -> ListSexpVector:
    """
    Load an R object from an ``.rds`` file via R ``readRDS()``.

    This returns the raw R object handle.

    Parameters
    ----------
    file : str
        Input path.
    **kwargs
        Forwarded to R ``readRDS()``.

    Returns
    -------
    rpy2.rinterface.ListSexpVector
        Raw R object.

    Examples
    --------
    ```python
    from brmspy import brms

    obj = brms.read_rds_raw("model.rds")
    ```
    """
    import rpy2.robjects as ro

    r_read_rds = typing.cast(typing.Callable, ro.r("readRDS"))

    kwargs = kwargs_r(kwargs)
    brmsobject = r_read_rds(file, **kwargs)
    return brmsobject

save_rds(object, file, **kwargs)

Save an R object to an .rds file via R saveRDS().

Parameters:

Name Type Description Default
object RListVectorExtension or ProxyListSexpVector

Object to save. If you pass a FitResult, the underlying brmsfit is saved.

required
file str

Output path.

required
**kwargs

Forwarded to R saveRDS() (for example compress="xz").

{}

Returns:

Type Description
None

Examples:

from brmspy import brms

model = brms.brm("y ~ x", data=df, chains=4)
brms.save_rds(model, "model.rds")
Source code in brmspy/_brms_functions/io.py
def save_rds(
    object: RListVectorExtension | ProxyListSexpVector, file: str, **kwargs
) -> None:
    """
    Save an R object to an ``.rds`` file via R ``saveRDS()``.

    Parameters
    ----------
    object : RListVectorExtension or ProxyListSexpVector
        Object to save. If you pass a `FitResult`, the underlying brmsfit is saved.
    file : str
        Output path.
    **kwargs
        Forwarded to R ``saveRDS()`` (for example ``compress="xz"``).

    Returns
    -------
    None

    Examples
    --------
    ```python
    from brmspy import brms

    model = brms.brm("y ~ x", data=df, chains=4)
    brms.save_rds(model, "model.rds")
    ```
    """
    import rpy2.robjects as ro

    if isinstance(object, RListVectorExtension):
        brmsfit = object.r
    else:
        brmsfit = object

    kwargs = kwargs_r(kwargs)

    r_save_rds = typing.cast(typing.Callable, ro.r("saveRDS"))
    r_save_rds(brmsfit, file, **kwargs)

get_data(dataset_name, **kwargs)

Load an R dataset and return it as a pandas DataFrame.

This is a thin wrapper around R's data() that loads the object into the R global environment and converts it to a :class:pandas.DataFrame.

Parameters:

Name Type Description Default
dataset_name str

Name of the dataset as used in R (e.g. "BTdata").

required
**kwargs

Additional keyword arguments forwarded to R's data() function, for example package="MCMCglmm" or other arguments supported by utils::data() in R.

{}

Returns:

Type Description
DataFrame

Dataset converted to a pandas DataFrame.

Raises:

Type Description
KeyError

If the dataset is not found in the R global environment after calling data().

RuntimeError

If conversion from the R object to a pandas DataFrame fails.

See Also

get_brms_data Convenience wrapper for datasets from the brms package.

Source code in brmspy/_brms_functions/io.py
def get_data(dataset_name: str, **kwargs) -> pd.DataFrame:
    """
    Load an R dataset and return it as a pandas DataFrame.

    This is a thin wrapper around R's ``data()`` that loads the object
    into the R global environment and converts it to a
    :class:`pandas.DataFrame`.

    Parameters
    ----------
    dataset_name : str
        Name of the dataset as used in R (e.g. ``"BTdata"``).
    **kwargs
        Additional keyword arguments forwarded to R's ``data()`` function,
        for example ``package="MCMCglmm"`` or other arguments supported
        by ``utils::data()`` in R.

    Returns
    -------
    pd.DataFrame
        Dataset converted to a pandas DataFrame.

    Raises
    ------
    KeyError
        If the dataset is not found in the R global environment after
        calling ``data()``.
    RuntimeError
        If conversion from the R object to a pandas DataFrame fails.

    See Also
    --------
    get_brms_data
        Convenience wrapper for datasets from the ``brms`` package.
    """
    import rpy2.robjects as ro

    r_kwargs = kwargs_r(kwargs)

    r_data = typing.cast(typing.Callable, ro.r["data"])
    r_data(dataset_name, **r_kwargs)
    r_obj = ro.globalenv[dataset_name]

    return typing.cast(pd.DataFrame, r_to_py(r_obj))

prior(prior, class_=None, coef=None, group=None, dpar=None, resp=None, nlpar=None, lb=None, ub=None, **kwargs)

Create a brms-style prior specification.

This function mirrors the behavior of brms::prior_string() and allows specifying priors for regression parameters, group-level effects, nonlinear parameters, distributional parameters, and more — using a typed Python interface. All arguments correspond directly to the parameters of prior_string() in brms.

Parameters:

Name Type Description Default
prior str

The prior definition as a string, exactly as brms expects it. Examples include ::

"normal(0, 1)"
"student_t(3, 0, 1.5)"
"exponential(2)"
"lkj(2)"
required
class_ str

Parameter class (e.g. "b", "sd", "Intercept"). This corresponds to class in brms. class cannot be used as a parameter in Python (reserved keyword), so class_ is used instead.

None
coef str

Coefficient name for class-level effects.

None
group str

Grouping variable for hierarchical/multilevel effects.

None
dpar str

Distributional parameter (e.g. "sigma" or "phi").

None
resp str

Response variable name for multivariate models.

None
nlpar str

Nonlinear parameter name if using nonlinear formulas.

None
lb float

Lower bound for truncated priors.

None
ub float

Upper bound for truncated priors.

None
**kwargs Any

Any additional keyword arguments supported by brms::prior_string(). These are forwarded unchanged.

{}

Returns:

Type Description
PriorSpec

A typed prior specification object used by brmspy.brms.brm() and brmspy.brms.make_stancode().

See Also

brms::prior_string : R documentation

Notes

This function does not validate the prior expression string itself — validation occurs inside brms.

Examples:

from brmspy.brms import prior

p_intercept = prior("student_t(3, 0, 1.95)", class_="Intercept")
p_slope = prior("normal(0, 1)", class_="b", coef="age")
p_sd = prior("exponential(2)", class_="sd", group="region")
p_trunc = prior("normal(0, 1)", class_="b", coef="income", lb=0)
Source code in brmspy/_brms_functions/prior.py
def prior(
    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,
    **kwargs: Any,
) -> PriorSpec:
    """
    Create a brms-style prior specification.

    This function mirrors the behavior of ``brms::prior_string()`` and allows
    specifying priors for regression parameters, group-level effects, nonlinear
    parameters, distributional parameters, and more — using a typed Python
    interface. All arguments correspond directly to the parameters of
    ``prior_string()`` in brms.

    Parameters
    ----------
    prior : str
        The prior definition as a string, exactly as brms expects it.
        Examples include ::

            "normal(0, 1)"
            "student_t(3, 0, 1.5)"
            "exponential(2)"
            "lkj(2)"

    class_ : str, optional
        Parameter class (e.g. ``"b"``, ``"sd"``, ``"Intercept"``).
        This corresponds to ``class`` in brms. ``class`` cannot be used as a
        parameter in Python (reserved keyword), so ``class_`` is used instead.

    coef : str, optional
        Coefficient name for class-level effects.

    group : str, optional
        Grouping variable for hierarchical/multilevel effects.

    dpar : str, optional
        Distributional parameter (e.g. ``"sigma"`` or ``"phi"``).

    resp : str, optional
        Response variable name for multivariate models.

    nlpar : str, optional
        Nonlinear parameter name if using nonlinear formulas.

    lb : float, optional
        Lower bound for truncated priors.

    ub : float, optional
        Upper bound for truncated priors.

    **kwargs
        Any additional keyword arguments supported by ``brms::prior_string()``.
        These are forwarded unchanged.

    Returns
    -------
    PriorSpec
        A typed prior specification object used by `brmspy.brms.brm()` and
        `brmspy.brms.make_stancode()`.

    See Also
    --------
    brms::prior_string : [R documentation](https://paulbuerkner.com/brms/reference/prior_string.html)

    Notes
    -----
    This function does **not** validate the prior expression string itself —
    validation occurs inside brms.

    Examples
    --------
    ```python
    from brmspy.brms import prior

    p_intercept = prior("student_t(3, 0, 1.95)", class_="Intercept")
    p_slope = prior("normal(0, 1)", class_="b", coef="age")
    p_sd = prior("exponential(2)", class_="sd", group="region")
    p_trunc = prior("normal(0, 1)", class_="b", coef="income", lb=0)
    ```
    """
    if "class" in kwargs:
        kwargs["class_"] = kwargs["class"]

    return PriorSpec(
        prior=prior,
        class_=class_,
        coef=coef,
        group=group,
        dpar=dpar,
        resp=resp,
        nlpar=nlpar,
        lb=lb,
        ub=ub,
        **kwargs,
    )

get_prior(formula, data=None, family='gaussian', **kwargs)

Get default priors for a model specification.

Wrapper around R brms::get_prior().

Returns a DataFrame with default priors for each parameter class in the specified brms model. Useful for reviewing and customizing priors before fitting.

Parameters:

Name Type Description Default
formula str or FormulaConstruct

Model formula (e.g. "y ~ x + (1|group)") or a composed formula.

required
data DataFrame or dict

Dataset containing model variables. Required for data-dependent priors

None
family str or ListSexpVector

Distribution family (e.g., "gaussian", "poisson", "binomial")

"gaussian"
**kwargs

Additional arguments passed to brms::get_prior() (e.g., autocor, data2, knots, drop_unused_levels)

{}

Returns:

Type Description
DataFrame

DataFrame with columns: prior, class, coef, group, resp, dpar, nlpar, lb, ub, source. Each row represents a parameter or parameter class that can have a custom prior.

See Also

default_prior : Generic function for getting default priors prior : Create custom prior specifications brms::get_prior : R documentation

Examples:

from brmspy import brms
from brmspy.brms import prior

priors_df = brms.get_prior("y ~ x", data=df)

custom_priors = [
    prior("normal(0, 0.5)", class_="b"),
    prior("exponential(2)", class_="sigma"),
]

fit = brms.brm("y ~ x", data=df, priors=custom_priors, chains=4)
Source code in brmspy/_brms_functions/prior.py
def get_prior(
    formula: str | FormulaConstruct, data=None, family="gaussian", **kwargs
) -> pd.DataFrame:
    """
    Get default priors for a model specification.

    Wrapper around R ``brms::get_prior()``.

    Returns a DataFrame with default priors for each parameter class in the specified
    brms model. Useful for reviewing and customizing priors before fitting.

    Parameters
    ----------
    formula : str or FormulaConstruct
        Model formula (e.g. ``"y ~ x + (1|group)"``) or a composed formula.
    data : pd.DataFrame or dict, optional
        Dataset containing model variables. Required for data-dependent priors
    family : str or ListSexpVector, default="gaussian"
        Distribution family (e.g., "gaussian", "poisson", "binomial")
    **kwargs
        Additional arguments passed to brms::get_prior()
        (e.g., autocor, data2, knots, drop_unused_levels)

    Returns
    -------
    pd.DataFrame
        DataFrame with columns: prior, class, coef, group, resp, dpar, nlpar, lb, ub, source.
        Each row represents a parameter or parameter class that can have a custom prior.

    See Also
    --------
    default_prior : Generic function for getting default priors
    prior : Create custom prior specifications
    brms::get_prior : [R documentation](https://paulbuerkner.com/brms/reference/get_prior.html)

    Examples
    --------
    ```python
    from brmspy import brms
    from brmspy.brms import prior

    priors_df = brms.get_prior("y ~ x", data=df)

    custom_priors = [
        prior("normal(0, 0.5)", class_="b"),
        prior("exponential(2)", class_="sigma"),
    ]

    fit = brms.brm("y ~ x", data=df, priors=custom_priors, chains=4)
    ```
    """
    import rpy2.robjects as ro

    formula_obj = _execute_formula(formula)

    r_get_prior = cast(Callable, ro.r("brms::get_prior"))
    collected_args = kwargs_r(
        {"formula": formula_obj, "data": data, "family": family, **kwargs}
    )

    df_r = r_get_prior(**collected_args)
    df = pd.DataFrame(cast(Any, r_to_py(df_r)))

    return df

default_prior(object, data=None, family='gaussian', **kwargs)

Get default priors for brms model parameters (generic function).

Wrapper around R brms::default_prior().

Generic function to retrieve default prior specifications for all parameters in a brms model. Accepts formula objects, brmsformula objects, or other model specification objects. This is the generic version of get_prior().

Parameters:

Name Type Description Default
object str, FormulaResult, or ListSexpVector

Model specification: formula string, brmsformula object, mvbrmsformula, or any object that can be coerced to these classes

required
data DataFrame or dict

Dataset containing model variables. Required for data-dependent priors

None
family str or ListSexpVector

Distribution family (e.g., "gaussian", "poisson", "binomial"). Can be a list of families for multivariate models

"gaussian"
**kwargs

Additional arguments passed to brms::get_prior() (e.g., autocor, data2, knots, drop_unused_levels, sparse)

{}

Returns:

Type Description
DataFrame

DataFrame with columns: prior, class, coef, group, resp, dpar, nlpar, lb, ub, source. Each row specifies a parameter class with its default prior. The 'prior' column is empty except for internal defaults.

See Also

get_prior : Convenience function with formula parameter prior : Create custom prior specifications brms::default_prior : R documentation

Examples:

Get default priors for a Poisson model:

from brmspy import brms

priors = brms.default_prior(
    object="count ~ zAge + zBase * Trt + (1|patient)",
    data=epilepsy,
    family="poisson"
)
print(priors)

Use with formula object:

from brmspy import brms

f = brms.formula("y ~ x + (1|group)")
priors = brms.default_prior(f, data=df, family="gaussian")
Source code in brmspy/_brms_functions/prior.py
def default_prior(
    object: RListVectorExtension | ListSexpVector | FormulaConstruct | str,
    data=None,
    family="gaussian",
    **kwargs,
) -> pd.DataFrame:
    """
    Get default priors for brms model parameters (generic function).

    Wrapper around R ``brms::default_prior()``.

    Generic function to retrieve default prior specifications for all parameters
    in a brms model. Accepts formula objects, brmsformula objects, or other model
    specification objects. This is the generic version of get_prior().

    Parameters
    ----------
    object : str, FormulaResult, or ListSexpVector
        Model specification: formula string, brmsformula object, mvbrmsformula,
        or any object that can be coerced to these classes
    data : pd.DataFrame or dict, optional
        Dataset containing model variables. Required for data-dependent priors
    family : str or ListSexpVector, default="gaussian"
        Distribution family (e.g., "gaussian", "poisson", "binomial").
        Can be a list of families for multivariate models
    **kwargs
        Additional arguments passed to brms::get_prior()
        (e.g., autocor, data2, knots, drop_unused_levels, sparse)

    Returns
    -------
    pd.DataFrame
        DataFrame with columns: prior, class, coef, group, resp, dpar, nlpar, lb, ub, source.
        Each row specifies a parameter class with its default prior. The 'prior' column
        is empty except for internal defaults.

    See Also
    --------
    get_prior : Convenience function with formula parameter
    prior : Create custom prior specifications
    brms::default_prior : [R documentation](https://paulbuerkner.com/brms/reference/default_prior.html)

    Examples
    --------
    Get default priors for a Poisson model:

    ```python
    from brmspy import brms

    priors = brms.default_prior(
        object="count ~ zAge + zBase * Trt + (1|patient)",
        data=epilepsy,
        family="poisson"
    )
    print(priors)
    ```

    Use with formula object:

    ```python
    from brmspy import brms

    f = brms.formula("y ~ x + (1|group)")
    priors = brms.default_prior(f, data=df, family="gaussian")
    ```
    """
    import rpy2.robjects as ro

    r_get_prior = cast(Callable, ro.r("brms::get_prior"))
    collected_args = kwargs_r({"data": data, "family": family, **kwargs})

    obj_resolved = object
    if isinstance(object, FormulaConstruct):
        obj_resolved = _execute_formula(object)

    df_r = r_get_prior(py_to_r(obj_resolved), **collected_args)
    df = pd.DataFrame(cast(Any, r_to_py(df_r)))

    return df

brm(formula, data, priors=None, family='gaussian', sample_prior='no', sample=True, backend='cmdstanr', formula_args=None, cores=2, *, return_idata=True, **brm_args)

brm(formula: FormulaConstruct | ProxyListSexpVector | str, data: dict | pd.DataFrame, priors: Sequence[PriorSpec] | None = ..., family: str | ListSexpVector | None = ..., sample_prior: str = ..., sample: bool = ..., backend: str = ..., formula_args: dict | None = ..., cores: int | None = ..., *, return_idata: Literal[True] = True, **brm_args: Any) -> FitResult
brm(formula: FormulaConstruct | ProxyListSexpVector | str, data: dict | pd.DataFrame, priors: Sequence[PriorSpec] | None = ..., family: str | ListSexpVector | None = ..., sample_prior: str = ..., sample: bool = ..., backend: str = ..., formula_args: dict | None = ..., cores: int | None = ..., *, return_idata: Literal[False], **brm_args: Any) -> ProxyListSexpVector

Fit a Bayesian regression model with brms.

This is a thin wrapper around R brms::brm() that returns a structured FitResult (including an ArviZ InferenceData).

Parameters:

Name Type Description Default
formula str or FormulaConstruct

Model formula. Accepts a plain brms formula string (e.g. "y ~ x + (1|g)") or a composed formula created via brmspy.brms.bf() / brmspy.brms.lf() (typically imported as from brmspy.brms import bf, lf).

required
data dict or DataFrame

Model data.

required
priors Sequence[PriorSpec] or None

Optional prior specifications created via brmspy.brms.prior().

None
family str or ListSexpVector or None

brms family specification (e.g. "gaussian", "poisson").

"gaussian"
sample_prior str

Passed to brms. Common values: "no", "yes", "only".

"no"
sample bool

If False, compile the model without sampling (brms empty=TRUE).

True
backend str

Stan backend. Common values: "cmdstanr" or "rstan".

"cmdstanr"
formula_args dict or None

Reserved for future use. Currently ignored.

None
cores int or None

Number of cores for brms/cmdstanr.

2
return_idata bool

When working with large datasets, you might not want the full idata. when False, you get the R object proxy which can be forwarded to posterior_epred or other functions

True
**brm_args

Additional keyword arguments passed to R brms::brm() (e.g. chains, iter, warmup, seed).

{}

Returns:

Type Description
FitResult

Result object with idata (ArviZ InferenceData) and an underlying R handle.

See Also

brms::brm : R documentation

Warnings

Using cores <= 1 can be unstable in embedded R sessions and may crash the worker process. Prefer cores >= 2.

Examples:

from brmspy import brms

fit = brms.brm("y ~ x + (1|g)", data=df, family="gaussian", chains=4, cores=4)

fit.idata.posterior
Source code in brmspy/_brms_functions/brm.py
def brm(
    formula: FormulaConstruct | ProxyListSexpVector | str,
    data: dict | pd.DataFrame,
    priors: Sequence[PriorSpec] | None = None,
    family: str | ListSexpVector | None = "gaussian",
    sample_prior: str = "no",
    sample: bool = True,
    backend: str = "cmdstanr",
    formula_args: dict | None = None,
    cores: int | None = 2,
    *,
    return_idata: bool = True,
    **brm_args,
) -> FitResult | ProxyListSexpVector:
    """
    Fit a Bayesian regression model with brms.

    This is a thin wrapper around R ``brms::brm()`` that returns a structured
    `FitResult` (including an ArviZ `InferenceData`).

    Parameters
    ----------
    formula : str or FormulaConstruct
        Model formula. Accepts a plain brms formula string (e.g. ``"y ~ x + (1|g)"``)
        or a composed formula created via `brmspy.brms.bf()` / `brmspy.brms.lf()`
        (typically imported as ``from brmspy.brms import bf, lf``).
    data : dict or pandas.DataFrame
        Model data.
    priors : Sequence[PriorSpec] or None, default=None
        Optional prior specifications created via `brmspy.brms.prior()`.
    family : str or rpy2.rinterface.ListSexpVector or None, default="gaussian"
        brms family specification (e.g. ``"gaussian"``, ``"poisson"``).
    sample_prior : str, default="no"
        Passed to brms. Common values: ``"no"``, ``"yes"``, ``"only"``.
    sample : bool, default=True
        If ``False``, compile the model without sampling (brms ``empty=TRUE``).
    backend : str, default="cmdstanr"
        Stan backend. Common values: ``"cmdstanr"`` or ``"rstan"``.
    formula_args : dict or None, default=None
        Reserved for future use. Currently ignored.
    cores : int or None, default=2
        Number of cores for brms/cmdstanr.
    return_idata : bool, default True
        When working with large datasets, you might not want the full idata.
        when False, you get the R object proxy which can be forwarded to posterior_epred
        or other functions
    **brm_args
        Additional keyword arguments passed to R ``brms::brm()`` (e.g. ``chains``,
        ``iter``, ``warmup``, ``seed``).

    Returns
    -------
    FitResult
        Result object with `idata` (ArviZ `InferenceData`) and an underlying R handle.

    See Also
    --------
    brms::brm : [R documentation](https://paulbuerkner.com/brms/reference/brm.html)

    Warnings
    --------
    Using ``cores <= 1`` can be unstable in embedded R sessions and may crash the
    worker process. Prefer ``cores >= 2``.

    Examples
    --------
    ```python
    from brmspy import brms

    fit = brms.brm("y ~ x + (1|g)", data=df, family="gaussian", chains=4, cores=4)

    fit.idata.posterior
    ```
    """
    import rpy2.robjects as ro
    import rpy2.robjects.packages as packages

    fun_brm = cast(Callable, ro.r("brms::brm"))

    if backend == "cmdstanr":
        try:
            cmdstanr = packages.importr("cmdstanr")
        except:
            cmdstanr = None
        if cmdstanr is None:
            raise RuntimeError(
                "cmdstanr backend is not installed! Please run install_brms(install_cmdstanr=True)"
            )

    if backend == "rstan":
        try:
            rstan = packages.importr("rstan")
        except:
            rstan = None
        if rstan is None:
            raise RuntimeError(
                "rstan backend is not installed! Please run install_brms(install_rstan=True)"
            )

    # Formula checks. These should never be reached in the first place
    # if they are, the library is calling brm() from main directly without remote call
    assert not isinstance(formula, SexpWrapper)
    assert formula is not None
    if formula_args and isinstance(formula, str):
        formula = bf(formula, **formula_args)

    formula_obj = _execute_formula(formula)

    # Convert data to R format
    data_r = py_to_r(data)

    # Setup priors
    brms_prior = _build_priors(priors)

    # Prepare brm() arguments
    brm_kwargs: dict[str, Any] = {
        "formula": formula_obj,
        "data": data_r,
        "family": family,
        "sample_prior": sample_prior,
        "backend": backend,
        "cores": cores,
    }

    # Add priors if specified
    if len(brms_prior) > 0:
        brm_kwargs["prior"] = brms_prior

    # Add user-specified arguments
    brm_kwargs.update(brm_args)

    brm_kwargs = kwargs_r(brm_kwargs)

    # Set empty=TRUE if not sampling
    if not sample:
        brm_kwargs["empty"] = True
        log("Creating empty r object (no sampling)...")
    else:
        log(f"Fitting model with brms (backend: {backend})...")

    # Call brms::brm() with all arguments
    fit = fun_brm(**brm_kwargs)

    log("Fit done!")

    # Handle return type conversion
    if not return_idata:
        return fit

    if not sample:
        return FitResult(idata=IDBrm(), r=fit)

    idata = brmsfit_to_idata(fit)
    return FitResult(idata=idata, r=fit)

fit(formula, data, priors=None, family='gaussian', sample_prior='no', sample=True, backend='cmdstanr', formula_args=None, cores=2, *, return_idata=True, **brm_args)

brm(formula: FormulaConstruct | ProxyListSexpVector | str, data: dict | pd.DataFrame, priors: Sequence[PriorSpec] | None = ..., family: str | ListSexpVector | None = ..., sample_prior: str = ..., sample: bool = ..., backend: str = ..., formula_args: dict | None = ..., cores: int | None = ..., *, return_idata: Literal[True] = True, **brm_args: Any) -> FitResult
brm(formula: FormulaConstruct | ProxyListSexpVector | str, data: dict | pd.DataFrame, priors: Sequence[PriorSpec] | None = ..., family: str | ListSexpVector | None = ..., sample_prior: str = ..., sample: bool = ..., backend: str = ..., formula_args: dict | None = ..., cores: int | None = ..., *, return_idata: Literal[False], **brm_args: Any) -> ProxyListSexpVector

Fit a Bayesian regression model with brms.

This is a thin wrapper around R brms::brm() that returns a structured FitResult (including an ArviZ InferenceData).

Parameters:

Name Type Description Default
formula str or FormulaConstruct

Model formula. Accepts a plain brms formula string (e.g. "y ~ x + (1|g)") or a composed formula created via brmspy.brms.bf() / brmspy.brms.lf() (typically imported as from brmspy.brms import bf, lf).

required
data dict or DataFrame

Model data.

required
priors Sequence[PriorSpec] or None

Optional prior specifications created via brmspy.brms.prior().

None
family str or ListSexpVector or None

brms family specification (e.g. "gaussian", "poisson").

"gaussian"
sample_prior str

Passed to brms. Common values: "no", "yes", "only".

"no"
sample bool

If False, compile the model without sampling (brms empty=TRUE).

True
backend str

Stan backend. Common values: "cmdstanr" or "rstan".

"cmdstanr"
formula_args dict or None

Reserved for future use. Currently ignored.

None
cores int or None

Number of cores for brms/cmdstanr.

2
return_idata bool

When working with large datasets, you might not want the full idata. when False, you get the R object proxy which can be forwarded to posterior_epred or other functions

True
**brm_args

Additional keyword arguments passed to R brms::brm() (e.g. chains, iter, warmup, seed).

{}

Returns:

Type Description
FitResult

Result object with idata (ArviZ InferenceData) and an underlying R handle.

See Also

brms::brm : R documentation

Warnings

Using cores <= 1 can be unstable in embedded R sessions and may crash the worker process. Prefer cores >= 2.

Examples:

from brmspy import brms

fit = brms.brm("y ~ x + (1|g)", data=df, family="gaussian", chains=4, cores=4)

fit.idata.posterior
Source code in brmspy/_brms_functions/brm.py
def brm(
    formula: FormulaConstruct | ProxyListSexpVector | str,
    data: dict | pd.DataFrame,
    priors: Sequence[PriorSpec] | None = None,
    family: str | ListSexpVector | None = "gaussian",
    sample_prior: str = "no",
    sample: bool = True,
    backend: str = "cmdstanr",
    formula_args: dict | None = None,
    cores: int | None = 2,
    *,
    return_idata: bool = True,
    **brm_args,
) -> FitResult | ProxyListSexpVector:
    """
    Fit a Bayesian regression model with brms.

    This is a thin wrapper around R ``brms::brm()`` that returns a structured
    `FitResult` (including an ArviZ `InferenceData`).

    Parameters
    ----------
    formula : str or FormulaConstruct
        Model formula. Accepts a plain brms formula string (e.g. ``"y ~ x + (1|g)"``)
        or a composed formula created via `brmspy.brms.bf()` / `brmspy.brms.lf()`
        (typically imported as ``from brmspy.brms import bf, lf``).
    data : dict or pandas.DataFrame
        Model data.
    priors : Sequence[PriorSpec] or None, default=None
        Optional prior specifications created via `brmspy.brms.prior()`.
    family : str or rpy2.rinterface.ListSexpVector or None, default="gaussian"
        brms family specification (e.g. ``"gaussian"``, ``"poisson"``).
    sample_prior : str, default="no"
        Passed to brms. Common values: ``"no"``, ``"yes"``, ``"only"``.
    sample : bool, default=True
        If ``False``, compile the model without sampling (brms ``empty=TRUE``).
    backend : str, default="cmdstanr"
        Stan backend. Common values: ``"cmdstanr"`` or ``"rstan"``.
    formula_args : dict or None, default=None
        Reserved for future use. Currently ignored.
    cores : int or None, default=2
        Number of cores for brms/cmdstanr.
    return_idata : bool, default True
        When working with large datasets, you might not want the full idata.
        when False, you get the R object proxy which can be forwarded to posterior_epred
        or other functions
    **brm_args
        Additional keyword arguments passed to R ``brms::brm()`` (e.g. ``chains``,
        ``iter``, ``warmup``, ``seed``).

    Returns
    -------
    FitResult
        Result object with `idata` (ArviZ `InferenceData`) and an underlying R handle.

    See Also
    --------
    brms::brm : [R documentation](https://paulbuerkner.com/brms/reference/brm.html)

    Warnings
    --------
    Using ``cores <= 1`` can be unstable in embedded R sessions and may crash the
    worker process. Prefer ``cores >= 2``.

    Examples
    --------
    ```python
    from brmspy import brms

    fit = brms.brm("y ~ x + (1|g)", data=df, family="gaussian", chains=4, cores=4)

    fit.idata.posterior
    ```
    """
    import rpy2.robjects as ro
    import rpy2.robjects.packages as packages

    fun_brm = cast(Callable, ro.r("brms::brm"))

    if backend == "cmdstanr":
        try:
            cmdstanr = packages.importr("cmdstanr")
        except:
            cmdstanr = None
        if cmdstanr is None:
            raise RuntimeError(
                "cmdstanr backend is not installed! Please run install_brms(install_cmdstanr=True)"
            )

    if backend == "rstan":
        try:
            rstan = packages.importr("rstan")
        except:
            rstan = None
        if rstan is None:
            raise RuntimeError(
                "rstan backend is not installed! Please run install_brms(install_rstan=True)"
            )

    # Formula checks. These should never be reached in the first place
    # if they are, the library is calling brm() from main directly without remote call
    assert not isinstance(formula, SexpWrapper)
    assert formula is not None
    if formula_args and isinstance(formula, str):
        formula = bf(formula, **formula_args)

    formula_obj = _execute_formula(formula)

    # Convert data to R format
    data_r = py_to_r(data)

    # Setup priors
    brms_prior = _build_priors(priors)

    # Prepare brm() arguments
    brm_kwargs: dict[str, Any] = {
        "formula": formula_obj,
        "data": data_r,
        "family": family,
        "sample_prior": sample_prior,
        "backend": backend,
        "cores": cores,
    }

    # Add priors if specified
    if len(brms_prior) > 0:
        brm_kwargs["prior"] = brms_prior

    # Add user-specified arguments
    brm_kwargs.update(brm_args)

    brm_kwargs = kwargs_r(brm_kwargs)

    # Set empty=TRUE if not sampling
    if not sample:
        brm_kwargs["empty"] = True
        log("Creating empty r object (no sampling)...")
    else:
        log(f"Fitting model with brms (backend: {backend})...")

    # Call brms::brm() with all arguments
    fit = fun_brm(**brm_kwargs)

    log("Fit done!")

    # Handle return type conversion
    if not return_idata:
        return fit

    if not sample:
        return FitResult(idata=IDBrm(), r=fit)

    idata = brmsfit_to_idata(fit)
    return FitResult(idata=idata, r=fit)

summary(model, **kwargs)

Generate comprehensive summary statistics for a fitted brms model.

Returns a SummaryResult dataclass containing model information, parameter estimates, and diagnostic information. The SummaryResult object provides pretty printing via str() or print() and structured access to all components.

BRMS documentation and parameters

Parameters:

Name Type Description Default
model FitResult

Fitted model returned by brmspy.brms.brm().

required
**kwargs

Additional arguments passed to brms::summary(), such as: - probs: Quantiles for credible intervals, e.g., probs=(0.025, 0.975) - robust: Use robust estimates (median, MAD), default False

{}

Returns:

Type Description
SummaryResult

A dataclass containing:

  • formula (str): Model formula as string
  • data_name (str): Name of the data object used
  • group (str): Grouping structure information
  • nobs (int): Number of observations
  • ngrps (Dict[str, int]): Number of groups per grouping variable
  • autocor (Optional[dict]): Autocorrelation structure if present
  • prior (pd.DataFrame): Prior specifications used
  • algorithm (str): Sampling algorithm (e.g., "sampling")
  • sampler (str): Sampler specification (e.g., "sample(hmc)")
  • total_ndraws (int): Total number of post-warmup draws
  • chains (float): Number of chains
  • iter (float): Iterations per chain
  • warmup (float): Warmup iterations per chain
  • thin (float): Thinning interval
  • has_rhat (bool): Whether Rhat diagnostics are reported
  • fixed (pd.DataFrame): Population-level (fixed) effects estimates
  • spec_pars (pd.DataFrame): Family-specific parameters (e.g., sigma)
  • cor_pars (pd.DataFrame): Correlation parameters if present
  • random (dict): Group-level (random) effects by grouping variable
See Also

brms::summary.brmsfit : R documentation

Examples:

Basic usage with pretty printing:

import brmspy

model = brmspy.fit("y ~ x", data=data, chains=4)
summary = brmspy.summary(model)

# Pretty print full summary
print(summary)

Access specific components:

# Get population-level effects as DataFrame
fixed_effects = summary.fixed
print(fixed_effects)

# Get family-specific parameters (e.g., sigma)
spec_params = summary.spec_pars
print(spec_params)

# Access random effects (if present)
random_effects = summary.random
for group_name, group_df in random_effects.items():
    print(f"Random effects for {group_name}:")
    print(group_df)

# Check model metadata
print(f"Formula: {summary.formula}")
print(f"Total draws: {summary.total_ndraws}")
print(f"Rhat reported: {summary.has_rhat}")

Custom credible intervals:

# Use 90% credible intervals instead of default 95%
summary_90 = brmspy.summary(model, probs=(0.05, 0.95))
print(summary_90.fixed)
Source code in brmspy/_brms_functions/diagnostics.py
def summary(model: FitResult, **kwargs) -> SummaryResult:
    """
    Generate comprehensive summary statistics for a fitted brms model.

    Returns a `SummaryResult` dataclass containing model information,
    parameter estimates, and diagnostic information. The SummaryResult object provides
    pretty printing via `str()` or `print()` and structured access to all components.

    [BRMS documentation and parameters](https://paulbuerkner.com/brms/reference/summary.brmsfit.html)

    Parameters
    ----------
    model : FitResult
        Fitted model returned by `brmspy.brms.brm()`.
    **kwargs
        Additional arguments passed to brms::summary(), such as:
        - probs: Quantiles for credible intervals, e.g., `probs=(0.025, 0.975)`
        - robust: Use robust estimates (median, MAD), default False

    Returns
    -------
    SummaryResult
        A dataclass containing:

        - **formula** (str): Model formula as string
        - **data_name** (str): Name of the data object used
        - **group** (str): Grouping structure information
        - **nobs** (int): Number of observations
        - **ngrps** (Dict[str, int]): Number of groups per grouping variable
        - **autocor** (Optional[dict]): Autocorrelation structure if present
        - **prior** (pd.DataFrame): Prior specifications used
        - **algorithm** (str): Sampling algorithm (e.g., "sampling")
        - **sampler** (str): Sampler specification (e.g., "sample(hmc)")
        - **total_ndraws** (int): Total number of post-warmup draws
        - **chains** (float): Number of chains
        - **iter** (float): Iterations per chain
        - **warmup** (float): Warmup iterations per chain
        - **thin** (float): Thinning interval
        - **has_rhat** (bool): Whether Rhat diagnostics are reported
        - **fixed** (pd.DataFrame): Population-level (fixed) effects estimates
        - **spec_pars** (pd.DataFrame): Family-specific parameters (e.g., sigma)
        - **cor_pars** (pd.DataFrame): Correlation parameters if present
        - **random** (dict): Group-level (random) effects by grouping variable

    See Also
    --------
    brms::summary.brmsfit : [R documentation](https://paulbuerkner.com/brms/reference/summary.brmsfit.html)

    Examples
    --------
    Basic usage with pretty printing:

    ```python
    import brmspy

    model = brmspy.fit("y ~ x", data=data, chains=4)
    summary = brmspy.summary(model)

    # Pretty print full summary
    print(summary)
    ```

    Access specific components:

    ```python
    # Get population-level effects as DataFrame
    fixed_effects = summary.fixed
    print(fixed_effects)

    # Get family-specific parameters (e.g., sigma)
    spec_params = summary.spec_pars
    print(spec_params)

    # Access random effects (if present)
    random_effects = summary.random
    for group_name, group_df in random_effects.items():
        print(f"Random effects for {group_name}:")
        print(group_df)

    # Check model metadata
    print(f"Formula: {summary.formula}")
    print(f"Total draws: {summary.total_ndraws}")
    print(f"Rhat reported: {summary.has_rhat}")
    ```

    Custom credible intervals:

    ```python
    # Use 90% credible intervals instead of default 95%
    summary_90 = brmspy.summary(model, probs=(0.05, 0.95))
    print(summary_90.fixed)
    ```
    """

    import rpy2.robjects as ro

    kwargs = kwargs_r(kwargs)
    r_summary = cast(Callable, ro.r("summary"))
    summary_r = r_summary(model.r, **kwargs)

    _default_get_r = lambda param: f"function(x) x${param}"
    _get_methods_r: dict[str, Callable[[str], str]] = {
        # Extract a clean formula string: "y ~ x1 + x2 + ..."
        "formula": lambda param: (
            "function(x) { paste(deparse(x$formula$formula), collapse = ' ') }"
        ),
    }

    names = summary_r.names
    get = lambda param: r_to_py(
        cast(Callable, ro.r(_get_methods_r.get(param, _default_get_r)(param)))(
            summary_r
        )
    )
    out = iterate_robject_to_dataclass(
        names=names, get=get, target_dataclass=SummaryResult, r=summary_r
    )

    return cast(SummaryResult, out)

fixef(object, summary=True, robust=False, probs=(0.025, 0.975), pars=None, **kwargs)

Extract population-level (fixed) effects estimates from a fitted brms model.

Returns a pandas DataFrame containing estimates and uncertainty intervals for all population-level parameters (fixed effects). By default, returns summary statistics (mean, standard error, credible intervals). Can also return raw posterior samples when summary=False.

BRMS documentation

Parameters:

Name Type Description Default
object FitResult or ListSexpVector

Fitted model returned by brmspy.brms.brm() or an R brmsfit object.

required
summary bool

If True, return summary statistics (mean/median, SE/MAD, credible intervals). If False, return matrix of posterior samples (iterations × parameters).

True
robust bool

If True, use median and MAD instead of mean and SD for summary statistics. Only used when summary=True.

False
probs tuple of float

Quantiles for credible intervals, e.g., (0.025, 0.975) for 95% intervals. Only used when summary=True.

(0.025, 0.975)
pars list of str

Specific parameter names to extract. If None, returns all fixed effects. Useful for subsetting when you only need specific coefficients.

None
**kwargs

Additional arguments passed to brms::fixef()

{}

Returns:

Type Description
DataFrame

When summary=True (default): DataFrame with parameters as rows and columns for Estimate, Est.Error, Q2.5, Q97.5 (or other quantiles specified in probs), and optionally Rhat and Bulk_ESS/Tail_ESS diagnostics.

When summary=False: DataFrame with posterior samples where rows are iterations and columns are parameters. Shape is (n_iterations × n_parameters).

See Also

brms::fixef.brmsfit : R documentation summary() : Full model summary with all parameter types

Examples:

Basic usage with summary statistics:

import brmspy

model = brmspy.fit("y ~ x1 + x2", data=data, chains=4)

# Get fixed effects summary
fixed_effects = brmspy.fixef(model)
print(fixed_effects)
#             Estimate  Est.Error      Q2.5     Q97.5
# Intercept  10.234567   0.123456  9.992345  10.47689
# x1          0.456789   0.098765  0.263456   0.65012
# x2         -0.234567   0.087654 -0.406789  -0.06234

Get specific parameters only:

# Extract only specific coefficients
x1_x2_effects = brmspy.fixef(model, pars=["x1", "x2"])
print(x1_x2_effects)

Use robust estimates (median and MAD):

# Use median and MAD instead of mean and SD
robust_effects = brmspy.fixef(model, robust=True)
print(robust_effects)

Custom credible intervals:

# Get 90% credible intervals
effects_90 = brmspy.fixef(model, probs=(0.05, 0.95))
print(effects_90)

Get raw posterior samples:

# Get full posterior samples matrix
samples = brmspy.fixef(model, summary=False)
print(samples.shape)  # (n_iterations, n_parameters)

# Can then compute custom statistics
import numpy as np
custom_quantile = np.percentile(samples["x1"], 90)
Source code in brmspy/_brms_functions/diagnostics.py
def fixef(
    object: FitResult | ListSexpVector,
    summary=True,
    robust=False,
    probs=(0.025, 0.975),
    pars=None,
    **kwargs,
) -> pd.DataFrame:
    """
    Extract population-level (fixed) effects estimates from a fitted brms model.

    Returns a pandas DataFrame containing estimates and uncertainty intervals for
    all population-level parameters (fixed effects). By default, returns summary
    statistics (mean, standard error, credible intervals). Can also return raw
    posterior samples when `summary=False`.

    [BRMS documentation](https://paulbuerkner.com/brms/reference/fixef.brmsfit.html)

    Parameters
    ----------
    object : FitResult or ListSexpVector
        Fitted model returned by `brmspy.brms.brm()` or an R brmsfit object.
    summary : bool, default=True
        If True, return summary statistics (mean/median, SE/MAD, credible intervals).
        If False, return matrix of posterior samples (iterations × parameters).
    robust : bool, default=False
        If True, use median and MAD instead of mean and SD for summary statistics.
        Only used when `summary=True`.
    probs : tuple of float, default=(0.025, 0.975)
        Quantiles for credible intervals, e.g., (0.025, 0.975) for 95% intervals.
        Only used when `summary=True`.
    pars : list of str, optional
        Specific parameter names to extract. If None, returns all fixed effects.
        Useful for subsetting when you only need specific coefficients.
    **kwargs
        Additional arguments passed to brms::fixef()

    Returns
    -------
    pd.DataFrame
        When `summary=True` (default):
            DataFrame with parameters as rows and columns for Estimate, Est.Error,
            Q2.5, Q97.5 (or other quantiles specified in `probs`), and optionally
            Rhat and Bulk_ESS/Tail_ESS diagnostics.

        When `summary=False`:
            DataFrame with posterior samples where rows are iterations and columns
            are parameters. Shape is (n_iterations × n_parameters).

    See Also
    --------
    brms::fixef.brmsfit : [R documentation](https://paulbuerkner.com/brms/reference/fixef.brmsfit.html)
    summary() : Full model summary with all parameter types

    Examples
    --------
    Basic usage with summary statistics:

    ```python
    import brmspy

    model = brmspy.fit("y ~ x1 + x2", data=data, chains=4)

    # Get fixed effects summary
    fixed_effects = brmspy.fixef(model)
    print(fixed_effects)
    #             Estimate  Est.Error      Q2.5     Q97.5
    # Intercept  10.234567   0.123456  9.992345  10.47689
    # x1          0.456789   0.098765  0.263456   0.65012
    # x2         -0.234567   0.087654 -0.406789  -0.06234
    ```

    Get specific parameters only:

    ```python
    # Extract only specific coefficients
    x1_x2_effects = brmspy.fixef(model, pars=["x1", "x2"])
    print(x1_x2_effects)
    ```

    Use robust estimates (median and MAD):

    ```python
    # Use median and MAD instead of mean and SD
    robust_effects = brmspy.fixef(model, robust=True)
    print(robust_effects)
    ```

    Custom credible intervals:

    ```python
    # Get 90% credible intervals
    effects_90 = brmspy.fixef(model, probs=(0.05, 0.95))
    print(effects_90)
    ```

    Get raw posterior samples:

    ```python
    # Get full posterior samples matrix
    samples = brmspy.fixef(model, summary=False)
    print(samples.shape)  # (n_iterations, n_parameters)

    # Can then compute custom statistics
    import numpy as np
    custom_quantile = np.percentile(samples["x1"], 90)
    ```
    """
    import rpy2.robjects as ro

    obj_r = py_to_r(object)
    kwargs = kwargs_r(
        {"summary": summary, "robust": robust, "probs": probs, "pars": pars, **kwargs}
    )
    r_fixef = cast(Callable, ro.r("brms::fixef"))
    r_df = r_fixef(obj_r, **kwargs)
    return cast(pd.DataFrame, r_to_py(r_df))

ranef(object, summary=True, robust=False, probs=(0.025, 0.975), pars=None, groups=None, **kwargs)

Extract group-level (random) effects as xarray DataArrays.

This is a wrapper around brms::ranef(). For summary=True (default), each grouping factor is returned as a 3D array with dimensions ("group", "stat", "coef"). For summary=False, each factor is returned as ("draw", "group", "coef") with one slice per posterior draw.

Parameters:

Name Type Description Default
object FitResult or ListVector

Fitted model returned by :func:brmspy.brms.fit or an R brmsfit object / summary list.

required
summary bool

If True, return posterior summaries for the group-level effects (means, errors, intervals). If False, return per-draw random effects.

True
robust bool

If True, use robust summaries (median and MAD) instead of mean and SD. Passed through to brms::ranef() when summary=True.

False
probs tuple of float

Central posterior interval probabilities, as in brms::ranef(). Only used when summary=True.

(0.025, 0.975)
pars str or sequence of str

Subset of group-level parameters to include. Passed to brms::ranef().

None
groups str or sequence of str

Subset of grouping factors to include. Passed to brms::ranef().

None
**kwargs

Additional keyword arguments forwarded to brms::ranef().

{}

Returns:

Type Description
dict[str, DataArray]

Mapping from grouping-factor name (e.g. "patient") to a DataArray:

  • summary=True: dims ("group", "stat", "coef"), with stat typically containing ["Estimate", "Est.Error", "Q2.5", "Q97.5"].
  • summary=False: dims ("draw", "group", "coef"), where draw indexes posterior samples.

Examples:

Compute summary random effects and inspect all coefficients for a single group level:

from brmspy import brms
from brmspy.brms import ranef

fit = brms.fit("count ~ zAge + zBase * Trt + (1 + zBase + Trt | patient)",
               data=data, family="poisson")

re = ranef(fit)  # summary=True by default
patient_re = re["patient"].sel(group="1", stat="Estimate")

Extract per-draw random effects for downstream MCMC analysis:

re_draws = ranef(fit, summary=False)
patient_draws = re_draws["patient"]       # dims: ("draw", "group", "coef")
first_draw = patient_draws.sel(draw=0)
Source code in brmspy/_brms_functions/diagnostics.py
def ranef(
    object: FitResult | ListSexpVector,
    summary: bool = True,
    robust: bool = False,
    probs=(0.025, 0.975),
    pars=None,
    groups=None,
    **kwargs,
) -> dict[str, xr.DataArray]:
    """
    Extract group-level (random) effects as xarray DataArrays.

    This is a wrapper around ``brms::ranef()``. For ``summary=True`` (default),
    each grouping factor is returned as a 3D array with dimensions
    ``("group", "stat", "coef")``. For ``summary=False``, each factor is
    returned as ``("draw", "group", "coef")`` with one slice per posterior draw.

    Parameters
    ----------
    object : FitResult or rpy2.robjects.ListVector
        Fitted model returned by :func:`brmspy.brms.fit` or an R ``brmsfit``
        object / summary list.
    summary : bool, default True
        If True, return posterior summaries for the group-level effects
        (means, errors, intervals). If False, return per-draw random effects.
    robust : bool, default False
        If True, use robust summaries (median and MAD) instead of mean and SD.
        Passed through to ``brms::ranef()`` when ``summary=True``.
    probs : tuple of float, default (0.025, 0.975)
        Central posterior interval probabilities, as in ``brms::ranef()``.
        Only used when ``summary=True``.
    pars : str or sequence of str, optional
        Subset of group-level parameters to include. Passed to ``brms::ranef()``.
    groups : str or sequence of str, optional
        Subset of grouping factors to include. Passed to ``brms::ranef()``.
    **kwargs
        Additional keyword arguments forwarded to ``brms::ranef()``.

    Returns
    -------
    dict[str, xarray.DataArray]
        Mapping from grouping-factor name (e.g. ``"patient"``) to a
        ``DataArray``:

        * ``summary=True``: dims ``("group", "stat", "coef")``,
          with ``stat`` typically containing
          ``["Estimate", "Est.Error", "Q2.5", "Q97.5"]``.
        * ``summary=False``: dims ``("draw", "group", "coef")``,
          where ``draw`` indexes posterior samples.

    Examples
    --------
    Compute summary random effects and inspect all coefficients for a single
    group level:

    ```python
    from brmspy import brms
    from brmspy.brms import ranef

    fit = brms.fit("count ~ zAge + zBase * Trt + (1 + zBase + Trt | patient)",
                   data=data, family="poisson")

    re = ranef(fit)  # summary=True by default
    patient_re = re["patient"].sel(group="1", stat="Estimate")
    ```

    Extract per-draw random effects for downstream MCMC analysis:

    ```python
    re_draws = ranef(fit, summary=False)
    patient_draws = re_draws["patient"]       # dims: ("draw", "group", "coef")
    first_draw = patient_draws.sel(draw=0)
    ```
    """
    import rpy2.robjects as ro

    obj_r = py_to_r(object)
    kwargs = kwargs_r(
        {"summary": summary, "robust": robust, "probs": probs, "pars": pars, **kwargs}
    )

    r_ranef = cast(Callable, ro.r("brms::ranef"))
    r_list = r_ranef(obj_r, **kwargs)

    out: dict[str, xr.DataArray] = {}

    for name in r_list.names:
        # R 3D array for this grouping factor
        r_arr = cast(Callable, ro.r(f"function(x) x${name}"))(r_list)
        dims = list(r_arr.do_slot("dim"))  # length-3

        # dimnames is a list of length 3, some entries may be NULL
        dimnames_r = r_arr.do_slot("dimnames")
        dimnames: list[list[str] | None] = []
        for dn in dimnames_r:
            if dn == ro.NULL:
                dimnames.append(None)
            else:
                dimnames.append(list(cast(Iterable, r_to_py(dn))))

        p_arr = np.asarray(r_arr).reshape(dims)

        if summary:
            # brms: 1=group levels, 2=stats, 3=coefs
            groups_dn, stats_dn, coefs_dn = dimnames

            da = xr.DataArray(
                p_arr,
                dims=("group", "stat", "coef"),
                coords={
                    "group": groups_dn,
                    "stat": stats_dn,
                    "coef": coefs_dn,
                },
            )
        else:
            # brms: 1=draws, 2=group levels, 3=coefs
            draws_dn, groups_dn, coefs_dn = dimnames
            n_draws = dims[0]
            if draws_dn is None:
                # brms does not name draws, so create a simple index
                draws_dn = list(range(n_draws))

            da = xr.DataArray(
                p_arr,
                dims=("draw", "group", "coef"),
                coords={
                    "draw": draws_dn,
                    "group": groups_dn,
                    "coef": coefs_dn,
                },
            )

        out[name] = da
    return out

posterior_summary(object, variable=None, probs=(0.025, 0.975), robust=False, **kwargs)

Extract posterior summary statistics for all or selected model parameters.

Provides a DataFrame with estimates, standard errors, and credible intervals for all parameters in a brms model, including fixed effects, random effects, and auxiliary parameters. More comprehensive than fixef() or ranef() as it covers all parameter types.

BRMS documentation

Parameters:

Name Type Description Default
object FitResult or ListSexpVector

Fitted model returned by brmspy.brms.brm() or an R brmsfit object.

required
variable str or list of str

Specific variable name(s) to extract. If None, returns all parameters. Supports regex patterns for flexible selection.

None
probs tuple of float

Quantiles for credible intervals, e.g., (0.025, 0.975) for 95% intervals.

(0.025, 0.975)
robust bool

If True, use median and MAD instead of mean and SD for summary statistics.

False
**kwargs

Additional arguments passed to brms::posterior_summary()

{}

Returns:

Type Description
DataFrame

DataFrame with parameters as rows and columns for Estimate, Est.Error, and quantiles (e.g., Q2.5, Q97.5). Includes all model parameters: population-level effects, group-level effects, and auxiliary parameters.

See Also

brms::posterior_summary : R documentation https://paulbuerkner.com/brms/reference/posterior_summary.brmsfit.html fixef() : Extract only population-level effects ranef() : Extract only group-level effects

Examples:

Get summary for all parameters:

import brmspy

model = brmspy.fit("y ~ x1 + (1|group)", data=data, chains=4)

# Get all parameter summaries
all_params = brmspy.posterior_summary(model)
print(all_params)

Extract specific parameters:

# Get summary for specific parameters
intercept = brmspy.posterior_summary(model, variable="b_Intercept")
print(intercept)

# Multiple parameters
fixed_only = brmspy.posterior_summary(model, variable=["b_Intercept", "b_x1"])
print(fixed_only)

Custom credible intervals with robust estimates:

# 90% intervals with median/MAD
robust_summary = brmspy.posterior_summary(
    model,
    probs=(0.05, 0.95),
    robust=True
)
print(robust_summary)
Source code in brmspy/_brms_functions/diagnostics.py
def posterior_summary(
    object: FitResult | ListSexpVector,
    variable=None,
    probs=(0.025, 0.975),
    robust=False,
    **kwargs,
) -> pd.DataFrame:
    """
    Extract posterior summary statistics for all or selected model parameters.

    Provides a DataFrame with estimates, standard errors, and credible intervals
    for all parameters in a brms model, including fixed effects, random effects,
    and auxiliary parameters. More comprehensive than `fixef()` or `ranef()` as it covers all
    parameter types.

    [BRMS documentation](https://paulbuerkner.com/brms/reference/posterior_summary.brmsfit.html)

    Parameters
    ----------
    object : FitResult or ListSexpVector
        Fitted model returned by `brmspy.brms.brm()` or an R brmsfit object.
    variable : str or list of str, optional
        Specific variable name(s) to extract. If None, returns all parameters.
        Supports regex patterns for flexible selection.
    probs : tuple of float, default=(0.025, 0.975)
        Quantiles for credible intervals, e.g., (0.025, 0.975) for 95% intervals.
    robust : bool, default=False
        If True, use median and MAD instead of mean and SD for summary statistics.
    **kwargs
        Additional arguments passed to brms::posterior_summary()

    Returns
    -------
    pd.DataFrame
        DataFrame with parameters as rows and columns for Estimate, Est.Error,
        and quantiles (e.g., Q2.5, Q97.5). Includes all model parameters:
        population-level effects, group-level effects, and auxiliary parameters.

    See Also
    --------
    brms::posterior_summary : R documentation
        https://paulbuerkner.com/brms/reference/posterior_summary.brmsfit.html
    fixef() : Extract only population-level effects
    ranef() : Extract only group-level effects

    Examples
    --------
    Get summary for all parameters:

    ```python
    import brmspy

    model = brmspy.fit("y ~ x1 + (1|group)", data=data, chains=4)

    # Get all parameter summaries
    all_params = brmspy.posterior_summary(model)
    print(all_params)
    ```

    Extract specific parameters:

    ```python
    # Get summary for specific parameters
    intercept = brmspy.posterior_summary(model, variable="b_Intercept")
    print(intercept)

    # Multiple parameters
    fixed_only = brmspy.posterior_summary(model, variable=["b_Intercept", "b_x1"])
    print(fixed_only)
    ```

    Custom credible intervals with robust estimates:

    ```python
    # 90% intervals with median/MAD
    robust_summary = brmspy.posterior_summary(
        model,
        probs=(0.05, 0.95),
        robust=True
    )
    print(robust_summary)
    ```
    """
    import rpy2.robjects as ro

    obj_r = py_to_r(object)
    kwargs = kwargs_r(
        {"variable": variable, "probs": probs, "robust": robust, **kwargs}
    )

    r_fun = cast(Callable, ro.r("brms::posterior_summary"))
    r_df = r_fun(obj_r, **kwargs)
    return cast(pd.DataFrame, r_to_py(r_df))

prior_summary(object, all=True, **kwargs)

Extract prior specifications used in a fitted brms model.

Returns a DataFrame containing all prior distributions that were used (either explicitly set or defaults) when fitting the model. Useful for documenting model specifications and understanding which priors were applied.

BRMS documentation

Parameters:

Name Type Description Default
object FitResult or ListVector

Fitted model returned by brmspy.brms.brm() or an R brmsfit object.

required
all bool

If True, return all priors including default priors. If False, return only explicitly set priors.

True
**kwargs

Additional arguments passed to brms::prior_summary()

{}

Returns:

Type Description
DataFrame

DataFrame with columns describing prior specifications: - prior: Prior distribution formula - class: Parameter class (b, sd, Intercept, etc.) - coef: Specific coefficient (if applicable) - group: Grouping factor (if applicable) - resp: Response variable (for multivariate models) - dpar: Distributional parameter (if applicable) - nlpar: Non-linear parameter (if applicable) - lb/ub: Bounds for truncated priors - source: Origin of prior (default, user, etc.)

See Also

brms::prior_summary : R documentation https://paulbuerkner.com/brms/reference/prior_summary.brmsfit.html get_prior() : Get prior structure before fitting default_prior() : Get default priors for a model

Examples:

Get all priors used in a model:

import brmspy

model = brmspy.fit(
    "y ~ x1 + (1|group)",
    data=data,
    priors=[brmspy.prior("normal(0, 1)", "b")],
    chains=4
)

# Get all priors (including defaults)
priors = brmspy.prior_summary(model)
print(priors)

Get only explicitly set priors:

# Get only user-specified priors
user_priors = brmspy.prior_summary(model, all=False)
print(user_priors)

Compare with what would be used before fitting:

# Before fitting - check default priors
default_priors = brmspy.get_prior("y ~ x1", data=data)

# After fitting - see what was actually used
used_priors = brmspy.prior_summary(model)
Source code in brmspy/_brms_functions/diagnostics.py
def prior_summary(
    object: FitResult | ListSexpVector, all=True, **kwargs
) -> pd.DataFrame:
    """
    Extract prior specifications used in a fitted brms model.

    Returns a DataFrame containing all prior distributions that were used
    (either explicitly set or defaults) when fitting the model. Useful for
    documenting model specifications and understanding which priors were applied.

    [BRMS documentation](https://paulbuerkner.com/brms/reference/prior_summary.brmsfit.html)

    Parameters
    ----------
    object : FitResult or ListVector
        Fitted model returned by `brmspy.brms.brm()` or an R brmsfit object.
    all : bool, default=True
        If True, return all priors including default priors.
        If False, return only explicitly set priors.
    **kwargs
        Additional arguments passed to brms::prior_summary()

    Returns
    -------
    pd.DataFrame
        DataFrame with columns describing prior specifications:
        - prior: Prior distribution formula
        - class: Parameter class (b, sd, Intercept, etc.)
        - coef: Specific coefficient (if applicable)
        - group: Grouping factor (if applicable)
        - resp: Response variable (for multivariate models)
        - dpar: Distributional parameter (if applicable)
        - nlpar: Non-linear parameter (if applicable)
        - lb/ub: Bounds for truncated priors
        - source: Origin of prior (default, user, etc.)

    See Also
    --------
    brms::prior_summary : R documentation
        https://paulbuerkner.com/brms/reference/prior_summary.brmsfit.html
    get_prior() : Get prior structure before fitting
    default_prior() : Get default priors for a model

    Examples
    --------
    Get all priors used in a model:

    ```python
    import brmspy

    model = brmspy.fit(
        "y ~ x1 + (1|group)",
        data=data,
        priors=[brmspy.prior("normal(0, 1)", "b")],
        chains=4
    )

    # Get all priors (including defaults)
    priors = brmspy.prior_summary(model)
    print(priors)
    ```

    Get only explicitly set priors:

    ```python
    # Get only user-specified priors
    user_priors = brmspy.prior_summary(model, all=False)
    print(user_priors)
    ```

    Compare with what would be used before fitting:

    ```python
    # Before fitting - check default priors
    default_priors = brmspy.get_prior("y ~ x1", data=data)

    # After fitting - see what was actually used
    used_priors = brmspy.prior_summary(model)
    ```
    """
    import rpy2.robjects as ro

    obj_r = py_to_r(object)
    kwargs = kwargs_r({"all": all, **kwargs})

    r_fun = cast(Callable, ro.r("brms::prior_summary"))
    r_df = r_fun(obj_r, **kwargs)
    return cast(pd.DataFrame, r_to_py(r_df))

validate_newdata(newdata, object, re_formula=None, allow_new_levels=False, newdata2=None, resp=None, check_response=True, incl_autocor=True, group_vars=None, req_vars=None, **kwargs)

Validate new data for predictions from a fitted brms model.

Ensures that new data contains all required variables and has the correct structure for making predictions. Checks variable types, factor levels, grouping variables, and autocorrelation structures. This function is primarily used internally by prediction methods but can be called directly for debugging or validation purposes.

BRMS documentation

Parameters:

Name Type Description Default
newdata DataFrame

DataFrame containing new data to be validated against the model. Must include all predictor variables used in the model formula.

required
object FitResult or ListSexpVector

Fitted model returned by brmspy.brms.brm() or an R brmsfit object.

required
re_formula str

Formula string specifying group-level effects to include in validation. If None (default), include all group-level effects. If NA, include no group-level effects.

None
allow_new_levels bool

Whether to allow new levels of grouping variables not present in the original training data. If False, raises an error for new levels.

False
newdata2 DataFrame

Additional data that cannot be passed via newdata, such as objects used in autocorrelation structures or stanvars.

None
resp str or list of str

Names of response variables to validate. If specified, validation is performed only for the specified responses (relevant for multivariate models).

None
check_response bool

Whether to check if response variables are present in newdata. Set to False when making predictions where response is not needed.

True
incl_autocor bool

Whether to include autocorrelation structures originally specified in the model. If True, validates autocorrelation-related variables.

True
group_vars list of str

Names of specific grouping variables to validate. If None (default), validates all grouping variables present in the model.

None
req_vars list of str

Names of specific variables required in newdata. If None (default), all variables from the original training data are required (unless excluded by other parameters).

None
**kwargs

Additional arguments passed to brms::validate_newdata()

{}

Returns:

Type Description
DataFrame

Validated DataFrame based on newdata, potentially with added or modified columns to ensure compatibility with the model.

Raises:

Type Description
ValueError

If newdata is missing required variables

ValueError

If factor levels in newdata don't match those in training data (when allow_new_levels=False)

ValueError

If grouping variables have invalid structure

See Also

brms::validate_newdata : R documentation https://paulbuerkner.com/brms/reference/validate_newdata.html posterior_predict() : Uses validate_newdata internally posterior_epred() : Uses validate_newdata internally

Examples:

Basic validation for prediction data:

import brmspy
import pandas as pd

# Fit model
model = brmspy.fit("y ~ x1 + x2", data=train_data, chains=4)

# Prepare new data
new_data = pd.DataFrame({
    'x1': [1.0, 2.0, 3.0],
    'x2': [0.5, 1.0, 1.5]
})

# Validate before prediction
validated_data = brmspy.validate_newdata(new_data, model)
print(validated_data)

Validate with group-level effects:

# Model with random effects
model = brmspy.fit("y ~ x + (1|group)", data=train_data, chains=4)

# New data with grouping variable
new_data = pd.DataFrame({
    'x': [1.0, 2.0],
    'group': ['A', 'B']  # Must match training data groups
})

# Validate - will error if groups A or B weren't in training
validated_data = brmspy.validate_newdata(
    new_data,
    model,
    allow_new_levels=False
)

Allow new levels for population-level predictions:

# Allow new group levels (makes population-level predictions only)
new_data_with_new_groups = pd.DataFrame({
    'x': [3.0, 4.0],
    'group': ['C', 'D']  # New groups not in training
})

validated_data = brmspy.validate_newdata(
    new_data_with_new_groups,
    model,
    allow_new_levels=True
)

Skip response variable checking:

# When making predictions, response not needed
new_data = pd.DataFrame({'x1': [1.0, 2.0]})

validated_data = brmspy.validate_newdata(
    new_data,
    model,
    check_response=False
)
Source code in brmspy/_brms_functions/diagnostics.py
def validate_newdata(
    newdata: pd.DataFrame,
    object: ListSexpVector | FitResult,
    re_formula: str | None = None,
    allow_new_levels: bool = False,
    newdata2: pd.DataFrame | None = None,
    resp=None,
    check_response=True,
    incl_autocor=True,
    group_vars=None,
    req_vars=None,
    **kwargs,
) -> pd.DataFrame:
    """
    Validate new data for predictions from a fitted brms model.

    Ensures that new data contains all required variables and has the correct
    structure for making predictions. Checks variable types, factor levels,
    grouping variables, and autocorrelation structures. This function is primarily
    used internally by prediction methods but can be called directly for debugging
    or validation purposes.

    [BRMS documentation](https://paulbuerkner.com/brms/reference/validate_newdata.html)

    Parameters
    ----------
    newdata : pd.DataFrame
        DataFrame containing new data to be validated against the model.
        Must include all predictor variables used in the model formula.
    object : FitResult or ListSexpVector
        Fitted model returned by `brmspy.brms.brm()` or an R brmsfit object.
    re_formula : str, optional
        Formula string specifying group-level effects to include in validation.
        If None (default), include all group-level effects.
        If NA, include no group-level effects.
    allow_new_levels : bool, default=False
        Whether to allow new levels of grouping variables not present in
        the original training data. If False, raises an error for new levels.
    newdata2 : pd.DataFrame, optional
        Additional data that cannot be passed via `newdata`, such as objects
        used in autocorrelation structures or stanvars.
    resp : str or list of str, optional
        Names of response variables to validate. If specified, validation
        is performed only for the specified responses (relevant for multivariate models).
    check_response : bool, default=True
        Whether to check if response variables are present in newdata.
        Set to False when making predictions where response is not needed.
    incl_autocor : bool, default=True
        Whether to include autocorrelation structures originally specified
        in the model. If True, validates autocorrelation-related variables.
    group_vars : list of str, optional
        Names of specific grouping variables to validate. If None (default),
        validates all grouping variables present in the model.
    req_vars : list of str, optional
        Names of specific variables required in newdata. If None (default),
        all variables from the original training data are required (unless
        excluded by other parameters).
    **kwargs
        Additional arguments passed to brms::validate_newdata()

    Returns
    -------
    pd.DataFrame
        Validated DataFrame based on newdata, potentially with added or
        modified columns to ensure compatibility with the model.

    Raises
    ------
    ValueError
        If newdata is missing required variables
    ValueError
        If factor levels in newdata don't match those in training data
        (when allow_new_levels=False)
    ValueError
        If grouping variables have invalid structure

    See Also
    --------
    brms::validate_newdata : R documentation
        https://paulbuerkner.com/brms/reference/validate_newdata.html
    posterior_predict() : Uses validate_newdata internally
    posterior_epred() : Uses validate_newdata internally

    Examples
    --------
    Basic validation for prediction data:

    ```python
    import brmspy
    import pandas as pd

    # Fit model
    model = brmspy.fit("y ~ x1 + x2", data=train_data, chains=4)

    # Prepare new data
    new_data = pd.DataFrame({
        'x1': [1.0, 2.0, 3.0],
        'x2': [0.5, 1.0, 1.5]
    })

    # Validate before prediction
    validated_data = brmspy.validate_newdata(new_data, model)
    print(validated_data)
    ```

    Validate with group-level effects:

    ```python
    # Model with random effects
    model = brmspy.fit("y ~ x + (1|group)", data=train_data, chains=4)

    # New data with grouping variable
    new_data = pd.DataFrame({
        'x': [1.0, 2.0],
        'group': ['A', 'B']  # Must match training data groups
    })

    # Validate - will error if groups A or B weren't in training
    validated_data = brmspy.validate_newdata(
        new_data,
        model,
        allow_new_levels=False
    )
    ```

    Allow new levels for population-level predictions:

    ```python
    # Allow new group levels (makes population-level predictions only)
    new_data_with_new_groups = pd.DataFrame({
        'x': [3.0, 4.0],
        'group': ['C', 'D']  # New groups not in training
    })

    validated_data = brmspy.validate_newdata(
        new_data_with_new_groups,
        model,
        allow_new_levels=True
    )
    ```

    Skip response variable checking:

    ```python
    # When making predictions, response not needed
    new_data = pd.DataFrame({'x1': [1.0, 2.0]})

    validated_data = brmspy.validate_newdata(
        new_data,
        model,
        check_response=False
    )
    ```
    """
    import rpy2.robjects as ro

    r_validate_newdata = cast(Callable, ro.r("brms::validate_newdata"))
    kwargs = kwargs_r(
        {
            "newdata": newdata,
            "object": object,
            "re_formula": re_formula,
            "allow_new_levels": allow_new_levels,
            "newdata2": newdata2,
            "resp": resp,
            "check_response": check_response,
            "incl_autocor": incl_autocor,
            "group_vars": group_vars,
            "req_vars": req_vars,
            **kwargs,
        }
    )
    res_r = r_validate_newdata(**kwargs)
    return cast(pd.DataFrame, r_to_py(res_r))

call(function, *args, **kwargs)

Call an R function by name with brmspy type conversion.

This is intended as an escape hatch for R/brms functionality that does not yet have a dedicated wrapper.

Parameters:

Name Type Description Default
function str

Function name. If not namespaced, brmspy tries brms::<function> first, then falls back to evaluating the name directly (e.g. "stats::AIC").

required
*args

Positional arguments.

()
**kwargs

Keyword arguments.

{}

Returns:

Type Description
Any

Converted return value.

Examples:

>>> from brmspy import brms
>>> fit = brms.brm("y ~ x", data=df, chains=4)
>>> aic = brms.call("stats::AIC", fit)
Source code in brmspy/_brms_functions/generic.py
def call(function: str, *args, **kwargs) -> Any:
    """
    Call an R function by name with brmspy type conversion.

    This is intended as an escape hatch for R/brms functionality that does not
    yet have a dedicated wrapper.

    Parameters
    ----------
    function : str
        Function name. If not namespaced, brmspy tries ``brms::<function>`` first,
        then falls back to evaluating the name directly (e.g. ``"stats::AIC"``).
    *args
        Positional arguments.
    **kwargs
        Keyword arguments.

    Returns
    -------
    Any
        Converted return value.

    Examples
    --------
    >>> from brmspy import brms
    >>> fit = brms.brm("y ~ x", data=df, chains=4)
    >>> aic = brms.call("stats::AIC", fit)
    """
    import rpy2.robjects as ro

    func_name = sanitised_name(function)
    args = [py_to_r(arg) for arg in args]
    kwargs = kwargs_r({**kwargs})
    try:
        r_fun = cast(
            Callable, ro.r(f"suppressWarnings(suppressMessages(brms::{func_name}))")
        )
    except Exception:
        r_fun = cast(Callable, ro.r(func_name))

    r_result = r_fun(*args, **kwargs)
    return r_to_py(r_result)

bf(*formulas, **formula_args)

Build a brms model formula.

This is the primary entrypoint for specifying the mean model and can be combined with other formula parts (e.g. lf, nlf, acformula) using +.

Parameters:

Name Type Description Default
*formulas str

One or more brms formula strings (e.g. "y ~ x + (1|group)"). Multiple formulas are commonly used for multivariate models.

()
**formula_args

Keyword arguments forwarded to R brms::brmsformula() (for example decomp="QR", center=True, sparse=True, nl=True, loop=True).

{}

Returns:

Type Description
FormulaConstruct

A composable formula specification.

See Also

brms::brmsformula : R documentation

Examples:

Basic formula:

from brmspy.brms import bf

f = bf("y ~ x1 + x2 + (1|group)")

QR decomposition (often helps with collinearity):

from brmspy.brms import bf

f = bf("reaction ~ days + (days|subject)", decomp="QR")

Multivariate formula + residual correlation:

from brmspy.brms import bf, set_rescor

f = bf("mvbind(y1, y2) ~ x") + set_rescor(True)
Source code in brmspy/_brms_functions/formula.py
def bf(*formulas: str, **formula_args) -> FormulaConstruct:
    """
    Build a brms model formula.

    This is the primary entrypoint for specifying the mean model and can be
    combined with other formula parts (e.g. `lf`, `nlf`, `acformula`) using ``+``.

    Parameters
    ----------
    *formulas : str
        One or more brms formula strings (e.g. ``"y ~ x + (1|group)"``). Multiple
        formulas are commonly used for multivariate models.
    **formula_args
        Keyword arguments forwarded to R ``brms::brmsformula()`` (for example
        ``decomp="QR"``, ``center=True``, ``sparse=True``, ``nl=True``, ``loop=True``).

    Returns
    -------
    FormulaConstruct
        A composable formula specification.

    See Also
    --------
    brms::brmsformula : [R documentation](https://paulbuerkner.com/brms/reference/brmsformula.html)

    Examples
    --------
    Basic formula:

    ```python
    from brmspy.brms import bf

    f = bf("y ~ x1 + x2 + (1|group)")
    ```

    QR decomposition (often helps with collinearity):

    ```python
    from brmspy.brms import bf

    f = bf("reaction ~ days + (days|subject)", decomp="QR")
    ```

    Multivariate formula + residual correlation:

    ```python
    from brmspy.brms import bf, set_rescor

    f = bf("mvbind(y1, y2) ~ x") + set_rescor(True)
    ```
    """
    part = FormulaPart(_fun="bf", _args=list(formulas), _kwargs=formula_args)
    return FormulaConstruct._formula_parse(part)

lf(*formulas, flist=None, dpar=None, resp=None, center=None, cmc=None, sparse=None, decomp=None)

Add linear formulas for distributional / non-linear parameters.

This wraps R brms::lf() and is typically used to model distributional parameters such as sigma (heteroskedasticity) or to specify predictors for non-linear parameters.

Parameters:

Name Type Description Default
*formulas str | FormulaConstruct | FormulaPart | ProxyListSexpVector

One or more formulas such as "sigma ~ x".

()
flist

Optional list of formulas (advanced; mirrors brms).

None
dpar str or None

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

None
resp str or None

Response name for multivariate models.

None
center bool | None

Forwarded to R brms::lf().

None
cmc bool | None

Forwarded to R brms::lf().

None
sparse bool | None

Forwarded to R brms::lf().

None
decomp bool | None

Forwarded to R brms::lf().

None

Returns:

Type Description
FormulaConstruct

A composable formula specification that can be combined using +.

See Also

brms::lf : R documentation

Examples:

Model mean + sigma:

from brmspy.brms import bf, lf

f = bf("y ~ x") + lf("sigma ~ x", dpar="sigma")
Source code in brmspy/_brms_functions/formula.py
def lf(
    *formulas: str | FormulaConstruct | FormulaPart | ProxyListSexpVector,
    flist=None,
    dpar: str | None = None,
    resp: str | None = None,
    center: bool | None = None,
    cmc: bool | None = None,
    sparse: bool | None = None,
    decomp: str | None = None,
) -> FormulaConstruct:
    """
    Add linear formulas for distributional / non-linear parameters.

    This wraps R ``brms::lf()`` and is typically used to model distributional
    parameters such as ``sigma`` (heteroskedasticity) or to specify predictors
    for non-linear parameters.

    Parameters
    ----------
    *formulas
        One or more formulas such as ``"sigma ~ x"``.
    flist
        Optional list of formulas (advanced; mirrors brms).
    dpar : str or None, default=None
        Distributional parameter name (e.g. ``"sigma"``, ``"phi"``).
    resp : str or None, default=None
        Response name for multivariate models.
    center, cmc, sparse, decomp
        Forwarded to R ``brms::lf()``.

    Returns
    -------
    FormulaConstruct
        A composable formula specification that can be combined using ``+``.

    See Also
    --------
    brms::lf : [R documentation](https://paulbuerkner.com/brms/reference/lf.html)

    Examples
    --------
    Model mean + sigma:

    ```python
    from brmspy.brms import bf, lf

    f = bf("y ~ x") + lf("sigma ~ x", dpar="sigma")
    ```
    """
    formula_args = {
        "flist": flist,
        "dpar": dpar,
        "resp": resp,
        "center": center,
        "cmc": cmc,
        "sparse": sparse,
        "decomp": decomp,
    }
    result = FormulaConstruct._formula_parse(
        FormulaPart("lf", list(formulas), formula_args)
    )
    return result

nlf(*formulas, flist=None, dpar=None, resp=None, loop=None)

Add non-linear formulas.

Wraps R brms::nlf(). This is used together with set_nl() and parameter definitions in lf() to specify non-linear models.

Parameters:

Name Type Description Default
*formulas str | FormulaConstruct | FormulaPart | ProxyListSexpVector

One or more non-linear formulas (e.g. "y ~ a * exp(b * x)").

()
flist

Optional list of formulas (advanced; mirrors brms).

None
dpar str or None

Distributional parameter name (optional).

None
resp str or None

Response name for multivariate models.

None
loop bool or None

Forwarded to R brms::nlf(loop=...).

None

Returns:

Type Description
FormulaConstruct

A composable formula specification.

See Also

brms::nlf : R documentation

Examples:

from brmspy.brms import bf, nlf, set_nl

f = bf("y ~ 1") + nlf("y ~ a * exp(b * x)") + set_nl()
Source code in brmspy/_brms_functions/formula.py
def nlf(
    *formulas: str | FormulaConstruct | FormulaPart | ProxyListSexpVector,
    flist=None,
    dpar: str | None = None,
    resp: str | None = None,
    loop: bool | None = None,
) -> FormulaConstruct:
    """
    Add non-linear formulas.

    Wraps R ``brms::nlf()``. This is used together with `set_nl()` and parameter
    definitions in `lf()` to specify non-linear models.

    Parameters
    ----------
    *formulas
        One or more non-linear formulas (e.g. ``"y ~ a * exp(b * x)"``).
    flist
        Optional list of formulas (advanced; mirrors brms).
    dpar : str or None, default=None
        Distributional parameter name (optional).
    resp : str or None, default=None
        Response name for multivariate models.
    loop : bool or None, default=None
        Forwarded to R ``brms::nlf(loop=...)``.

    Returns
    -------
    FormulaConstruct
        A composable formula specification.

    See Also
    --------
    brms::nlf : [R documentation](https://paulbuerkner.com/brms/reference/nlf.html)

    Examples
    --------
    ```python
    from brmspy.brms import bf, nlf, set_nl

    f = bf("y ~ 1") + nlf("y ~ a * exp(b * x)") + set_nl()
    ```
    """
    formula_args = {
        "flist": flist,
        "dpar": dpar,
        "resp": resp,
        "loop": loop,
    }
    return FormulaConstruct._formula_parse(FormulaPart("nlf", formulas, formula_args))

acformula(autocor, resp=None)

Add an autocorrelation structure.

Wraps R brms::acformula().

Parameters:

Name Type Description Default
autocor str

One-sided autocorrelation formula (e.g. "~ arma(p = 1, q = 1)").

required
resp str or None

Response name for multivariate models.

None

Returns:

Type Description
FormulaConstruct

A composable formula specification.

See Also

brms::acformula : R documentation

Examples:

from brmspy.brms import bf, acformula

f = bf("y ~ x") + acformula("~ arma(p = 1, q = 1)")
Source code in brmspy/_brms_functions/formula.py
def acformula(
    autocor: str,
    resp: str | None = None,
) -> FormulaConstruct:
    """
    Add an autocorrelation structure.

    Wraps R ``brms::acformula()``.

    Parameters
    ----------
    autocor : str
        One-sided autocorrelation formula (e.g. ``"~ arma(p = 1, q = 1)"``).
    resp : str or None, default=None
        Response name for multivariate models.

    Returns
    -------
    FormulaConstruct
        A composable formula specification.

    See Also
    --------
    brms::acformula : [R documentation](https://paulbuerkner.com/brms/reference/acformula.html)

    Examples
    --------
    ```python
    from brmspy.brms import bf, acformula

    f = bf("y ~ x") + acformula("~ arma(p = 1, q = 1)")
    ```
    """
    formula_args = {"resp": resp}
    return FormulaConstruct._formula_parse(
        FormulaPart("acformula", [autocor], formula_args)
    )

set_rescor(rescor=True)

Control residual correlations in multivariate models.

Wraps R brms::set_rescor().

Parameters:

Name Type Description Default
rescor bool

Whether to model residual correlations.

True

Returns:

Type Description
FormulaConstruct

A composable formula specification.

See Also

brms::set_rescor : R documentation

Examples:

from brmspy.brms import bf, set_rescor

f = bf("y1 ~ x") + bf("y2 ~ z") + set_rescor(True)
Source code in brmspy/_brms_functions/formula.py
def set_rescor(rescor: bool = True) -> FormulaConstruct:
    """
    Control residual correlations in multivariate models.

    Wraps R ``brms::set_rescor()``.

    Parameters
    ----------
    rescor : bool, default=True
        Whether to model residual correlations.

    Returns
    -------
    FormulaConstruct
        A composable formula specification.

    See Also
    --------
    brms::set_rescor : [R documentation](https://paulbuerkner.com/brms/reference/set_rescor.html)

    Examples
    --------
    ```python
    from brmspy.brms import bf, set_rescor

    f = bf("y1 ~ x") + bf("y2 ~ z") + set_rescor(True)
    ```
    """
    formula_args = {
        "rescor": rescor,
    }
    return FormulaConstruct._formula_parse(FormulaPart("set_rescor", [], formula_args))

set_mecor(mecor=True)

Control correlations between latent me() terms.

Wraps R brms::set_mecor().

Parameters:

Name Type Description Default
mecor bool

Whether to model correlations between latent variables introduced by me().

True

Returns:

Type Description
FormulaConstruct

A composable formula specification.

See Also

brms::set_mecor : R documentation

Examples:

from brmspy.brms import bf, set_mecor

f = bf("y ~ me(x, sdx)") + set_mecor(True)
Source code in brmspy/_brms_functions/formula.py
def set_mecor(mecor: bool = True) -> FormulaConstruct:
    """
    Control correlations between latent ``me()`` terms.

    Wraps R ``brms::set_mecor()``.

    Parameters
    ----------
    mecor : bool, default=True
        Whether to model correlations between latent variables introduced by ``me()``.

    Returns
    -------
    FormulaConstruct
        A composable formula specification.

    See Also
    --------
    brms::set_mecor : [R documentation](https://paulbuerkner.com/brms/reference/set_mecor.html)

    Examples
    --------
    ```python
    from brmspy.brms import bf, set_mecor

    f = bf("y ~ me(x, sdx)") + set_mecor(True)
    ```
    """
    formula_args = {
        "mecor": mecor,
    }
    return FormulaConstruct._formula_parse(FormulaPart("set_mecor", [], formula_args))

set_nl(dpar=None, resp=None)

Mark a model (or part of it) as non-linear.

Wraps R brms::set_nl().

Parameters:

Name Type Description Default
dpar str or None

Distributional parameter name (if only part of the model is non-linear).

None
resp str or None

Response name for multivariate models.

None

Returns:

Type Description
FormulaConstruct

A composable formula specification.

See Also

brms::set_nl : R documentation

Examples:

from brmspy.brms import bf, lf, set_nl

f = bf("y ~ a * inv_logit(x * b)") + lf("a + b ~ z") + set_nl()
Source code in brmspy/_brms_functions/formula.py
def set_nl(
    dpar: str | None = None,
    resp: str | None = None,
) -> FormulaConstruct:
    """
    Mark a model (or part of it) as non-linear.

    Wraps R ``brms::set_nl()``.

    Parameters
    ----------
    dpar : str or None, default=None
        Distributional parameter name (if only part of the model is non-linear).
    resp : str or None, default=None
        Response name for multivariate models.

    Returns
    -------
    FormulaConstruct
        A composable formula specification.

    See Also
    --------
    brms::set_nl : [R documentation](https://paulbuerkner.com/brms/reference/set_nl.html)

    Examples
    --------
    ```python
    from brmspy.brms import bf, lf, set_nl

    f = bf("y ~ a * inv_logit(x * b)") + lf("a + b ~ z") + set_nl()
    ```
    """
    formula_args = {
        "dpar": dpar,
        "resp": resp,
    }
    return FormulaConstruct._formula_parse(FormulaPart("set_nl", [], formula_args))

formula(*formulas, **formula_args)

Build a brms model formula.

This is the primary entrypoint for specifying the mean model and can be combined with other formula parts (e.g. lf, nlf, acformula) using +.

Parameters:

Name Type Description Default
*formulas str

One or more brms formula strings (e.g. "y ~ x + (1|group)"). Multiple formulas are commonly used for multivariate models.

()
**formula_args

Keyword arguments forwarded to R brms::brmsformula() (for example decomp="QR", center=True, sparse=True, nl=True, loop=True).

{}

Returns:

Type Description
FormulaConstruct

A composable formula specification.

See Also

brms::brmsformula : R documentation

Examples:

Basic formula:

from brmspy.brms import bf

f = bf("y ~ x1 + x2 + (1|group)")

QR decomposition (often helps with collinearity):

from brmspy.brms import bf

f = bf("reaction ~ days + (days|subject)", decomp="QR")

Multivariate formula + residual correlation:

from brmspy.brms import bf, set_rescor

f = bf("mvbind(y1, y2) ~ x") + set_rescor(True)
Source code in brmspy/_brms_functions/formula.py
def bf(*formulas: str, **formula_args) -> FormulaConstruct:
    """
    Build a brms model formula.

    This is the primary entrypoint for specifying the mean model and can be
    combined with other formula parts (e.g. `lf`, `nlf`, `acformula`) using ``+``.

    Parameters
    ----------
    *formulas : str
        One or more brms formula strings (e.g. ``"y ~ x + (1|group)"``). Multiple
        formulas are commonly used for multivariate models.
    **formula_args
        Keyword arguments forwarded to R ``brms::brmsformula()`` (for example
        ``decomp="QR"``, ``center=True``, ``sparse=True``, ``nl=True``, ``loop=True``).

    Returns
    -------
    FormulaConstruct
        A composable formula specification.

    See Also
    --------
    brms::brmsformula : [R documentation](https://paulbuerkner.com/brms/reference/brmsformula.html)

    Examples
    --------
    Basic formula:

    ```python
    from brmspy.brms import bf

    f = bf("y ~ x1 + x2 + (1|group)")
    ```

    QR decomposition (often helps with collinearity):

    ```python
    from brmspy.brms import bf

    f = bf("reaction ~ days + (days|subject)", decomp="QR")
    ```

    Multivariate formula + residual correlation:

    ```python
    from brmspy.brms import bf, set_rescor

    f = bf("mvbind(y1, y2) ~ x") + set_rescor(True)
    ```
    """
    part = FormulaPart(_fun="bf", _args=list(formulas), _kwargs=formula_args)
    return FormulaConstruct._formula_parse(part)

posterior_epred(model, newdata=None, **kwargs)

posterior_epred(model: FitResult | ProxyListSexpVector, newdata: Literal[None] = None) -> IDResult[IDPosterior]
posterior_epred(model: FitResult | ProxyListSexpVector, newdata: pd.DataFrame) -> IDResult[IDPredictions]

Compute expected posterior predictions (noise-free).

Wrapper around R brms::posterior_epred(). This returns draws of the expected value (typically on the response scale), without observation noise.

Parameters:

Name Type Description Default
model FitResult

Fitted model.

required
newdata DataFrame or None

New data for predictions. If None, uses the training data.

None
**kwargs

Forwarded to brms::posterior_epred().

{}

Returns:

Type Description
PosteriorEpredResult

Result containing idata (ArviZ InferenceData) and an underlying R handle.

See Also

brms::posterior_epred : R documentation

Examples:

from brmspy import brms

fit = brms.brm("y ~ x", data=df, chains=4)
ep = brms.posterior_epred(fit)

ep.idata.posterior
Source code in brmspy/_brms_functions/prediction.py
def posterior_epred(
    model: FitResult | ProxyListSexpVector,
    newdata: pd.DataFrame | None = None,
    **kwargs,
) -> IDResult:
    """
    Compute expected posterior predictions (noise-free).

    Wrapper around R ``brms::posterior_epred()``. This returns draws of the
    expected value (typically on the response scale), without observation noise.

    Parameters
    ----------
    model : FitResult
        Fitted model.
    newdata : pandas.DataFrame or None, default=None
        New data for predictions. If ``None``, uses the training data.
    **kwargs
        Forwarded to ``brms::posterior_epred()``.

    Returns
    -------
    PosteriorEpredResult
        Result containing `idata` (ArviZ `InferenceData`) and an underlying R handle.

    See Also
    --------
    brms::posterior_epred : [R documentation](https://paulbuerkner.com/brms/reference/posterior_epred.brmsfit.html)

    Examples
    --------
    ```python
    from brmspy import brms

    fit = brms.brm("y ~ x", data=df, chains=4)
    ep = brms.posterior_epred(fit)

    ep.idata.posterior
    ```
    """
    model_r = py_to_r(model)
    data_r = py_to_r(newdata)
    kwargs = kwargs_r(kwargs)

    resp_names = _brmsfit_get_response_names(model_r)
    dims, coords = _brmsfit_get_dims_and_coords(
        model_r, resp_names=resp_names, newdata=newdata
    )

    result, r = _brmsfit_get_predict_generic(
        model_r,
        newdata=data_r,
        function="brms::posterior_epred",
        resp_names=resp_names,
        **kwargs,
    )

    if newdata is None:
        idata = az.from_dict(posterior=result, coords=coords, dims=dims)
        idata = cast(IDPosterior, idata)
    else:
        idata = az.from_dict(predictions=result, coords=coords, dims=dims)
        idata = cast(IDPredictions, idata)

    _idata_add_resp_names_suffix(idata, "_mean", resp_names)

    # Add constant data
    constant_data_dict = _brmsfit_get_constant_data(
        model_r, newdata=newdata, resp_names=resp_names
    )
    group_name = "constant_data" if newdata is None else "predictions_constant_data"
    _arviz_add_constant_data(idata, constant_data_dict, group_name)

    return IDResult(r=cast(ProxyListSexpVector, r), idata=idata)

posterior_linpred(model, newdata=None, **kwargs)

posterior_linpred(model: FitResult | ProxyListSexpVector, newdata: Literal[None] = None, **kwargs) -> IDResult[IDPosterior]
posterior_linpred(model: FitResult | ProxyListSexpVector, newdata: pd.DataFrame, **kwargs) -> IDResult[IDPredictions]

Draw from the linear predictor.

Wrapper around R brms::posterior_linpred(). This typically returns draws on the link scale (before applying the inverse link), unless you pass transform=True.

Parameters:

Name Type Description Default
model FitResult

Fitted model.

required
newdata DataFrame or None

New data for predictions. If None, uses the training data.

None
**kwargs

Forwarded to brms::posterior_linpred() (commonly transform or ndraws).

{}

Returns:

Type Description
PosteriorLinpredResult

Result containing idata (ArviZ InferenceData) and an underlying R handle.

See Also

brms::posterior_linpred : R documentation

Examples:

from brmspy import brms

fit = brms.brm("y ~ x", data=df, chains=4)
lp = brms.posterior_linpred(fit, transform=False)

lp.idata.predictions
Source code in brmspy/_brms_functions/prediction.py
def posterior_linpred(
    model: FitResult | ProxyListSexpVector,
    newdata: pd.DataFrame | None = None,
    **kwargs,
) -> IDResult:
    """
    Draw from the linear predictor.

    Wrapper around R ``brms::posterior_linpred()``. This typically returns draws
    on the link scale (before applying the inverse link), unless you pass
    ``transform=True``.

    Parameters
    ----------
    model : FitResult
        Fitted model.
    newdata : pandas.DataFrame or None, default=None
        New data for predictions. If ``None``, uses the training data.
    **kwargs
        Forwarded to ``brms::posterior_linpred()`` (commonly ``transform`` or ``ndraws``).

    Returns
    -------
    PosteriorLinpredResult
        Result containing `idata` (ArviZ `InferenceData`) and an underlying R handle.

    See Also
    --------
    brms::posterior_linpred : [R documentation](https://paulbuerkner.com/brms/reference/posterior_linpred.brmsfit.html)

    Examples
    --------
    ```python
    from brmspy import brms

    fit = brms.brm("y ~ x", data=df, chains=4)
    lp = brms.posterior_linpred(fit, transform=False)

    lp.idata.predictions
    ```
    """
    import rpy2.robjects as ro

    model_r = py_to_r(model)
    data_r = py_to_r(newdata)
    kwargs = kwargs_r(kwargs)

    resp_names = _brmsfit_get_response_names(model_r)
    dims, coords = _brmsfit_get_dims_and_coords(
        model_r, resp_names=resp_names, newdata=newdata
    )

    result, r = _brmsfit_get_predict_generic(
        model_r,
        newdata=data_r,
        function="brms::posterior_linpred",
        resp_names=resp_names,
        **kwargs,
    )

    if newdata is None:
        idata = az.from_dict(
            posterior=result,
            dims=dims,
            coords=coords,
        )
        idata = cast(IDPosterior, idata)
    else:
        idata = az.from_dict(
            predictions=result,
            dims=dims,
            coords=coords,
        )
        idata = cast(IDPredictions, idata)

    _idata_add_resp_names_suffix(idata, "_linpred", resp_names)

    # Add constant data
    constant_data_dict = _brmsfit_get_constant_data(
        model_r, newdata=newdata, resp_names=resp_names
    )
    group_name = "constant_data" if newdata is None else "predictions_constant_data"
    _arviz_add_constant_data(idata, constant_data_dict, group_name)

    return IDResult(r=cast(ProxyListSexpVector, r), idata=idata)

posterior_predict(model, newdata=None, **kwargs)

posterior_predict(model: FitResult | ProxyListSexpVector, newdata: Literal[None] = None, **kwargs) -> IDResult[IDPosteriorPredictive]
posterior_predict(model: FitResult | ProxyListSexpVector, newdata: pd.DataFrame, **kwargs) -> IDResult[IDPredictions]

Draw from the posterior predictive distribution (includes observation noise).

Wrapper around R brms::posterior_predict().

Parameters:

Name Type Description Default
model FitResult

Fitted model.

required
newdata DataFrame or None

New data for predictions. If None, uses the training data.

None
**kwargs

Forwarded to brms::posterior_predict().

{}

Returns:

Type Description
PosteriorPredictResult

Result containing idata (ArviZ InferenceData) and an underlying R handle.

See Also

brms::posterior_predict : R documentation

Examples:

from brmspy import brms

fit = brms.brm("y ~ x", data=df, chains=4)
pp = brms.posterior_predict(fit)

pp.idata.posterior_predictive
Source code in brmspy/_brms_functions/prediction.py
def posterior_predict(
    model: FitResult | ProxyListSexpVector,
    newdata: pd.DataFrame | None = None,
    **kwargs,
) -> IDResult:
    """
    Draw from the posterior predictive distribution (includes observation noise).

    Wrapper around R ``brms::posterior_predict()``.

    Parameters
    ----------
    model : FitResult
        Fitted model.
    newdata : pandas.DataFrame or None, default=None
        New data for predictions. If ``None``, uses the training data.
    **kwargs
        Forwarded to ``brms::posterior_predict()``.

    Returns
    -------
    PosteriorPredictResult
        Result containing `idata` (ArviZ `InferenceData`) and an underlying R handle.

    See Also
    --------
    brms::posterior_predict : [R documentation](https://paulbuerkner.com/brms/reference/posterior_predict.brmsfit.html)

    Examples
    --------
    ```python
    from brmspy import brms

    fit = brms.brm("y ~ x", data=df, chains=4)
    pp = brms.posterior_predict(fit)

    pp.idata.posterior_predictive
    ```
    """
    model_r = py_to_r(model)
    data_r = py_to_r(newdata)
    kwargs = kwargs_r(kwargs)

    resp_names = _brmsfit_get_response_names(model_r)
    dims, coords = _brmsfit_get_dims_and_coords(
        model_r, resp_names=resp_names, newdata=newdata
    )

    result, r = _brmsfit_get_predict_generic(
        model_r,
        newdata=data_r,
        function="brms::posterior_predict",
        resp_names=resp_names,
        **kwargs,
    )

    if newdata is None:
        idata = az.from_dict(
            posterior_predictive=result,
            dims=dims,
            coords=coords,
        )
        idata = cast(IDPosteriorPredictive, idata)
    else:
        idata = az.from_dict(
            predictions=result,
            dims=dims,
            coords=coords,
        )
        idata = cast(IDPredictions, idata)

    # Add constant data
    constant_data_dict = _brmsfit_get_constant_data(
        model_r, newdata=newdata, resp_names=resp_names
    )
    group_name = "constant_data" if newdata is None else "predictions_constant_data"
    _arviz_add_constant_data(idata, constant_data_dict, group_name)

    return IDResult(r=cast(ProxyListSexpVector, r), idata=idata)

log_lik(model, newdata=None, **kwargs)

log_lik(model: FitResult | ProxyListSexpVector, newdata: Literal[None] = None, **kwargs) -> IDResult[IDLogLikelihoodInsample]
log_lik(model: FitResult | ProxyListSexpVector, newdata: pd.DataFrame, **kwargs) -> IDResult[IDLogLikelihoodOutsample]

Compute pointwise log-likelihood draws.

Wrapper around R brms::log_lik(). The result is useful for LOO/WAIC via ArviZ.

Parameters:

Name Type Description Default
model FitResult

Fitted model.

required
newdata DataFrame or None

New data. If None, uses the training data.

None
**kwargs

Forwarded to brms::log_lik().

{}

Returns:

Type Description
LogLikResult

Result containing idata (ArviZ InferenceData) and an underlying R handle.

See Also

brms::log_lik : R documentation

Examples:

from brmspy import brms
import arviz as az

fit = brms.brm("y ~ x", data=df, chains=4)
ll = brms.log_lik(fit)

az.loo(ll.idata)
Source code in brmspy/_brms_functions/prediction.py
def log_lik(
    model: FitResult | ProxyListSexpVector,
    newdata: pd.DataFrame | None = None,
    **kwargs,
) -> IDResult:
    """
    Compute pointwise log-likelihood draws.

    Wrapper around R ``brms::log_lik()``. The result is useful for LOO/WAIC via ArviZ.

    Parameters
    ----------
    model : FitResult
        Fitted model.
    newdata : pandas.DataFrame or None, default=None
        New data. If ``None``, uses the training data.
    **kwargs
        Forwarded to ``brms::log_lik()``.

    Returns
    -------
    LogLikResult
        Result containing `idata` (ArviZ `InferenceData`) and an underlying R handle.

    See Also
    --------
    brms::log_lik : [R documentation](https://paulbuerkner.com/brms/reference/log_lik.brmsfit.html)

    Examples
    --------
    ```python
    from brmspy import brms
    import arviz as az

    fit = brms.brm("y ~ x", data=df, chains=4)
    ll = brms.log_lik(fit)

    az.loo(ll.idata)
    ```
    """
    import rpy2.robjects as ro

    model_r = py_to_r(model)
    data_r = py_to_r(newdata)
    kwargs = kwargs_r(kwargs)

    resp_names = _brmsfit_get_response_names(model_r)
    dims, coords = _brmsfit_get_dims_and_coords(
        model_r, resp_names=resp_names, newdata=newdata
    )

    result, r = _brmsfit_get_predict_generic(
        model_r,
        newdata=data_r,
        function="brms::log_lik",
        resp_names=resp_names,
        **kwargs,
    )
    if newdata is None:
        idata = az.from_dict(log_likelihood=result, dims=dims, coords=coords)
        idata = cast(IDLogLikelihoodInsample, idata)
    else:
        idata = az.from_dict(log_likelihood=result, dims=dims, coords=coords)
        idata = cast(IDLogLikelihoodOutsample, idata)

    # Add constant data
    constant_data_dict = _brmsfit_get_constant_data(
        model_r, newdata=newdata, resp_names=resp_names
    )
    group_name = "constant_data" if newdata is None else "predictions_constant_data"
    _arviz_add_constant_data(idata, constant_data_dict, group_name)

    return IDResult(r=cast(ProxyListSexpVector, r), idata=idata)

posterior(model, **kwargs)

Return posterior draws as idata.

Wrapper around R posterior::as_draws_df().

Parameters:

Name Type Description Default
model FitResult

Fitted model.

required
**kwargs

Forwarded to posterior::as_draws_df(). e.g inc_warmup, regex, variable

{}

Returns:

Type Description
PosteriorEpredResult

Result containing idata (ArviZ InferenceData) and an underlying R handle.

Examples:

from brmspy import brms

fit = brms.brm("y ~ x", data=df, chains=4)
ep = brms.posterior(fit)

ep.idata.posterior
Source code in brmspy/_brms_functions/prediction.py
def posterior(
    model: FitResult | ProxyListSexpVector, **kwargs
) -> IDResult[IDPosterior]:
    """
    Return posterior draws as idata.

    Wrapper around R ``posterior::as_draws_df()``.

    Parameters
    ----------
    model : FitResult
        Fitted model.
    **kwargs
        Forwarded to ``posterior::as_draws_df()``. e.g inc_warmup, regex, variable

    Returns
    -------
    PosteriorEpredResult
        Result containing `idata` (ArviZ `InferenceData`) and an underlying R handle.

    Examples
    --------
    ```python
    from brmspy import brms

    fit = brms.brm("y ~ x", data=df, chains=4)
    ep = brms.posterior(fit)

    ep.idata.posterior
    ```
    """
    model_r = py_to_r(model)
    kwargs = kwargs_r(kwargs)

    resp_names = _brmsfit_get_response_names(model_r)
    dims, coords = _brmsfit_get_dims_and_coords(model_r, resp_names=resp_names)

    result, r = _brmsfit_get_posterior(model_r, **kwargs)
    idata = az.from_dict(posterior=result, dims=dims, coords=coords)

    # Add constant data
    constant_data_dict = _brmsfit_get_constant_data(
        model_r, newdata=None, resp_names=resp_names
    )
    _arviz_add_constant_data(
        idata, constant_data_dict, "constant_data", obs_id=coords["obs_id"]
    )

    return IDResult(r=cast(ProxyListSexpVector, r), idata=cast(IDPosterior, idata))

observed_data(model)

Source code in brmspy/_brms_functions/prediction.py
def observed_data(model: FitResult | ProxyListSexpVector) -> IDResult[IDObservedData]:
    import rpy2.robjects as ro

    model_r = py_to_r(model)

    resp_names = _brmsfit_get_response_names(model_r)
    dims, coords = _brmsfit_get_dims_and_coords(model_r, resp_names=resp_names)

    result = _brmsfit_get_observed_data(model_r, resp_names=resp_names)
    r = cast(Any, ro.NULL)

    idata = az.from_dict(observed_data=result, coords=coords, dims=dims)
    idata = cast(IDObservedData, idata)

    # Add constant data
    constant_data_dict = _brmsfit_get_constant_data(
        model_r, newdata=None, resp_names=resp_names
    )
    _arviz_add_constant_data(idata, constant_data_dict, "constant_data")

    return IDResult(r=r, idata=idata)

make_stancode(formula, data, priors=None, family='poisson', sample_prior='no', formula_args=None)

Generate Stan code using R brms::make_stancode().

Useful for inspecting the generated Stan model before fitting.

Parameters:

Name Type Description Default
formula str or FormulaConstruct

Model formula.

required
data DataFrame

Model data.

required
priors Sequence[PriorSpec] or None

Optional prior specifications created via brmspy.brms.prior().

None
family str

Distribution family (e.g. "gaussian", "poisson").

"poisson"
sample_prior str

Prior sampling mode passed to brms ("no", "yes", "only").

"no"
formula_args dict or None

Reserved for future use. Currently ignored.

None

Returns:

Type Description
str

Complete Stan program as a string.

See Also

brms::make_stancode : R documentation

Examples:

from brmspy import brms

epilepsy = brms.get_brms_data("epilepsy")
code = brms.make_stancode(
    "count ~ zAge + zBase * Trt + (1|patient)",
    data=epilepsy,
    family="poisson",
)

assert isinstance(code, str)
Source code in brmspy/_brms_functions/stan.py
def make_stancode(
    formula: FormulaConstruct | str,
    data: pd.DataFrame,
    priors: typing.Sequence[PriorSpec] | None = None,
    family: str = "poisson",
    sample_prior: str = "no",
    formula_args: dict | None = None,
) -> str:
    """
    Generate Stan code using R ``brms::make_stancode()``.

    Useful for inspecting the generated Stan model before fitting.

    Parameters
    ----------
    formula : str or FormulaConstruct
        Model formula.
    data : pandas.DataFrame
        Model data.
    priors : Sequence[PriorSpec] or None, default=None
        Optional prior specifications created via `brmspy.brms.prior()`.
    family : str, default="poisson"
        Distribution family (e.g. ``"gaussian"``, ``"poisson"``).
    sample_prior : str, default="no"
        Prior sampling mode passed to brms (``"no"``, ``"yes"``, ``"only"``).
    formula_args : dict or None, default=None
        Reserved for future use. Currently ignored.

    Returns
    -------
    str
        Complete Stan program as a string.

    See Also
    --------
    brms::make_stancode : [R documentation](https://paulbuerkner.com/brms/reference/make_stancode.html)

    Examples
    --------
    ```python
    from brmspy import brms

    epilepsy = brms.get_brms_data("epilepsy")
    code = brms.make_stancode(
        "count ~ zAge + zBase * Trt + (1|patient)",
        data=epilepsy,
        family="poisson",
    )

    assert isinstance(code, str)
    ```
    """
    import rpy2.robjects as ro

    fun_make_stancode = typing.cast(typing.Callable, ro.r("brms::make_stancode"))

    data_r = py_to_r(data)
    priors_r = _build_priors(priors)
    if isinstance(formula, FormulaConstruct):
        formula_obj = _execute_formula(formula)
    else:
        if formula_args is None:
            formula_args = {}
        formula = FormulaConstruct._formula_parse(formula)
        formula_obj = _execute_formula(formula)

    if len(priors_r) > 0:
        return fun_make_stancode(
            formula=formula_obj,
            data=data_r,
            prior=priors_r,
            family=family,
            sample_prior=sample_prior,
        )[0]
    else:
        return fun_make_stancode(
            formula=formula_obj, data=data_r, family=family, sample_prior=sample_prior
        )[0]

brmsfamily(family, link=None, link_sigma='log', link_shape='log', link_nu='logm1', link_phi='log', link_kappa='log', link_beta='log', link_zi='logit', link_hu='logit', link_zoi='logit', link_coi='logit', link_disc='log', link_bs='log', link_ndt='log', link_bias='logit', link_xi='log1p', link_alpha='identity', link_quantile='logit', threshold='flexible', refcat=None, **kwargs)

Family objects provide a convenient way to specify the details of the models used by many model fitting functions. The family functions presented here are for use with brms only and will not work with other model fitting functions such as glm or glmer. However, the standard family functions as described in family will work with brms.

Parameters:

Name Type Description Default
family

A character string naming the distribution family of the response variable to be used in the model. Currently, the following families are supported: gaussian, student, binomial, bernoulli, beta-binomial, poisson, negbinomial, geometric, Gamma, skew_normal, lognormal, shifted_lognormal, exgaussian, wiener, inverse.gaussian, exponential, weibull, frechet, Beta, dirichlet, von_mises, asym_laplace, gen_extreme_value, categorical, multinomial, cumulative, cratio, sratio, acat, hurdle_poisson, hurdle_negbinomial, hurdle_gamma, hurdle_lognormal, hurdle_cumulative, zero_inflated_binomial, zero_inflated_beta_binomial, zero_inflated_beta, zero_inflated_negbinomial, zero_inflated_poisson, and zero_one_inflated_beta.

required
link str | None

A specification for the model link function. This can be a name/expression or character string. See the 'Details' section for more information on link functions supported by each family.

None
link_sigma str

Link of auxiliary parameter sigma if being predicted.

'log'
link_shape str

Link of auxiliary parameter shape if being predicted.

'log'
link_nu str

Link of auxiliary parameter nu if being predicted.

'logm1'
link_phi str

Link of auxiliary parameter phi if being predicted.

'log'
link_kappa str

Link of auxiliary parameter kappa if being predicted.

'log'
link_beta str

Link of auxiliary parameter beta if being predicted.

'log'
link_zi str

Link of auxiliary parameter zi if being predicted.

'logit'
link_hu str

Link of auxiliary parameter hu if being predicted.

'logit'
link_zoi str

Link of auxiliary parameter zoi if being predicted.

'logit'
link_coi str

Link of auxiliary parameter coi if being predicted.

'logit'
link_disc str

Link of auxiliary parameter disc if being predicted.

'log'
link_bs str

Link of auxiliary parameter bs if being predicted.

'log'
link_ndt str

Link of auxiliary parameter ndt if being predicted.

'log'
link_bias str

Link of auxiliary parameter bias if being predicted.

'logit'
link_xi str

Link of auxiliary parameter xi if being predicted.

'log1p'
link_alpha str

Link of auxiliary parameter alpha if being predicted.

'identity'
link_quantile str

Link of auxiliary parameter quantile if being predicted.

'logit'
threshold str

A character string indicating the type of thresholds (i.e. intercepts) used in an ordinal model. "flexible" provides the standard unstructured thresholds, "equidistant" restricts the distance between consecutive thresholds to the same value, and "sum_to_zero" ensures the thresholds sum to zero.

'flexible'
refcat str | None

Optional name of the reference response category used in categorical, multinomial, dirichlet and logistic_normal models. If NULL (the default), the first category is used as the reference. If NA, all categories will be predicted, which requires strong priors or carefully specified predictor terms in order to lead to an identified model.

None
Source code in brmspy/_brms_functions/families.py
def brmsfamily(
    family,
    link: str | None = None,
    link_sigma: str = "log",
    link_shape: str = "log",
    link_nu: str = "logm1",
    link_phi: str = "log",
    link_kappa: str = "log",
    link_beta: str = "log",
    link_zi: str = "logit",
    link_hu: str = "logit",
    link_zoi: str = "logit",
    link_coi: str = "logit",
    link_disc: str = "log",
    link_bs: str = "log",
    link_ndt: str = "log",
    link_bias: str = "logit",
    link_xi: str = "log1p",
    link_alpha: str = "identity",
    link_quantile: str = "logit",
    threshold: str = "flexible",
    refcat: str | None = None,
    **kwargs,
) -> ListSexpVector:
    """
    Family objects provide a convenient way to specify the details of the models used by many model fitting functions. The family functions presented here are for use with brms only and will **not** work with other model fitting functions such as glm or glmer. However, the standard family functions as described in family will work with brms.

    Parameters
    ----------
    family
        A character string naming the distribution family of the response variable to be used in the model. Currently, the following families are supported: gaussian, student, binomial, bernoulli, beta-binomial, poisson, negbinomial, geometric, Gamma, skew_normal, lognormal, shifted_lognormal, exgaussian, wiener, inverse.gaussian, exponential, weibull, frechet, Beta, dirichlet, von_mises, asym_laplace, gen_extreme_value, categorical, multinomial, cumulative, cratio, sratio, acat, hurdle_poisson, hurdle_negbinomial, hurdle_gamma, hurdle_lognormal, hurdle_cumulative, zero_inflated_binomial, zero_inflated_beta_binomial, zero_inflated_beta, zero_inflated_negbinomial, zero_inflated_poisson, and zero_one_inflated_beta.
    link
        A specification for the model link function. This can be a name/expression or character string. See the 'Details' section for more information on link functions supported by each family.
    link_sigma
        Link of auxiliary parameter sigma if being predicted.
    link_shape
        Link of auxiliary parameter shape if being predicted.
    link_nu
        Link of auxiliary parameter nu if being predicted.
    link_phi
        Link of auxiliary parameter phi if being predicted.
    link_kappa
        Link of auxiliary parameter kappa if being predicted.
    link_beta
        Link of auxiliary parameter beta if being predicted.
    link_zi
        Link of auxiliary parameter zi if being predicted.
    link_hu
        Link of auxiliary parameter hu if being predicted.
    link_zoi
        Link of auxiliary parameter zoi if being predicted.
    link_coi
        Link of auxiliary parameter coi if being predicted.
    link_disc
        Link of auxiliary parameter disc if being predicted.
    link_bs
        Link of auxiliary parameter bs if being predicted.
    link_ndt
        Link of auxiliary parameter ndt if being predicted.
    link_bias
        Link of auxiliary parameter bias if being predicted.
    link_xi
        Link of auxiliary parameter xi if being predicted.
    link_alpha
        Link of auxiliary parameter alpha if being predicted.
    link_quantile
        Link of auxiliary parameter quantile if being predicted.
    threshold
        A character string indicating the type of thresholds (i.e. intercepts) used in an ordinal model. "flexible" provides the standard unstructured thresholds, "equidistant" restricts the distance between consecutive thresholds to the same value, and "sum_to_zero" ensures the thresholds sum to zero.
    refcat
        Optional name of the reference response category used in categorical, multinomial, dirichlet and logistic_normal models. If NULL (the default), the first category is used as the reference. If NA, all categories will be predicted, which requires strong priors or carefully specified predictor terms in order to lead to an identified model.

    """
    import rpy2.robjects as ro

    r_brmsfamily = cast(Callable, ro.r("brms::brmsfamily"))

    collected_args = {
        "family": family,
        "link": link,
        "link_sigma": link_sigma,
        "link_shape": link_shape,
        "link_nu": link_nu,
        "link_phi": link_phi,
        "link_kappa": link_kappa,
        "link_beta": link_beta,
        "link_zi": link_zi,
        "link_hu": link_hu,
        "link_zoi": link_zoi,
        "link_coi": link_coi,
        "link_disc": link_disc,
        "link_bs": link_bs,
        "link_ndt": link_ndt,
        "link_bias": link_bias,
        "link_xi": link_xi,
        "link_alpha": link_alpha,
        "link_quantile": link_quantile,
        "threshold": threshold,
        "refcat": refcat,
        **kwargs,
    }
    collected_args = kwargs_r(collected_args)

    return r_brmsfamily(**collected_args)

family(fit, **kwargs)

Extract family object from a fitted model.

Parameters:

Name Type Description Default
fit FitResult or ListSexpVector

Fitted brms model

required
Source code in brmspy/_brms_functions/families.py
def family(fit: FitResult | ListSexpVector, **kwargs) -> ListSexpVector:
    """Extract family object from a fitted model.

    Parameters
    ----------
    fit : FitResult or ListSexpVector
        Fitted brms model
    """
    import rpy2.robjects as ro

    if isinstance(fit, IDResult):
        r_fit = fit.r
    else:
        r_fit = fit

    r_family = cast(Callable, ro.r("family"))
    kwargs = kwargs_r(kwargs)

    return r_family(r_fit, **kwargs)

student(link='identity', link_sigma='log', link_nu='logm1', **kwargs)

Student's t distribution for robust regression.

Parameters:

Name Type Description Default
link str

Link function for the mean

'identity'
link_sigma str

Link function for sigma parameter

'log'
link_nu str

Link function for degrees of freedom parameter

'logm1'
Source code in brmspy/_brms_functions/families.py
def student(
    link: str = "identity", link_sigma: str = "log", link_nu: str = "logm1", **kwargs
) -> ListSexpVector:
    """Student's t distribution for robust regression.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_sigma : str
        Link function for sigma parameter
    link_nu : str
        Link function for degrees of freedom parameter
    """
    return brmsfamily(
        family="student",
        link=link,
        link_sigma=link_sigma,
        link_nu=link_nu,
        **kwargs,
    )

bernoulli(link='logit', **kwargs)

Bernoulli distribution for binary 0/1 outcomes.

Parameters:

Name Type Description Default
link str

Link function for the probability parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def bernoulli(link: str = "logit", **kwargs) -> ListSexpVector:
    """Bernoulli distribution for binary 0/1 outcomes.

    Parameters
    ----------
    link : str
        Link function for the probability parameter
    """
    return brmsfamily(
        family="bernoulli",
        link=link,
        **kwargs,
    )

beta_binomial(link='logit', link_phi='log', **kwargs)

Beta-binomial distribution for overdispersed binomial data.

Parameters:

Name Type Description Default
link str

Link function for the probability parameter

'logit'
link_phi str

Link function for the precision parameter

'log'
Source code in brmspy/_brms_functions/families.py
def beta_binomial(
    link: str = "logit", link_phi: str = "log", **kwargs
) -> ListSexpVector:
    """Beta-binomial distribution for overdispersed binomial data.

    Parameters
    ----------
    link : str
        Link function for the probability parameter
    link_phi : str
        Link function for the precision parameter
    """
    return brmsfamily(
        family="beta_binomial",
        link=link,
        link_phi=link_phi,
        **kwargs,
    )

negbinomial(link='log', link_shape='log', **kwargs)

Negative binomial distribution for overdispersed count data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'log'
link_shape str

Link function for the shape parameter

'log'
Source code in brmspy/_brms_functions/families.py
def negbinomial(link: str = "log", link_shape: str = "log", **kwargs) -> ListSexpVector:
    """Negative binomial distribution for overdispersed count data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_shape : str
        Link function for the shape parameter
    """
    return brmsfamily(
        family="negbinomial",
        link=link,
        link_shape=link_shape,
        **kwargs,
    )

negbinomial2(link='log', link_sigma='log', **kwargs)

Source code in brmspy/_brms_functions/families.py
def negbinomial2(
    link: str = "log", link_sigma: str = "log", **kwargs
) -> ListSexpVector:
    return brmsfamily(
        family="negbinomial2",
        link=link,
        link_sigma=link_sigma,
        **kwargs,
    )

geometric(link='log', **kwargs)

Geometric distribution for count data (negative binomial with shape=1).

Parameters:

Name Type Description Default
link str

Link function for the mean

'log'
Source code in brmspy/_brms_functions/families.py
def geometric(link: str = "log", **kwargs) -> ListSexpVector:
    """Geometric distribution for count data (negative binomial with shape=1).

    Parameters
    ----------
    link : str
        Link function for the mean
    """
    return brmsfamily(
        family="geometric",
        link=link,
        **kwargs,
    )

discrete_weibull(link='logit', link_shape='log', **kwargs)

Source code in brmspy/_brms_functions/families.py
def discrete_weibull(
    link: str = "logit", link_shape: str = "log", **kwargs
) -> ListSexpVector:
    return brmsfamily(
        family="discrete_weibull",
        link=link,
        link_shape=link_shape,
        **kwargs,
    )

com_poisson(link='log', link_shape='log', **kwargs)

Source code in brmspy/_brms_functions/families.py
def com_poisson(link: str = "log", link_shape: str = "log", **kwargs) -> ListSexpVector:
    return brmsfamily(
        family="com_poisson",
        link=link,
        link_shape=link_shape,
        **kwargs,
    )

lognormal(link='identity', link_sigma='log', **kwargs)

Lognormal distribution for positive continuous data.

Parameters:

Name Type Description Default
link str

Link function for the mean on log scale

'identity'
link_sigma str

Link function for sigma parameter

'log'
Source code in brmspy/_brms_functions/families.py
def lognormal(
    link: str = "identity", link_sigma: str = "log", **kwargs
) -> ListSexpVector:
    """Lognormal distribution for positive continuous data.

    Parameters
    ----------
    link : str
        Link function for the mean on log scale
    link_sigma : str
        Link function for sigma parameter
    """
    return brmsfamily(
        family="lognormal",
        link=link,
        link_sigma=link_sigma,
        **kwargs,
    )

shifted_lognormal(link='identity', link_sigma='log', link_ndt='log', **kwargs)

Shifted lognormal distribution with non-decision time parameter.

Parameters:

Name Type Description Default
link str

Link function for the mean

'identity'
link_sigma str

Link function for sigma parameter

'log'
link_ndt str

Link function for non-decision time parameter

'log'
Source code in brmspy/_brms_functions/families.py
def shifted_lognormal(
    link: str = "identity", link_sigma: str = "log", link_ndt: str = "log", **kwargs
) -> ListSexpVector:
    """Shifted lognormal distribution with non-decision time parameter.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_sigma : str
        Link function for sigma parameter
    link_ndt : str
        Link function for non-decision time parameter
    """
    return brmsfamily(
        family="shifted_lognormal",
        link=link,
        link_sigma=link_sigma,
        link_ndt=link_ndt,
        **kwargs,
    )

skew_normal(link='identity', link_sigma='log', link_alpha='identity', **kwargs)

Skew normal distribution for asymmetric continuous data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'identity'
link_sigma str

Link function for sigma parameter

'log'
link_alpha str

Link function for skewness parameter

'identity'
Source code in brmspy/_brms_functions/families.py
def skew_normal(
    link: str = "identity",
    link_sigma: str = "log",
    link_alpha: str = "identity",
    **kwargs,
) -> ListSexpVector:
    """Skew normal distribution for asymmetric continuous data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_sigma : str
        Link function for sigma parameter
    link_alpha : str
        Link function for skewness parameter
    """
    return brmsfamily(
        family="skew_normal",
        link=link,
        link_sigma=link_sigma,
        link_alpha=link_alpha,
        **kwargs,
    )

exponential(link='log', **kwargs)

Exponential distribution for time-to-event data.

Parameters:

Name Type Description Default
link str

Link function for the rate parameter

'log'
Source code in brmspy/_brms_functions/families.py
def exponential(link: str = "log", **kwargs) -> ListSexpVector:
    """Exponential distribution for time-to-event data.

    Parameters
    ----------
    link : str
        Link function for the rate parameter
    """
    return brmsfamily(
        family="exponential",
        link=link,
        **kwargs,
    )

weibull(link='log', link_shape='log', **kwargs)

Weibull distribution for survival and reliability analysis.

Parameters:

Name Type Description Default
link str

Link function for the scale parameter

'log'
link_shape str

Link function for the shape parameter

'log'
Source code in brmspy/_brms_functions/families.py
def weibull(link: str = "log", link_shape: str = "log", **kwargs) -> ListSexpVector:
    """Weibull distribution for survival and reliability analysis.

    Parameters
    ----------
    link : str
        Link function for the scale parameter
    link_shape : str
        Link function for the shape parameter
    """
    return brmsfamily(
        family="weibull",
        link=link,
        link_shape=link_shape,
        **kwargs,
    )

frechet(link='log', link_nu='logm1', **kwargs)

Frechet distribution for extreme value analysis.

Parameters:

Name Type Description Default
link str

Link function for the scale parameter

'log'
link_nu str

Link function for the shape parameter

'logm1'
Source code in brmspy/_brms_functions/families.py
def frechet(link: str = "log", link_nu: str = "logm1", **kwargs) -> ListSexpVector:
    """Frechet distribution for extreme value analysis.

    Parameters
    ----------
    link : str
        Link function for the scale parameter
    link_nu : str
        Link function for the shape parameter
    """
    return brmsfamily(
        family="frechet",
        link=link,
        link_nu=link_nu,
        **kwargs,
    )

gen_extreme_value(link='identity', link_sigma='log', link_xi='log1p', **kwargs)

Generalized extreme value distribution for extreme events.

Parameters:

Name Type Description Default
link str

Link function for the location parameter

'identity'
link_sigma str

Link function for the scale parameter

'log'
link_xi str

Link function for the shape parameter

'log1p'
Source code in brmspy/_brms_functions/families.py
def gen_extreme_value(
    link: str = "identity", link_sigma: str = "log", link_xi: str = "log1p", **kwargs
) -> ListSexpVector:
    """Generalized extreme value distribution for extreme events.

    Parameters
    ----------
    link : str
        Link function for the location parameter
    link_sigma : str
        Link function for the scale parameter
    link_xi : str
        Link function for the shape parameter
    """
    return brmsfamily(
        family="gen_extreme_value",
        link=link,
        link_sigma=link_sigma,
        link_xi=link_xi,
        **kwargs,
    )

exgaussian(link='identity', link_sigma='log', link_beta='log', **kwargs)

Ex-Gaussian distribution for reaction time data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'identity'
link_sigma str

Link function for Gaussian SD parameter

'log'
link_beta str

Link function for exponential rate parameter

'log'
Source code in brmspy/_brms_functions/families.py
def exgaussian(
    link: str = "identity", link_sigma: str = "log", link_beta: str = "log", **kwargs
) -> ListSexpVector:
    """Ex-Gaussian distribution for reaction time data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_sigma : str
        Link function for Gaussian SD parameter
    link_beta : str
        Link function for exponential rate parameter
    """
    return brmsfamily(
        family="exgaussian",
        link=link,
        link_sigma=link_sigma,
        link_beta=link_beta,
        **kwargs,
    )

wiener(link='identity', link_bs='log', link_ndt='log', link_bias='logit', **kwargs)

Wiener diffusion model for two-choice reaction time data.

Parameters:

Name Type Description Default
link str

Link function for drift rate

'identity'
link_bs str

Link function for boundary separation

'log'
link_ndt str

Link function for non-decision time

'log'
link_bias str

Link function for initial bias

'logit'
Source code in brmspy/_brms_functions/families.py
def wiener(
    link: str = "identity",
    link_bs: str = "log",
    link_ndt: str = "log",
    link_bias: str = "logit",
    **kwargs,
) -> ListSexpVector:
    """Wiener diffusion model for two-choice reaction time data.

    Parameters
    ----------
    link : str
        Link function for drift rate
    link_bs : str
        Link function for boundary separation
    link_ndt : str
        Link function for non-decision time
    link_bias : str
        Link function for initial bias
    """
    return brmsfamily(
        family="wiener",
        link=link,
        link_bs=link_bs,
        link_ndt=link_ndt,
        link_bias=link_bias,
        **kwargs,
    )

Beta(link='logit', link_phi='log', **kwargs)

Beta distribution for data between 0 and 1.

Parameters:

Name Type Description Default
link str

Link function for the mean

'logit'
link_phi str

Link function for the precision parameter

'log'
Source code in brmspy/_brms_functions/families.py
def Beta(link: str = "logit", link_phi: str = "log", **kwargs) -> ListSexpVector:
    """Beta distribution for data between 0 and 1.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_phi : str
        Link function for the precision parameter
    """
    return brmsfamily(
        family="beta",
        link=link,
        link_phi=link_phi,
        **kwargs,
    )

xbeta(link='logit', link_phi='log', link_kappa='log', **kwargs)

Extended beta distribution with additional shape parameter.

Parameters:

Name Type Description Default
link str

Link function for the mean

'logit'
link_phi str

Link function for precision parameter

'log'
link_kappa str

Link function for kappa shape parameter

'log'
Source code in brmspy/_brms_functions/families.py
def xbeta(
    link: str = "logit", link_phi: str = "log", link_kappa: str = "log", **kwargs
) -> ListSexpVector:
    """Extended beta distribution with additional shape parameter.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_phi : str
        Link function for precision parameter
    link_kappa : str
        Link function for kappa shape parameter
    """
    return brmsfamily(
        family="xbeta",
        link=link,
        link_phi=link_phi,
        link_kappa=link_kappa,
        **kwargs,
    )

dirichlet(link='logit', link_phi='log', refcat=None, **kwargs)

Dirichlet distribution for compositional data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'logit'
link_phi str

Link function for the precision parameter

'log'
refcat str

Reference category

None
Source code in brmspy/_brms_functions/families.py
def dirichlet(
    link: str = "logit", link_phi: str = "log", refcat: str | None = None, **kwargs
) -> ListSexpVector:
    """Dirichlet distribution for compositional data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_phi : str
        Link function for the precision parameter
    refcat : str, optional
        Reference category
    """
    return brmsfamily(
        family="dirichlet",
        link=link,
        link_phi=link_phi,
        refcat=refcat,
        **kwargs,
    )

dirichlet2(link='log', refcat=None, **kwargs)

Source code in brmspy/_brms_functions/families.py
def dirichlet2(
    link: str = "log",
    # NOTE: R version uses refcat = NA; here default None
    refcat: str | None = None,
    **kwargs,
) -> ListSexpVector:
    return brmsfamily(
        family="dirichlet2",
        link=link,
        refcat=refcat,
        **kwargs,
    )

logistic_normal(link='identity', link_sigma='log', refcat=None, **kwargs)

Logistic-normal distribution for compositional data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'identity'
link_sigma str

Link function for sigma parameter

'log'
refcat str

Reference category

None
Source code in brmspy/_brms_functions/families.py
def logistic_normal(
    link: str = "identity",
    link_sigma: str = "log",
    refcat: str | None = None,
    **kwargs,
) -> ListSexpVector:
    """Logistic-normal distribution for compositional data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_sigma : str
        Link function for sigma parameter
    refcat : str, optional
        Reference category
    """
    return brmsfamily(
        family="logistic_normal",
        link=link,
        link_sigma=link_sigma,
        refcat=refcat,
        **kwargs,
    )

von_mises(link='tan_half', link_kappa='log', **kwargs)

Von Mises distribution for circular/directional data.

Parameters:

Name Type Description Default
link str

Link function for the mean direction

'tan_half'
link_kappa str

Link function for concentration parameter

'log'
Source code in brmspy/_brms_functions/families.py
def von_mises(
    link: str = "tan_half", link_kappa: str = "log", **kwargs
) -> ListSexpVector:
    """Von Mises distribution for circular/directional data.

    Parameters
    ----------
    link : str
        Link function for the mean direction
    link_kappa : str
        Link function for concentration parameter
    """
    return brmsfamily(
        family="von_mises",
        link=link,
        link_kappa=link_kappa,
        **kwargs,
    )

asym_laplace(link='identity', link_sigma='log', link_quantile='logit', **kwargs)

Asymmetric Laplace distribution for quantile regression.

Parameters:

Name Type Description Default
link str

Link function for the location

'identity'
link_sigma str

Link function for sigma parameter

'log'
link_quantile str

Link function for the quantile parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def asym_laplace(
    link: str = "identity",
    link_sigma: str = "log",
    link_quantile: str = "logit",
    **kwargs,
) -> ListSexpVector:
    """Asymmetric Laplace distribution for quantile regression.

    Parameters
    ----------
    link : str
        Link function for the location
    link_sigma : str
        Link function for sigma parameter
    link_quantile : str
        Link function for the quantile parameter
    """
    return brmsfamily(
        family="asym_laplace",
        link=link,
        link_sigma=link_sigma,
        link_quantile=link_quantile,
        **kwargs,
    )

zero_inflated_asym_laplace(link='identity', link_sigma='log', link_quantile='logit', link_zi='logit', **kwargs)

Source code in brmspy/_brms_functions/families.py
def zero_inflated_asym_laplace(
    link: str = "identity",
    link_sigma: str = "log",
    link_quantile: str = "logit",
    link_zi: str = "logit",
    **kwargs,
) -> ListSexpVector:
    return brmsfamily(
        family="zero_inflated_asym_laplace",
        link=link,
        link_sigma=link_sigma,
        link_quantile=link_quantile,
        link_zi=link_zi,
        **kwargs,
    )

cox(link='log', **kwargs)

Cox proportional hazards model for survival data.

Parameters:

Name Type Description Default
link str

Link function for the hazard rate

'log'
Source code in brmspy/_brms_functions/families.py
def cox(link: str = "log", **kwargs) -> ListSexpVector:
    """Cox proportional hazards model for survival data.

    Parameters
    ----------
    link : str
        Link function for the hazard rate
    """
    # original R wrapper doesn't pass slink; brmsfamily doesn't need it
    return brmsfamily(
        family="cox",
        link=link,
        **kwargs,
    )

hurdle_poisson(link='log', link_hu='logit', **kwargs)

Hurdle Poisson distribution for zero-inflated count data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'log'
link_hu str

Link function for hurdle parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def hurdle_poisson(
    link: str = "log", link_hu: str = "logit", **kwargs
) -> ListSexpVector:
    """Hurdle Poisson distribution for zero-inflated count data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_hu : str
        Link function for hurdle parameter
    """
    return brmsfamily(
        family="hurdle_poisson",
        link=link,
        link_hu=link_hu,
        **kwargs,
    )

hurdle_negbinomial(link='log', link_shape='log', link_hu='logit', **kwargs)

Hurdle negative binomial for overdispersed zero-inflated count data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'log'
link_shape str

Link function for shape parameter

'log'
link_hu str

Link function for hurdle parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def hurdle_negbinomial(
    link: str = "log", link_shape: str = "log", link_hu: str = "logit", **kwargs
) -> ListSexpVector:
    """Hurdle negative binomial for overdispersed zero-inflated count data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_shape : str
        Link function for shape parameter
    link_hu : str
        Link function for hurdle parameter
    """
    return brmsfamily(
        family="hurdle_negbinomial",
        link=link,
        link_shape=link_shape,
        link_hu=link_hu,
        **kwargs,
    )

hurdle_gamma(link='log', link_shape='log', link_hu='logit', **kwargs)

Hurdle Gamma distribution for zero-inflated positive continuous data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'log'
link_shape str

Link function for shape parameter

'log'
link_hu str

Link function for hurdle parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def hurdle_gamma(
    link: str = "log", link_shape: str = "log", link_hu: str = "logit", **kwargs
) -> ListSexpVector:
    """Hurdle Gamma distribution for zero-inflated positive continuous data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_shape : str
        Link function for shape parameter
    link_hu : str
        Link function for hurdle parameter
    """
    return brmsfamily(
        family="hurdle_gamma",
        link=link,
        link_shape=link_shape,
        link_hu=link_hu,
        **kwargs,
    )

hurdle_lognormal(link='identity', link_sigma='log', link_hu='logit', **kwargs)

Hurdle lognormal for zero-inflated positive continuous data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'identity'
link_sigma str

Link function for sigma parameter

'log'
link_hu str

Link function for hurdle parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def hurdle_lognormal(
    link: str = "identity", link_sigma: str = "log", link_hu: str = "logit", **kwargs
) -> ListSexpVector:
    """Hurdle lognormal for zero-inflated positive continuous data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_sigma : str
        Link function for sigma parameter
    link_hu : str
        Link function for hurdle parameter
    """
    return brmsfamily(
        family="hurdle_lognormal",
        link=link,
        link_sigma=link_sigma,
        link_hu=link_hu,
        **kwargs,
    )

hurdle_cumulative(link='logit', link_hu='logit', link_disc='log', threshold='flexible', **kwargs)

Hurdle cumulative for zero-inflated ordinal data.

Parameters:

Name Type Description Default
link str

Link function for the ordinal response

'logit'
link_hu str

Link function for hurdle parameter

'logit'
link_disc str

Link function for discrimination parameter

'log'
threshold str

Type of threshold structure

'flexible'
Source code in brmspy/_brms_functions/families.py
def hurdle_cumulative(
    link: str = "logit",
    link_hu: str = "logit",
    link_disc: str = "log",
    threshold: str = "flexible",
    **kwargs,
) -> ListSexpVector:
    """Hurdle cumulative for zero-inflated ordinal data.

    Parameters
    ----------
    link : str
        Link function for the ordinal response
    link_hu : str
        Link function for hurdle parameter
    link_disc : str
        Link function for discrimination parameter
    threshold : str
        Type of threshold structure
    """
    return brmsfamily(
        family="hurdle_cumulative",
        link=link,
        link_hu=link_hu,
        link_disc=link_disc,
        threshold=threshold,
        **kwargs,
    )

zero_inflated_beta(link='logit', link_phi='log', link_zi='logit', **kwargs)

Zero-inflated beta for data between 0 and 1 with excess zeros.

Parameters:

Name Type Description Default
link str

Link function for the mean

'logit'
link_phi str

Link function for precision parameter

'log'
link_zi str

Link function for zero-inflation parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def zero_inflated_beta(
    link: str = "logit", link_phi: str = "log", link_zi: str = "logit", **kwargs
) -> ListSexpVector:
    """Zero-inflated beta for data between 0 and 1 with excess zeros.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_phi : str
        Link function for precision parameter
    link_zi : str
        Link function for zero-inflation parameter
    """
    return brmsfamily(
        family="zero_inflated_beta",
        link=link,
        link_phi=link_phi,
        link_zi=link_zi,
        **kwargs,
    )

zero_one_inflated_beta(link='logit', link_phi='log', link_zoi='logit', link_coi='logit', **kwargs)

Zero-one-inflated beta for data between 0 and 1 with excess zeros and ones.

Parameters:

Name Type Description Default
link str

Link function for the mean

'logit'
link_phi str

Link function for precision parameter

'log'
link_zoi str

Link function for zero-or-one inflation parameter

'logit'
link_coi str

Link function for conditional one inflation parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def zero_one_inflated_beta(
    link: str = "logit",
    link_phi: str = "log",
    link_zoi: str = "logit",
    link_coi: str = "logit",
    **kwargs,
) -> ListSexpVector:
    """Zero-one-inflated beta for data between 0 and 1 with excess zeros and ones.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_phi : str
        Link function for precision parameter
    link_zoi : str
        Link function for zero-or-one inflation parameter
    link_coi : str
        Link function for conditional one inflation parameter
    """
    return brmsfamily(
        family="zero_one_inflated_beta",
        link=link,
        link_phi=link_phi,
        link_zoi=link_zoi,
        link_coi=link_coi,
        **kwargs,
    )

zero_inflated_poisson(link='log', link_zi='logit', **kwargs)

Zero-inflated Poisson for count data with excess zeros.

Parameters:

Name Type Description Default
link str

Link function for the mean

'log'
link_zi str

Link function for zero-inflation parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def zero_inflated_poisson(
    link: str = "log", link_zi: str = "logit", **kwargs
) -> ListSexpVector:
    """Zero-inflated Poisson for count data with excess zeros.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_zi : str
        Link function for zero-inflation parameter
    """
    return brmsfamily(
        family="zero_inflated_poisson",
        link=link,
        link_zi=link_zi,
        **kwargs,
    )

zero_inflated_negbinomial(link='log', link_shape='log', link_zi='logit', **kwargs)

Zero-inflated negative binomial for overdispersed count data with excess zeros.

Parameters:

Name Type Description Default
link str

Link function for the mean

'log'
link_shape str

Link function for shape parameter

'log'
link_zi str

Link function for zero-inflation parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def zero_inflated_negbinomial(
    link: str = "log", link_shape: str = "log", link_zi: str = "logit", **kwargs
) -> ListSexpVector:
    """Zero-inflated negative binomial for overdispersed count data with excess zeros.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_shape : str
        Link function for shape parameter
    link_zi : str
        Link function for zero-inflation parameter
    """
    return brmsfamily(
        family="zero_inflated_negbinomial",
        link=link,
        link_shape=link_shape,
        link_zi=link_zi,
        **kwargs,
    )

zero_inflated_binomial(link='logit', link_zi='logit', **kwargs)

Zero-inflated binomial for binary count data with excess zeros.

Parameters:

Name Type Description Default
link str

Link function for probability parameter

'logit'
link_zi str

Link function for zero-inflation parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def zero_inflated_binomial(
    link: str = "logit", link_zi: str = "logit", **kwargs
) -> ListSexpVector:
    """Zero-inflated binomial for binary count data with excess zeros.

    Parameters
    ----------
    link : str
        Link function for probability parameter
    link_zi : str
        Link function for zero-inflation parameter
    """
    return brmsfamily(
        family="zero_inflated_binomial",
        link=link,
        link_zi=link_zi,
        **kwargs,
    )

zero_inflated_beta_binomial(link='logit', link_phi='log', link_zi='logit', **kwargs)

Zero-inflated beta-binomial for overdispersed binomial data with excess zeros.

Parameters:

Name Type Description Default
link str

Link function for probability parameter

'logit'
link_phi str

Link function for precision parameter

'log'
link_zi str

Link function for zero-inflation parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def zero_inflated_beta_binomial(
    link: str = "logit", link_phi: str = "log", link_zi: str = "logit", **kwargs
) -> ListSexpVector:
    """Zero-inflated beta-binomial for overdispersed binomial data with excess zeros.

    Parameters
    ----------
    link : str
        Link function for probability parameter
    link_phi : str
        Link function for precision parameter
    link_zi : str
        Link function for zero-inflation parameter
    """
    return brmsfamily(
        family="zero_inflated_beta_binomial",
        link=link,
        link_phi=link_phi,
        link_zi=link_zi,
        **kwargs,
    )

categorical(link='logit', refcat=None, **kwargs)

Categorical distribution for unordered multi-category outcomes.

Parameters:

Name Type Description Default
link str

Link function for category probabilities

'logit'
refcat str

Reference category

None
Source code in brmspy/_brms_functions/families.py
def categorical(
    link: str = "logit", refcat: str | None = None, **kwargs
) -> ListSexpVector:
    """Categorical distribution for unordered multi-category outcomes.

    Parameters
    ----------
    link : str
        Link function for category probabilities
    refcat : str, optional
        Reference category
    """
    return brmsfamily(
        family="categorical",
        link=link,
        refcat=refcat,
        **kwargs,
    )

multinomial(link='logit', refcat=None, **kwargs)

Multinomial distribution for count data across multiple categories.

Parameters:

Name Type Description Default
link str

Link function for category probabilities

'logit'
refcat str

Reference category

None
Source code in brmspy/_brms_functions/families.py
def multinomial(
    link: str = "logit", refcat: str | None = None, **kwargs
) -> ListSexpVector:
    """Multinomial distribution for count data across multiple categories.

    Parameters
    ----------
    link : str
        Link function for category probabilities
    refcat : str, optional
        Reference category
    """
    return brmsfamily(
        family="multinomial",
        link=link,
        refcat=refcat,
        **kwargs,
    )

dirichlet_multinomial(link='logit', link_phi='log', refcat=None, **kwargs)

Dirichlet-multinomial for overdispersed categorical count data.

Parameters:

Name Type Description Default
link str

Link function for category probabilities

'logit'
link_phi str

Link function for precision parameter

'log'
refcat str

Reference category

None
Source code in brmspy/_brms_functions/families.py
def dirichlet_multinomial(
    link: str = "logit", link_phi: str = "log", refcat: str | None = None, **kwargs
) -> ListSexpVector:
    """Dirichlet-multinomial for overdispersed categorical count data.

    Parameters
    ----------
    link : str
        Link function for category probabilities
    link_phi : str
        Link function for precision parameter
    refcat : str, optional
        Reference category
    """
    return brmsfamily(
        family="dirichlet_multinomial",
        link=link,
        link_phi=link_phi,
        refcat=refcat,
        **kwargs,
    )

cumulative(link='logit', link_disc='log', threshold='flexible', **kwargs)

Cumulative (proportional odds) model for ordinal outcomes.

Parameters:

Name Type Description Default
link str

Link function for cumulative probabilities

'logit'
link_disc str

Link function for discrimination parameter

'log'
threshold str

Type of threshold structure

'flexible'
Source code in brmspy/_brms_functions/families.py
def cumulative(
    link: str = "logit", link_disc: str = "log", threshold: str = "flexible", **kwargs
) -> ListSexpVector:
    """Cumulative (proportional odds) model for ordinal outcomes.

    Parameters
    ----------
    link : str
        Link function for cumulative probabilities
    link_disc : str
        Link function for discrimination parameter
    threshold : str
        Type of threshold structure
    """
    return brmsfamily(
        family="cumulative",
        link=link,
        link_disc=link_disc,
        threshold=threshold,
        **kwargs,
    )

sratio(link='logit', link_disc='log', threshold='flexible', **kwargs)

Sequential (stopping) ratio model for ordinal outcomes.

Parameters:

Name Type Description Default
link str

Link function for sequential ratios

'logit'
link_disc str

Link function for discrimination parameter

'log'
threshold str

Type of threshold structure

'flexible'
Source code in brmspy/_brms_functions/families.py
def sratio(
    link: str = "logit", link_disc: str = "log", threshold: str = "flexible", **kwargs
) -> ListSexpVector:
    """Sequential (stopping) ratio model for ordinal outcomes.

    Parameters
    ----------
    link : str
        Link function for sequential ratios
    link_disc : str
        Link function for discrimination parameter
    threshold : str
        Type of threshold structure
    """
    return brmsfamily(
        family="sratio",
        link=link,
        link_disc=link_disc,
        threshold=threshold,
        **kwargs,
    )

cratio(link='logit', link_disc='log', threshold='flexible', **kwargs)

Continuation ratio model for ordinal outcomes.

Parameters:

Name Type Description Default
link str

Link function for continuation ratios

'logit'
link_disc str

Link function for discrimination parameter

'log'
threshold str

Type of threshold structure

'flexible'
Source code in brmspy/_brms_functions/families.py
def cratio(
    link: str = "logit", link_disc: str = "log", threshold: str = "flexible", **kwargs
) -> ListSexpVector:
    """Continuation ratio model for ordinal outcomes.

    Parameters
    ----------
    link : str
        Link function for continuation ratios
    link_disc : str
        Link function for discrimination parameter
    threshold : str
        Type of threshold structure
    """
    return brmsfamily(
        family="cratio",
        link=link,
        link_disc=link_disc,
        threshold=threshold,
        **kwargs,
    )

acat(link='logit', link_disc='log', threshold='flexible', **kwargs)

Adjacent category model for ordinal outcomes.

Parameters:

Name Type Description Default
link str

Link function for adjacent category ratios

'logit'
link_disc str

Link function for discrimination parameter

'log'
threshold str

Type of threshold structure

'flexible'
Source code in brmspy/_brms_functions/families.py
def acat(
    link: str = "logit", link_disc: str = "log", threshold: str = "flexible", **kwargs
) -> ListSexpVector:
    """Adjacent category model for ordinal outcomes.

    Parameters
    ----------
    link : str
        Link function for adjacent category ratios
    link_disc : str
        Link function for discrimination parameter
    threshold : str
        Type of threshold structure
    """
    return brmsfamily(
        family="acat",
        link=link,
        link_disc=link_disc,
        threshold=threshold,
        **kwargs,
    )

gaussian(link='identity', link_sigma='log', **kwargs)

Gaussian (normal) distribution for continuous data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'identity'
link_sigma str

Link function for the standard deviation

'log'
Source code in brmspy/_brms_functions/families.py
def gaussian(
    link: str = "identity",
    link_sigma: str = "log",
    **kwargs,
) -> ListSexpVector:
    """Gaussian (normal) distribution for continuous data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_sigma : str
        Link function for the standard deviation
    """
    return brmsfamily(
        family="gaussian",
        link=link,
        link_sigma=link_sigma,
        **kwargs,
    )

poisson(link='log', **kwargs)

Poisson distribution for count data.

Parameters:

Name Type Description Default
link str

Link function for the rate parameter

'log'
Source code in brmspy/_brms_functions/families.py
def poisson(
    link: str = "log",
    **kwargs,
) -> ListSexpVector:
    """Poisson distribution for count data.

    Parameters
    ----------
    link : str
        Link function for the rate parameter
    """
    return brmsfamily(
        family="poisson",
        link=link,
        **kwargs,
    )

binomial(link='logit', **kwargs)

Binomial distribution for binary count data.

Parameters:

Name Type Description Default
link str

Link function for the probability parameter

'logit'
Source code in brmspy/_brms_functions/families.py
def binomial(
    link: str = "logit",
    **kwargs,
) -> ListSexpVector:
    """Binomial distribution for binary count data.

    Parameters
    ----------
    link : str
        Link function for the probability parameter
    """
    return brmsfamily(
        family="binomial",
        link=link,
        **kwargs,
    )

Gamma(link='log', link_shape='log', **kwargs)

Gamma distribution for positive continuous data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'log'
link_shape str

Link function for the shape parameter

'log'
Source code in brmspy/_brms_functions/families.py
def Gamma(
    link: str = "log",
    link_shape: str = "log",
    **kwargs,
) -> ListSexpVector:
    """Gamma distribution for positive continuous data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_shape : str
        Link function for the shape parameter
    """
    return brmsfamily(
        family="Gamma",
        link=link,
        link_shape=link_shape,
        **kwargs,
    )

inverse_gaussian(link='1/mu^2', link_shape='log', **kwargs)

Inverse Gaussian distribution for positive continuous data.

Parameters:

Name Type Description Default
link str

Link function for the mean

'1/mu^2'
link_shape str

Link function for the shape parameter

'log'
Source code in brmspy/_brms_functions/families.py
def inverse_gaussian(
    link: str = "1/mu^2",
    link_shape: str = "log",
    **kwargs,
) -> ListSexpVector:
    """Inverse Gaussian distribution for positive continuous data.

    Parameters
    ----------
    link : str
        Link function for the mean
    link_shape : str
        Link function for the shape parameter
    """
    return brmsfamily(
        family="inverse.gaussian",
        link=link,
        link_shape=link_shape,
        **kwargs,
    )

get_brms_version()

Get installed brms R package version.

Returns:

Type Description
str

Version object or None

Raises:

Type Description
ImportError

If brms is not installed

Examples:

from brmspy import brms
version = brms.get_brms_version()
print(f"brms version: {version}")
Source code in brmspy/_runtime/__init__.py
def get_brms_version() -> Version | None:
    """
    Get installed brms R package version.

    Returns
    -------
    str
        Version object or None

    Raises
    ------
    ImportError
        If brms is not installed

    Examples
    --------

    ```python
    from brmspy import brms
    version = brms.get_brms_version()
    print(f"brms version: {version}")
    ```
    """
    version = status().brms_version
    if version is None:
        return None
    return Version(version)

find_local_runtime()

Find an installed runtime matching the current system fingerprint.

Uses system_fingerprint() to compute the current system identity and searches the local runtime store for a matching runtime directory.

Returns:

Type Description
Path or None

Path to the matching runtime root directory if found, otherwise None.

Notes

This function is a pure lookup: it does not install, activate, or modify any runtime state.

Source code in brmspy/_runtime/__init__.py
def find_local_runtime() -> Path | None:
    """
    Find an installed runtime matching the current system fingerprint.

    Uses ``system_fingerprint()`` to compute the current system identity and
    searches the local runtime store for a matching runtime directory.

    Returns
    -------
    Path or None
        Path to the matching runtime root directory if found,
        otherwise ``None``.

    Notes
    -----
    This function is a pure lookup:
    it does not install, activate, or modify any runtime state.
    """
    fingerprint = system_fingerprint()
    return _storage.find_runtime_by_fingerprint(fingerprint)

get_active_runtime()

Get path to currently active prebuilt runtime.

Returns CONFIGURED runtime, not whether it is loaded.

Returns:

Type Description
Path or None

Path to active runtime directory, or None if not configured

Notes

Returns None if: - No runtime configured in config file - Config file doesn't exist - Config file is corrupted

Examples:

from brmspy import get_active_runtime

runtime_path = get_active_runtime()
if runtime_path and runtime_path.exists():
    print(f"Active runtime: {runtime_path}")
else:
    print("No active runtime configured")
Source code in brmspy/_runtime/__init__.py
def get_active_runtime() -> Path | None:
    """
    Get path to currently active prebuilt runtime.

    Returns CONFIGURED runtime, not whether it is loaded.

    Returns
    -------
    Path or None
        Path to active runtime directory, or None if not configured

    Notes
    -----
    Returns None if:
    - No runtime configured in config file
    - Config file doesn't exist
    - Config file is corrupted

    Examples
    --------
    ```python
    from brmspy import get_active_runtime

    runtime_path = get_active_runtime()
    if runtime_path and runtime_path.exists():
        print(f"Active runtime: {runtime_path}")
    else:
        print("No active runtime configured")
    ```
    """
    _status = status()
    if not _status:
        return None

    return _status.active_runtime

status()

Query current runtime status without side effects.

Returns:

Type Description
RuntimeStatus

Dataclass with comprehensive state information including:

  • Active runtime path and activation state
  • System fingerprint and toolchain info
  • Prebuilt compatibility and availability
  • Installed brms/cmdstanr/rstan versions
Source code in brmspy/_runtime/__init__.py
def status() -> RuntimeStatus:
    """
    Query current runtime status without side effects.

    Returns
    -------
    RuntimeStatus
        Dataclass with comprehensive state information including:

        - Active runtime path and activation state
        - System fingerprint and toolchain info
        - Prebuilt compatibility and availability
        - Installed brms/cmdstanr/rstan versions
    """
    from brmspy._runtime import _config, _platform, _r_packages, _state, _storage

    system = _platform.get_system_info()

    return RuntimeStatus(
        active_runtime=_config.get_active_runtime_path(),
        is_activated=_state.has_stored_env(),
        system=system,
        can_use_prebuilt=_platform.can_use_prebuilt(),
        prebuilt_available=_platform.is_prebuilt_available(system.fingerprint),
        compatibility_issues=tuple(_platform.get_compatibility_issues()),
        installed_runtimes=tuple(_storage.list_installed_runtimes()),
        brms_version=_r_packages.get_package_version("brms"),
        cmdstanr_version=_r_packages.get_package_version("cmdstanr"),
        rstan_version=_r_packages.get_package_version("rstan"),
    )