_brms_module
Main brms module with Pythonic API.
Attributes¶
FitResult = IDResult[IDBrm]
module-attribute
¶
Classes¶
IDResult
dataclass
¶
Bases: Generic[T_idata], RListVectorExtension
Generic result container with arviz and R objects.
Attributes:
| Name | Type | Description |
|---|---|---|
idata |
InferenceData
|
arviz InferenceData object |
r |
ListVector
|
R object from brms |
Source code in brmspy/types/brms_results.py
LooResult
dataclass
¶
Bases: RListVectorExtension
Parsed brms::loo() result.
Attributes:
| Name | Type | Description |
|---|---|---|
estimates, pointwise, diagnostics |
DataFrame
|
LOO tables. |
psis_object |
Any or None
|
PSIS object (if present). May be an R-handle wrapper depending on conversion. |
elpd_loo, p_loo, looic |
float
|
Key scalar metrics. |
se_elpd_loo, se_p_loo, se_looic |
float
|
Standard errors for the corresponding scalars. |
Source code in brmspy/types/brms_results.py
Attributes¶
estimates
instance-attribute
¶
pointwise
instance-attribute
¶
diagnostics
instance-attribute
¶
psis_object
instance-attribute
¶
elpd_loo
instance-attribute
¶
p_loo
instance-attribute
¶
looic
instance-attribute
¶
se_elpd_loo
instance-attribute
¶
se_p_loo
instance-attribute
¶
se_looic
instance-attribute
¶
Functions¶
__repr__()
¶
Pretty print LOO-CV results.
Source code in brmspy/types/brms_results.py
__init__(r, estimates, pointwise, diagnostics, psis_object, elpd_loo, p_loo, looic, se_elpd_loo, se_p_loo, se_looic)
¶
LooCompareResult
dataclass
¶
Bases: RListVectorExtension
Result of comparing models by a LOO-style criterion.
Attributes:
| Name | Type | Description |
|---|---|---|
table |
DataFrame
|
Comparison table. |
criterion |
str
|
Criterion name (e.g. |
Source code in brmspy/types/brms_results.py
IDPosterior
¶
IDPosteriorPredictive
¶
Bases: IDConstantData
Typed .posterior_predictive extension to idata
Source code in brmspy/types/brms_results.py
IDPredictions
¶
IDLogLikelihoodInsample
¶
IDLogLikelihoodOutsample
¶
Bases: IDPredictionsConstantData
Typed .log_likelihood extension to idata
Source code in brmspy/types/brms_results.py
IDObservedData
¶
IDConstantData
¶
IDPredictionsConstantData
¶
Bases: InferenceData
Typed .predictions_constant_data extension to idata
Source code in brmspy/types/brms_results.py
RListVectorExtension
dataclass
¶
Generic result container with R objects.
Attributes:
| Name | Type | Description |
|---|---|---|
r |
ListVector
|
R object from brms |
Source code in brmspy/types/brms_results.py
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)
¶
FormulaPart
dataclass
¶
A single formula helper invocation.
Instances of this type represent a call like bf("y ~ x") or set_rescor(True)
without executing anything. They are primarily used as nodes inside a
FormulaConstruct.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
_fun
|
Literal[...]
|
Whitelisted formula helper name. |
required |
_args
|
Sequence[Primitive]
|
Positional arguments for the helper. |
required |
_kwargs
|
Mapping[str, Primitive]
|
Keyword arguments for the helper. |
required |
Notes
This is a low-level type. Most users should construct these via the public
helper functions in brmspy.brms.
Source code in brmspy/types/formula_dsl.py
Attributes¶
_fun
instance-attribute
¶
_args
instance-attribute
¶
_kwargs
instance-attribute
¶
Functions¶
__post_init__()
¶
Validate _fun, _args, and _kwargs types after construction.
Source code in brmspy/types/formula_dsl.py
__str__()
¶
Render a readable fun(arg1, ..., kw=...) representation.
Source code in brmspy/types/formula_dsl.py
__repr__()
¶
__init__(_fun, _args, _kwargs)
¶
Functions¶
log(*msg, method_name=None, level=logging.INFO)
¶
Log a message with automatic method name detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
str
|
The message to log |
()
|
method_name
|
str
|
The name of the method/function. If None, will auto-detect from call stack. |
None
|
level
|
int
|
Logging level (default: logging.INFO) |
INFO
|
Source code in brmspy/helpers/log.py
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
_get_brms()
¶
Get brms R package, importing on first access.
Source code in brmspy/_runtime/_state.py
get_brms_data(dataset_name, **kwargs)
¶
Load an example dataset from the R brms package.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Dataset name (for example |
required |
**kwargs
|
Forwarded to R |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Dataset converted to a DataFrame. |
Examples:
Source code in brmspy/_brms_functions/io.py
read_rds_fit(file, **kwargs)
¶
Load a saved brms model from an .rds file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
str
|
Input path containing a saved brmsfit. |
required |
**kwargs
|
Forwarded to R |
{}
|
Returns:
| Type | Description |
|---|---|
FitResult
|
|
Examples:
Source code in brmspy/_brms_functions/io.py
read_rds_raw(file, **kwargs)
¶
Load an R object from an .rds file via R readRDS().
This returns the raw R object handle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
str
|
Input path. |
required |
**kwargs
|
Forwarded to R |
{}
|
Returns:
| Type | Description |
|---|---|
ListSexpVector
|
Raw R object. |
Examples:
Source code in brmspy/_brms_functions/io.py
save_rds(object, file, **kwargs)
¶
Save an R object to an .rds file via R saveRDS().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object
|
RListVectorExtension or ProxyListSexpVector
|
Object to save. If you pass a |
required |
file
|
str
|
Output path. |
required |
**kwargs
|
Forwarded to R |
{}
|
Returns:
| Type | Description |
|---|---|
None
|
|
Examples:
from brmspy import brms
model = brms.brm("y ~ x", data=df, chains=4)
brms.save_rds(model, "model.rds")
Source code in brmspy/_brms_functions/io.py
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. |
required |
**kwargs
|
Additional keyword arguments forwarded to R's |
{}
|
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 |
RuntimeError
|
If conversion from the R object to a pandas DataFrame fails. |
See Also
get_brms_data
Convenience wrapper for datasets from the brms package.
Source code in brmspy/_brms_functions/io.py
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 :: |
required |
class_
|
str
|
Parameter class (e.g. |
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. |
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 |
{}
|
Returns:
| Type | Description |
|---|---|
PriorSpec
|
A typed prior specification object used by |
See Also
brms::prior_string : R documentation
Notes
This function does not validate the prior expression string itself — validation occurs inside brms.
Examples:
from brmspy.brms import prior
p_intercept = prior("student_t(3, 0, 1.95)", class_="Intercept")
p_slope = prior("normal(0, 1)", class_="b", coef="age")
p_sd = prior("exponential(2)", class_="sd", group="region")
p_trunc = prior("normal(0, 1)", class_="b", coef="income", lb=0)
Source code in brmspy/_brms_functions/prior.py
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 119 120 121 122 123 124 125 126 | |
get_prior(formula, data=None, family='gaussian', **kwargs)
¶
Get default priors for a model specification.
Wrapper around R brms::get_prior().
Returns a DataFrame with default priors for each parameter class in the specified brms model. Useful for reviewing and customizing priors before fitting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str or FormulaConstruct
|
Model formula (e.g. |
required |
data
|
DataFrame or dict
|
Dataset containing model variables. Required for data-dependent priors |
None
|
family
|
str or ListSexpVector
|
Distribution family (e.g., "gaussian", "poisson", "binomial") |
"gaussian"
|
**kwargs
|
Additional arguments passed to brms::get_prior() (e.g., autocor, data2, knots, drop_unused_levels) |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: prior, class, coef, group, resp, dpar, nlpar, lb, ub, source. Each row represents a parameter or parameter class that can have a custom prior. |
See Also
default_prior : Generic function for getting default priors prior : Create custom prior specifications brms::get_prior : R documentation
Examples:
from brmspy import brms
from brmspy.brms import prior
priors_df = brms.get_prior("y ~ x", data=df)
custom_priors = [
prior("normal(0, 0.5)", class_="b"),
prior("exponential(2)", class_="sigma"),
]
fit = brms.brm("y ~ x", data=df, priors=custom_priors, chains=4)
Source code in brmspy/_brms_functions/prior.py
default_prior(object, data=None, family='gaussian', **kwargs)
¶
Get default priors for brms model parameters (generic function).
Wrapper around R brms::default_prior().
Generic function to retrieve default prior specifications for all parameters in a brms model. Accepts formula objects, brmsformula objects, or other model specification objects. This is the generic version of get_prior().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object
|
str, FormulaResult, or ListSexpVector
|
Model specification: formula string, brmsformula object, mvbrmsformula, or any object that can be coerced to these classes |
required |
data
|
DataFrame or dict
|
Dataset containing model variables. Required for data-dependent priors |
None
|
family
|
str or ListSexpVector
|
Distribution family (e.g., "gaussian", "poisson", "binomial"). Can be a list of families for multivariate models |
"gaussian"
|
**kwargs
|
Additional arguments passed to brms::get_prior() (e.g., autocor, data2, knots, drop_unused_levels, sparse) |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: prior, class, coef, group, resp, dpar, nlpar, lb, ub, source. Each row specifies a parameter class with its default prior. The 'prior' column is empty except for internal defaults. |
See Also
get_prior : Convenience function with formula parameter prior : Create custom prior specifications brms::default_prior : R documentation
Examples:
Get default priors for a Poisson model:
from brmspy import brms
priors = brms.default_prior(
object="count ~ zAge + zBase * Trt + (1|patient)",
data=epilepsy,
family="poisson"
)
print(priors)
Use with formula object:
from brmspy import brms
f = brms.formula("y ~ x + (1|group)")
priors = brms.default_prior(f, data=df, family="gaussian")
Source code in brmspy/_brms_functions/prior.py
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 | |
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 | |
fit(formula, data, priors=None, family='gaussian', sample_prior='no', sample=True, backend='cmdstanr', formula_args=None, cores=2, *, return_idata=True, **brm_args)
¶
brm(formula: FormulaConstruct | ProxyListSexpVector | str, data: dict | pd.DataFrame, priors: Sequence[PriorSpec] | None = ..., family: str | ListSexpVector | None = ..., sample_prior: str = ..., sample: bool = ..., backend: str = ..., formula_args: dict | None = ..., cores: int | None = ..., *, return_idata: Literal[True] = True, **brm_args: Any) -> FitResult
brm(formula: FormulaConstruct | ProxyListSexpVector | str, data: dict | pd.DataFrame, priors: Sequence[PriorSpec] | None = ..., family: str | ListSexpVector | None = ..., sample_prior: str = ..., sample: bool = ..., backend: str = ..., formula_args: dict | None = ..., cores: int | None = ..., *, return_idata: Literal[False], **brm_args: Any) -> ProxyListSexpVector
Fit a Bayesian regression model with brms.
This is a thin wrapper around R brms::brm() that returns a structured
FitResult (including an ArviZ InferenceData).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str or FormulaConstruct
|
Model formula. Accepts a plain brms formula string (e.g. |
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 | |
summary(model, **kwargs)
¶
Generate comprehensive summary statistics for a fitted brms model.
Returns a SummaryResult dataclass containing model information,
parameter estimates, and diagnostic information. The SummaryResult object provides
pretty printing via str() or print() and structured access to all components.
BRMS documentation and parameters
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model returned by |
required |
**kwargs
|
Additional arguments passed to brms::summary(), such as:
- probs: Quantiles for credible intervals, e.g., |
{}
|
Returns:
| Type | Description |
|---|---|
SummaryResult
|
A dataclass containing:
|
See Also
brms::summary.brmsfit : R documentation
Examples:
Basic usage with pretty printing:
import brmspy
model = brmspy.fit("y ~ x", data=data, chains=4)
summary = brmspy.summary(model)
# Pretty print full summary
print(summary)
Access specific components:
# Get population-level effects as DataFrame
fixed_effects = summary.fixed
print(fixed_effects)
# Get family-specific parameters (e.g., sigma)
spec_params = summary.spec_pars
print(spec_params)
# Access random effects (if present)
random_effects = summary.random
for group_name, group_df in random_effects.items():
print(f"Random effects for {group_name}:")
print(group_df)
# Check model metadata
print(f"Formula: {summary.formula}")
print(f"Total draws: {summary.total_ndraws}")
print(f"Rhat reported: {summary.has_rhat}")
Custom credible intervals:
# Use 90% credible intervals instead of default 95%
summary_90 = brmspy.summary(model, probs=(0.05, 0.95))
print(summary_90.fixed)
Source code in brmspy/_brms_functions/diagnostics.py
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 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 | |
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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object
|
FitResult or ListSexpVector
|
Fitted model returned by |
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 |
False
|
probs
|
tuple of float
|
Quantiles for credible intervals, e.g., (0.025, 0.975) for 95% intervals.
Only used when |
(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 When |
See Also
brms::fixef.brmsfit : R documentation summary() : Full model summary with all parameter types
Examples:
Basic usage with summary statistics:
import brmspy
model = brmspy.fit("y ~ x1 + x2", data=data, chains=4)
# Get fixed effects summary
fixed_effects = brmspy.fixef(model)
print(fixed_effects)
# Estimate Est.Error Q2.5 Q97.5
# Intercept 10.234567 0.123456 9.992345 10.47689
# x1 0.456789 0.098765 0.263456 0.65012
# x2 -0.234567 0.087654 -0.406789 -0.06234
Get specific parameters only:
# Extract only specific coefficients
x1_x2_effects = brmspy.fixef(model, pars=["x1", "x2"])
print(x1_x2_effects)
Use robust estimates (median and MAD):
# Use median and MAD instead of mean and SD
robust_effects = brmspy.fixef(model, robust=True)
print(robust_effects)
Custom credible intervals:
Get raw posterior samples:
# Get full posterior samples matrix
samples = brmspy.fixef(model, summary=False)
print(samples.shape) # (n_iterations, n_parameters)
# Can then compute custom statistics
import numpy as np
custom_quantile = np.percentile(samples["x1"], 90)
Source code in brmspy/_brms_functions/diagnostics.py
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 | |
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: |
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 |
False
|
probs
|
tuple of float
|
Central posterior interval probabilities, as in |
(0.025, 0.975)
|
pars
|
str or sequence of str
|
Subset of group-level parameters to include. Passed to |
None
|
groups
|
str or sequence of str
|
Subset of grouping factors to include. Passed to |
None
|
**kwargs
|
Additional keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, DataArray]
|
Mapping from grouping-factor name (e.g.
|
Examples:
Compute summary random effects and inspect all coefficients for a single group level:
from brmspy import brms
from brmspy.brms import ranef
fit = brms.fit("count ~ zAge + zBase * Trt + (1 + zBase + Trt | patient)",
data=data, family="poisson")
re = ranef(fit) # summary=True by default
patient_re = re["patient"].sel(group="1", stat="Estimate")
Extract per-draw random effects for downstream MCMC analysis:
re_draws = ranef(fit, summary=False)
patient_draws = re_draws["patient"] # dims: ("draw", "group", "coef")
first_draw = patient_draws.sel(draw=0)
Source code in brmspy/_brms_functions/diagnostics.py
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 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object
|
FitResult or ListSexpVector
|
Fitted model returned by |
required |
variable
|
str or list of str
|
Specific variable name(s) to extract. If None, returns all parameters. Supports regex patterns for flexible selection. |
None
|
probs
|
tuple of float
|
Quantiles for credible intervals, e.g., (0.025, 0.975) for 95% intervals. |
(0.025, 0.975)
|
robust
|
bool
|
If True, use median and MAD instead of mean and SD for summary statistics. |
False
|
**kwargs
|
Additional arguments passed to brms::posterior_summary() |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with parameters as rows and columns for Estimate, Est.Error, and quantiles (e.g., Q2.5, Q97.5). Includes all model parameters: population-level effects, group-level effects, and auxiliary parameters. |
See Also
brms::posterior_summary : R documentation https://paulbuerkner.com/brms/reference/posterior_summary.brmsfit.html fixef() : Extract only population-level effects ranef() : Extract only group-level effects
Examples:
Get summary for all parameters:
import brmspy
model = brmspy.fit("y ~ x1 + (1|group)", data=data, chains=4)
# Get all parameter summaries
all_params = brmspy.posterior_summary(model)
print(all_params)
Extract specific parameters:
# Get summary for specific parameters
intercept = brmspy.posterior_summary(model, variable="b_Intercept")
print(intercept)
# Multiple parameters
fixed_only = brmspy.posterior_summary(model, variable=["b_Intercept", "b_x1"])
print(fixed_only)
Custom credible intervals with robust estimates:
# 90% intervals with median/MAD
robust_summary = brmspy.posterior_summary(
model,
probs=(0.05, 0.95),
robust=True
)
print(robust_summary)
Source code in brmspy/_brms_functions/diagnostics.py
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | |
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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object
|
FitResult or ListVector
|
Fitted model returned by |
required |
all
|
bool
|
If True, return all priors including default priors. If False, return only explicitly set priors. |
True
|
**kwargs
|
Additional arguments passed to brms::prior_summary() |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns describing prior specifications: - prior: Prior distribution formula - class: Parameter class (b, sd, Intercept, etc.) - coef: Specific coefficient (if applicable) - group: Grouping factor (if applicable) - resp: Response variable (for multivariate models) - dpar: Distributional parameter (if applicable) - nlpar: Non-linear parameter (if applicable) - lb/ub: Bounds for truncated priors - source: Origin of prior (default, user, etc.) |
See Also
brms::prior_summary : R documentation https://paulbuerkner.com/brms/reference/prior_summary.brmsfit.html get_prior() : Get prior structure before fitting default_prior() : Get default priors for a model
Examples:
Get all priors used in a model:
import brmspy
model = brmspy.fit(
"y ~ x1 + (1|group)",
data=data,
priors=[brmspy.prior("normal(0, 1)", "b")],
chains=4
)
# Get all priors (including defaults)
priors = brmspy.prior_summary(model)
print(priors)
Get only explicitly set priors:
# Get only user-specified priors
user_priors = brmspy.prior_summary(model, all=False)
print(user_priors)
Compare with what would be used before fitting:
# Before fitting - check default priors
default_priors = brmspy.get_prior("y ~ x1", data=data)
# After fitting - see what was actually used
used_priors = brmspy.prior_summary(model)
Source code in brmspy/_brms_functions/diagnostics.py
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 | |
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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
newdata
|
DataFrame
|
DataFrame containing new data to be validated against the model. Must include all predictor variables used in the model formula. |
required |
object
|
FitResult or ListSexpVector
|
Fitted model returned by |
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 |
None
|
resp
|
str or list of str
|
Names of response variables to validate. If specified, validation is performed only for the specified responses (relevant for multivariate models). |
None
|
check_response
|
bool
|
Whether to check if response variables are present in newdata. Set to False when making predictions where response is not needed. |
True
|
incl_autocor
|
bool
|
Whether to include autocorrelation structures originally specified in the model. If True, validates autocorrelation-related variables. |
True
|
group_vars
|
list of str
|
Names of specific grouping variables to validate. If None (default), validates all grouping variables present in the model. |
None
|
req_vars
|
list of str
|
Names of specific variables required in newdata. If None (default), all variables from the original training data are required (unless excluded by other parameters). |
None
|
**kwargs
|
Additional arguments passed to brms::validate_newdata() |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Validated DataFrame based on newdata, potentially with added or modified columns to ensure compatibility with the model. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If newdata is missing required variables |
ValueError
|
If factor levels in newdata don't match those in training data (when allow_new_levels=False) |
ValueError
|
If grouping variables have invalid structure |
See Also
brms::validate_newdata : R documentation https://paulbuerkner.com/brms/reference/validate_newdata.html posterior_predict() : Uses validate_newdata internally posterior_epred() : Uses validate_newdata internally
Examples:
Basic validation for prediction data:
import brmspy
import pandas as pd
# Fit model
model = brmspy.fit("y ~ x1 + x2", data=train_data, chains=4)
# Prepare new data
new_data = pd.DataFrame({
'x1': [1.0, 2.0, 3.0],
'x2': [0.5, 1.0, 1.5]
})
# Validate before prediction
validated_data = brmspy.validate_newdata(new_data, model)
print(validated_data)
Validate with group-level effects:
# Model with random effects
model = brmspy.fit("y ~ x + (1|group)", data=train_data, chains=4)
# New data with grouping variable
new_data = pd.DataFrame({
'x': [1.0, 2.0],
'group': ['A', 'B'] # Must match training data groups
})
# Validate - will error if groups A or B weren't in training
validated_data = brmspy.validate_newdata(
new_data,
model,
allow_new_levels=False
)
Allow new levels for population-level predictions:
# Allow new group levels (makes population-level predictions only)
new_data_with_new_groups = pd.DataFrame({
'x': [3.0, 4.0],
'group': ['C', 'D'] # New groups not in training
})
validated_data = brmspy.validate_newdata(
new_data_with_new_groups,
model,
allow_new_levels=True
)
Skip response variable checking:
# When making predictions, response not needed
new_data = pd.DataFrame({'x1': [1.0, 2.0]})
validated_data = brmspy.validate_newdata(
new_data,
model,
check_response=False
)
Source code in brmspy/_brms_functions/diagnostics.py
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 | |
call(function, *args, **kwargs)
¶
Call an R function by name with brmspy type conversion.
This is intended as an escape hatch for R/brms functionality that does not yet have a dedicated wrapper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
str
|
Function name. If not namespaced, brmspy tries |
required |
*args
|
Positional arguments. |
()
|
|
**kwargs
|
Keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Converted return value. |
Examples:
>>> from brmspy import brms
>>> fit = brms.brm("y ~ x", data=df, chains=4)
>>> aic = brms.call("stats::AIC", fit)
Source code in brmspy/_brms_functions/generic.py
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
lf(*formulas, flist=None, dpar=None, resp=None, center=None, cmc=None, sparse=None, decomp=None)
¶
Add linear formulas for distributional / non-linear parameters.
This wraps R brms::lf() and is typically used to model distributional
parameters such as sigma (heteroskedasticity) or to specify predictors
for non-linear parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*formulas
|
str | FormulaConstruct | FormulaPart | ProxyListSexpVector
|
One or more formulas such as |
()
|
flist
|
Optional list of formulas (advanced; mirrors brms). |
None
|
|
dpar
|
str or None
|
Distributional parameter name (e.g. |
None
|
resp
|
str or None
|
Response name for multivariate models. |
None
|
center
|
bool | None
|
Forwarded to R |
None
|
cmc
|
bool | None
|
Forwarded to R |
None
|
sparse
|
bool | None
|
Forwarded to R |
None
|
decomp
|
bool | None
|
Forwarded to R |
None
|
Returns:
| Type | Description |
|---|---|
FormulaConstruct
|
A composable formula specification that can be combined using |
See Also
brms::lf : R documentation
Examples:
Model mean + sigma:
Source code in brmspy/_brms_functions/formula.py
nlf(*formulas, flist=None, dpar=None, resp=None, loop=None)
¶
Add non-linear formulas.
Wraps R brms::nlf(). This is used together with set_nl() and parameter
definitions in lf() to specify non-linear models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*formulas
|
str | FormulaConstruct | FormulaPart | ProxyListSexpVector
|
One or more non-linear formulas (e.g. |
()
|
flist
|
Optional list of formulas (advanced; mirrors brms). |
None
|
|
dpar
|
str or None
|
Distributional parameter name (optional). |
None
|
resp
|
str or None
|
Response name for multivariate models. |
None
|
loop
|
bool or None
|
Forwarded to R |
None
|
Returns:
| Type | Description |
|---|---|
FormulaConstruct
|
A composable formula specification. |
See Also
brms::nlf : R documentation
Examples:
Source code in brmspy/_brms_functions/formula.py
acformula(autocor, resp=None)
¶
Add an autocorrelation structure.
Wraps R brms::acformula().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
autocor
|
str
|
One-sided autocorrelation formula (e.g. |
required |
resp
|
str or None
|
Response name for multivariate models. |
None
|
Returns:
| Type | Description |
|---|---|
FormulaConstruct
|
A composable formula specification. |
See Also
brms::acformula : R documentation
Examples:
Source code in brmspy/_brms_functions/formula.py
set_rescor(rescor=True)
¶
Control residual correlations in multivariate models.
Wraps R brms::set_rescor().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rescor
|
bool
|
Whether to model residual correlations. |
True
|
Returns:
| Type | Description |
|---|---|
FormulaConstruct
|
A composable formula specification. |
See Also
brms::set_rescor : R documentation
Examples:
Source code in brmspy/_brms_functions/formula.py
set_mecor(mecor=True)
¶
Control correlations between latent me() terms.
Wraps R brms::set_mecor().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mecor
|
bool
|
Whether to model correlations between latent variables introduced by |
True
|
Returns:
| Type | Description |
|---|---|
FormulaConstruct
|
A composable formula specification. |
See Also
brms::set_mecor : R documentation
Examples:
Source code in brmspy/_brms_functions/formula.py
set_nl(dpar=None, resp=None)
¶
Mark a model (or part of it) as non-linear.
Wraps R brms::set_nl().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dpar
|
str or None
|
Distributional parameter name (if only part of the model is non-linear). |
None
|
resp
|
str or None
|
Response name for multivariate models. |
None
|
Returns:
| Type | Description |
|---|---|
FormulaConstruct
|
A composable formula specification. |
See Also
brms::set_nl : R documentation
Examples:
from brmspy.brms import bf, lf, set_nl
f = bf("y ~ a * inv_logit(x * b)") + lf("a + b ~ z") + set_nl()
Source code in brmspy/_brms_functions/formula.py
formula(*formulas, **formula_args)
¶
Build a brms model formula.
This is the primary entrypoint for specifying the mean model and can be
combined with other formula parts (e.g. lf, nlf, acformula) using +.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*formulas
|
str
|
One or more brms formula strings (e.g. |
()
|
**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
posterior_epred(model, newdata=None, **kwargs)
¶
Compute expected posterior predictions (noise-free).
Wrapper around R brms::posterior_epred(). This returns draws of the
expected value (typically on the response scale), without observation noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
newdata
|
DataFrame or None
|
New data for predictions. If |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
PosteriorEpredResult
|
Result containing |
See Also
brms::posterior_epred : R documentation
Examples:
from brmspy import brms
fit = brms.brm("y ~ x", data=df, chains=4)
ep = brms.posterior_epred(fit)
ep.idata.posterior
Source code in brmspy/_brms_functions/prediction.py
posterior_linpred(model, newdata=None, **kwargs)
¶
Draw from the linear predictor.
Wrapper around R brms::posterior_linpred(). This typically returns draws
on the link scale (before applying the inverse link), unless you pass
transform=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
newdata
|
DataFrame or None
|
New data for predictions. If |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
PosteriorLinpredResult
|
Result containing |
See Also
brms::posterior_linpred : R documentation
Examples:
from brmspy import brms
fit = brms.brm("y ~ x", data=df, chains=4)
lp = brms.posterior_linpred(fit, transform=False)
lp.idata.predictions
Source code in brmspy/_brms_functions/prediction.py
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 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | |
posterior_predict(model, newdata=None, **kwargs)
¶
Draw from the posterior predictive distribution (includes observation noise).
Wrapper around R brms::posterior_predict().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
newdata
|
DataFrame or None
|
New data for predictions. If |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
PosteriorPredictResult
|
Result containing |
See Also
brms::posterior_predict : R documentation
Examples:
from brmspy import brms
fit = brms.brm("y ~ x", data=df, chains=4)
pp = brms.posterior_predict(fit)
pp.idata.posterior_predictive
Source code in brmspy/_brms_functions/prediction.py
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 | |
log_lik(model, newdata=None, **kwargs)
¶
Compute pointwise log-likelihood draws.
Wrapper around R brms::log_lik(). The result is useful for LOO/WAIC via ArviZ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
newdata
|
DataFrame or None
|
New data. If |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
LogLikResult
|
Result containing |
See Also
brms::log_lik : R documentation
Examples:
from brmspy import brms
import arviz as az
fit = brms.brm("y ~ x", data=df, chains=4)
ll = brms.log_lik(fit)
az.loo(ll.idata)
Source code in brmspy/_brms_functions/prediction.py
posterior(model, **kwargs)
¶
Return posterior draws as idata.
Wrapper around R posterior::as_draws_df().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
PosteriorEpredResult
|
Result containing |
Examples:
from brmspy import brms
fit = brms.brm("y ~ x", data=df, chains=4)
ep = brms.posterior(fit)
ep.idata.posterior
Source code in brmspy/_brms_functions/prediction.py
observed_data(model)
¶
Source code in brmspy/_brms_functions/prediction.py
make_stancode(formula, data, priors=None, family='poisson', sample_prior='no', formula_args=None)
¶
Generate Stan code using R brms::make_stancode().
Useful for inspecting the generated Stan model before fitting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str or FormulaConstruct
|
Model formula. |
required |
data
|
DataFrame
|
Model data. |
required |
priors
|
Sequence[PriorSpec] or None
|
Optional prior specifications created via |
None
|
family
|
str
|
Distribution family (e.g. |
"poisson"
|
sample_prior
|
str
|
Prior sampling mode passed to brms ( |
"no"
|
formula_args
|
dict or None
|
Reserved for future use. Currently ignored. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Complete Stan program as a string. |
See Also
brms::make_stancode : R documentation
Examples:
from brmspy import brms
epilepsy = brms.get_brms_data("epilepsy")
code = brms.make_stancode(
"count ~ zAge + zBase * Trt + (1|patient)",
data=epilepsy,
family="poisson",
)
assert isinstance(code, str)
Source code in brmspy/_brms_functions/stan.py
brmsfamily(family, link=None, link_sigma='log', link_shape='log', link_nu='logm1', link_phi='log', link_kappa='log', link_beta='log', link_zi='logit', link_hu='logit', link_zoi='logit', link_coi='logit', link_disc='log', link_bs='log', link_ndt='log', link_bias='logit', link_xi='log1p', link_alpha='identity', link_quantile='logit', threshold='flexible', refcat=None, **kwargs)
¶
Family objects provide a convenient way to specify the details of the models used by many model fitting functions. The family functions presented here are for use with brms only and will not work with other model fitting functions such as glm or glmer. However, the standard family functions as described in family will work with brms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
family
|
A character string naming the distribution family of the response variable to be used in the model. Currently, the following families are supported: gaussian, student, binomial, bernoulli, beta-binomial, poisson, negbinomial, geometric, Gamma, skew_normal, lognormal, shifted_lognormal, exgaussian, wiener, inverse.gaussian, exponential, weibull, frechet, Beta, dirichlet, von_mises, asym_laplace, gen_extreme_value, categorical, multinomial, cumulative, cratio, sratio, acat, hurdle_poisson, hurdle_negbinomial, hurdle_gamma, hurdle_lognormal, hurdle_cumulative, zero_inflated_binomial, zero_inflated_beta_binomial, zero_inflated_beta, zero_inflated_negbinomial, zero_inflated_poisson, and zero_one_inflated_beta. |
required | |
link
|
str | None
|
A specification for the model link function. This can be a name/expression or character string. See the 'Details' section for more information on link functions supported by each family. |
None
|
link_sigma
|
str
|
Link of auxiliary parameter sigma if being predicted. |
'log'
|
link_shape
|
str
|
Link of auxiliary parameter shape if being predicted. |
'log'
|
link_nu
|
str
|
Link of auxiliary parameter nu if being predicted. |
'logm1'
|
link_phi
|
str
|
Link of auxiliary parameter phi if being predicted. |
'log'
|
link_kappa
|
str
|
Link of auxiliary parameter kappa if being predicted. |
'log'
|
link_beta
|
str
|
Link of auxiliary parameter beta if being predicted. |
'log'
|
link_zi
|
str
|
Link of auxiliary parameter zi if being predicted. |
'logit'
|
link_hu
|
str
|
Link of auxiliary parameter hu if being predicted. |
'logit'
|
link_zoi
|
str
|
Link of auxiliary parameter zoi if being predicted. |
'logit'
|
link_coi
|
str
|
Link of auxiliary parameter coi if being predicted. |
'logit'
|
link_disc
|
str
|
Link of auxiliary parameter disc if being predicted. |
'log'
|
link_bs
|
str
|
Link of auxiliary parameter bs if being predicted. |
'log'
|
link_ndt
|
str
|
Link of auxiliary parameter ndt if being predicted. |
'log'
|
link_bias
|
str
|
Link of auxiliary parameter bias if being predicted. |
'logit'
|
link_xi
|
str
|
Link of auxiliary parameter xi if being predicted. |
'log1p'
|
link_alpha
|
str
|
Link of auxiliary parameter alpha if being predicted. |
'identity'
|
link_quantile
|
str
|
Link of auxiliary parameter quantile if being predicted. |
'logit'
|
threshold
|
str
|
A character string indicating the type of thresholds (i.e. intercepts) used in an ordinal model. "flexible" provides the standard unstructured thresholds, "equidistant" restricts the distance between consecutive thresholds to the same value, and "sum_to_zero" ensures the thresholds sum to zero. |
'flexible'
|
refcat
|
str | None
|
Optional name of the reference response category used in categorical, multinomial, dirichlet and logistic_normal models. If NULL (the default), the first category is used as the reference. If NA, all categories will be predicted, which requires strong priors or carefully specified predictor terms in order to lead to an identified model. |
None
|
Source code in brmspy/_brms_functions/families.py
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 119 120 | |
family(fit, **kwargs)
¶
Extract family object from a fitted model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit
|
FitResult or ListSexpVector
|
Fitted brms model |
required |
Source code in brmspy/_brms_functions/families.py
student(link='identity', link_sigma='log', link_nu='logm1', **kwargs)
¶
Student's t distribution for robust regression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'identity'
|
link_sigma
|
str
|
Link function for sigma parameter |
'log'
|
link_nu
|
str
|
Link function for degrees of freedom parameter |
'logm1'
|
Source code in brmspy/_brms_functions/families.py
bernoulli(link='logit', **kwargs)
¶
Bernoulli distribution for binary 0/1 outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the probability parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
beta_binomial(link='logit', link_phi='log', **kwargs)
¶
Beta-binomial distribution for overdispersed binomial data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the probability parameter |
'logit'
|
link_phi
|
str
|
Link function for the precision parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
negbinomial(link='log', link_shape='log', **kwargs)
¶
Negative binomial distribution for overdispersed count data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'log'
|
link_shape
|
str
|
Link function for the shape parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
negbinomial2(link='log', link_sigma='log', **kwargs)
¶
geometric(link='log', **kwargs)
¶
Geometric distribution for count data (negative binomial with shape=1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'log'
|
Source code in brmspy/_brms_functions/families.py
discrete_weibull(link='logit', link_shape='log', **kwargs)
¶
com_poisson(link='log', link_shape='log', **kwargs)
¶
lognormal(link='identity', link_sigma='log', **kwargs)
¶
Lognormal distribution for positive continuous data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean on log scale |
'identity'
|
link_sigma
|
str
|
Link function for sigma parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
shifted_lognormal(link='identity', link_sigma='log', link_ndt='log', **kwargs)
¶
Shifted lognormal distribution with non-decision time parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'identity'
|
link_sigma
|
str
|
Link function for sigma parameter |
'log'
|
link_ndt
|
str
|
Link function for non-decision time parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
skew_normal(link='identity', link_sigma='log', link_alpha='identity', **kwargs)
¶
Skew normal distribution for asymmetric continuous data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'identity'
|
link_sigma
|
str
|
Link function for sigma parameter |
'log'
|
link_alpha
|
str
|
Link function for skewness parameter |
'identity'
|
Source code in brmspy/_brms_functions/families.py
exponential(link='log', **kwargs)
¶
Exponential distribution for time-to-event data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the rate parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
weibull(link='log', link_shape='log', **kwargs)
¶
Weibull distribution for survival and reliability analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the scale parameter |
'log'
|
link_shape
|
str
|
Link function for the shape parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
frechet(link='log', link_nu='logm1', **kwargs)
¶
Frechet distribution for extreme value analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the scale parameter |
'log'
|
link_nu
|
str
|
Link function for the shape parameter |
'logm1'
|
Source code in brmspy/_brms_functions/families.py
gen_extreme_value(link='identity', link_sigma='log', link_xi='log1p', **kwargs)
¶
Generalized extreme value distribution for extreme events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the location parameter |
'identity'
|
link_sigma
|
str
|
Link function for the scale parameter |
'log'
|
link_xi
|
str
|
Link function for the shape parameter |
'log1p'
|
Source code in brmspy/_brms_functions/families.py
exgaussian(link='identity', link_sigma='log', link_beta='log', **kwargs)
¶
Ex-Gaussian distribution for reaction time data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'identity'
|
link_sigma
|
str
|
Link function for Gaussian SD parameter |
'log'
|
link_beta
|
str
|
Link function for exponential rate parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
wiener(link='identity', link_bs='log', link_ndt='log', link_bias='logit', **kwargs)
¶
Wiener diffusion model for two-choice reaction time data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for drift rate |
'identity'
|
link_bs
|
str
|
Link function for boundary separation |
'log'
|
link_ndt
|
str
|
Link function for non-decision time |
'log'
|
link_bias
|
str
|
Link function for initial bias |
'logit'
|
Source code in brmspy/_brms_functions/families.py
Beta(link='logit', link_phi='log', **kwargs)
¶
Beta distribution for data between 0 and 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'logit'
|
link_phi
|
str
|
Link function for the precision parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
xbeta(link='logit', link_phi='log', link_kappa='log', **kwargs)
¶
Extended beta distribution with additional shape parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'logit'
|
link_phi
|
str
|
Link function for precision parameter |
'log'
|
link_kappa
|
str
|
Link function for kappa shape parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
dirichlet(link='logit', link_phi='log', refcat=None, **kwargs)
¶
Dirichlet distribution for compositional data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'logit'
|
link_phi
|
str
|
Link function for the precision parameter |
'log'
|
refcat
|
str
|
Reference category |
None
|
Source code in brmspy/_brms_functions/families.py
dirichlet2(link='log', refcat=None, **kwargs)
¶
Source code in brmspy/_brms_functions/families.py
logistic_normal(link='identity', link_sigma='log', refcat=None, **kwargs)
¶
Logistic-normal distribution for compositional data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'identity'
|
link_sigma
|
str
|
Link function for sigma parameter |
'log'
|
refcat
|
str
|
Reference category |
None
|
Source code in brmspy/_brms_functions/families.py
von_mises(link='tan_half', link_kappa='log', **kwargs)
¶
Von Mises distribution for circular/directional data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean direction |
'tan_half'
|
link_kappa
|
str
|
Link function for concentration parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
asym_laplace(link='identity', link_sigma='log', link_quantile='logit', **kwargs)
¶
Asymmetric Laplace distribution for quantile regression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the location |
'identity'
|
link_sigma
|
str
|
Link function for sigma parameter |
'log'
|
link_quantile
|
str
|
Link function for the quantile parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
zero_inflated_asym_laplace(link='identity', link_sigma='log', link_quantile='logit', link_zi='logit', **kwargs)
¶
Source code in brmspy/_brms_functions/families.py
cox(link='log', **kwargs)
¶
Cox proportional hazards model for survival data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the hazard rate |
'log'
|
Source code in brmspy/_brms_functions/families.py
hurdle_poisson(link='log', link_hu='logit', **kwargs)
¶
Hurdle Poisson distribution for zero-inflated count data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'log'
|
link_hu
|
str
|
Link function for hurdle parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
hurdle_negbinomial(link='log', link_shape='log', link_hu='logit', **kwargs)
¶
Hurdle negative binomial for overdispersed zero-inflated count data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'log'
|
link_shape
|
str
|
Link function for shape parameter |
'log'
|
link_hu
|
str
|
Link function for hurdle parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
hurdle_gamma(link='log', link_shape='log', link_hu='logit', **kwargs)
¶
Hurdle Gamma distribution for zero-inflated positive continuous data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'log'
|
link_shape
|
str
|
Link function for shape parameter |
'log'
|
link_hu
|
str
|
Link function for hurdle parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
hurdle_lognormal(link='identity', link_sigma='log', link_hu='logit', **kwargs)
¶
Hurdle lognormal for zero-inflated positive continuous data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'identity'
|
link_sigma
|
str
|
Link function for sigma parameter |
'log'
|
link_hu
|
str
|
Link function for hurdle parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
hurdle_cumulative(link='logit', link_hu='logit', link_disc='log', threshold='flexible', **kwargs)
¶
Hurdle cumulative for zero-inflated ordinal data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the ordinal response |
'logit'
|
link_hu
|
str
|
Link function for hurdle parameter |
'logit'
|
link_disc
|
str
|
Link function for discrimination parameter |
'log'
|
threshold
|
str
|
Type of threshold structure |
'flexible'
|
Source code in brmspy/_brms_functions/families.py
zero_inflated_beta(link='logit', link_phi='log', link_zi='logit', **kwargs)
¶
Zero-inflated beta for data between 0 and 1 with excess zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'logit'
|
link_phi
|
str
|
Link function for precision parameter |
'log'
|
link_zi
|
str
|
Link function for zero-inflation parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
zero_one_inflated_beta(link='logit', link_phi='log', link_zoi='logit', link_coi='logit', **kwargs)
¶
Zero-one-inflated beta for data between 0 and 1 with excess zeros and ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'logit'
|
link_phi
|
str
|
Link function for precision parameter |
'log'
|
link_zoi
|
str
|
Link function for zero-or-one inflation parameter |
'logit'
|
link_coi
|
str
|
Link function for conditional one inflation parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
zero_inflated_poisson(link='log', link_zi='logit', **kwargs)
¶
Zero-inflated Poisson for count data with excess zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'log'
|
link_zi
|
str
|
Link function for zero-inflation parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
zero_inflated_negbinomial(link='log', link_shape='log', link_zi='logit', **kwargs)
¶
Zero-inflated negative binomial for overdispersed count data with excess zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'log'
|
link_shape
|
str
|
Link function for shape parameter |
'log'
|
link_zi
|
str
|
Link function for zero-inflation parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
zero_inflated_binomial(link='logit', link_zi='logit', **kwargs)
¶
Zero-inflated binomial for binary count data with excess zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for probability parameter |
'logit'
|
link_zi
|
str
|
Link function for zero-inflation parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
zero_inflated_beta_binomial(link='logit', link_phi='log', link_zi='logit', **kwargs)
¶
Zero-inflated beta-binomial for overdispersed binomial data with excess zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for probability parameter |
'logit'
|
link_phi
|
str
|
Link function for precision parameter |
'log'
|
link_zi
|
str
|
Link function for zero-inflation parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
categorical(link='logit', refcat=None, **kwargs)
¶
Categorical distribution for unordered multi-category outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for category probabilities |
'logit'
|
refcat
|
str
|
Reference category |
None
|
Source code in brmspy/_brms_functions/families.py
multinomial(link='logit', refcat=None, **kwargs)
¶
Multinomial distribution for count data across multiple categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for category probabilities |
'logit'
|
refcat
|
str
|
Reference category |
None
|
Source code in brmspy/_brms_functions/families.py
dirichlet_multinomial(link='logit', link_phi='log', refcat=None, **kwargs)
¶
Dirichlet-multinomial for overdispersed categorical count data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for category probabilities |
'logit'
|
link_phi
|
str
|
Link function for precision parameter |
'log'
|
refcat
|
str
|
Reference category |
None
|
Source code in brmspy/_brms_functions/families.py
cumulative(link='logit', link_disc='log', threshold='flexible', **kwargs)
¶
Cumulative (proportional odds) model for ordinal outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for cumulative probabilities |
'logit'
|
link_disc
|
str
|
Link function for discrimination parameter |
'log'
|
threshold
|
str
|
Type of threshold structure |
'flexible'
|
Source code in brmspy/_brms_functions/families.py
sratio(link='logit', link_disc='log', threshold='flexible', **kwargs)
¶
Sequential (stopping) ratio model for ordinal outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for sequential ratios |
'logit'
|
link_disc
|
str
|
Link function for discrimination parameter |
'log'
|
threshold
|
str
|
Type of threshold structure |
'flexible'
|
Source code in brmspy/_brms_functions/families.py
cratio(link='logit', link_disc='log', threshold='flexible', **kwargs)
¶
Continuation ratio model for ordinal outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for continuation ratios |
'logit'
|
link_disc
|
str
|
Link function for discrimination parameter |
'log'
|
threshold
|
str
|
Type of threshold structure |
'flexible'
|
Source code in brmspy/_brms_functions/families.py
acat(link='logit', link_disc='log', threshold='flexible', **kwargs)
¶
Adjacent category model for ordinal outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for adjacent category ratios |
'logit'
|
link_disc
|
str
|
Link function for discrimination parameter |
'log'
|
threshold
|
str
|
Type of threshold structure |
'flexible'
|
Source code in brmspy/_brms_functions/families.py
gaussian(link='identity', link_sigma='log', **kwargs)
¶
Gaussian (normal) distribution for continuous data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'identity'
|
link_sigma
|
str
|
Link function for the standard deviation |
'log'
|
Source code in brmspy/_brms_functions/families.py
poisson(link='log', **kwargs)
¶
Poisson distribution for count data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the rate parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
binomial(link='logit', **kwargs)
¶
Binomial distribution for binary count data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the probability parameter |
'logit'
|
Source code in brmspy/_brms_functions/families.py
Gamma(link='log', link_shape='log', **kwargs)
¶
Gamma distribution for positive continuous data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'log'
|
link_shape
|
str
|
Link function for the shape parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
inverse_gaussian(link='1/mu^2', link_shape='log', **kwargs)
¶
Inverse Gaussian distribution for positive continuous data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
str
|
Link function for the mean |
'1/mu^2'
|
link_shape
|
str
|
Link function for the shape parameter |
'log'
|
Source code in brmspy/_brms_functions/families.py
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:
Source code in brmspy/_runtime/__init__.py
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 |
Notes
This function is a pure lookup: it does not install, activate, or modify any runtime state.
Source code in brmspy/_runtime/__init__.py
get_active_runtime()
¶
Get path to currently active prebuilt runtime.
Returns CONFIGURED runtime, not whether it is loaded.
Returns:
| Type | Description |
|---|---|
Path or None
|
Path to active runtime directory, or None if not configured |
Notes
Returns None if: - No runtime configured in config file - Config file doesn't exist - Config file is corrupted
Examples:
from brmspy import get_active_runtime
runtime_path = get_active_runtime()
if runtime_path and runtime_path.exists():
print(f"Active runtime: {runtime_path}")
else:
print("No active runtime configured")
Source code in brmspy/_runtime/__init__.py
status()
¶
Query current runtime status without side effects.
Returns:
| Type | Description |
|---|---|
RuntimeStatus
|
Dataclass with comprehensive state information including:
|