brm
Model fitting wrappers.
This module contains the brms::brm() wrapper used by brmspy.brms.fit() /
brmspy.brms.brm().
Notes
This code executes inside the worker process (the process that hosts the embedded R session).
Attributes¶
FitResult = IDResult[IDBrm]
module-attribute
¶
ProxyListSexpVector = Union[SexpWrapper, ListSexpVector, None]
module-attribute
¶
Classes¶
SexpWrapper
dataclass
¶
Lightweight handle for an R object stored in the worker.
The worker keeps the real rpy2 Sexp in an internal cache and replaces it in
results with this wrapper. When passed back to the worker, the wrapper is
resolved to the original Sexp again.
Notes
SexpWrapperinstances are only meaningful within the lifetime of the worker process that produced them. After a worker restart, previously returned wrappers can no longer be reattached.- This type exists to keep the main process free of rpy2 / embedded-R state.
Source code in brmspy/types/session.py
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 |
dims |
dict
|
Dimension specifications for variables (inherited from |
See Also
brmspy.brms.brm : Creates fitted model results (alias: brmspy.brms.fit).
arviz.InferenceData : Base class documentation.
Examples:
from brmspy import brms
model = brms.brm("y ~ x", data=df, chains=4)
# Type checking and autocomplete
assert isinstance(model.idata, IDFit)
print(model.idata.posterior)
Source code in brmspy/types/brms_results.py
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., |
class_ |
(str, optional)
|
Parameter class: |
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., |
resp |
(str, optional)
|
Response variable for multivariate models. |
nlpar |
(str, optional)
|
Non-linear parameter name. |
lb |
(float, optional)
|
Lower bound for truncated priors. |
ub |
(float, optional)
|
Upper bound for truncated priors. |
See Also
prior : Factory function to create PriorSpec instances.
brms::prior_string : R documentation
Examples:
Create prior specifications (prefer using prior()):
from brmspy.types import PriorSpec
# Fixed effect prior
p1 = PriorSpec(prior="normal(0, 1)", class_="b")
# Group-level SD prior
p2 = PriorSpec(prior="exponential(2)", class_="sd", group="patient")
# Coefficient-specific prior with bounds
p3 = PriorSpec(prior="normal(0, 1)", class_="b", coef="age", lb=0)
Source code in brmspy/types/brms_results.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
Attributes¶
prior
instance-attribute
¶
class_ = None
class-attribute
instance-attribute
¶
coef = None
class-attribute
instance-attribute
¶
group = None
class-attribute
instance-attribute
¶
dpar = None
class-attribute
instance-attribute
¶
resp = None
class-attribute
instance-attribute
¶
nlpar = None
class-attribute
instance-attribute
¶
lb = None
class-attribute
instance-attribute
¶
ub = None
class-attribute
instance-attribute
¶
Functions¶
to_brms_kwargs()
¶
Convert PriorSpec to keyword arguments for brms::prior_string().
Maps Python dataclass fields to R function arguments, handling
the class_ -> class parameter name conversion.
Returns:
| Type | Description |
|---|---|
dict
|
Keyword arguments ready for brms::prior_string() |
Examples:
from brmspy import prior
p = prior("normal(0, 1)", class_="b", coef="age")
kwargs = p.to_brms_kwargs()
print(kwargs)
# {'prior': 'normal(0, 1)', 'class': 'b', 'coef': 'age'}
Source code in brmspy/types/brms_results.py
__init__(prior, class_=None, coef=None, group=None, dpar=None, resp=None, nlpar=None, lb=None, ub=None)
¶
FormulaConstruct
dataclass
¶
A composite formula expression built from parts.
FormulaConstruct stores a tree of nodes (FormulaPart and/or R objects)
representing expressions combined with +. It is primarily created by
calling the public formula helpers exposed by brmspy.brms.
Notes
The + operator supports grouping:
a + b + cbecomes a single summand (one “group”)(a + b) + (a + b)becomes two summands (two “groups”)
Use iter_summands()
to iterate over these groups in a deterministic way.
Source code in brmspy/types/formula_dsl.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
Attributes¶
_parts
instance-attribute
¶
Functions¶
_formula_parse(obj)
classmethod
¶
Convert a supported value into a FormulaConstruct.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Other
|
One of: |
required |
Returns:
| Type | Description |
|---|---|
FormulaConstruct
|
|
Source code in brmspy/types/formula_dsl.py
__add__(other)
¶
Combine two formula expressions with +.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Other
|
Value to add. Strings are treated as |
required |
Returns:
| Type | Description |
|---|---|
FormulaConstruct
|
New combined expression. |
Source code in brmspy/types/formula_dsl.py
__radd__(other)
¶
iter_summands()
¶
Iterate over arithmetic groups (summands).
Returns:
| Type | Description |
|---|---|
Iterator[tuple[FormulaPart | ProxyListSexpVector, ...]]
|
Each yielded tuple represents one summand/group. |
Examples:
from brmspy.brms import bf, gaussian, set_rescor
f = bf("y ~ x") + gaussian() + set_rescor(True)
for summand in f.iter_summands():
print(summand)
Source code in brmspy/types/formula_dsl.py
__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]
|
|
Source code in brmspy/types/formula_dsl.py
__str__()
¶
_pretty(node, _outer=True)
¶
Source code in brmspy/types/formula_dsl.py
__repr__()
¶
__init__(_parts)
¶
Functions¶
log(*msg, method_name=None, level=logging.INFO)
¶
Log a message with automatic method name detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
str
|
The message to log |
()
|
method_name
|
str
|
The name of the method/function. If None, will auto-detect from call stack. |
None
|
level
|
int
|
Logging level (default: logging.INFO) |
INFO
|
Source code in brmspy/helpers/log.py
log_warning(msg, method_name=None)
¶
Log a warning message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
str
|
The warning message to log |
required |
method_name
|
str
|
The name of the method/function. If None, will auto-detect from call stack. |
None
|
Source code in brmspy/helpers/log.py
brmsfit_to_idata(brmsfit_obj, model_data=None)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
kwargs_r(kwargs)
¶
Convert Python keyword arguments to R-compatible format.
Convenience function that applies py_to_r() to all values in a keyword arguments dictionary, preparing them for R function calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
dict or None
|
Dictionary of keyword arguments where values may be Python objects (dicts, lists, DataFrames, arrays, etc.) |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with same keys but R-compatible values, or empty dict if None |
Notes
This is a thin wrapper around py_to_r() that operates on dictionaries.
It's commonly used to prepare keyword arguments for R function calls via rpy2.
Examples:
from brmspy.helpers.conversion import kwargs_r
import pandas as pd
import numpy as np
# Prepare kwargs for R function
py_kwargs = {
'data': pd.DataFrame({'y': [1, 2], 'x': [1, 2]}),
'prior': {'b': [0, 1]},
'chains': 4,
'iter': 2000
}
r_kwargs = kwargs_r(py_kwargs)
# All values converted to R objects
# Can now call: r_function(**r_kwargs)
See Also
py_to_r : Underlying conversion function for individual values brmspy.brms.fit : Uses this to prepare user kwargs for R
Source code in brmspy/helpers/_rpy2/_conversion.py
py_to_r(obj)
¶
Convert arbitrary Python objects to R objects via rpy2.
Comprehensive converter that handles nested structures (dicts, lists), DataFrames, arrays, and scalars. Uses rpy2's converters with special handling for dictionaries (→ R named lists) and lists of dicts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
any
|
Python object to convert. Supported types: - None → R NULL - dict → R named list (ListVector), recursively - list/tuple of dicts → R list of named lists - list/tuple (other) → R vector or list - pd.DataFrame → R data.frame - np.ndarray → R vector/matrix - scalars (int, float, str, bool) → R atomic types |
required |
Returns:
| Type | Description |
|---|---|
rpy2 R object
|
R representation of the Python object |
Notes
Conversion Rules:
- None: → R NULL
- DataFrames: → R data.frame (via pandas2ri)
- Dictionaries: → R named list (ListVector), recursively converting values
- Lists of dicts: → R list with 1-based indexed names containing named lists
- Other lists/tuples: → R vectors or lists (via rpy2 default)
- NumPy arrays: → R vectors/matrices (via numpy2ri)
- Scalars: → R atomic values
Recursive Conversion:
Dictionary values are recursively converted, allowing nested structures:
List of Dicts:
Lists containing only dicts are converted to R lists with 1-based indexing:
Examples:
from brmspy.helpers.conversion import py_to_r
import numpy as np
import pandas as pd
# Scalars
py_to_r(5) # R: 5
py_to_r("hello") # R: "hello"
py_to_r(None) # R: NULL
# Arrays
py_to_r(np.array([1, 2, 3])) # R: c(1, 2, 3)
# DataFrames
df = pd.DataFrame({'x': [1, 2], 'y': [3, 4]})
py_to_r(df) # R: data.frame(x = c(1, 2), y = c(3, 4))
See Also
r_to_py : Convert R objects back to Python kwargs_r : Convert keyword arguments dict for R function calls brmspy.brms.fit : Uses this for converting data to R
Source code in brmspy/helpers/_rpy2/_converters/_dispatch.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | |
_build_priors(priors=None)
¶
Build R brms prior object from Python PriorSpec specifications.
Converts a sequence of PriorSpec objects to a single combined R brms prior
object by calling brms::prior_string() for each spec and combining with +.
Used internally by fit() to translate Python prior specifications to R.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
priors
|
sequence of PriorSpec
|
List of prior specifications. Each PriorSpec contains: - prior: Prior distribution string (e.g., "normal(0, 1)") - class_: Parameter class (e.g., "b", "Intercept", "sigma") - coef: Specific coefficient name (optional) - group: Group-level effects (optional) If None or empty, returns empty list (brms uses default priors) |
None
|
Returns:
| Type | Description |
|---|---|
R brmsprior object or list
|
Combined R brms prior object if priors provided, empty list otherwise |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If combined result is not a valid brmsprior object |
Notes
Prior Combination:
Multiple priors are combined using R's + operator:
This creates a single brmsprior object containing all specifications.
brms Prior Classes:
Common parameter classes: - b: Population-level effects (regression coefficients) - Intercept: Model intercept - sigma: Residual standard deviation (for gaussian family) - sd: Standard deviation of group-level effects - cor: Correlation of group-level effects
Prior String Format:
brms uses Stan-style prior specifications: - Normal: "normal(mean, sd)" - Student-t: "student_t(df, location, scale)" - Cauchy: "cauchy(location, scale)" - Exponential: "exponential(rate)" - Uniform: "uniform(lower, upper)"
Examples:
from brmspy.types import PriorSpec
from brmspy.helpers.priors import _build_priors
# Single prior for regression coefficients
priors = [
PriorSpec(
prior="normal(0, 1)",
class_="b"
)
]
brms_prior = _build_priors(priors)
See Also
brmspy.types.PriorSpec : Prior specification class brmspy.brms.fit : Uses this to convert priors for model fitting brms::prior : R brms prior specification brms::set_prior : R function for setting priors
References
.. [1] brms prior documentation: https://paul-buerkner.github.io/brms/reference/set_prior.html .. [2] Stan prior choice recommendations: https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations
Source code in brmspy/helpers/_rpy2/_priors.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
_execute_formula(formula)
¶
Source code in brmspy/_brms_functions/formula.py
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. |
()
|
**formula_args
|
Keyword arguments forwarded to R |
{}
|
Returns:
| Type | Description |
|---|---|
FormulaConstruct
|
A composable formula specification. |
See Also
brms::brmsformula : R documentation
Examples:
Basic formula:
QR decomposition (often helps with collinearity):
Multivariate formula + residual correlation:
Source code in brmspy/_brms_functions/formula.py
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. |
required |
data
|
dict or DataFrame
|
Model data. |
required |
priors
|
Sequence[PriorSpec] or None
|
Optional prior specifications created via |
None
|
family
|
str or ListSexpVector or None
|
brms family specification (e.g. |
"gaussian"
|
sample_prior
|
str
|
Passed to brms. Common values: |
"no"
|
sample
|
bool
|
If |
True
|
backend
|
str
|
Stan backend. Common values: |
"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 |
{}
|
Returns:
| Type | Description |
|---|---|
FitResult
|
Result object with |
See Also
brms::brm : R documentation
Warnings
Using cores <= 1 can be unstable in embedded R sessions and may crash the
worker process. Prefer cores >= 2.
Examples:
from brmspy import brms
fit = brms.brm("y ~ x + (1|g)", data=df, family="gaussian", chains=4, cores=4)
fit.idata.posterior
Source code in brmspy/_brms_functions/brm.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | |