API Reference
This API reference provides detailed documentation for the classes and functions in the pybmc package. It is automatically generated from the docstrings in the source code.
Dataset
A general-purpose dataset class for loading and managing model data for Bayesian model combination workflows.
Supports .h5 and .csv files, and provides data splitting functionality.
Source code in pybmc/data.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 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 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 | |
__init__(data_source=None, verbose=True)
Initialize the Dataset object.
:param data_source: Path to the data file (.h5 or .csv). :param verbose: If True, display warnings and informational messages. Default is True.
Source code in pybmc/data.py
get_subset(property_name, filters=None, models_to_include=None)
Return a filtered, wide-format DataFrame for a given property.
:param property_name: Name of the property (e.g., "BE", "ChRad"). :param filters: Dictionary of filtering rules applied to the domain columns (e.g., {"Z": (26, 28)}). :param models_to_include: Optional list of model names to retain in the output. If None, all model columns are retained. :return: Filtered wide-format DataFrame with columns: domain keys + model columns.
Source code in pybmc/data.py
load_data(models, keys=None, domain_keys=None, model_column='model', truth_column_name=None)
Load data for each property and return a dictionary of synchronized DataFrames. Each DataFrame has columns: domain_keys + one column per model for that property.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
list
|
List of model names (for HDF5 keys or filtering CSV). |
required |
keys
|
list
|
List of property names to extract (each will be a key in the output dict). |
None
|
domain_keys
|
list
|
List of columns used to define the common domain (default ['N', 'Z']). |
None
|
model_column
|
str
|
Name of the column in the CSV that identifies which model each row belongs to. Only used for CSV files; ignored for HDF5 files. |
'model'
|
truth_column_name
|
str
|
Name of the truth model. If provided, the truth data will be left-joined to the common domain of the other models, allowing the truth data to have a smaller domain than the models. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary where each key is a property name and each value is a DataFrame with columns: domain_keys + one column per model for that property. The DataFrames are synchronized to the intersection of the domains for all models. If truth_column_name is provided, truth data is left-joined (may have NaN values). |
Supports both .h5 and .csv files.
Source code in pybmc/data.py
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 | |
separate_points_distance_allSets(list1, list2, distance1, distance2)
Separates points in list1 into three groups based on their proximity to any point in list2.
:param list1: List of (x, y) tuples. :param list2: List of (x, y) tuples. :param distance: The threshold distance to determine proximity. :return: Two lists - close_points and distant_points.
Source code in pybmc/data.py
split_data(data_dict, property_name, splitting_algorithm='random', **kwargs)
Split data into training, validation, and testing sets using random or inside-to-outside logic.
:param data_dict: Dictionary output from load_data, where keys are property names and values are DataFrames.
:param property_name: The key in data_dict specifying which DataFrame to use for splitting.
:param splitting_algorithm: 'random' (default) or 'inside_to_outside'.
:param kwargs: Additional arguments depending on the chosen algorithm.
For 'random': train_size, val_size, test_size
For 'inside_to_outside': stable_points (list of (x, y)), distance1, distance2
:return: Tuple of train, validation, test datasets as DataFrames.
Source code in pybmc/data.py
view_data(property_name=None, model_name=None)
View data flexibly based on input parameters.
- No arguments: returns available property names and model names.
- property_name only: returns the full DataFrame for that property.
- model_name only: Return model values across all properties.
- property_name + model_name: returns a Series of values for the model.
:param property_name: Optional property name :param model_name: Optional model name :return: dict, DataFrame, or Series depending on input.
Source code in pybmc/data.py
BayesianModelCombination
The main idea of this class is to perform Bayesian Model Combination (BMC) on the set of models that we choose from the dataset class. What should this class contain: + Orthogonalization step. + Perform Bayesian inference on the training data that we extract from the Dataset class. + Predictions for certain isotopes.
Source code in pybmc/bmc.py
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 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 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 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 | |
__init__(models_list, data_dict, truth_column_name, weights=None, constraint='unconstrained', error_model='homoscedastic')
Initialize the BayesianModelCombination class.
:param models_list: List of model names
:param data_dict: Dictionary from load_data() where each key is a model name and each value is a DataFrame of properties
:param truth_column_name: Name of the column containing the truth values.
:param weights: Optional initial weights for the models.
:param constraint: Weight constraint mode. Options:
- "unconstrained" (default): No constraints on model weights.
- "simplex": Forces weights to lie on the probability simplex
(each weight between 0 and 1, weights sum to 1). Uses a
Metropolis-within-Gibbs sampler to enforce the constraint.
:param error_model: Noise structure of the combination. Options
(see :mod:pybmc.error_models for the variance forms):
- "homoscedastic" (default): A single constant variance.
- "hetero_pc_dist" / "hetero_pc_dist_quad": Variance
linear/quadratic in the distance from the training centroid
in principal-component space.
- "hetero_model_var" / "hetero_model_var_quad": Variance
linear/quadratic in the spread among model predictions.
- "hetero_combined_linear" / "hetero_combined_quadratic":
Variance depending on both metrics.
Heteroscedastic error models currently require the
"unconstrained" weight mode.
Source code in pybmc/bmc.py
evaluate(domain_filter=None, seed=DEFAULT_PREDICTIVE_SEED)
Evaluate the model combination using coverage calculation.
:param domain_filter: dict with optional domain key ranges, e.g., {"Z": (20, 30), "N": (20, 40)} :param seed: Seed for the posterior predictive draws underlying the coverage calculation. Defaults to a fixed constant so repeated calls are reproducible. :return: coverage list for each percentile
Source code in pybmc/bmc.py
get_weights(summary=True)
Compute model weights from posterior samples.
Converts the sampled coefficient vectors (beta) into model weights
using the transformation omega = beta @ Vt_hat + 1/M, where M is
the number of models. In simplex-constrained mode, all weights are
guaranteed to be non-negative and sum to 1.
:param summary: If True (default), return a dictionary with
'mean', 'std', 'median' arrays keyed by statistic.
If False, return the full (n_samples, n_models) weight matrix.
:return: Weight summary dict or full weight matrix.
:raises ValueError: If train() has not been called.
Source code in pybmc/bmc.py
orthogonalize(property, train_df, components_kept)
Perform orthogonalization for the specified property using training data.
:param property: The nuclear property to orthogonalize on (e.g., 'BE'). :param train_index: Training data from split_data :param components_kept: Number of SVD components to retain.
Source code in pybmc/bmc.py
predict(property, seed=DEFAULT_PREDICTIVE_SEED)
Predict a specified property using the model weights learned during training.
:param property: The property name to predict (e.g., 'ChRad'). :param seed: Seed for the posterior predictive draws (subsampling of the posterior samples and the noise added on top). Defaults to a fixed constant so repeated calls are reproducible; pass a different value for independent draws. :return: - rndm_m: array of shape (n_samples, n_points), full posterior draws - lower_df: DataFrame with columns domain_keys + ['Predicted_Lower'] - median_df: DataFrame with columns domain_keys + ['Predicted_Median'] - upper_df: DataFrame with columns domain_keys + ['Predicted_Upper']
Source code in pybmc/bmc.py
train(training_options=None)
Train the model combination using training data and optional training parameters.
All error models (the homoscedastic one included) share the
likelihood y_i ~ N(X_i . b, sigma_i^2) and are trained with
the same Gibbs-within-Metropolis sampler; the homoscedastic
model is simply the case where the variance basis is the
constant column alone, so sigma_i^2 = sigma^2.
:param training_options: Dictionary of training options. Keys:
- 'iterations': (int) Number of retained Gibbs samples (default 50000)
- 'sampler': (str) Override the constraint mode for this training run.
"unconstrained" or "simplex". If not provided, uses the
instance-level self.constraint set at initialization.
- 'error_model': (str) Override the error model for this training
run (see VALID_ERROR_MODELS). If not provided, uses the
instance-level self.error_model set at initialization.
- 'seed': (int) Seed for the sampler. If not provided, the
sampler draws from the shared package-wide generator
(see :mod:pybmc.rng), which is seeded at import.
- 'b_mean_prior': (np.ndarray) Prior mean vector (default zeros)
(unconstrained sampler)
- 'b_mean_cov': (np.ndarray) Prior covariance matrix (default diag(S_hat²))
(unconstrained sampler)
- 'nu0_chosen': (float) Degrees of freedom for variance prior (default 1.0)
(simplex sampler only)
- 'sigma20_chosen': (float) Prior variance (default 0.02)
(simplex sampler only)
- 'burn': (int) Burn-in iterations (default 10000 for simplex,
5000 otherwise)
- 'stepsize': (float) Proposal step size (default 0.001)
(simplex sampler only)
- 'proposal_scales': (list) Diagonal of the Metropolis-Hastings
proposal covariance for the variance parameters; sensible
per-model defaults are used if omitted
(unconstrained sampler)
- 'init_params': (list) Initial values for the non-constant
variance parameters (unconstrained sampler)
- 'prior_spec': (list of (shape, scale)) Gamma priors for the
variance parameters (unconstrained sampler)
- 'adapt_proposal': (bool) Rescale the proposal during burn-in
toward 'target_acceptance' (default True)
(unconstrained sampler)
- 'target_acceptance': (float) Acceptance rate targeted by the
burn-in adaptation (default 0.25)
(unconstrained sampler)
After training with the unconstrained sampler, the
Metropolis-Hastings acceptance rate of the variance parameters
is available in self.mh_acceptance_rate_.
Source code in pybmc/bmc.py
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 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 | |
USVt_hat_extraction(U, S, Vt, components_kept)
Extracts reduced-dimensionality matrices from SVD results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
U
|
ndarray
|
Left singular vectors. |
required |
S
|
ndarray
|
Singular values. |
required |
Vt
|
ndarray
|
Right singular vectors (transposed). |
required |
components_kept
|
int
|
Number of components to retain. |
required |
Returns:
| Type | Description |
|---|---|
|
tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]:
- |
Source code in pybmc/inference_utils.py
gibbs_sampler(y, X, iterations, prior_info=None, burn=5000, seed=None)
Gibbs sampler for the homoscedastic (constant-variance) model.
The homoscedastic model is the constant-only special case of the
heteroscedastic likelihood (sigma_i^2 = sigma^2 for every point),
so this is a thin wrapper around gibbs_sampler_heteroscedastic
with a constant-only variance basis. There is no separate
homoscedastic likelihood implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ndarray
|
Response vector (centered). |
required |
X
|
ndarray
|
Design matrix. |
required |
iterations
|
int
|
Number of retained posterior samples. |
required |
prior_info
|
dict
|
Optional priors with keys
|
None
|
burn
|
int
|
Burn-in iterations (default: 5000). |
5000
|
seed
|
int | Generator | None
|
Seed for
the sampler. None (default) draws from the shared
package-wide generator (see :mod: |
None
|
Returns:
| Type | Description |
|---|---|
|
numpy.ndarray: Posterior samples |
Source code in pybmc/inference_utils.py
gibbs_sampler_heteroscedastic(y, X, variance_basis, iterations, burn=5000, proposal_scales=None, init_params=None, prior_spec=None, b_mean_prior=None, b_mean_cov=None, adapt_proposal=True, target_acceptance=0.25, seed=None)
Gibbs-within-Metropolis sampler for the shared error-model likelihood.
The regression model is y_i ~ N(X_i . b, sigma_i^2) with a
per-point variance that is linear in basis functions of the
heteroscedasticity metrics:
``sigma_i^2 = variance_basis[i] . theta``
The homoscedastic model is the special case where the basis is a
single column of ones, so theta = [sigma^2] is the constant
variance. All error models share this one likelihood.
The coefficients b are updated with a conjugate (weighted
least-squares) Gibbs step; the variance parameters theta with a
positivity-constrained Gaussian random-walk Metropolis-Hastings step
under Gamma priors. Because theta is kept strictly positive by
the MH step and variance_basis is validated to be non-negative
with a leading column of ones, every per-point variance satisfies
sigma_i^2 >= theta_1 > 0 by construction — no variance flooring
is applied during sampling. The only floor is on the initial
constant term, which is estimated from the data residuals and could
otherwise be exactly zero for a perfectly fitting model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ndarray
|
Centered response vector, shape |
required |
X
|
ndarray
|
Design matrix (principal components), shape
|
required |
variance_basis
|
ndarray
|
Variance design matrix |
required |
iterations
|
int
|
Number of retained posterior samples. |
required |
burn
|
int
|
Burn-in iterations discarded before retention (default: 5000). |
5000
|
proposal_scales
|
list[float]
|
Diagonal of the Gaussian
random-walk proposal covariance for |
None
|
init_params
|
list[float]
|
Initial values for the
non-constant entries of |
None
|
prior_spec
|
list[tuple[float, float]]
|
Gamma prior
|
None
|
b_mean_prior
|
ndarray
|
Prior mean for |
None
|
b_mean_cov
|
ndarray
|
Prior covariance for |
None
|
adapt_proposal
|
bool
|
If True (default), rescale the
proposal covariance during burn-in toward
|
True
|
target_acceptance
|
float
|
Acceptance rate targeted by the burn-in adaptation (default: 0.25). |
0.25
|
seed
|
int | Generator | None
|
Seed for
the sampler. None (default) draws from the shared
package-wide generator (see :mod: |
None
|
Returns:
| Type | Description |
|---|---|
|
tuple[numpy.ndarray, float]:
- |
Source code in pybmc/inference_utils.py
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 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 | |
gibbs_sampler_simplex(y, X, Vt_hat, S_hat, iterations, prior_info, burn=10000, stepsize=0.001, seed=None)
Performs Gibbs sampling with simplex constraints on model weights.
The likelihood is the same homoscedastic Gaussian model used by the
unconstrained sampler (y_i ~ N(X_i . b, sigma^2)); only the
weight constraint differs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ndarray
|
Centered response vector. |
required |
X
|
ndarray
|
Design matrix of principal components. |
required |
Vt_hat
|
ndarray
|
Normalized right singular vectors. |
required |
S_hat
|
ndarray
|
Singular values. |
required |
iterations
|
int
|
Number of sampling iterations. |
required |
prior_info
|
list[float]
|
|
required |
burn
|
int
|
Burn-in iterations (default: 10000). |
10000
|
stepsize
|
float
|
Proposal step size (default: 0.001). |
0.001
|
seed
|
int | Generator | None
|
Seed for
the sampler. None (default) draws from the shared
package-wide generator (see :mod: |
None
|
Returns:
| Type | Description |
|---|---|
|
numpy.ndarray: Posterior samples |
Source code in pybmc/inference_utils.py
coverage(percentiles, rndm_m, models_output, truth_column)
Calculates coverage percentages for credible intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
percentiles
|
list[int]
|
Percentiles to evaluate (e.g., |
required |
rndm_m
|
ndarray
|
Posterior samples of predictions. |
required |
models_output
|
DataFrame
|
DataFrame containing true values. |
required |
truth_column
|
str
|
Name of column with true values. |
required |
Returns:
| Type | Description |
|---|---|
|
list[float]: Coverage percentages for each percentile. |
Source code in pybmc/sampling_utils.py
coverage_quality(percentiles, coverage_results)
Scalar calibration score: mean |empirical - nominal| coverage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
percentiles
|
array - like
|
Nominal credible-interval widths in
percent (as passed to |
required |
coverage_results
|
array - like
|
Empirical coverage in percent. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
Mean absolute deviation in percentage points (lower is |
|
|
better; 0 is perfect calibration). |
Source code in pybmc/sampling_utils.py
diagnose_coverage_shape(percentiles, coverage_results, bias_tolerance=5.0, balance_threshold=0.7)
Classifies credible intervals as under-/over-dispersed or calibrated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
percentiles
|
array - like
|
Nominal interval widths in percent. |
required |
coverage_results
|
array - like
|
Empirical coverage in percent. |
required |
bias_tolerance
|
float
|
Mean absolute deviation (percentage points) below which the model counts as well calibrated (default: 5.0). |
5.0
|
balance_threshold
|
float
|
Fraction of intervals that must lie consistently on one side of nominal to call the direction (default: 0.7). |
0.7
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Keys |
|
|
|
||
|
|
||
|
|
||
|
intervals are too narrow (overconfident); overdispersed too wide. |
Source code in pybmc/sampling_utils.py
mace(rndm_m, y_true, quantile_levels=None)
Mean Absolute Calibration Error (MACE): a quantile-based calibration score.
Complementary to coverage/coverage_quality's two-sided central-interval
view: for each one-sided quantile level q, compares the empirical
fraction of true values at or below the predictive q-th percentile
against q itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rndm_m
|
ndarray
|
Posterior predictive draws, shape
|
required |
y_true
|
array - like
|
True/observed values, shape |
required |
quantile_levels
|
array - like
|
Quantile levels in percent, 0-100 (default: 5, 10, ..., 95). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
Mean absolute deviation between empirical and nominal |
|
|
quantile coverage, in percentage points (lower is better; 0 is |
||
|
perfect calibration). |
Source code in pybmc/sampling_utils.py
reduced_chi_square(rndm_m, y_true)
Reduced chi-squared statistic of the posterior predictive distribution.
chi^2_red = mean_i[ (y_true_i - mean_i)^2 / var_i ] where
mean_i/var_i are the posterior predictive mean/variance at
point i. A value near 1 indicates well-calibrated predictive
uncertainties; > 1 means the intervals are too narrow (overconfident,
"underdispersed" in the language of diagnose_coverage_shape); < 1
means too wide ("overdispersed").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rndm_m
|
ndarray
|
Posterior predictive draws, shape
|
required |
y_true
|
array - like
|
True/observed values, shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
Reduced chi-squared statistic. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the posterior predictive variance is non-positive at any point (a degenerate/zero-noise predictive distribution). |
Source code in pybmc/sampling_utils.py
rndm_m_heteroscedastic_calculator(filtered_model_predictions, samples, Vt_hat, variance_basis, seed=DEFAULT_PREDICTIVE_SEED)
Generates posterior predictive samples for any error model.
The noise added to each prediction has a per-point variance
sigma_i^2 = phi_i . theta where theta are the variance
parameters of each posterior draw. The homoscedastic model is the
special case of a constant-only basis (a single column of ones),
handled by the rndm_m_random_calculator convenience wrapper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filtered_model_predictions
|
ndarray
|
Model predictions,
shape |
required |
samples
|
ndarray
|
Posterior samples
|
required |
Vt_hat
|
ndarray
|
Normalized right singular vectors, shape
|
required |
variance_basis
|
ndarray
|
Variance design matrix for the
prediction points, shape |
required |
seed
|
int | None
|
Seed for the posterior predictive
draws (subsampling of |
DEFAULT_PREDICTIVE_SEED
|
Returns:
| Type | Description |
|---|---|
|
tuple[numpy.ndarray, list[numpy.ndarray]]:
- |
Source code in pybmc/sampling_utils.py
rndm_m_random_calculator(filtered_model_predictions, samples, Vt_hat, seed=DEFAULT_PREDICTIVE_SEED)
Posterior predictive samples for the homoscedastic model.
The homoscedastic model is the constant-only special case of the
heteroscedastic predictive distribution, so this delegates to
rndm_m_heteroscedastic_calculator with a constant-only variance
basis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filtered_model_predictions
|
ndarray
|
Model predictions. |
required |
samples
|
ndarray
|
Posterior samples |
required |
Vt_hat
|
ndarray
|
Normalized right singular vectors. |
required |
seed
|
int | None
|
Seed for the posterior predictive
draws (subsampling of |
DEFAULT_PREDICTIVE_SEED
|
Returns:
| Type | Description |
|---|---|
|
tuple[numpy.ndarray, list[numpy.ndarray]]:
- |
Source code in pybmc/sampling_utils.py
Heteroscedastic error models for Bayesian model combination.
All error models share the mean structure of the orthogonalized BMC regression and differ only in how the noise variance depends on the data point:
============================= ====================================================
name sigma_i^2
============================= ====================================================
homoscedastic sigma^2 (constant)
hetero_pc_dist alpha + beta * d_i
hetero_model_var alpha + beta * v_i
hetero_pc_dist_quad alpha + beta_1 d_i + beta_2 d_i^2
hetero_model_var_quad alpha + beta_1 v_i + beta_2 v_i^2
hetero_combined_linear alpha + beta_d d_i + beta_m v_i
hetero_combined_quadratic alpha + beta_d1 d_i + beta_d2 d_i^2
+ beta_m1 v_i + beta_m2 v_i^2
============================= ====================================================
with two physics-informed, per-point metrics:
pc_dist(d): Euclidean distance from the training-data centroid in principal-component space — grows away from the fitted region.model_var(v): variance among the individual model predictions — grows where the models disagree.
Both metrics are min-max normalized using the training points only, so values on extrapolated points can exceed 1.
Every model — the homoscedastic one included — is parametrized on the
variance (sigma^2) scale and shares the single likelihood
y_i ~ N(X_i . b, sigma_i^2) sampled by
:func:pybmc.inference_utils.gibbs_sampler_heteroscedastic; the
homoscedastic model is simply the case where the variance basis is the
constant column alone.
HeteroscedasticMetrics
Computes and normalizes the per-point metrics of the error models.
The object is fit on the training model predictions: it stores the training centroid in PC space and the training min/max of every metric. Metrics for any other set of points are then computed consistently and scaled with the training bounds, so extrapolated points can legitimately exceed 1.
Source code in pybmc/error_models.py
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 | |
__init__(metric_names)
:param metric_names: Metric names to compute
(subset of {'pc_dist', 'model_var'}).
Source code in pybmc/error_models.py
compute(model_predictions)
Computes normalized metrics for a set of points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_predictions
|
ndarray
|
Model outputs, shape
|
required |
Returns:
| Type | Description |
|---|---|
|
dict[str, numpy.ndarray]: Normalized metric arrays keyed by name. |
Source code in pybmc/error_models.py
fit(train_model_predictions, Vt_hat)
Fit the normalization on the training predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_model_predictions
|
ndarray
|
Training model
outputs, shape |
required |
Vt_hat
|
ndarray
|
Scaled right singular vectors from the orthogonalization step. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
HeteroscedasticMetrics |
|
Source code in pybmc/error_models.py
model_variance_metric(model_predictions)
Variance among the model predictions for each point (NaN-aware).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_predictions
|
ndarray
|
Model outputs, shape
|
required |
Returns:
| Type | Description |
|---|---|
|
numpy.ndarray: Per-point variance across models, shape |
Source code in pybmc/error_models.py
pc_distance_metric(model_predictions, Vt_hat, pc_centroid)
Distance of each point from a reference centroid in PC space.
The principal-component coordinates of a point are obtained by
projecting its raw model predictions with Vt_hat (for a
row-centered SVD this is identical to projecting the centered
predictions, since the right singular vectors are orthogonal to the
all-ones direction).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_predictions
|
ndarray
|
Model outputs, shape
|
required |
Vt_hat
|
ndarray
|
Scaled right singular vectors, shape
|
required |
pc_centroid
|
ndarray
|
Training centroid in PC space,
shape |
required |
Returns:
| Type | Description |
|---|---|
|
numpy.ndarray: Euclidean distances, shape |
Source code in pybmc/error_models.py
required_metrics(error_model)
Returns the metric names an error model needs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error_model
|
str
|
One of the keys of |
required |
Returns:
| Type | Description |
|---|---|
|
list[str]: Unique metric names (empty for |
Source code in pybmc/error_models.py
variance_basis(metrics, terms)
Builds the variance design matrix phi for a heteroscedastic model.
The per-point variance is sigma_i^2 = phi[i] . theta where the
first column of phi is ones (the constant term alpha).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics
|
dict[str, ndarray]
|
Metric arrays keyed by name. |
required |
terms
|
list[tuple[str, int]]
|
|
required |
Returns:
| Type | Description |
|---|---|
|
numpy.ndarray: Basis matrix, shape |
Source code in pybmc/error_models.py
variance_parameter_names(error_model)
Returns human-readable names of the variance parameters of a model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error_model
|
str
|
One of the keys of |
required |
Returns:
| Type | Description |
|---|---|
|
list[str]: Names such as |
|
|
|
|
|
is the variance itself). |
Source code in pybmc/error_models.py
Package-wide random-number generation.
All stochastic pybmc routines (the MCMC samplers in
:mod:pybmc.inference_utils and the posterior-predictive draws in
:mod:pybmc.sampling_utils) obtain their generator through
:func:get_rng, so the whole pipeline is driven by one seeded state:
- With
seed=Nonea function draws from the shared package-wide generator, which is seeded withDEFAULT_SEEDat import time. A fresh session that performs the same sequence of calls is therefore fully reproducible, training included. - With an explicit
seeda function uses an independent generator seeded with that value, so a single call is reproducible in isolation regardless of what ran before it.
Use set_seed to re-seed the shared generator mid-session (e.g. at the
top of a script or between repetitions of an experiment).
get_rng(seed=None)
Returns the generator to use for a stochastic routine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | Generator | None
|
If None, the shared
package-wide generator (seeded with |
None
|
Returns:
| Type | Description |
|---|---|
|
numpy.random.Generator: The generator to draw from. |
Source code in pybmc/rng.py
set_seed(seed=DEFAULT_SEED)
Re-seeds the shared package-wide generator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
New seed (default: |
DEFAULT_SEED
|
Returns:
| Type | Description |
|---|---|
|
numpy.random.Generator: The freshly seeded shared generator. |