Skip to content

Main Module

User-facing brms API.

Import this module to call brms functions from Python (for example brm, prior, posterior_predict, etc.). brmspy runs these calls through an isolated runtime so that R-side instability is less likely to take down your Python process.

Use brms.manage() to install brms / CmdStan, and to work with multiple isolated environments.

Examples:

from brmspy import brms
with brms.manage(environment_name="default") as ctx:
    ctx.install_brms(use_prebuilt=True)

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

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.

Functions

__repr__()

Pretty print LOO-CV results.

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").

IDPosterior

Bases: IDConstantData

Typed .posterior extension to idata

IDPosteriorPredictive

Bases: IDConstantData

Typed .posterior_predictive extension to idata

IDPredictions

Bases: IDPredictionsConstantData

Typed .predictions extension to idata

IDLogLikelihoodInsample

Bases: IDConstantData

Typed .log_likelihood extension to idata

IDLogLikelihoodOutsample

Bases: IDPredictionsConstantData

Typed .log_likelihood extension to idata

IDObservedData

Bases: IDConstantData

Typed .posterior extension to idata

IDConstantData

Bases: InferenceData

Typed .constant_data extension to idata

IDPredictionsConstantData

Bases: InferenceData

Typed .predictions_constant_data extension to idata

RListVectorExtension dataclass

Generic result container with R objects.

Attributes:

Name Type Description
r ListVector

R object from brms

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)

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)

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'}

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.

Functions

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

__radd__(other)

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

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)
__iter__()

Alias for 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]

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.

Functions

__post_init__()

Validate _fun, _args, and _kwargs types after construction.

__str__()

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

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

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

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

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

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")

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")

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.

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)

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)

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")

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

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

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)

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)

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)

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)

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)

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
)

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)

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)

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")

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()

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)")

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)

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)

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()

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)

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

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

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

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)

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

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)

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

family(fit, **kwargs)

Extract family object from a fitted model.

Parameters:

Name Type Description Default
fit FitResult or ListSexpVector

Fitted brms model

required

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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

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

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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

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

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

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'

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'

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'

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'

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'

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

Poisson distribution for count data.

Parameters:

Name Type Description Default
link str

Link function for the rate parameter

'log'

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

Binomial distribution for binary count data.

Parameters:

Name Type Description Default
link str

Link function for the probability parameter

'logit'

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'

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'

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}")

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.

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")

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