Skip to content

Main Module

Main brms module with Pythonic API.

Classes

FitResult dataclass

Bases: RListVectorExtension

Result from fit() function.

Attributes:

Name Type Description
idata InferenceData

arviz InferenceData with posterior, posterior_predictive, log_likelihood, and observed_data groups

r ListVector

brmsfit R object from brms::brm()

FormulaResult dataclass

Bases: RListVectorExtension

Result from formula() function.

Attributes:

Name Type Description
r ListVector

R brmsformula object

dict Dict

Python dictionary representation of formula

See Also

brmspy.brms.formula : Creates FormulaResult objects

Examples:

from brmspy import brms

# Create formula with options
f = brms.formula("y ~ x", decomp="QR")

# Use in fit()
model = brms.fit(f, data=df, chains=4)

GenericResult dataclass

Bases: RListVectorExtension

Generic result container with arviz and R objects.

Attributes:

Name Type Description
idata InferenceData

arviz InferenceData object

r ListVector

R object from brms

LogLikResult dataclass

Bases: RListVectorExtension

Result from log_lik() function.

Attributes:

Name Type Description
idata IDLogLik

arviz InferenceData with log-likelihood values

r ListVector

R matrix from brms::log_lik()

See Also

brmspy.brms.log_lik : Creates LogLikResult objects

Examples:

from brmspy import brms
import arviz as az

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

# Use for model comparison
loo = az.loo(model.idata)
print(loo)

LooResult dataclass

Bases: RListVectorExtension

Functions

__repr__()

Pretty print LOO-CV results.

PosteriorEpredResult dataclass

Bases: RListVectorExtension

Result from posterior_epred() function.

Attributes:

Name Type Description
idata InferenceData

arviz InferenceData with expected values in 'posterior' group

r ListVector

R matrix from brms::posterior_epred()

PosteriorLinpredResult dataclass

Bases: RListVectorExtension

Result from posterior_linpred() function.

Attributes:

Name Type Description
idata IDLinpred

arviz InferenceData with linear predictor values

r ListVector

R matrix from brms::posterior_linpred()

See Also

brmspy.brms.posterior_linpred : Creates PosteriorLinpredResult objects

Examples:

from brmspy import brms

model = brms.fit("count ~ age", data=df, family="poisson", chains=4)
linpred = brms.posterior_linpred(model)

# Linear predictor on log scale (for Poisson)
print(linpred.idata.predictions)

PosteriorPredictResult dataclass

Bases: RListVectorExtension

Result from posterior_predict() function.

Attributes:

Name Type Description
idata InferenceData

arviz InferenceData with predictions in 'posterior_predictive' group

r ListVector

R matrix from brms::posterior_predict()

RListVectorExtension dataclass

Generic result container with R objects.

Attributes:

Name Type Description
r ListVector

R object from brms

IDLinpred

Bases: InferenceData

Typed InferenceData for posterior_linpred results.

Contains linear predictor values (before applying link function).

Attributes:

Name Type Description
predictions Dataset

Linear predictor samples

See Also

brmspy.brms.posterior_linpred : Creates IDLinpred objects

IDEpred

Bases: InferenceData

Typed InferenceData for posterior_epred results.

Contains expected values E[Y|X] without observation noise.

Attributes:

Name Type Description
posterior Dataset

Expected value samples (no observation noise)

See Also

brmspy.brms.posterior_epred : Creates IDEpred objects

IDFit

Bases: InferenceData

Typed InferenceData for fitted brms models.

Extends arviz.InferenceData with type hints for IDE autocomplete. Guarantees the presence of specific data groups returned by fit().

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

dims dict

Dimension specifications for variables

See Also

brmspy.brms.fit : Creates IDFit objects arviz.InferenceData : Base class documentation

Examples:

from brmspy import brms
model = brms.fit("y ~ x", data=df, chains=4)

# Type checking and autocomplete
assert isinstance(model.idata, IDFit)
print(model.idata.posterior)  # IDE autocomplete works!

IDLogLik

Bases: InferenceData

Typed InferenceData for log_lik results.

Contains log-likelihood values for model comparison.

Attributes:

Name Type Description
log_likelihood Dataset

Log-likelihood values for each observation

See Also

brmspy.brms.log_lik : Creates IDLogLik objects arviz.loo : LOO-CV using log-likelihood

IDPredict

Bases: InferenceData

Typed InferenceData for posterior_predict results.

Contains posterior predictive samples with observation noise.

Attributes:

Name Type Description
posterior_predictive Dataset

Posterior predictive samples (includes observation noise)

See Also

brmspy.brms.posterior_predict : Creates IDPredict objects

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 https://paulbuerkner.com/brms/reference/prior_string.html

Examples:

Create prior specifications (prefer using prior() function):

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  # Truncated at zero
)

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

Functions

get_brms_data(dataset_name, **kwargs)

Load an example dataset from the R brms package.

This is a convenience wrapper around :func:get_data that fixes package="brms" and returns the dataset as a :class:pandas.DataFrame.

Parameters:

Name Type Description Default
dataset_name str

Name of the example dataset in the brms package (e.g. "epilepsy", "kidney", "inhaler").

required
**kwargs

Additional keyword arguments forwarded to :func:get_data and ultimately to R's data() function. These can be used to override defaults such as the target environment.

{}

Returns:

Type Description
DataFrame

Dataset as a pandas DataFrame with column names preserved.

See Also

get_data Generic loader for datasets from arbitrary R packages. brms R reference For a list of available example datasets and their structure.

Examples:

Load the epilepsy dataset::

from brmspy.runtime import get_brms_data

epilepsy = get_brms_data("epilepsy")
print(epilepsy.head())

Load the kidney dataset and inspect censoring::

kidney = get_brms_data("kidney")
print(kidney.shape)
print(kidney["censored"].value_counts())

read_rds_fit(file, **kwargs)

Load saved brmsfit object as FitResult with arviz InferenceData.

Reads a brmsfit object from an RDS file and converts it to a FitResult with both arviz InferenceData (.idata) and the raw R object (.r). This is the recommended way to load saved brms models for analysis and predictions in Python.

Parameters:

Name Type Description Default
file str

Path to RDS file containing saved brmsfit object

required
**kwargs dict

Additional arguments passed to R's readRDS():

  • refhook : function - Reference hook for deserialization
{}

Returns:

Type Description
FitResult

Object with two attributes: - .idata : arviz.InferenceData with posterior samples and diagnostics - .r : R brmsfit object for use with brms functions

Raises:

Type Description
Exception

If file doesn't exist or doesn't contain a valid brmsfit object

See Also

save_rds : Save brmsfit objects to RDS files read_rds_raw : Load as raw R object without conversion fit : Create brmsfit objects to save

Examples:

Basic loading and analysis:

from brmspy import brms
import arviz as az

# Load previously saved model
model = brms.read_rds_fit("my_model.rds")

# Analyze with arviz
az.summary(model.idata)
az.plot_trace(model.idata)

# Check diagnostics
print(az.rhat(model.idata))

Load and make predictions:

import pandas as pd

# Load saved model
model = brms.read_rds_fit("trained_model.rds")

# Create new data for predictions
newdata = pd.DataFrame({
    'x': [1.0, 2.0, 3.0],
    'group': ['A', 'B', 'A']
})

# Generate predictions
predictions = brms.posterior_predict(model, newdata=newdata)
print(predictions.idata.posterior_predictive)

Load model for comparison:

# Load multiple saved models
model1 = brms.read_rds_fit("model1.rds")
model2 = brms.read_rds_fit("model2.rds")

# Compare with arviz
comparison = az.compare({
    'model1': model1.idata,
    'model2': model2.idata
})
print(comparison)

Resume analysis from checkpoint:

# Load model from checkpoint during long computation
try:
    model = brms.read_rds_fit("checkpoint.rds")
    print("Loaded from checkpoint")
except:
    # Checkpoint doesn't exist, fit from scratch
    model = brms.fit(formula="y ~ x", data=data, chains=4)
    brms.save_rds(model, "checkpoint.rds")

# Continue analysis
summary = brms.summary(model)

read_rds_raw(file, **kwargs)

Load R object from RDS file as raw ListVector.

Reads an RDS file and returns the raw R object without any Python conversion or processing. Useful when you need direct access to the R object structure or want to inspect saved objects before full conversion.

Parameters:

Name Type Description Default
file str

Path to RDS file to load

required
**kwargs dict

Additional arguments passed to R's readRDS():

  • refhook : function - Reference hook for deserialization
{}

Returns:

Type Description
ListVector

Raw R ListVector object from the RDS file

See Also

read_rds_fit : Load as FitResult with arviz InferenceData save_rds : Save R objects to RDS files

Examples:

Load raw R object:

from brmspy import brms

# Load raw brmsfit object
raw_model = brms.read_rds_raw("model.rds")

# Access R object directly (for advanced users)
print(type(raw_model))  # rpy2.robjects.vectors.ListVector

Inspect object structure before conversion:

# Load raw to check what's in the file
raw_obj = brms.read_rds_raw("unknown_object.rds")

# Inspect R object attributes
print(raw_obj.names)

# Then decide how to process it
if "fit" in raw_obj.names:
    # It's a brmsfit, convert properly
    full_model = brms.read_rds_fit("unknown_object.rds")

save_rds(object, file, **kwargs)

Save brmsfit object or R object to RDS file.

Saves fitted brms models or other R objects to disk using R's saveRDS() function. This allows persisting models for later use, sharing fitted models, or creating model checkpoints during long computations.

Parameters:

Name Type Description Default
object FitResult or ListVector

Object to save. Can be: - FitResult from fit() - saves the underlying brmsfit R object - Any R ListVector object

required
file str

File path where object will be saved. Typically uses .rds extension but not required

required
**kwargs dict

Additional arguments passed to R's saveRDS():

  • compress : bool or str - Compression method: True (default), False, "gzip", "bzip2", "xz"
  • version : int - RDS format version (2 or 3)
  • ascii : bool - Use ASCII representation (default False)
  • refhook : function - Reference hook for serialization (NOT tested)
{}

Returns:

Type Description
None
See Also

read_rds_fit : Load saved brmsfit as FitResult read_rds_raw : Load saved object as raw R ListVector fit : Fit models that can be saved

Examples:

Save a fitted model:

from brmspy import brms

# Fit model
model = brms.fit(
    formula="y ~ x + (1|group)",
    data=data,
    family="gaussian",
    chains=4
)

# Save to file
brms.save_rds(model, "my_model.rds")

Save with compression options:

# High compression for storage
brms.save_rds(model, "model.rds", compress="xz")

# No compression for faster saving
brms.save_rds(model, "model.rds", compress=False)

Save and later reload:

# Save model
brms.save_rds(model, "model.rds")

# Later session: reload model
loaded_model = brms.read_rds_fit("model.rds")

# Use loaded model for predictions
predictions = brms.posterior_predict(loaded_model, newdata=new_data)

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.fit() and brmspy.make_stancode().

Notes

This function does not validate the prior expression string itself — validation occurs inside brms. Its purpose is to construct a structured, editor-friendly representation that seamlessly maps to rpy2 calls.

Examples:

Prior on the intercept ::

p = prior("student_t(3, 0, 1.95)", class_="Intercept")

Prior on a coefficient ::

p = prior("normal(0, 1)", class_="b", coef="age")

Group-level (hierarchical) SD prior ::

p = prior("exponential(2)", class_="sd", group="region")

Truncated prior ::

p = prior("normal(0, 1)", class_="b", coef="income", lb=0)

Multiple priors passed to fit ::

from brmspy import prior
priors = [
    prior("student_t(3, 0, 2)", class_="b", coef="zAge"),
    prior("exponential(2)", class_="sd", group="patient"),
]
model = brms.fit("y ~ zAge + (1|patient)", data=df, priors=priors)

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

Get default priors for all model parameters.

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 FormulaResult

Model formula (e.g., "y ~ x + (1|group)") or FormulaResult object

required
data DataFrame or dict

Dataset containing model variables. Required for data-dependent priors

None
family str or ListVector

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 https://paulbuerkner.com/brms/reference/get_prior.html

Examples:

Review default priors for a model:

from brmspy import brms

priors = brms.get_prior(
    formula="count ~ zAge + zBase * Trt + (1|patient)",
    data=epilepsy,
    family="poisson"
)
print(priors)
#   prior       class    coef      group  ...
#   student_t() Intercept  ...    ...     ...
#   (flat)      b          zAge    ...    ...

Customize and use priors:

from brmspy import brms, prior

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

# Create custom priors based on review
custom_priors = [
    prior("normal(0, 0.5)", class_="b"),
    prior("exponential(2)", class_="sigma")
]

model = brms.fit("y ~ x", data=df, priors=custom_priors)

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

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

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 ListVector

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 ListVector

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 https://paulbuerkner.com/brms/reference/get_prior.html

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, **brm_args)

Fit Bayesian regression model using brms.

Uses brms with cmdstanr backend for proper parameter naming. Returns FitResult with .idata (arviz.InferenceData) and .r (brmsfit) attributes.

BRMS documentation and parameters

Parameters:

Name Type Description Default
formula str

brms formula: formula string, e.g "y ~ x + (1|group)" or FormulaResult from formula()

required
data dict or DataFrame

Model data

required
priors list

Prior specifications: [("normal(0,1)", "b"), ("cauchy(0,2)", "sd")]

[]
family str

Distribution family: "gaussian", "poisson", "binomial", etc.

"gaussian"
sample_prior str

Sample from prior: "no", "yes", "only"

"no"
sample bool

Whether to sample. If False, returns compiled model with empty=TRUE

True
backend str

Stan backend: "cmdstanr" (recommended), "rstan"

"cmdstanr"
**brm_args

Additional brms::brm() arguments: chains=4, iter=2000, warmup=1000, cores=4, seed=123, thin=1, etc.

{}

Returns:

Type Description
FitResult

Object with .idata (arviz.InferenceData) and .r (brmsfit) attributes

See Also

brms::brm : R documentation https://paulbuerkner.com/brms/reference/brm.html posterior_epred : Expected value predictions posterior_predict : Posterior predictive samples formula : Create formula object with options

Warnings

cores <= 1 is unsafe in embedded R sessions. The single-process code path used by brms::brm() can crash the interpreter. Always use cores >= 2 to force parallel workers and avoid segfaults.

Examples:

Basic Poisson regression:

from brmspy import brms
import arviz as az

epilepsy = brms.get_brms_data("epilepsy")
model = brms.fit(
    formula="count ~ zAge + zBase * Trt + (1|patient)",
    data=epilepsy,
    family="poisson",
    chains=4,
    iter=2000
)

az.summary(model.idata)
With custom priors:

from brmspy import prior

model = brms.fit(
    formula="count ~ zAge + zBase * Trt + (1|patient)",
    data=epilepsy,
    priors=[
        prior("normal(0, 0.5)", class_="b"),
        prior("exponential(2)", class_="sd", group="patient")
    ],
    family="poisson",
    chains=4
)
Survival model with censoring:

kidney = brms.get_brms_data("kidney")

survival_model = brms.fit(
    formula="time | cens(censored) ~ age + sex + disease + (1|patient)",
    data=kidney,
    family="weibull",
    chains=4,
    iter=4000,
    warmup=2000,
    cores=4,
    seed=42
)
Gaussian model with distributional regression:

    # Model both mean and variance
    model = brms.fit(
        formula=brms.formula(
            "y ~ x",
            sigma ~ "z"  # Model heteroscedasticity
        ),
        data=data,
        family="gaussian",
        chains=4
    )

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

Fit Bayesian regression model using brms.

Uses brms with cmdstanr backend for proper parameter naming. Returns FitResult with .idata (arviz.InferenceData) and .r (brmsfit) attributes.

BRMS documentation and parameters

Parameters:

Name Type Description Default
formula str

brms formula: formula string, e.g "y ~ x + (1|group)" or FormulaResult from formula()

required
data dict or DataFrame

Model data

required
priors list

Prior specifications: [("normal(0,1)", "b"), ("cauchy(0,2)", "sd")]

[]
family str

Distribution family: "gaussian", "poisson", "binomial", etc.

"gaussian"
sample_prior str

Sample from prior: "no", "yes", "only"

"no"
sample bool

Whether to sample. If False, returns compiled model with empty=TRUE

True
backend str

Stan backend: "cmdstanr" (recommended), "rstan"

"cmdstanr"
**brm_args

Additional brms::brm() arguments: chains=4, iter=2000, warmup=1000, cores=4, seed=123, thin=1, etc.

{}

Returns:

Type Description
FitResult

Object with .idata (arviz.InferenceData) and .r (brmsfit) attributes

See Also

brms::brm : R documentation https://paulbuerkner.com/brms/reference/brm.html posterior_epred : Expected value predictions posterior_predict : Posterior predictive samples formula : Create formula object with options

Warnings

cores <= 1 is unsafe in embedded R sessions. The single-process code path used by brms::brm() can crash the interpreter. Always use cores >= 2 to force parallel workers and avoid segfaults.

Examples:

Basic Poisson regression:

from brmspy import brms
import arviz as az

epilepsy = brms.get_brms_data("epilepsy")
model = brms.fit(
    formula="count ~ zAge + zBase * Trt + (1|patient)",
    data=epilepsy,
    family="poisson",
    chains=4,
    iter=2000
)

az.summary(model.idata)
With custom priors:

from brmspy import prior

model = brms.fit(
    formula="count ~ zAge + zBase * Trt + (1|patient)",
    data=epilepsy,
    priors=[
        prior("normal(0, 0.5)", class_="b"),
        prior("exponential(2)", class_="sd", group="patient")
    ],
    family="poisson",
    chains=4
)
Survival model with censoring:

kidney = brms.get_brms_data("kidney")

survival_model = brms.fit(
    formula="time | cens(censored) ~ age + sex + disease + (1|patient)",
    data=kidney,
    family="weibull",
    chains=4,
    iter=4000,
    warmup=2000,
    cores=4,
    seed=42
)
Gaussian model with distributional regression:

    # Model both mean and variance
    model = brms.fit(
        formula=brms.formula(
            "y ~ x",
            sigma ~ "z"  # Model heteroscedasticity
        ),
        data=data,
        family="gaussian",
        chains=4
    )

summary(model, **kwargs)

Generate comprehensive summary statistics for 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 from fit()

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 https://paulbuerkner.com/brms/reference/summary.brmsfit.html

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 ListVector

Fitted model from fit() or 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 https://paulbuerkner.com/brms/reference/fixef.brmsfit.html 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 ListVector

Fitted model from fit() or 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 from fit() or 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 ListVector

Fitted model from fit() or 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 any brms or R function by name with automatic type conversion.

Generic wrapper for calling brms functions that don't have dedicated Python wrappers. Automatically converts Python arguments to R objects and R results back to Python. Tries brms::function_name first, then falls back to base R.

This function is useful for: - Accessing newer brms functions not yet wrapped in brmspy - Calling brms utility functions without writing custom wrappers - Quick exploration of brms functionality from Python

Parameters:

Name Type Description Default
function str

Name of the R function to call. Will be prefixed with 'brms::' if possible. Can also include namespace (e.g., "stats::predict").

required
*args

Positional arguments passed to the R function. Automatically converted from Python to R types (FitResult → brmsfit, DataFrame → data.frame, etc.).

()
**kwargs

Keyword arguments passed to the R function. Python parameter names are automatically converted to R conventions.

{}

Returns:

Type Description
Any

Result from R function, automatically converted to appropriate Python type (R data.frame → pandas DataFrame, R vector → numpy array, etc.).

See Also

py_to_r : Python to R type conversion r_to_py : R to Python type conversion

Examples:

Call brms functions not yet wrapped:

from brmspy import brms
from brmspy.brms_functions.generic import call

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

# Call brms::neff_ratio (not yet wrapped)
neff = call("neff_ratio", model)
print(neff)

# Call brms::rhat (not yet wrapped)
rhat = call("rhat", model)
print(rhat)

Call with keyword arguments:

# Call brms::hypothesis for testing hypotheses
hypothesis_result = call(
    "hypothesis",
    model,
    hypothesis="b_x1 > 0",
    alpha=0.05
)
print(hypothesis_result)

Access functions from other R packages:

# Call functions with namespace
result = call("stats::AIC", model)
print(result)

bf(formula, **formula_args)

Set up a model formula for brms package.

Allows defining (potentially non-linear) additive multilevel models for all parameters of the assumed response distribution.

Parameters:

Name Type Description Default
formula str

brms formula specification, e.g., "y ~ x + (1|group)"

required
**formula_args dict

Additional brms::brmsformula() arguments:

  • decomp : str Decomposition method (e.g., "QR" for QR decomposition)
  • center : bool Whether to center predictors (default True)
  • sparse : bool Use sparse matrix representation
  • nl : bool Whether formula is non-linear
  • loop : bool Use loop-based Stan code
{}

Returns:

Type Description
FormulaResult

Object with .r (R brmsformula object) and .dict (Python dict) attributes

See Also

brms::brmsformula : R documentation https://paulbuerkner.com/brms/reference/brmsformula.html fit : Fit model using formula

Examples:

Basic formula:

    from brmspy import brms
    f = brms.bf("y ~ x1 + x2 + (1|group)")

With QR decomposition for numerical stability:

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

Multivariate formula:

    f = brms.bf(
        "mvbind(y1, y2) ~ x1 + x2",
        center=True
    )

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

Specify linear formulas for distributional / non-linear parameters.

Parameters:

Name Type Description Default
*formulas str or FormulaResult

One or more formulas (e.g. "sigma ~ x", "nu ~ z").

()
flist list

Additional formulas passed as a list.

None
dpar str

Name of the distributional parameter (e.g. "sigma").

None
resp str

Response name in multivariate models.

None
center optional

Passed through to brms::lf().

None
cmc optional

Passed through to brms::lf().

None
sparse optional

Passed through to brms::lf().

None
decomp optional

Passed through to brms::lf().

None

Returns:

Type Description
FormulaResult

Object that can be added to a bf() formula via +.

Examples:

>>> f = bf("y ~ 1") + lf("sigma ~ x", dpar="sigma")

nlf(formula, *extra, flist=None, dpar=None, resp=None, loop=None)

Specify non-linear formulas for distributional parameters.

Parameters:

Name Type Description Default
formula str

Non-linear formula, e.g. "sigma ~ a * exp(b * x)".

required
*extra str or FormulaResult

Additional named parameters or formulas (rarely needed here; typically you use lf() for those).

()
flist list

Additional formulas passed as a list.

None
dpar str

Name of the distributional parameter.

None
resp str

Response name in multivariate models.

None
loop bool

Whether to compute inside a loop (brms::nlf(loop=...)).

None

Returns:

Type Description
FormulaResult

Object that can be added to a bf() formula via +.

Examples:

>>> f = bf("y ~ 1") + nlf("sigma ~ a * exp(b * x)")

acformula(autocor, resp=None)

Specify autocorrelation terms to add to a model.

Parameters:

Name Type Description Default
autocor str

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

required
resp str

Response name in multivariate models.

None

Returns:

Type Description
FormulaResult

Object that can be added to a bf() formula via +.

Examples:

>>> f = bf("y ~ x") + acformula("~ arma(p = 1, q = 1)")

set_rescor(rescor=True)

Control residual correlations in multivariate models.

Parameters:

Name Type Description Default
rescor bool

Whether to model residual correlations.

True

Returns:

Type Description
FormulaResult

Object that can be added to a multivariate formula via +.

Examples:

>>> f = bf("y1 ~ x") + bf("y2 ~ z") + set_rescor(True)

set_mecor(mecor=True)

Control correlations between latent me-terms.

Parameters:

Name Type Description Default
mecor bool

Whether to model correlations between me() latent variables.

True

Returns:

Type Description
FormulaResult

Object that can be added to a formula via +.

Examples:

>>> f = bf("y ~ me(x, sdx)") + set_mecor(True)

set_nl(dpar=None, resp=None)

Mark a formula as non-linear (or parts of it).

Parameters:

Name Type Description Default
dpar str

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

None
resp str

Response name in multivariate models.

None

Returns:

Type Description
FormulaResult

Object that can be added to a formula via +.

Examples:

>>> f = bf("y ~ a * inv_logit(x * b)") + lf("a + b ~ z") + set_nl()

formula(formula, **formula_args)

Set up a model formula for brms package.

Allows defining (potentially non-linear) additive multilevel models for all parameters of the assumed response distribution.

Parameters:

Name Type Description Default
formula str

brms formula specification, e.g., "y ~ x + (1|group)"

required
**formula_args dict

Additional brms::brmsformula() arguments:

  • decomp : str Decomposition method (e.g., "QR" for QR decomposition)
  • center : bool Whether to center predictors (default True)
  • sparse : bool Use sparse matrix representation
  • nl : bool Whether formula is non-linear
  • loop : bool Use loop-based Stan code
{}

Returns:

Type Description
FormulaResult

Object with .r (R brmsformula object) and .dict (Python dict) attributes

See Also

brms::brmsformula : R documentation https://paulbuerkner.com/brms/reference/brmsformula.html fit : Fit model using formula

Examples:

Basic formula:

    from brmspy import brms
    f = brms.bf("y ~ x1 + x2 + (1|group)")

With QR decomposition for numerical stability:

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

Multivariate formula:

    f = brms.bf(
        "mvbind(y1, y2) ~ x1 + x2",
        center=True
    )

posterior_epred(model, newdata, **kwargs)

Compute expected value of posterior predictive distribution.

Calls brms::posterior_epred() to get E[Y|data] without observation noise.

BRMS documentation and parameters

Parameters:

Name Type Description Default
model FitResult

Fitted model from fit()

required
newdata DataFrame

Data for predictions

required
**kwargs

Additional arguments to brms::posterior_epred()

{}

Returns:

Type Description
PosteriorEpredResult

Object with .idata and .r attributes

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

Compute linear predictor of the model.

Returns samples of the linear predictor (before applying the link function). Useful for understanding the model's predictions on the linear scale.

Parameters:

Name Type Description Default
model FitResult

Fitted model from fit()

required
newdata DataFrame

Data for predictions. If None, uses original data

None
**kwargs dict

Additional arguments to brms::posterior_linpred():

  • transform : bool - Apply inverse link function (default False)
  • ndraws : int - Number of posterior draws
  • summary : bool - Return summary statistics
{}

Returns:

Type Description
PosteriorLinpredResult

Object with .idata (IDLinpred) and .r (R matrix) attributes

See Also

brms::posterior_linpred : R documentation https://paulbuerkner.com/brms/reference/posterior_linpred.brmsfit.html posterior_epred : Expected values on response scale

Examples:

    from brmspy import brms

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

    # Linear predictor (log scale for Poisson)
    linpred = brms.posterior_linpred(model)
    print(linpred.idata.predictions)

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

Generate posterior predictive samples with observation noise.

Calls brms::posterior_predict() to get samples of Y_new|data.

BRMS documentation and parameters

Parameters:

Name Type Description Default
model FitResult

Fitted model from fit()

required
newdata DataFrame

Data for predictions. If None, uses original data

None
**kwargs

Additional arguments to brms::posterior_predict()

{}

Returns:

Type Description
PosteriorPredictResult

Object with .idata and .r attributes

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

Compute log-likelihood values.

Returns log p(y|theta) for each observation. Essential for model comparison via LOO-CV and WAIC.

Parameters:

Name Type Description Default
model FitResult

Fitted model from fit()

required
newdata DataFrame

Data for predictions. If None, uses original data

None
**kwargs dict

Additional arguments to brms::log_lik():

  • ndraws : int - Number of posterior draws
  • combine_chains : bool - Combine chains (default True)
{}

Returns:

Type Description
LogLikResult

Object with .idata (IDLogLik) and .r (R matrix) attributes

See Also

brms::log_lik : R documentation https://paulbuerkner.com/brms/reference/log_lik.brmsfit.html arviz.loo : Leave-One-Out Cross-Validation arviz.waic : Widely Applicable Information Criterion

Examples:

Compute log-likelihood for model comparison:

from brmspy import brms
import arviz as az

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

# LOO-CV for model comparison
loo = az.loo(model.idata)
print(loo)

Compare multiple models:

model1 = brms.fit("count ~ zAge + (1|patient)", data=epilepsy, family="poisson", chains=4)
model2 = brms.fit("count ~ zAge + zBase + (1|patient)", data=epilepsy, family="poisson", chains=4)

comp = az.compare({'model1': model1.idata, 'model2': model2.idata})
print(comp)

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

Generate Stan code using brms::make_stancode().

Useful for inspecting the generated Stan model before fitting, understanding the model structure, or using the code with other Stan interfaces.

Parameters:

Name Type Description Default
formula str or FormulaResult

brms formula specification

required
data DataFrame

Model data

required
priors list of PriorSpec

Prior specifications from prior() function

None
family str

Distribution family (gaussian, poisson, binomial, etc.)

"poisson"
sample_prior str

Whether to sample from prior: - "no": No prior samples - "yes": Include prior samples alongside posterior - "only": Sample from prior only (no data)

"no"
formula_args dict

Additional arguments passed to formula()

None

Returns:

Type Description
str

Complete Stan program code as string

See Also

brms::make_stancode : R documentation https://paulbuerkner.com/brms/reference/make_stancode.html fit : Fit model instead of just generating code make_standata : Generate Stan data block

Examples:

Generate Stan code for simple model:

from brmspy import brms
epilepsy = brms.get_brms_data("epilepsy")

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

print(stan_code[:500])  # Print first 500 characters

With custom priors:

    from brmspy import prior

    stan_code = brms.make_stancode(
        formula="count ~ zAge",
        data=epilepsy,
        priors=[prior("normal(0, 1)", class_="b")],
        family="poisson"
    )

For prior predictive checks (sample_prior="only"):

stan_code = brms.make_stancode(
    formula="count ~ zAge",
    data=epilepsy,
    family="poisson",
    sample_prior="only"
)

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 Optional[str]

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 Optional[str]

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
bhaz

Currently for experimental purposes only.

required

family(fit, **kwargs)

Extract family object from a fitted model.

Parameters:

Name Type Description Default
fit FitResult or ListVector

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'

install_brms(*, use_prebuilt=False, install_rtools=False, brms_version=None, cmdstanr_version=None, install_rstan=True, install_cmdstanr=True, rstan_version=None, activate=True, **kwargs)

Install brms R package, optionally cmdstanr and CmdStan compiler, or rstan.

WINDOWS WARNING: DO NOT run this if you have

Parameters:

Name Type Description Default
brms_version str

brms version: "latest", "2.23.0", or ">= 2.20.0"

"latest"
repo str | None

Extra CRAN repository URL

None
install_cmdstanr bool

Whether to install cmdstanr and build CmdStan compiler

True
install_rstan bool

Whether to install rstan (alternative to cmdstanr)

False
cmdstanr_version str

cmdstanr version: "latest", "0.8.1", or ">= 0.8.0"

"latest"
rstan_version str

rstan version: "latest", "2.32.6", or ">= 2.32.0"

"latest"
use_prebuilt bool

Uses fully prebuilt binaries for cmdstanr and brms and their dependencies. Ignores system R libraries and uses the latest brms and cmdstanr available for your system. Requires R>=4 and might not be compatible with some older systems or missing toolchains. Can reduce setup time by 50x.

False
install_rtools bool

Installs RTools (windows only) if they cant be found. WARNING: Modifies system path and runs the full rtools installer. Use with caution!

False

Examples:

Basic installation:

from brmspy import brms
brms.install_brms()
Install specific version:

brms.install_brms(brms_version="2.23.0")

Use rstan instead of cmdstanr:

brms.install_brms(install_cmdstanr=False, install_rstan=True)

Fast installation with prebuilt binaries: ```python brms.install_brms(use_prebuilt=True)

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

install_runtime(install_rtools=False)

Install prebuilt brmspy runtime bundle for fast setup.

Downloads and activates a precompiled runtime containing: - R packages (brms, cmdstanr, dependencies) - Compiled CmdStan binary - Complete environment ready for immediate use

This reduces setup time from ~30 minutes to ~1 minute by avoiding compilation. Available for specific platform/R version combinations.

This function reconfigures the running embedded R session to use an isolated library environment from downloaded binaries. It does not mix or break the default library tree already installed in the system.

Parameters:

Name Type Description Default
install_rtools bool

Installs RTools (windows only) if they cant be found. WARNING: Modifies system path and runs the full rtools installer.

False

Returns:

Type Description
bool

Path if installation succeeded, None otherwise

Raises:

Type Description
RuntimeError

If prebuilt binaries not available for this platform

Notes

Platform Support: Prebuilt binaries are available for: - Linux: x86_64, glibc >= 2.27, g++ >= 9 - macOS: x86_64 and arm64, clang >= 11 - Windows: x86_64 with Rtools

R Version: Runtime includes all R packages, so they must match your R installation's major.minor version (e.g., R 4.3.x).

System Fingerprint: Runtime is selected based on: - Operating system (linux/macos/windows) - CPU architecture (x86_64/arm64) - R version (major.minor)

Example: linux-x86_64-r4.3

See Also

install_brms : Main installation function

deactivate_runtime()

Deactivate current runtime and restore original R environment.

Raises:

Type Description
RuntimeError

If no runtime is currently active.

Notes

Side effects of deactivation:

  • Unloads brms/cmdstanr/rstan if loaded
  • Restores original .libPaths()
  • Restores original cmdstan path
  • Clears active_runtime from config
  • Invalidates cached R package singletons

activate_runtime(runtime_path=None)

Activate a runtime by mutating R environment.

Parameters:

Name Type Description Default
runtime_path Path or str or None

Path to runtime directory. If None, uses last active runtime from config.

None

Raises:

Type Description
ValueError

If runtime_path is None and no config exists.

FileNotFoundError

If runtime directory doesn't exist.

RuntimeError

If runtime structure is invalid or activation fails.

Notes

Side effects of activation:

  • Stores original R environment for later restoration
  • Unloads brms/cmdstanr/rstan if loaded
  • Sets R .libPaths() to runtime's Rlib/
  • Sets cmdstanr path to runtime's cmdstan/
  • Saves runtime_path to ~/.brmspy/config.json
  • Invalidates cached R package singletons

get_active_runtime()

Get path to currently active prebuilt runtime.

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

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.