Conversion
Classes¶
Functions¶
brmsfit_to_idata(brmsfit_obj, model_data=None)
¶
Convert brmsfit -> ArviZ InferenceData (uni- and multivariate).
generic_pred_to_idata(r_pred_obj, brmsfit_obj, newdata=None, var_name='pred', az_name='posterior')
¶
Generic converter for brms prediction matrices to ArviZ InferenceData.
Flexible conversion function that handles various brms prediction types (posterior_predict, posterior_epred, posterior_linpred, log_lik) and stores them in appropriate InferenceData groups with proper structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r_pred_obj
|
rpy2 R matrix
|
Prediction matrix from any brms prediction function Shape: (total_draws, n_observations) |
required |
brmsfit_obj
|
rpy2 R object (brmsfit)
|
Fitted model for extracting chain information |
required |
newdata
|
DataFrame
|
New data used for predictions. If provided, DataFrame index is used for observation coordinates |
None
|
var_name
|
str
|
Name for the variable in the InferenceData dataset |
"pred"
|
az_name
|
str
|
InferenceData group name. Common values: - "posterior": For expected values (epred) - "posterior_predictive": For predictions with noise (predict) - "predictions": For linear predictor (linpred) - "log_likelihood": For log-likelihood values |
"posterior"
|
Returns:
| Type | Description |
|---|---|
InferenceData
|
InferenceData with single group containing reshaped predictions as xarray DataArray with proper coordinates and dimensions |
Notes
InferenceData Group Selection:
Different prediction types should use appropriate groups: - Expected values (epred): 'posterior' - deterministic E[Y|X] - Predictions (predict): 'posterior_predictive' - with observation noise - Linear predictor (linpred): 'predictions' - before link function - Log-likelihood: 'log_likelihood' - for model comparison
Coordinates:
If newdata is a DataFrame, uses its index as observation coordinates. This preserves meaningful labels (dates, IDs, etc.) in ArviZ plots.
Examples:
import pandas as pd
from brmspy.helpers.conversion import generic_pred_to_idata
# Assume we have fitted model and prediction matrix
# r_epred = brms::posterior_epred(brmsfit, newdata=test_df)
test_df = pd.DataFrame({'x': [1, 2, 3]}, index=['A', 'B', 'C'])
idata = generic_pred_to_idata(
r_pred_obj=r_epred,
brmsfit_obj=brmsfit,
newdata=test_df,
var_name="expected_y",
az_name="posterior"
)
# Access predictions
print(idata.posterior['expected_y'].dims) # ('chain', 'draw', 'obs_id')
print(idata.posterior['expected_y'].coords['obs_id']) # ['A', 'B', 'C']
See Also
brms_epred_to_idata : Convenience wrapper for posterior_epred brms_predict_to_idata : Convenience wrapper for posterior_predict brms_linpred_to_idata : Convenience wrapper for posterior_linpred brms_log_lik_to_idata : Convenience wrapper for log_lik _reshape_r_prediction_to_arviz : Internal reshaping function
brms_epred_to_idata(r_epred_obj, brmsfit_obj, newdata=None, var_name='epred')
¶
Convert brms::posterior_epred result to ArviZ InferenceData.
Convenience wrapper for converting expected value predictions (posterior_epred) to InferenceData format. Stores in 'posterior' group as deterministic expected values E[Y|X] without observation noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r_epred_obj
|
rpy2 R matrix
|
Result from brms::posterior_epred() |
required |
brmsfit_obj
|
rpy2 R object (brmsfit)
|
Fitted model |
required |
newdata
|
DataFrame
|
New data used for predictions |
None
|
var_name
|
str
|
Variable name in InferenceData |
"epred"
|
Returns:
| Type | Description |
|---|---|
InferenceData
|
InferenceData with 'posterior' group containing expected values |
Notes
posterior_epred computes the expected value of the posterior predictive distribution (i.e., the mean outcome for given predictors): - For linear regression: E[Y|X] = μ = X·β - For Poisson regression: E[Y|X] = exp(X·β) - For logistic regression: E[Y|X] = logit⁻¹(X·β)
This is stored in the 'posterior' group (not 'posterior_predictive') because it represents deterministic expected values, not noisy predictions.
See Also
brmspy.brms.posterior_epred : High-level wrapper that calls this generic_pred_to_idata : Generic conversion function brms_predict_to_idata : For predictions with observation noise
brms_predict_to_idata(r_predict_obj, brmsfit_obj, newdata=None, var_name='y')
¶
Convert brms::posterior_predict result to ArviZ InferenceData.
Convenience wrapper for converting posterior predictions (posterior_predict) to InferenceData format. Stores in 'posterior_predictive' group as predictions including observation-level noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r_predict_obj
|
rpy2 R matrix
|
Result from brms::posterior_predict() |
required |
brmsfit_obj
|
rpy2 R object (brmsfit)
|
Fitted model |
required |
newdata
|
DataFrame
|
New data used for predictions |
None
|
var_name
|
str
|
Variable name in InferenceData |
"y"
|
Returns:
| Type | Description |
|---|---|
InferenceData
|
InferenceData with 'posterior_predictive' group containing predictions |
Notes
posterior_predict generates predictions from the posterior predictive distribution, including observation-level noise: - For linear regression: Y ~ Normal(μ, σ) - For Poisson regression: Y ~ Poisson(λ) - For logistic regression: Y ~ Bernoulli(p)
These predictions include all sources of uncertainty (parameter and observation) and are useful for: - Posterior predictive checks - Generating realistic synthetic data - Assessing model fit to observed data
See Also
brmspy.brms.posterior_predict : High-level wrapper that calls this generic_pred_to_idata : Generic conversion function brms_epred_to_idata : For expected values without noise
brms_linpred_to_idata(r_linpred_obj, brmsfit_obj, newdata=None, var_name='linpred')
¶
Convert brms::posterior_linpred result to ArviZ InferenceData.
Convenience wrapper for converting linear predictor values (posterior_linpred) to InferenceData format. Stores in 'predictions' group as linear predictor values before applying the link function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r_linpred_obj
|
rpy2 R matrix
|
Result from brms::posterior_linpred() |
required |
brmsfit_obj
|
rpy2 R object (brmsfit)
|
Fitted model |
required |
newdata
|
DataFrame
|
New data used for predictions |
None
|
var_name
|
str
|
Variable name in InferenceData |
"linpred"
|
Returns:
| Type | Description |
|---|---|
InferenceData
|
InferenceData with 'predictions' group containing linear predictor |
Notes
posterior_linpred returns the linear predictor η = X·β before applying the link function: - For linear regression: linpred = μ (same as epred since link is identity) - For Poisson regression: linpred = log(λ), epred = λ - For logistic regression: linpred = logit(p), epred = p
The linear predictor is useful for: - Understanding the scale of effects before transformation - Diagnosing model specification issues - Custom post-processing with different link functions
See Also
brmspy.brms.posterior_linpred : High-level wrapper that calls this generic_pred_to_idata : Generic conversion function brms_epred_to_idata : For expected values on response scale
brms_log_lik_to_idata(r_log_lik_obj, brmsfit_obj, newdata=None, var_name='log_lik')
¶
Convert brms::log_lik result to ArviZ InferenceData.
Convenience wrapper for converting pointwise log-likelihood values (log_lik) to InferenceData format. Stores in 'log_likelihood' group for use in model comparison and diagnostics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r_log_lik_obj
|
rpy2 R matrix
|
Result from brms::log_lik() |
required |
brmsfit_obj
|
rpy2 R object (brmsfit)
|
Fitted model |
required |
newdata
|
DataFrame
|
New data for log-likelihood calculation |
None
|
var_name
|
str
|
Variable name in InferenceData |
"log_lik"
|
Returns:
| Type | Description |
|---|---|
InferenceData
|
InferenceData with 'log_likelihood' group |
Notes
log_lik computes pointwise log-likelihood values for each observation, which are essential for:
- LOO-CV: Leave-one-out cross-validation via
az.loo() - WAIC: Widely applicable information criterion via
az.waic() - Model Comparison: Compare multiple models with
az.compare() - Outlier Detection: Identify poorly fit observations
Each MCMC draw × observation gets a log-likelihood value, representing how well that parameter draw explains that specific observation.
Examples:
from brmspy import fit
import arviz as az
# Fit model (log_lik included automatically)
result = fit("y ~ x", data={"y": [1, 2, 3], "x": [1, 2, 3]})
# Model comparison with LOO-CV
loo_result = az.loo(result.idata)
print(loo_result)
# Compare multiple models
model1_idata = fit("y ~ x", data=data1).idata
model2_idata = fit("y ~ x + x2", data=data2).idata
comparison = az.compare({"model1": model1_idata, "model2": model2_idata})
See Also
brmspy.brms.log_lik : High-level wrapper that calls this generic_pred_to_idata : Generic conversion function arviz.loo : Leave-one-out cross-validation arviz.waic : WAIC computation arviz.compare : Model comparison
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
r_to_py(obj)
¶
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
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