Repository navigation
Expand file tree
/
Copy pathbayesian_Kinetic_Estimator.py
More file actions
812 lines (679 loc) · 38.8 KB
/
Copy pathbayesian_Kinetic_Estimator.py
File metadata and controls
812 lines (679 loc) · 38.8 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
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
804
805
806
807
808
809
810
811
812
import numpy as np
import pymc as pm # Use pymc v4+
import aesara # Successor to Theano
import aesara.tensor as at # Tensor operations
import arviz as az
import matplotlib.pyplot as plt
from scipy.optimize import root # For solving NAEs numerically
import warnings # To warn about sampler choice
import time # To time execution
# ==============================================================================
# 1. Define Your CSTR Model Interface (User Needs to Provide These)
# ==============================================================================
# Placeholder for the user's function to calculate NAE residuals
# This function needs to be implemented based on the user's specific kinetic model
def cstr_model_residuals_user(y_ss, params, conditions):
"""
Calculates residuals for the user's CSTR steady-state NAE model.
Args:
y_ss (np.ndarray): Candidate steady-state variables (e.g., outlet concentrations).
The length depends on the user's model (n_states).
params (np.ndarray): Vector of kinetic parameters being estimated.
conditions (dict): Dictionary containing independent variables for the
*current* experiment (e.g., T, CA_in, Flow) AND
any fixed constants (e.g., V_reactor).
Returns:
np.ndarray: Vector of residuals (should have length n_states).
"""
# --- USER IMPLEMENTATION REQUIRED ---
# Example: Simple A -> B reaction (replace with actual model)
# Extract parameters and conditions
k = params[0]
CA_in = conditions['CA_in']
Q = conditions['Q']
V = conditions['V_reactor']
tau = V / Q
# State variables (example: outlet concentrations)
CA_ss, CB_ss = y_ss # Assuming n_states = 2 for this example
# Calculate reaction rate (example)
rate = k * CA_ss
# Calculate residuals (example mass balances)
res_A = (1/tau) * (CA_in - CA_ss) - rate
res_B = (1/tau) * (0 - CB_ss) + rate # Assuming CB_in = 0
# Return residuals based on the number of states in the user model
return np.array([res_A, res_B])
# --- END USER IMPLEMENTATION ---
# Placeholder for the user's function to calculate responses from solved states
# This function needs to be implemented based on the user's specific model
def calculate_responses_user(y_ss_solution, params, conditions):
"""
Calculates the desired model responses (e.g., conversion, selectivities)
from the solved steady-state variables.
Args:
y_ss_solution (np.ndarray): Solved steady-state variables from the NAE solver.
params (np.ndarray): Vector of kinetic parameters being estimated.
conditions (dict): Dictionary containing independent variables for the
*current* experiment AND any fixed constants.
Returns:
np.ndarray: Vector of calculated responses (must have length n_responses, e.g., 5).
"""
# --- USER IMPLEMENTATION REQUIRED ---
# Example: Calculate Conversion XA and Yield YB for A -> B
# Extract solved states and conditions
CA_ss, CB_ss = y_ss_solution # Assuming n_states = 2 from the example residual func
CA_in = conditions['CA_in']
# params might be needed if rates are recalculated here, but often not
# Calculate responses (example)
XA = (CA_in - CA_ss) / CA_in if CA_in > 1e-9 else 0.0
YB = CB_ss / CA_in if CA_in > 1e-9 else 0.0 # Yield based on inlet A
# Simulate having 5 responses (add dummy values for illustration)
Selectivity_1 = YB / XA if XA > 1e-9 else 0.0 # Example selectivity
Dummy_Response_3 = CA_ss * 0.1 # Example
Dummy_Response_4 = CB_ss * 0.2 # Example
Dummy_Response_5 = params[0] * 0.01 # Example depending on a parameter
# Ensure non-negative and finite values (important for likelihood)
responses = np.array([XA, Selectivity_1, Dummy_Response_3, Dummy_Response_4, Dummy_Response_5])
responses = np.nan_to_num(responses, nan=0.0, posinf=1e9, neginf=-1e9) # Handle potential division by zero etc.
responses = np.maximum(responses, 1e-9) # Ensure positive values if applicable
# Return the 5 calculated responses
return responses
# --- END USER IMPLEMENTATION ---
# ==============================================================================
# 2. Custom Aesara Op for NAE Solving and Likelihood Calculation (Revised)
# ==============================================================================
class LogLikeWithNAESolver(aesara.Op):
"""
Aesara Op to numerically solve NAEs for multiple experimental conditions
and compute the total log-likelihood.
Takes symbolic parameters (theta) and sigma as input.
Outputs scalar log-likelihood. Does NOT provide gradients for theta.
"""
itypes = [at.dvector, at.dvector] # Input types: theta (vector), sigma (vector, len=n_responses)
otypes = [at.dscalar] # Output type: total_logp (scalar)
def __init__(self,
residual_func, # User function for NAE residuals
calculate_responses_func, # User function to calculate responses
n_states, # Number of states solved for by NAE solver
n_responses, # Number of responses observed/predicted (e.g., 5)
independent_vars, # Shape: (n_experiments, n_independent_vars)
observed_responses, # Shape: (n_experiments, n_responses)
fixed_constants, # Dict of constants applicable to ALL experiments
initial_guess_func=None): # Optional: func(params, conditions) -> guess
"""
Args:
residual_func: User function calculating NAE residuals.
calculate_responses_func: User function calculating responses from y_ss.
n_states: Number of state variables solved for in NAE.
n_responses: Number of observed/predicted responses.
independent_vars: NumPy array of independent variables for each experiment.
observed_responses: NumPy array of observed responses for each experiment.
fixed_constants: Dict of fixed constants (e.g., reactor volume).
initial_guess_func: Optional function(params, conditions) -> guess_vector
to provide initial guesses for the solver.
"""
self.residual_func = residual_func
self.calculate_responses_func = calculate_responses_func
self.n_states = n_states
self.n_responses = n_responses
self.independent_vars = independent_vars
self.observed_responses = observed_responses
self.fixed_constants = fixed_constants
self.initial_guess_func = initial_guess_func
self.n_experiments = independent_vars.shape[0]
self.indep_var_names = list(independent_vars.dtype.names) if independent_vars.dtype.names else [f'indep_var_{i}' for i in range(independent_vars.shape[1])]
# Input validation
if observed_responses.shape[0] != self.n_experiments:
raise ValueError("Number of rows in independent_vars and observed_responses must match.")
if observed_responses.shape[1] != self.n_responses:
raise ValueError(f"Observed responses should have {self.n_responses} columns.")
# Pre-calculate for efficiency
self.log_2_pi = np.log(2 * np.pi)
def perform(self, node, inputs, outputs):
"""
Executes the numerical operations for all experiments.
Args:
node: Aesara node.
inputs: List containing NUMERICAL values of [theta_numpy, sigma_numpy].
outputs: List where the scalar output (total_logp) should be stored.
"""
theta_numpy = inputs[0]
sigma_numpy = inputs[1] # Should have length n_responses
# --- Validate Inputs ---
if np.any(sigma_numpy <= 0):
outputs[0][0] = np.array(-np.inf) # Penalize invalid sigma
return
if len(sigma_numpy) != self.n_responses:
# This check should ideally happen during model setup, but good fallback
print(f"Warning: Sigma shape mismatch. Expected {self.n_responses}, got {len(sigma_numpy)}")
outputs[0][0] = np.array(-np.inf)
return
total_log_likelihood = 0.0
solver_failures = 0
# --- Loop through each experiment ---
for i in range(self.n_experiments):
# Get independent variables for the current experiment
current_indep_vars = self.independent_vars[i]
current_observed = self.observed_responses[i] # Vector of observed responses for exp i
# Combine fixed constants and current independent variables
current_conditions = self.fixed_constants.copy()
# Handle structured array or plain numpy array for independent vars
if self.indep_var_names:
for idx, name in enumerate(self.indep_var_names):
current_conditions[name] = current_indep_vars[idx]
else: # Assuming plain array
for idx in range(len(current_indep_vars)):
current_conditions[f'indep_var_{idx}'] = current_indep_vars[idx]
# --- 1. Solve the NAE System for experiment i ---
if self.initial_guess_func:
initial_guess = self.initial_guess_func(theta_numpy, current_conditions)
else:
# Simple default guess - USER MAY NEED TO ADJUST THIS
initial_guess = np.ones(self.n_states) * 1e-3
sol = root(fun=self.residual_func,
x0=initial_guess,
args=(theta_numpy, current_conditions),
method='lm', # Levenberg-Marquardt often robust
tol=1e-8 # Might need adjustment
# Add other solver options if needed
)
if not sol.success:
# Solver failed for this condition: assign very low likelihood contribution
# This experiment provides strong evidence against these parameters
solver_failures += 1
# We don't set the *total* logp to -inf immediately,
# allow other experiments to contribute. But a single failure
# should heavily penalize the parameters. Assign a large negative value.
total_log_likelihood -= 1e6 # Penalize heavily
continue # Move to the next experiment
y_ss_solution = sol.x
# --- 2. Calculate Predicted Responses for experiment i ---
predicted_responses = self.calculate_responses_func(y_ss_solution, theta_numpy, current_conditions)
if len(predicted_responses) != self.n_responses:
print(f"Warning: calculate_responses_func returned {len(predicted_responses)} values, expected {self.n_responses}.")
total_log_likelihood = -np.inf # Stop calculation if response shape is wrong
break
# --- 3. Calculate Log-Likelihood contribution for experiment i ---
# Assuming independent Gaussian errors for each response type
log_like_exp_i = 0.0
for j in range(self.n_responses):
residual_sq = ((current_observed[j] - predicted_responses[j]) / sigma_numpy[j])**2
log_like_exp_i += -0.5 * self.log_2_pi - np.log(sigma_numpy[j]) - 0.5 * residual_sq
# Add contribution of this experiment to the total
total_log_likelihood += log_like_exp_i
# End loop through experiments
# Check for overall issues
if solver_failures > 0:
# Optional: Print warning if too many failures occur during sampling
# if np.random.rand() < 0.01: # Print occasionally
# print(f"Warning: NAE solver failed for {solver_failures}/{self.n_experiments} conditions for params {theta_numpy}")
pass # Already penalized in the loop
if not np.isfinite(total_log_likelihood):
# print(f"Warning: Non-finite total log-likelihood ({total_log_likelihood}) calculated for params {theta_numpy}, sigma {sigma_numpy}")
total_log_likelihood = -np.inf # Ensure sampler rejects
outputs[0][0] = np.array(total_log_likelihood)
# --- Gradient --- (Remains the same - no gradient through NAE solver)
def grad(self, inputs, output_grads):
theta, sigma = inputs
dL_dloglike = output_grads[0]
grad_theta = aesara.gradient.grad_undefined(self, 0, theta, "Gradient not defined for NAE solver parameters")
grad_sigma = aesara.gradient.grad_undefined(self, 1, sigma, "Gradient not defined for sigma in NAE likelihood Op")
return [grad_theta * dL_dloglike, grad_sigma * dL_dloglike]
# ==============================================================================
# 3. Bayesian Parameter Estimation Function (Revised for New Op)
# ==============================================================================
def run_bayesian_nae_estimation(
# User model functions
residual_func,
calculate_responses_func,
# User data and model structure
observed_responses, # Shape: (n_exp, n_responses)
independent_vars, # Shape: (n_exp, n_indep_vars)
fixed_constants, # Dict of fixed values
param_names, # List of parameter names (strings)
param_bounds, # List of [min, max] tuples/lists for parameters
n_states, # Number of NAE states (e.g., concentrations)
n_responses, # Number of observed responses (e.g., 5 for conversion+selectivities)
# Optional & MCMC settings
initial_guess_func=None, # Optional: func(params, conditions) -> guess
sigma_prior_beta=1.0, # Scale for HalfCauchy prior on measurement noise std dev
mcmc_draws=2000,
mcmc_tune=1500,
mcmc_chains=4,
mcmc_cores=1,
seed=None # Add seed for reproducibility
):
"""
Performs Bayesian estimation for parameters in a NAE model using PyMC,
handling multiple experimental conditions.
Args:
residual_func: User function defining NAE residuals (NumPy based).
calculate_responses_func: User function calculating responses from solved NAE states.
observed_responses: NumPy array (n_exp x n_responses) of observed data.
independent_vars: NumPy array (n_exp x n_indep_vars) of experimental conditions.
fixed_constants: Dict of fixed constants needed by model functions.
param_names: List of parameter names (strings).
param_bounds: List of [min, max] bounds for each parameter.
n_states: Total number of state variables solved for by the NAE solver.
n_responses: Number of responses measured/predicted per experiment.
initial_guess_func: Optional function(params, conditions) -> guess for NAE solver.
sigma_prior_beta: Scale parameter for the HalfCauchy prior on sigma.
mcmc_draws, mcmc_tune, mcmc_chains, mcmc_cores: MCMC settings.
seed: Random seed for reproducibility.
Returns:
arviz.InferenceData: Object containing MCMC samples and diagnostics.
pm.Model: The PyMC model object.
"""
n_params = len(param_names)
# Instantiate the custom Op with all necessary data
loglike_op = LogLikeWithNAESolver(
residual_func=residual_func,
calculate_responses_func=calculate_responses_func,
n_states=n_states,
n_responses=n_responses,
independent_vars=independent_vars,
observed_responses=observed_responses,
fixed_constants=fixed_constants,
initial_guess_func=initial_guess_func
)
print("Setting up PyMC model with custom NAE likelihood for multiple experiments...")
with pm.Model() as nae_model:
# --- Priors ---
params_list = []
# Suggestion: Use informative priors if possible based on literature or physical constraints
for i, name in enumerate(param_names):
low, high = param_bounds[i]
if low <= 0 and high > 0: # If parameter can span zero
param_prior = pm.Uniform(name, lower=low, upper=high, initval=np.clip((low + high) / 2.0, low+1e-6, high-1e-6)) # Avoid exactly 0?
elif low >=0 : # If parameter is strictly positive (like rate constants)
# Consider LogUniform or LogNormal if parameter spans orders of magnitude
param_prior = pm.Uniform(name, lower=low, upper=high, initval=(low + high) / 2.0)
else: # Strictly negative (less common for kinetics)
param_prior = pm.Uniform(name, lower=low, upper=high, initval=(low + high) / 2.0)
params_list.append(param_prior)
# Combine parameters into an Aesara vector
params_tt = at.as_tensor_variable(params_list)
# Prior for measurement error standard deviation (one per response type)
sigma = pm.HalfCauchy('sigma', beta=sigma_prior_beta, shape=n_responses, initval=np.full(n_responses, sigma_prior_beta * 0.1)) # Init smaller
# --- Likelihood (via Custom Op and pm.Potential) ---
# Calculate the total log-likelihood using the custom Op
logp = loglike_op(params_tt, sigma)
# Add the calculated log-likelihood to the model's total logp
pm.Potential('likelihood', logp)
# --- MCMC Sampling ---
print(f"Starting MCMC sampling ({mcmc_chains} chains, {mcmc_draws} draws + {mcmc_tune} tune)...")
warnings.warn(
f"Using Metropolis sampler for parameters {param_names} and potentially sigma due to gradient unavailability "
f"in the NAE solver Op. Sampling might be slow or inefficient. Consider increasing draws/tune."
f" Ensure parameters are identifiable from the data."
)
# Use Metropolis for parameters; might try NUTS for sigma if its gradient is available otherwise (unlikely here)
step_methods = [pm.Metropolis(vars=params_list + [sigma])] # Apply Metropolis to all vars
start_time = time.time()
trace = pm.sample(
draws=mcmc_draws,
tune=mcmc_tune,
step=step_methods, # Specify the sampler
chains=mcmc_chains,
cores=mcmc_cores,
return_inferencedata=True,
random_seed=seed,
# initvals={'sigma': np.full(n_responses, 0.1)} # Example initial value
)
end_time = time.time()
print(f"Sampling complete. Time elapsed: {end_time - start_time:.2f} seconds")
return trace, nae_model
# ==============================================================================
# 4. Helper Functions for Analysis / Visualization (Partially Revised for PPC)
# ==============================================================================
# print_mcmc_summary, plot_parameter_posteriors, plot_mcmc_traces remain the same
def print_mcmc_summary(trace, param_names, response_names=None):
"""Prints the ArviZ summary table for parameters and sigma."""
print("\nMCMC Summary Table:")
var_names_to_plot = param_names + ['sigma']
summary = az.summary(trace, var_names=var_names_to_plot, hdi_prob=0.95, round_to=4)
# Optionally rename sigma entries if response_names provided
if response_names and len(response_names) == len(trace.posterior['sigma'].isel(sigma_dim_0=0).values.flatten()):
sigma_labels = {f'sigma[{i}]': f'sigma_{name}' for i, name in enumerate(response_names)}
summary = summary.rename(index=sigma_labels)
print(summary)
return summary
def plot_parameter_posteriors(trace, param_names, response_names=None):
"""Plots the posterior distributions for parameters and sigma."""
print("\nPlotting parameter posteriors...")
var_names_to_plot = param_names + ['sigma']
axes = az.plot_posterior(trace, var_names=var_names_to_plot, hdi_prob=0.95)
# Optionally rename sigma titles if response_names provided
if response_names and len(response_names) == len(trace.posterior['sigma'].isel(sigma_dim_0=0).values.flatten()):
fig = axes.flatten()[0].get_figure()
sigma_axes = fig.axes[len(param_names):] # Get axes corresponding to sigma
for i, ax in enumerate(sigma_axes):
if i < len(response_names):
ax.set_title(f'sigma_{response_names[i]}')
plt.tight_layout()
plt.show()
def plot_mcmc_traces(trace, param_names, response_names=None):
"""Plots MCMC trace plots for convergence diagnostics."""
print("\nPlotting MCMC traces...")
var_names_to_plot = param_names + ['sigma']
axes = az.plot_trace(trace, var_names=var_names_to_plot)
# Optionally rename sigma titles if response_names provided
if response_names and len(response_names) == len(trace.posterior['sigma'].isel(sigma_dim_0=0).values.flatten()):
fig = axes.flatten()[0].get_figure()
# Trace plots usually have pairs of axes (posterior + trace)
sigma_axes_indices = range(len(param_names) * 2, (len(param_names) + len(response_names)) * 2)
all_axes = fig.axes
for plot_idx, ax_idx in enumerate(sigma_axes_indices):
if ax_idx < len(all_axes):
ax = all_axes[ax_idx]
response_idx = plot_idx // 2 # Each response has two plots
if response_idx < len(response_names):
# Only change title for the first plot in the pair (the posterior density)
if plot_idx % 2 == 0:
ax.set_title(f'sigma_{response_names[response_idx]}')
else: # Clear title for the trace plot part? Or keep default like 'sigma[i]'
pass # ax.set_title("") # Or keep the default trace title
plt.tight_layout()
plt.show()
def posterior_predictive_check_nae(
trace,
residual_func,
calculate_responses_func,
n_states,
n_responses,
independent_vars,
observed_responses,
fixed_constants,
param_names,
n_samples=500,
initial_guess_func=None):
"""
Generates posterior predictive samples for NAE models across multiple experiments.
Manually solves NAE for parameters drawn from the posterior trace.
"""
print("\nGenerating posterior predictive samples...")
# Extract posterior samples
posterior = trace.posterior.stack(sample=("chain", "draw"))
param_samples = np.array([posterior[pname].values for pname in param_names]).T
sigma_samples = posterior['sigma'].values # Shape (n_total_samples, n_responses)
n_total_samples = param_samples.shape[0]
if n_total_samples == 0:
print("Warning: No samples found in the trace posterior.")
return None
if n_samples > n_total_samples:
n_samples = n_total_samples
print(f"Warning: Requested n_samples ({n_samples}) > available samples ({n_total_samples}). Using {n_total_samples}.")
# Randomly select samples from the posterior trace
indices = np.random.choice(n_total_samples, n_samples, replace=False)
selected_params = param_samples[indices, :]
selected_sigmas = sigma_samples[indices, :]
# Store PPC samples: shape (n_ppc_samples, n_experiments, n_responses)
n_experiments = independent_vars.shape[0]
ppc_samples_mean = np.zeros((n_samples, n_experiments, n_responses)) # Store mean predictions
ppc_samples_noisy = np.zeros((n_samples, n_experiments, n_responses)) # Store predictions with noise
failures_count = 0
indep_var_names = list(independent_vars.dtype.names) if independent_vars.dtype.names else [f'indep_var_{i}' for i in range(independent_vars.shape[1])]
for s_idx in range(n_samples):
params = selected_params[s_idx, :]
sigmas = selected_sigmas[s_idx, :] # Vector of sigmas for this sample
for exp_idx in range(n_experiments):
# Get conditions for this experiment
current_indep_vars = independent_vars[exp_idx]
current_conditions = fixed_constants.copy()
if indep_var_names:
for idx, name in enumerate(indep_var_names):
current_conditions[name] = current_indep_vars[idx]
else:
for idx in range(len(current_indep_vars)):
current_conditions[f'indep_var_{idx}'] = current_indep_vars[idx]
# Solve NAE for this sample and condition
if initial_guess_func:
initial_guess = initial_guess_func(params, current_conditions)
else:
initial_guess = np.ones(n_states) * 1e-3 # Adjust if needed
sol = root(fun=residual_func, x0=initial_guess, args=(params, current_conditions), method='lm', tol=1e-8)
if sol.success:
y_ss_pred = sol.x
# Calculate predicted responses (mean prediction)
predicted_responses = calculate_responses_func(y_ss_pred, params, current_conditions)
# Ensure correct shape before assignment
if len(predicted_responses) == n_responses:
ppc_samples_mean[s_idx, exp_idx, :] = predicted_responses
# Simulate observation noise for this experiment's predictions
noise = np.random.normal(0, sigmas, size=n_responses)
ppc_samples_noisy[s_idx, exp_idx, :] = predicted_responses + noise
else:
print(f"PPC Warning: Response shape mismatch for sample {s_idx}, exp {exp_idx}.")
# Fill with NaN or keep as zero? Let's use NaN for mean, noisy already zeros.
ppc_samples_mean[s_idx, exp_idx, :] = np.nan
failures_count += 1 # Count as a failure
else:
# Handle solver failure - fill predictions with NaN
ppc_samples_mean[s_idx, exp_idx, :] = np.nan
ppc_samples_noisy[s_idx, exp_idx, :] = np.nan # Can't generate noisy version either
failures_count += 1
if failures_count > 0:
print(f"PPC Warning: NAE solver failed or response calculation failed for {failures_count} out of {n_samples * n_experiments} predictions.")
# Create an ArviZ InferenceData object for PPC
# We use the "noisy" samples as the 'y_hat' for typical PPC plots
ppc_idata = az.from_dict(posterior_predictive={'y_hat': ppc_samples_noisy})
return ppc_idata, ppc_samples_mean # Return idata and mean predictions
def plot_posterior_predictive_check(ppc_idata, observed_responses, response_names=None):
"""Plots posterior predictive checks (observed vs predicted)."""
if ppc_idata is None:
print("Cannot plot posterior predictive: No PPC data generated.")
return
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:
print("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)]
# Get the posterior predictive samples
# ArviZ expects shape (chains * draws, observations) -> (n_samples, n_experiments * n_responses)
# Our ppc_samples_noisy shape is (n_samples, n_experiments, n_responses)
# We need to provide observed data correctly matched to predictions.
# Easiest is often Observed vs. Predicted plot.
y_hat = ppc_idata.posterior_predictive['y_hat'].values # Shape (chains, draws, n_exp, n_resp)
# Stack chains and draws
y_hat_stacked = y_hat.reshape(-1, n_experiments, n_responses) # Shape (n_samples, n_exp, n_resp)
# Calculate mean prediction and HDI for each experiment and response
y_hat_mean = np.nanmean(y_hat_stacked, axis=0) # Shape (n_exp, n_resp)
hdi_prob = 0.94 # Standard ArviZ HDI
y_hat_hdi = az.hdi(y_hat_stacked, hdi=hdi_prob, axis=0) # Shape (n_exp, n_resp, 2) [lower, upper]
# Create Observed vs. Predicted plots for each response
n_cols = min(3, n_responses)
n_rows = (n_responses + n_cols - 1) // n_cols
fig, axes = plt.subplots(n_rows, n_cols, figsize=(5 * n_cols, 5 * n_rows), squeeze=False)
axes = axes.flatten()
print("\nPlotting Posterior Predictive Checks (Observed vs. Predicted)...")
for j in range(n_responses):
ax = axes[j]
obs_j = observed_responses[:, j]
pred_mean_j = y_hat_mean[:, j]
pred_hdi_j = y_hat_hdi[:, j, :]
# Calculate error bars for HDI
y_err = np.abs(pred_hdi_j.T - pred_mean_j) # Shape (2, n_exp)
ax.errorbar(obs_j, pred_mean_j, yerr=y_err, fmt='o', alpha=0.6, capsize=3, label=f'{hdi_prob*100}% HDI')
# Add parity line
lims = [min(ax.get_xlim()[0], ax.get_ylim()[0]),
max(ax.get_xlim()[1], ax.get_ylim()[1])]
lims = [min(lims[0], np.nanmin(obs_j), np.nanmin(pred_mean_j)),
max(lims[1], np.nanmax(obs_j), np.nanmax(pred_mean_j))]
padding = (lims[1] - lims[0]) * 0.05
lims = [lims[0] - padding, lims[1] + padding]
ax.plot(lims, lims, 'k--', alpha=0.7, label='Parity')
ax.set_xlabel("Observed " + response_names[j])
ax.set_ylabel("Predicted " + response_names[j])
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)
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # Adjust layout for suptitle
plt.show()
# Optional: Plot distribution comparison (like the original code)
# This compares the overall distribution of observed vs predicted
print("\nPlotting Posterior Predictive Checks (Distributions)...")
fig_dist, axes_dist = plt.subplots(n_rows, n_cols, figsize=(5 * n_cols, 4 * n_rows), squeeze=False)
axes_dist = axes_dist.flatten()
for j in range(n_responses):
ax = axes_dist[j]
obs_vals = observed_responses[:, j]
# Flatten predictions across all samples and experiments for distribution plot
ppc_vals_flat = y_hat_stacked[:, :, j].flatten()
# Remove NaNs that might result from solver failures
ppc_vals_flat = ppc_vals_flat[~np.isnan(ppc_vals_flat)]
az.plot_dist(obs_vals, color='k', label='Observed Data', ax=ax)
az.plot_dist(ppc_vals_flat, color='C0', label='Posterior Predictive', ax=ax)
ax.set_xlabel(f'Value ({response_names[j]})')
ax.set_ylabel('Density')
ax.set_title(f'PPC Distribution - {response_names[j]}')
ax.legend()
ax.grid(True, linestyle=':')
for k in range(n_responses, len(axes_dist)):
axes_dist[k].set_visible(False)
plt.suptitle("Posterior Predictive Check (Overall Distributions)")
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.show()
# ==============================================================================
# 5. Example Usage (Adapted for User's Scenario)
# ==============================================================================
if __name__ == "__main__":
print("Running Bayesian NAE Estimation for CSTR with Experimental Data...")
# --- User-Specific Setup ---
# 1. Define Kinetic Parameter Names and Priors
param_names_user = ['k1', 'k2'] # Example: Rate constants
param_bounds_user = [(0.01, 10.0), (0.001, 5.0)] # Example bounds (adjust based on knowledge)
# 2. Define Fixed Constants
fixed_constants_user = {'V_reactor': 10.0} # Example: Reactor volume in L
# 3. Define Names for Independent Variables (used for conditions dict)
# MUST match the order of columns in the independent_vars_user array
independent_variable_names = ['CA_in', 'Q', 'Temperature'] # Example
# 4. Define Number of States in NAE and Number of Responses
n_states_user = 2 # Example: [CA_ss, CB_ss] solved internally
n_responses_user = 5 # Conversion + 4 Selectivities/Yields/Concentrations
response_names_user = ['ConversionA', 'SelectivityB', 'SelectivityC', 'YieldD', 'ConcE'] # Example names
# 5. Load or Generate Experimental Data
# Ideally: Load your actual data here
# observed_responses_user = np.loadtxt('path/to/your/observed_data.csv', delimiter=',')
# independent_vars_user_raw = np.loadtxt('path/to/your/independent_vars.csv', delimiter=',')
# # Important: Structure independent_vars for easy access by name if possible
# independent_vars_user = np.core.records.fromarrays(
# independent_vars_user_raw.T,
# names=','.join(independent_variable_names)
# )
# ---- Generate Synthetic Data for Demonstration ----
print("\n--- Generating Synthetic Data for Demonstration ---")
true_params_user = np.array([0.75, 0.15]) # Example true values for k1, k2
n_experiments_user = 20 # Number of different experimental conditions
# Generate varying independent variables (example)
np.random.seed(42) # for reproducibility
indep_vars_data = {
'CA_in': np.random.uniform(0.5, 1.5, n_experiments_user),
'Q': np.random.uniform(0.8, 1.2, n_experiments_user),
'Temperature': np.random.uniform(300, 350, n_experiments_user) # Example if Temp is used
}
# Create structured array
independent_vars_user = np.array(
list(zip(*[indep_vars_data[name] for name in independent_variable_names])),
dtype=[(name, 'f8') for name in independent_variable_names]
)
# print("Example Independent Variables:\n", independent_vars_user[:3])
# Calculate true responses for each condition using the model functions
true_responses_user = np.zeros((n_experiments_user, n_responses_user))
print("Calculating true responses for synthetic data generation...")
for i in range(n_experiments_user):
current_indep_vars = independent_vars_user[i]
current_conditions = fixed_constants_user.copy()
for name in independent_variable_names:
current_conditions[name] = current_indep_vars[name]
# Solve NAE with true parameters
initial_guess_true = np.ones(n_states_user) * 0.1 # Adjust guess if needed
sol_true = root(fun=cstr_model_residuals_user, # Use the USER's residual func
x0=initial_guess_true,
args=(true_params_user, current_conditions),
method='lm', tol=1e-8)
if not sol_true.success:
print(f"Warning: Could not solve true state for experiment {i} conditions: {current_conditions}")
true_responses_user[i, :] = np.nan # Mark as invalid
continue
y_ss_true = sol_true.x
# Calculate responses with true parameters
responses = calculate_responses_user(y_ss_true, true_params_user, current_conditions) # Use USER's response func
true_responses_user[i, :] = responses
# Add noise to simulate real measurements
# Use relative noise for things like conversion/selectivity, absolute for concentrations?
# Example: Relative noise for first 3, Absolute for last 2
relative_noise_std = np.array([0.05, 0.08, 0.08]) # 5%, 8%, 8% relative error std dev
absolute_noise_std = np.array([0.01, 0.02]) # Absolute error std dev
measurement_noise_std_dev = np.concatenate( (relative_noise_std, absolute_noise_std) ) # For setting prior later
observed_responses_user = np.zeros_like(true_responses_user)
for i in range(n_experiments_user):
if np.isnan(true_responses_user[i,0]): continue # Skip if true solution failed
noise_realization = np.zeros(n_responses_user)
# Relative noise
noise_realization[:3] = true_responses_user[i, :3] * np.random.normal(0, relative_noise_std)
# Absolute noise
noise_realization[3:] = np.random.normal(0, absolute_noise_std)
observed_responses_user[i,:] = true_responses_user[i,:] + noise_realization
# Ensure realistic bounds (e.g., conversion <= 1, selectivities >= 0) - specific to user's responses
observed_responses_user[i, 0] = np.clip(observed_responses_user[i, 0], 0, 1) # Clip conversion example
observed_responses_user[i, 1:] = np.maximum(observed_responses_user[i, 1:], 1e-9) # Ensure others positive
# Remove rows where true solution failed (important!)
valid_rows = ~np.isnan(observed_responses_user[:, 0])
observed_responses_user = observed_responses_user[valid_rows, :]
independent_vars_user = independent_vars_user[valid_rows]
print(f"Generated {observed_responses_user.shape[0]} valid noisy observations.")
# print("Example Observed Responses:\n", observed_responses_user[:3])
# ---- End Synthetic Data Generation ----
# --- Run Bayesian Estimation ---
# Optional: Define a smarter initial guess function if needed
# def my_initial_guess_func(params, conditions):
# # Logic based on params and conditions to get a better guess
# # Example: maybe guess conversion based on k1 and tau?
# tau = conditions['V_reactor'] / conditions['Q']
# k1_guess = params[0]
# # ... more logic ...
# return np.ones(n_states_user) * 0.1 # Return guess vector
estimation_trace, estimation_model = run_bayesian_nae_estimation(
residual_func=cstr_model_residuals_user, # Pass the USER'S function
calculate_responses_func=calculate_responses_user, # Pass the USER'S function
observed_responses=observed_responses_user,
independent_vars=independent_vars_user,
fixed_constants=fixed_constants_user,
param_names=param_names_user,
param_bounds=param_bounds_user,
n_states=n_states_user,
n_responses=n_responses_user,
# initial_guess_func=my_initial_guess_func, # Optional
sigma_prior_beta=0.1, # Adjust prior scale based on expected noise magnitude
mcmc_draws=5000, # Metropolis often needs more draws
mcmc_tune=5000, # And more tuning
mcmc_chains=4,
mcmc_cores=4, # Use multiple cores if available
seed=123 # For reproducibility
)
# --- Analyze Results ---
summary_table = print_mcmc_summary(estimation_trace, param_names_user, response_names=response_names_user)
plot_parameter_posteriors(estimation_trace, param_names_user, response_names=response_names_user)
plot_mcmc_traces(estimation_trace, param_names_user, response_names=response_names_user) # Crucial for Metropolis
# Perform and plot posterior predictive checks
ppc_idata, ppc_mean_predictions = posterior_predictive_check_nae(
trace=estimation_trace,
residual_func=cstr_model_residuals_user, # USER'S function
calculate_responses_func=calculate_responses_user, # USER'S function
n_states=n_states_user,
n_responses=n_responses_user,
independent_vars=independent_vars_user,
observed_responses=observed_responses_user,
fixed_constants=fixed_constants_user,
param_names=param_names_user,
n_samples=500, # Number of posterior samples to use for PPC
# initial_guess_func=my_initial_guess_func # Optional
)
plot_posterior_predictive_check(ppc_idata, observed_responses_user, response_names=response_names_user)
print("\nExample Finished.")