Repository navigation
Expand file tree
/
Copy pathvisualize_bayesian_optimization.py
More file actions
660 lines (591 loc) · 30.2 KB
/
Copy pathvisualize_bayesian_optimization.py
File metadata and controls
660 lines (591 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
440
441
442
443
444
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
538
539
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
628
629
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
import numpy as np
from scipy import optimize
import arviz as az
import matplotlib.pyplot as plt
import pandas as pd
import warnings # Already imported in your main script presumably
import traceback
import xarray as xr # Import xarray for explicit checks
import logging
import os
from datetime import datetime
def print_mcmc_summary(trace, param_names, response_names=None):
"""Prints summary of MCMC trace for given parameter names."""
logging.info("\nMCMC Summary:")
var_names_to_plot = param_names + ['sigma']
try:
summary = az.summary(trace, var_names_to_plot,
hdi_prob=0.95, round_to=3)
return summary
except Exception as e:
logging.warning(f"Error during az.summary calculation: {e}")
return None
def plot_parameter_posteriors(trace, param_names):
"""Plots posterior distributions of parameters and sigma."""
logging.info("\nplotting parameter Posterior Distributions:")
if not isinstance(trace, az.InferenceData):
logging.error("Input 'trace' is not an Arviz inferenceData object.")
return
var_names_to_plot = list(param_names)
if hasattr(trace, "posterior") and 'sigma' in getattr(trace, "posterior", {}):
var_names_to_plot.append('sigma')
else:
logging.warning(
"sigma not found in trace.posterior. plotting only specified param_names.")
nan_found = False
for var_name in var_names_to_plot:
posterior = getattr(trace, "posterior", None)
if posterior is not None and var_name in posterior:
data_array = posterior[var_name]
if np.isnan(data_array.values).any():
nan_found = True
logging.warning(
f"NaNs found in posterior samples for variable: {var_name}")
else:
logging.warning(
f"Variable '{var_name}' not found in trace.posterior. Skipping.")
if var_name in var_names_to_plot:
var_names_to_plot.remove(var_name)
if not var_names_to_plot:
logging.error("No valid variables found to plot after checks.")
try:
logging.info(f"Attempting to plot: {var_names_to_plot}")
axes = az.plot_posterior(
trace, var_names=var_names_to_plot, hdi_prob=0.95)
if axes is None or (isinstance(axes, np.ndarray) and axes.size == 0):
logging.error(
"az.plot_posterior returned None or empty axes. plotting failed.")
return
fig = None
if isinstance(axes, np.ndarray) and axes.size > 0:
fig = axes.ravel()[0].figure
elif hasattr(axes, 'figure'):
fig = axes.figure
if fig is not None:
fig.tight_layout()
# Define output_dir before using it
output_dir = "plots"
if not os.path.exists(output_dir):
try:
os.mkdir(output_dir)
logging.info(f"Created output directory: {output_dir}")
except OSError as e:
logging.error(
f"Could not create output directory {output_dir}: {e}")
output_dir = "."
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"parameter_posterior_{timestamp}.png"
save_path = os.path.join(output_dir, filename)
try:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logging.info(
f"parameter posterior plot saved to : {save_path}")
except Exception as e_save:
logging.error(f"Failed to save plot to {save_path}: {e_save}")
plt.show()
except FloatingPointError as fpe: # Specifically catch FPEs that might relate to NaN/inf
logging.error(f"FloatingPointError during plotting: {fpe}")
logging.error(
"This often indicates NaNs or Infs in the data passed to plotting.")
except TypeError as te: # Catch TypeErrors like "cannot convert float NaN to integer"
logging.error(f"TypeError during plotting: {te}")
logging.error(
"This might be due to NaNs where integers are expected or data type issues.")
except Exception as e:
logging.error(
f"An unexpected error occurred during az.plot_posterior: {e}")
# Logs the full traceback
logging.exception("Traceback for the plotting error:")
def plot_mcmc_traces(trace, param_names, response_names=None):
"""Plots MCMC trace plots for convergence diagnostics."""
logging.info("\nPlotting MCMC Trace Plots:")
if not isinstance(trace, az.InferenceData):
logging.error(
"Input 'trace' is not an ArviZ InferenceData object. cannot plot traces.")
return
var_names_to_plot = param_names + ['sigma']
axes = az.plot_trace(trace, var_names=var_names_to_plot)
if axes is None or (isinstance(axes, np.ndarray) and axes.size == 0):
logging.error(
"az.plot_trace returned None or empty array. plotting failed.")
fig = axes.ravel()[0].figure
if fig is not None:
plt.tight_layout()
output_dir = "plots"
if not os.path.exists(output_dir):
try:
os.mkdir(output_dir)
logging.info(f"Created output directory: {output_dir}")
except OSError as e:
logging.error(
f"Could not create output directory {output_dir}: {e}")
output_dir = "."
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"mcmc_traces_{timestamp}.png"
save_path = os.path.join(output_dir, filename)
try:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logging.info(f"parameter posterior plot saved to : {save_path}")
except Exception as e_save:
logging.error(f"Failed to save plot to {save_path}: {e_save}")
plt.show()
else:
logging.error(
"could not obtain figure object from Arviz trace plot. cannot save or show.")
# ==============================================================================
# Your posterior_predictive_checks_nae function
# ==============================================================================
def posterior_predictive_checks_nae(
trace, # ArviZ InferenceData object from pm.sample
residual_func,
calculate_responses_func,
n_states, # Number of states in the NAE system
n_responses, # Number of observed responses
independent_vars, # EXPECTED TO BE A LIST OF DICTIONARIES
observed_responses, # Shape (n_experiments, n_responses)
fixed_constants, # Dictionary of fixed values
param_names, # List of parameter names (strings)
n_samples=500, # Number of posterior predictive samples to generate
initial_guess_func=None
):
"""
Generates posterior predictive samples for NAE models across multiple experiments.
Manually solves NAE equations for parameters drawn from the posterior trace.
Returns:
tuple: (arviz.InferenceData or np.ndarray containing PPC samples, numpy.ndarray of mean predictions)
Returns (None, None) if critical errors occur during setup.
Returns (raw_ppc_array, mean_ppc_array) if Arviz conversion fails.
"""
print("\nGenerating Posterior Predictive samples . . .")
ppc_samples_mean = None # Initialize
ppc_samples_noisy = None # Initialize
# --- Step 1: Extract and Validate Posterior Samples ---
try:
posterior = trace.posterior
param_samples_list = []
for pname in param_names:
if pname not in posterior:
raise ValueError(
f"Parameter '{pname}' not found in trace.posterior.")
param_data = posterior[pname].stack(
sample=("chain", "draw")).values
param_samples_list.append(param_data.reshape(-1))
if not param_samples_list:
raise ValueError("No parameter samples could be extracted.")
param_samples = np.stack(param_samples_list, axis=-1)
if 'sigma' not in posterior:
raise ValueError("'sigma' variable not found in trace.posterior.")
sigma_data_array = posterior['sigma']
response_dim_names = [
d for d in sigma_data_array.dims if d not in ('chain', 'draw')]
if len(response_dim_names) == 1:
response_dim_name = response_dim_names[0]
sigma_samples_stacked = sigma_data_array.stack(
sample=("chain", "draw")).transpose("sample", response_dim_name)
sigma_samples = sigma_samples_stacked.values
elif len(response_dim_names) == 0 and n_responses == 1:
sigma_samples_stacked = sigma_data_array.stack(
sample=("chain", "draw"))
sigma_samples = sigma_samples_stacked.values[:, np.newaxis]
else:
# Try to infer dimension name based on shape if default names weren't clear
response_dim_index = -1
for i, dim_size in enumerate(sigma_data_array.shape):
if dim_size == n_responses and sigma_data_array.dims[i] not in ('chain', 'draw'):
response_dim_index = i
break
if response_dim_index != -1:
response_dim_name = sigma_data_array.dims[response_dim_index]
logging.info(
f"DEBUG PPC: Inferred response dim name for sigma: '{response_dim_name}'")
sigma_samples_stacked = sigma_data_array.stack(
sample=("chain", "draw")).transpose("sample", response_dim_name)
sigma_samples = sigma_samples_stacked.values
else:
raise ValueError(
f"Could not reliably determine response dimension for 'sigma'. Dims: {sigma_data_array.dims}, Shape: {sigma_data_array.shape} Expected n_responses: {n_responses}")
n_total_samples = param_samples.shape[0]
if n_total_samples == 0:
logging.info(
"Warning: No posterior samples found after processing trace.")
return None, None
if sigma_samples.shape[0] != n_total_samples:
raise ValueError(
f"Shape mismatch between param_samples ({param_samples.shape[0]}) and sigma_samples ({sigma_samples.shape[0]})")
if sigma_samples.shape[1] != n_responses:
raise ValueError(
f"Shape mismatch for sigma_samples response dimension. Expected {n_responses}, Got {sigma_samples.shape[1]}.")
if n_samples > n_total_samples:
logging.info(
f"Warning: Requested n_samples ({n_samples}) exceeds available samples ({n_total_samples}). Using {n_total_samples}.")
n_samples = n_total_samples
indices = np.arange(n_total_samples)
else:
indices = np.random.choice(
n_total_samples, n_samples, replace=False)
logging.info(f"DEBUG PPC: param_samples shape: {param_samples.shape}")
logging.info(f"DEBUG PPC: sigma_samples shape: {sigma_samples.shape}")
logging.info(f"DEBUG PPC: Using n_samples: {n_samples}")
# print(f"DEBUG PPC: Max index sampled: {np.max(indices)}") # Debug print from last run
selected_params = param_samples[indices, :]
selected_sigmas = sigma_samples[indices, :]
logging.info(
f"DEBUG PPC: selected_params shape: {selected_params.shape}")
logging.info(
f"DEBUG PPC: selected_sigmas shape: {selected_sigmas.shape}")
except Exception as setup_e:
logging.warning(
f"PPC Error: Failed during posterior sample extraction/validation: {setup_e}")
traceback.print_exc()
return None, None
# --- Step 2: Prepare for and Run Prediction Loop ---
try:
if not isinstance(independent_vars, (list, tuple)):
warnings.warn(
"'independent_vars' expected as list of dicts, proceeding with len(). Check structure if errors occur.", UserWarning)
try:
n_experiments = len(independent_vars)
except TypeError:
raise TypeError(
"Cannot determine number of experiments from 'independent_vars'. Please provide a list of dictionaries.")
else:
n_experiments = len(independent_vars)
if n_experiments != observed_responses.shape[0]:
raise ValueError(
f"Mismatch between n_experiments from independent_vars ({n_experiments}) and observed_responses ({observed_responses.shape[0]})")
ppc_samples_mean = np.full(
(n_samples, n_experiments, n_responses), np.nan)
ppc_samples_noisy = np.full(
(n_samples, n_experiments, n_responses), np.nan)
failures_count = 0
total_predictions = n_samples * n_experiments
# --- Main Loop ---
for s_idx in range(n_samples):
params = selected_params[s_idx, :]
sigma = selected_sigmas[s_idx, :]
for exp_idx in range(n_experiments):
try:
# --- Get Conditions ---
if not (isinstance(independent_vars, (list, tuple)) and exp_idx < len(independent_vars) and isinstance(independent_vars[exp_idx], dict)):
raise TypeError(
f"Expected independent_vars[{exp_idx}] to be a dict, but structure is incorrect or index out of bounds.")
current_conditions_exp = independent_vars[exp_idx]
args_for_kinetic_model = (
current_conditions_exp['spacetime'],
current_conditions_exp['T'],
current_conditions_exp['pBDOin'],
current_conditions_exp['w'],
params,
fixed_constants['Nbrxn'],
fixed_constants['elem'],
fixed_constants['comp'],
fixed_constants['surface_entropies'],
fixed_constants['Sint'],
fixed_constants['p_tot'],
fixed_constants['Tavg'],
current_conditions_exp['BENE']
)
current_conditions_for_resp = current_conditions_exp
# --- Initial Guess ---
initial_guess = None
if initial_guess_func:
try:
initial_guess = initial_guess_func(
params, current_conditions_exp, fixed_constants)
except Exception:
pass
if initial_guess is None and 'F_guess' in current_conditions_exp:
initial_guess = current_conditions_exp['F_guess']
if initial_guess is None:
initial_guess = np.ones(n_states) * 1e-3
if not isinstance(initial_guess, np.ndarray) or initial_guess.shape != (n_states,):
initial_guess = np.ones(n_states) * 1e-3
# --- Solve NAE ---
sol = optimize.least_squares(fun=residual_func, x0=initial_guess,
args=args_for_kinetic_model, method='lm', ftol=1e-7)
# --- Process Solution ---
if sol.success:
y_ss_pred = sol.x
if not np.all(np.isfinite(y_ss_pred)):
failures_count += 1
continue # Skip rest for this exp
predicted_responses = calculate_responses_func(
y_ss_pred, params, current_conditions_for_resp, fixed_constants)
if predicted_responses is not None and len(predicted_responses) == n_responses and np.all(np.isfinite(predicted_responses)):
ppc_samples_mean[s_idx, exp_idx,
:] = predicted_responses
valid_sigma = np.maximum(sigma, 1e-9)
noise = np.random.normal(
0, valid_sigma, size=n_responses)
ppc_samples_noisy[s_idx, exp_idx,
:] = predicted_responses + noise
else:
failures_count += 1 # Failed response calc
else:
failures_count += 1 # Solver failed
except Exception as loop_e:
logging.warning(
f"PPC Error: Calculation failed for sample {s_idx}, exp {exp_idx}: {loop_e}")
failures_count += 1 # Count failure, predictions remain NaN
# --- Progress Update ---
if (s_idx + 1) % 100 == 0:
logging.info(
f" ... generated PPC samples for {s_idx + 1}/{n_samples} posterior draws.")
# --- End Loops ---
if failures_count > 0:
logging.info(
f"PPC Warning: NAE solver failed or response calculations failed for {failures_count} out of {total_predictions} total predictions.")
# try: # Add try block around Arviz/xarray creation
# --- Step 3: Create Arviz InferenceData object (Manual xarray Approach) ---
if np.all(np.isnan(ppc_samples_noisy)):
logging.warning(
"PPC Error: All posterior predictive samples resulted in NaN. Cannot create InferenceData.")
return None, None
# Should be (n_samples, n_exp, n_resp)
logging.info(
f"DEBUG PPC: ppc_samples_noisy shape (final for Arviz): {ppc_samples_noisy.shape}")
# Use actual number of samples generated
n_samples_actual = ppc_samples_noisy.shape[0]
n_experiments = ppc_samples_noisy.shape[1]
# n_responses = ppc_samples_noisy.shape[2] # Already available as input arg
# Define coordinates
coords = {
# Add chain/draw explicitly for Arviz compatibility if desired downstream
'chain': [0],
'draw': np.arange(n_samples_actual),
'experiment_idx': np.arange(n_experiments),
'response_idx': np.arange(n_responses)
}
# Define dimensions for the FINAL DataArray structure Arviz expects
# (chain, draw, exp_dim, resp_dim)
y_hat_dims = ['chain', 'draw', 'experiment_idx', 'response_idx']
# Reshape the numpy array to match the target dimensions
# Add a 'chain' dimension of size 1
ppc_reshaped = ppc_samples_noisy[np.newaxis, :, :, :]
# Should be (1, n_samples, n_exp, n_resp)
logging.info(
f"DEBUG PPC: ppc_reshaped shape (for DataArray): {ppc_reshaped.shape}")
# Create the xarray DataArray manually for posterior predictive
posterior_predictive_da = xr.DataArray(
ppc_reshaped,
coords={
'chain': coords['chain'],
'draw': coords['draw'],
'experiment_idx': coords['experiment_idx'],
'response_idx': coords['response_idx']
},
dims=y_hat_dims,
name='y_hat' # Name the variable within the dataset
)
# Create an xarray Dataset for the posterior_predictive group
posterior_predictive_ds = xr.Dataset(
{'y_hat': posterior_predictive_da})
# Create the xarray Dataset for observed data
observed_data_da = xr.DataArray(
observed_responses,
coords={
'experiment_idx': coords['experiment_idx'],
'response_idx': coords['response_idx']
},
# Dimensions for observed data
dims=['experiment_idx', 'response_idx'],
name='y_obs'
)
observed_data_ds = xr.Dataset({'y_obs': observed_data_da})
# --- Assemble the InferenceData object ---
# Use the Datasets directly, bypassing from_dict issues
logging.info(
"DEBUG PPC: Attempting Arviz InferenceData creation from Datasets...")
ppc_idata = az.InferenceData(
posterior_predictive=posterior_predictive_ds,
observed_data=observed_data_ds
# We can add the original posterior later if needed:
# posterior=trace.posterior
)
# --- Verification ---
if "posterior_predictive" not in ppc_idata or "y_hat" not in ppc_idata["posterior_predictive"]:
raise RuntimeError(
"Manual Arviz InferenceData object missing 'posterior_predictive' group or 'y_hat'.")
if "observed_data" not in ppc_idata or "y_obs" not in ppc_idata["observed_data"]:
raise RuntimeError(
"Manual Arviz InferenceData object missing 'observed_data' group or 'y_obs'.")
logging.info(
f"DEBUG PPC: Created ppc_idata['posterior_predictive']['y_hat'] dims: {ppc_idata['posterior_predictive']['y_hat'].dims}")
logging.info(
f"DEBUG PPC: Created ppc_idata['observed_data']['y_obs'] dims: {ppc_idata['observed_data']['y_obs'].dims}")
# These should now correctly show ('chain', 'draw', 'experiment_idx', 'response_idx') for y_hat
# And ('experiment_idx', 'response_idx') for y_obs
logging.info(
"Posterior predictive check data generated successfully (Arviz InferenceData - Manual).")
return ppc_idata, ppc_samples_mean
except Exception as ppc_e:
# Catch errors during xarray/Arviz creation or the preceding loop setup
logging.info(
f"PPC Error: Failed during prediction/Arviz creation: {ppc_e}")
traceback.print_exc()
warnings.warn(
"Failed to create ArviZ InferenceData object. Returning raw PPC arrays instead.", UserWarning)
if ppc_samples_noisy is not None:
return ppc_samples_noisy, ppc_samples_mean
else:
return None, None
# ==============================================================================
# Your plotting function (from previous post, might need adjustments)
# ==============================================================================
def plot_posterior_predictive_checks(ppc_idata, observed_responses, response_names=None):
"""Plots posterior predictive checks (observed vs predicted)."""
if ppc_idata is None:
logging.info(
"Cannot plot posterior predictive: No PPC data available.")
return
if isinstance(ppc_idata, az.InferenceData):
if "posterior_predictive" not in ppc_idata or "y_hat" not in ppc_idata["posterior_predictive"]:
logging.info(
"Cannot plot posterior predictive: 'posterior_predictive' group or 'y_hat' variable missing.")
return
# xarray DataArray
y_hat_all_samples = ppc_idata["posterior_predictive"]["y_hat"]
logging.info(
f"DEBUG plot_ppc: Found y_hat dimensions: {y_hat_all_samples.dims}")
# Should now be ('chain', 'draw', 'experiment_idx', 'response_idx')
# --- Stack chain and draw into 'sample' ---
# Ensure dimensions exist before stacking
if 'chain' in y_hat_all_samples.dims and 'draw' in y_hat_all_samples.dims:
y_hat_stacked_da = y_hat_all_samples.stack(sample=("chain", "draw")).transpose(
"sample", "experiment_idx", "response_idx")
sample_dim_name = "sample"
else:
# Fallback if somehow chain/draw weren't created (shouldn't happen now)
warnings.warn(
"Chain/Draw dimensions not found as expected. Adjusting...", UserWarning)
# Assume the first dimension represents samples if stack fails
sample_dim_name = y_hat_all_samples.dims[0]
obs_dims = y_hat_all_samples.dims[1:]
y_hat_stacked_da = y_hat_all_samples.rename(
{sample_dim_name: "sample"}).transpose("sample", *obs_dims)
# Should be ('sample', 'experiment_idx', 'response_idx')
logging.info(
f"DEBUG plot_ppc: Stacked y_hat dims: {y_hat_stacked_da.dims}")
logging.info(
f"DEBUG plot_ppc: Using sample dimension: '{sample_dim_name}'")
# Calculate mean and HDI along the 'sample' dimension
# Result should have dims ('experiment_idx', 'response_idx')
y_hat_mean_da = y_hat_stacked_da.mean(
dim=str(sample_dim_name), skipna=True)
hdi_prob = 0.94
try:
y_hat_hdi_ds = az.hdi(
y_hat_stacked_da.dropna(dim=sample_dim_name, how='all'),
hdi_prob=hdi_prob,
input_core_dims=[[sample_dim_name]]
)
# Result should have dims ('experiment_idx', 'response_idx', 'hdi')
y_hat_hdi_da = y_hat_hdi_ds['y_hat']
logging.info(
f"DEBUG plot_ppc: Calculated HDI dims: {y_hat_hdi_da.dims}")
# --- Extract numpy arrays using dimension names ---
y_hat_mean = y_hat_mean_da.transpose(
'experiment_idx', 'response_idx').values
# If y_hat_hdi_da is an xarray DataArray, use dimension names; if it's a NumPy array, use axes or skip transpose
if hasattr(y_hat_hdi_da, "transpose") and hasattr(y_hat_hdi_da, "dims"):
y_hat_hdi = y_hat_hdi_da.transpose(
'experiment_idx', 'response_idx', 'hdi').values
else:
# Assume it's a NumPy array, so just use as is
y_hat_hdi = np.asarray(y_hat_hdi_da)
except Exception as hdi_e: # Broad exception catch for HDI issues
logging.warning(f"ERROR calculating HDI: {hdi_e}")
# Create NaN placeholders if HDI fails
hdi_shape_expected = (
observed_responses.shape[0], observed_responses.shape[1], 2)
y_hat_hdi = np.full(hdi_shape_expected, np.nan)
# Still try to get the mean
try:
y_hat_mean = y_hat_mean_da.transpose(
'experiment_idx', 'response_idx').values
except: # If mean also failed or dimensions wrong
y_hat_mean = np.full(observed_responses.shape, np.nan)
logging.info(
"Skipping plotting error bars due to HDI calculation failure.")
# --- Handle Fallback case (if ppc_idata was NumPy array) ---
elif isinstance(ppc_idata, np.ndarray):
# ... (previous numpy handling code remains the same) ...
logging.warning(
"Warning: Plotting PPC from raw NumPy array (Arviz conversion failed).")
# ... calculation of y_hat_mean, y_hat_hdi for numpy ...
else:
logging.warning(
f"Cannot plot posterior predictive: ppc_idata is of unexpected type {type(ppc_idata)}.")
return
# --- Plotting Logic (same as before) ---
n_experiments, n_responses = observed_responses.shape
if response_names is None:
response_names = [f'Response {i+1}' for i in range(n_responses)]
if len(response_names) != n_responses:
logging.warning(
f'Warning: length of response_names does not match n_responses. Using default names.')
response_names = [f'Response {i+1}' for i in range(n_responses)]
n_cols = min(3, n_responses)
# Correct calculation for rows to ensure enough subplots
n_rows = int(np.ceil(n_responses / n_cols))
fig, axes = plt.subplots(n_rows, n_cols, figsize=(
5*n_cols, 5*n_rows), squeeze=False)
axes = axes.flatten()
logging.info(
f'\nPlotting posterior predictive checks (observed vs predicted) . . .')
for j in range(n_responses):
if j >= len(axes): # Avoid index error if n_rows*n_cols is less than n_responses (shouldn't happen with ceil)
break
ax = axes[j]
obs_j = observed_responses[:, j]
pred_mean_j = y_hat_mean[:, j]
pred_hdi_lower = y_hat_hdi[:, j, 0]
pred_hdi_upper = y_hat_hdi[:, j, 1]
# Calculate error bars for HDI relative to the mean
# Ensure non-negative error
y_err_lower = np.maximum(0, pred_mean_j - pred_hdi_lower)
# Ensure non-negative error
y_err_upper = np.maximum(0, pred_hdi_upper - pred_mean_j)
y_err = np.array([y_err_lower, y_err_upper]) # Shape (2, n_exp)
# Filter out NaNs before plotting errorbar
valid_mask = np.isfinite(obs_j) & np.isfinite(
pred_mean_j) & np.all(np.isfinite(y_err), axis=0)
if not np.any(valid_mask):
logging.warning(
f"Warning: No valid data points to plot for {response_names[j]}. Skipping.")
ax.set_title(f"{response_names[j]} (No valid data)")
ax.grid(True, linestyle=':')
continue
ax.errorbar(obs_j[valid_mask], pred_mean_j[valid_mask], yerr=y_err[:, valid_mask],
fmt='o', capsize=3, alpha=0.6, label=f'{hdi_prob*100:.0f}% HDI', ms=4, elinewidth=1)
# Determine limits based on valid data only for plotting
valid_obs = obs_j[valid_mask]
valid_pred_mean = pred_mean_j[valid_mask]
valid_pred_lower = pred_hdi_lower[valid_mask]
valid_pred_upper = pred_hdi_upper[valid_mask]
min_val = min(np.min(valid_obs), np.min(valid_pred_lower))
max_val = max(np.max(valid_obs), np.max(valid_pred_upper))
# Add padding for limits
lim_range = max_val - min_val
# Add padding, handle near-zero range
padding = lim_range * 0.05 if lim_range > 1e-6 else 0.1
lims = [min_val - padding, max_val + padding]
# Ensure limits are reasonable (e.g., not crossing zero inappropriately if data is positive)
if min_val >= 0 and lims[0] < 0:
lims[0] = 0
ax.plot(lims, lims, 'k--', alpha=0.7, label='Parity')
ax.set_xlabel("Observed " + response_names[j]) # Add space
ax.set_ylabel("Predicted " + response_names[j]) # Add space
ax.set_title(response_names[j])
ax.legend()
ax.grid(True, linestyle=':')
ax.set_xlim(lims)
ax.set_ylim(lims)
# Hide unused axes
for k in range(n_responses, len(axes)):
axes[k].set_visible(False)
plt.suptitle("Posterior predictive check: Observed vs Predicted",
fontsize=16, y=0.98) # Adjust y slightly
# Adjust layout rect based on suptitle position
plt.tight_layout(rect=(0, 0, 1, 0.96))
plt.show()