_conversion
Attributes¶
__all__ = ['py_to_r', 'r_to_py']
module-attribute
¶
TypeDims = dict[str, list[str]]
module-attribute
¶
TypeCoords = dict[str, np.ndarray]
module-attribute
¶
Classes¶
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
Functions¶
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 | |
r_to_py(obj, shm=None)
¶
Convert R objects to Python objects via rpy2.
Comprehensive converter that handles R lists (named/unnamed), vectors, formulas, and language objects. Provides sensible Python equivalents for all R types with special handling for edge cases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
rpy2 R object
|
R object to convert to Python |
required |
Returns:
| Type | Description |
|---|---|
any
|
Python representation of the R object: - R NULL → None - Named list → dict (recursively) - Unnamed list → list (recursively) - Length-1 vector → scalar (int, float, str, bool) - Length-N vector → list of scalars - Formula/Language object → str (descriptive representation) - Other objects → default rpy2 conversion or str fallback |
Notes
Conversion Rules:
- R NULL: → Python None
- Atomic vectors (numeric, character, logical):
- Length 1: → Python scalar (int, float, str, bool)
- Length >1: → Python list of scalars
- Named lists (ListVector with names): → Python dict, recursively
- Unnamed lists: → Python list, recursively
- Formulas (e.g.,
y ~ x): → String representation - Language objects (calls, expressions): → String representation
- Functions: → String representation
- Everything else: Try default rpy2 conversion, fallback to string
Recursive Conversion:
List elements and dictionary values are recursively converted:
Safe Fallback:
R language objects, formulas, and functions are converted to descriptive strings rather than attempting complex conversions that might fail.
Examples:
from brmspy.helpers.conversion import r_to_py
import rpy2.robjects as ro
# R NULL
r_to_py(ro.NULL) # None
# Scalars
r_to_py(ro.IntVector([5])) # 5
r_to_py(ro.FloatVector([3.14])) # 3.14
r_to_py(ro.StrVector(["hello"])) # "hello"
# Vectors
r_to_py(ro.IntVector([1, 2, 3])) # [1, 2, 3]
See Also
py_to_r : Convert Python objects to R brmspy.brms.summary : Returns Python-friendly summary dict
Source code in brmspy/helpers/_rpy2/_converters/_dispatch.py
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 | |
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
_coerce_stan_types(stan_code, stan_data)
¶
Coerce Python numeric types to match Stan data block requirements.
Parses the Stan program's data block to determine variable types (int vs real)
and automatically coerces Python data to match. Handles both old Stan syntax
(int Y[N]) and new array syntax (array[N] int Y). Converts single-element
arrays to scalars when appropriate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stan_code
|
str
|
Complete Stan program code containing a data block |
required |
stan_data
|
dict
|
Dictionary of data to pass to Stan, with keys matching Stan variable names |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Type-coerced data dictionary with: - Integer types coerced to int/int64 where Stan expects int - Single-element arrays converted to scalars - Multi-element arrays preserved with correct dtype |
Notes
Stan Type Coercion:
Stan requires strict type matching:
- int variables must receive integer values
- real variables can receive floats
- Arrays must have consistent element types
Syntax Support:
Old Stan syntax (pre-2.26):
New Stan syntax (2.26+):
Scalar Coercion:
Single-element numpy arrays are automatically converted to scalars:
- np.array([5]) → 5
- np.array([5.0]) → 5.0
Examples:
stan_code = '''
data {
int N;
array[N] int y;
array[N] real x;
}
model {
y ~ poisson_log(x);
}
'''
# Python data with incorrect types
data = {
'N': 3.0, # Should be int
'y': np.array([1.5, 2.5, 3.5]), # Should be int
'x': np.array([0.1, 0.2, 0.3]) # OK as real
}
# Coerce to match Stan requirements
coerced = _coerce_stan_types(stan_code, data)
# Result: {'N': 3, 'y': array([1, 2, 3]), 'x': array([0.1, 0.2, 0.3])}
See Also
brmspy.brms.make_stancode : Generate Stan code from brms formula brmspy.brms.fit : Automatically applies type coercion during fitting
Source code in brmspy/helpers/_rpy2/_conversion.py
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 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 | |
_brmsfit_get_posterior(brmsfit_obj, **kwargs)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_response_names(brmsfit_obj)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
_is_unique(values)
¶
Return True if all values are unique (no duplicates).
_get_obs_id_from_r_data(r_data, n_obs)
¶
Decide obs_id for in-sample data from brmsfit$data.
Priority:
1. _obs_id_ column if present and unique.
2. rownames if present and unique.
3. fallback: np.arange(n_obs).
Source code in brmspy/helpers/_rpy2/_conversion.py
_get_obs_id_from_newdata(newdata, n_obs)
¶
Decide obs_id for newdata (out-of-sample).
Priority:
1. obs_id column if present and unique.
2. newdata.index (with warning if not unique).
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_dims_and_coords(brmsfit_obj, newdata=None, resp_names=None)
¶
Infer dims/coords for ArviZ from a brmsfit object and optional newdata.
Rules for obs_id:
- If newdata is None:
1) If obs_id column exists in fit$data and is unique: use that.
2) Else, if rownames of fit$data are unique: use those.
3) Else: use a sequential integer range [0, N).
- If newdata is not None:
1) If obs_id column exists in newdata and is unique: use that.
2) Else: use newdata.index (with a warning if not unique).
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_observed_data(brmsfit_obj, resp_names=None)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
_reshape_to_arviz(values, n_chains, n_draws)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_counts(brmsfit_obj)
¶
returns (ndraws, nchains) ndraws - draws per chain
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_predict_generic(brmsfit_obj, function='brms::posterior_predict', resp_names=None, **kwargs)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_constant_data(brmsfit_obj, newdata=None, resp_names=None)
¶
Extract constant_data for ArviZ.
- If newdata is None: use brmsfit$data.
- Else: use the provided newdata.
- Drop response columns and 'obs_id' (responses go to observed_data, obs_id is handled as a coord).
- Return a dict[var_name -> np.ndarray] with length N (N = number of rows).
Source code in brmspy/helpers/_rpy2/_conversion.py
_arviz_add_constant_data(idata, constant_data_dict, group_name='constant_data', obs_id=None)
¶
Add a non-draw group (constant_data or predictions_constant_data) to an idata.
Extracts obs_id coords directly from the existing idata. This avoids ArviZ's auto (chain, draw) dims and keeps the group purely 1D along obs_id.
Source code in brmspy/helpers/_rpy2/_conversion.py
_idata_add_resp_names_suffix(idata, suffix, resp_names)
¶
In-place: append suffix to all variables in resp_names across all
applicable InferenceData groups.
Mutates idata directly.
Source code in brmspy/helpers/_rpy2/_conversion.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