Bayesian uncertainty analysis#
R.A. Collenteur, Eawag, June, 2023
In this notebook it is shown how the MCMC-algorithm can be used to estimate the model parameters and quantify the (parameter) uncertainties for a Pastas model using a Bayesian approach. For this the EmceeSolver is introduced, based on the emcee Python package.
Besides Pastas the following Python Packages have to be installed to run this notebook:
import corner
import emcee
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pastas as ps
ps.set_log_level("ERROR")
ps.show_versions()
Pastas : 2.0.0
Python : 3.14.0
Numpy : 2.4.6
Pandas : 3.0.3
Scipy : 1.17.1
Matplotlib : 3.10.9
Numba : 0.65.1
1. Create a Pastas Model#
The first step is to create a Pastas Model, including the RechargeModel to simulate the effect of precipitation and evaporation on the heads. Here, we first estimate the model parameters using the standard least-squares approach.
head = pd.read_csv(
"data/B32C0639001.csv", parse_dates=["date"], index_col="date"
).squeeze()
evap = pd.read_csv("data/evap_260.csv", index_col=0, parse_dates=[0]).squeeze()
rain = pd.read_csv("data/rain_260.csv", index_col=0, parse_dates=[0]).squeeze()
ml = ps.Model(head)
ml.add_noisemodel(ps.ArNoiseModel())
# Select a recharge model
rch = ps.rch.FlexModel()
rm = ps.RechargeModel(rain, evap, recharge=rch, rfunc=ps.Gamma(), name="rch")
ml.add_stressmodel(rm)
ml.solve(tmin="1990")
ax = ml.plot(figsize=(10, 3))
Fit report head Fit Statistics
==================================================
nfev 35 EVP 87.37
nobs 351 R2 0.87
noise True RMSE 0.07
tmin 1990-01-01 00:00:00 AICc -2048.61
tmax 2005-10-14 00:00:00 BIC -2014.39
freq D Obj 0.49
freq_obs None ___
warmup 3650 days 00:00:00 Interp. No
Parameters (9 optimized)
==================================================
optimal initial vary
rch_A 0.473048 0.630436 True
rch_n 0.674025 1.000000 True
rch_a 311.234331 10.000000 True
rch_srmax 75.363926 250.000000 True
rch_lp 0.250000 0.250000 False
rch_ks 50.997527 100.000000 True
rch_gamma 2.203450 2.000000 True
rch_kv 1.999647 1.000000 True
rch_simax 2.000000 2.000000 False
constant_d 0.790329 1.359779 True
noise_alpha 42.580834 15.000000 True
2. Use the EmceeSolver#
We will now use the EmceeSolve solver to estimate the model parameters and their uncertainties. This solver wraps the Emcee package, which implements different versions of MCMC. A good understanding of Emcee helps when using this solver, so it comes recommended to check out their documentation as well.
To set up the solver, a number of decisions need to be made:
Determine the priors of the parameters
Choose a (log) likelihood function
Choose the number of steps and thinning
2a. Choose and set the priors#
The first step is to choose and set the priors of the parameters. This is done by using the ml.set_parameter method and the dist argument (from distribution). Any distribution from the scipy.stats can be chosen (https://docs.scipy.org/doc/scipy/tutorial/stats/continuous.html), for example uniform, norm, or lognorm. Here, for the sake of the example, we set all prior distributions to a normal distribution.
# Set the initial parameters to a normal distribution
for name in ml.parameters.index:
ml.set_parameter(name, dist="norm")
ml.parameters
| initial | pmin | pmax | vary | name | dist | stderr | optimal | |
|---|---|---|---|---|---|---|---|---|
| rch_A | 0.630436 | 0.00001 | 63.043598 | True | rch | norm | 0.047620 | 0.473048 |
| rch_n | 1.000000 | 0.10000 | 5.000000 | True | rch | norm | 0.031943 | 0.674025 |
| rch_a | 10.000000 | 0.01000 | 10000.000000 | True | rch | norm | 64.881837 | 311.234331 |
| rch_srmax | 250.000000 | 0.00001 | 1000.000000 | True | rch | norm | 42.277454 | 75.363926 |
| rch_lp | 0.250000 | 0.00001 | 1.000000 | False | rch | norm | NaN | 0.250000 |
| rch_ks | 100.000000 | 0.00001 | 10000.000000 | True | rch | norm | 59.061896 | 50.997527 |
| rch_gamma | 2.000000 | 0.00001 | 20.000000 | True | rch | norm | 0.201305 | 2.203450 |
| rch_kv | 1.000000 | 0.25000 | 2.000000 | True | rch | norm | 0.424225 | 1.999647 |
| rch_simax | 2.000000 | 0.00000 | 10.000000 | False | rch | norm | NaN | 2.000000 |
| constant_d | 1.359779 | NaN | NaN | True | constant | norm | 0.052656 | 0.790329 |
| noise_alpha | 15.000000 | 0.00001 | 5000.000000 | True | noise | norm | 6.544576 | 42.580834 |
Pastas will use the initial value of the parameter for the loc argument of the distribution (e.g., the mean of a normal distribution), and the stderr as the scale argument (e.g., the standard deviation of a normal distribution). Only for the parameters with a uniform distribution, the pmin and pmax values are used to determine a uniform prior. By default, all parameters are assigned a uniform prior.
2b. Create the solver instance#
The next step is to create an instance of the EmceeSolve solver class. At this stage all the settings need to be provided on how the Ensemble Sampler is created (https://emcee.readthedocs.io/en/stable/user/sampler/). Important settings are the nwalkers, the moves, the objective_function. More advanced options are to parallelize the MCMC algorithm (parallel=True), and to set a backend to store the results. Here’s an example:
# Choose the objective function
ln_prob = ps.objfunc.GaussianLikelihoodAr1()
# Create the EmceeSolver with some settings
s = ps.EmceeSolve(
nwalkers=20,
moves=emcee.moves.DEMove(),
objective_function=ln_prob,
progress_bar=True,
parallel=False,
)
In the above code we created an EmceeSolve instance with 20 walkers, which take steps according to the DEMove move algorithm (see Emcee docs), and a Gaussian likelihood function that assumes AR1 correlated errors. Different objective functions are available, see the Pastas documentation on the different options.
Depending on the likelihood function, a number of additional parameters need to be inferred. These parameters are not added to the Pastas Model instance, but are available from the solver object. Using the set_parameter method of the solver, these parameters can be changed. In this example where we use the GaussianLikelihoodAr1 function the sigma and theta are estimated; the unknown standard deviation of the errors and the autoregressive parameter.
s.parameters
| initial | pmin | pmax | vary | stderr | name | dist | |
|---|---|---|---|---|---|---|---|
| ln_var | 0.05 | 1.000000e-10 | 1.00000 | True | 0.01 | ln | uniform |
| ln_phi | 0.50 | 1.000000e-10 | 0.99999 | True | 0.20 | ln | uniform |
s.set_parameter("ln_var", initial=0.0028, vary=False, dist="norm")
s.parameters
| initial | pmin | pmax | vary | stderr | name | dist | |
|---|---|---|---|---|---|---|---|
| ln_var | 0.0028 | 1.000000e-10 | 1.00000 | False | 0.01 | ln | norm |
| ln_phi | 0.5000 | 1.000000e-10 | 0.99999 | True | 0.20 | ln | uniform |
2c. Run the solver and solve the model#
After setting the parameters and creating a EmceeSolve solver instance we are now ready to run the MCMC analysis. We can do this by running ml.solve. We can pass the same parameters that we normally provide to this method (e.g., tmin or fit_constant). Here we use the initial parameters from our least-square solve, and do not fit a noise model, because we take autocorrelated errors into account through the likelihood function.
All the arguments that are not used by ml.solve, for example steps and tune, are passed on to the run_mcmc method from the sampler (see Emcee docs). The most important is the steps argument, that determines how many steps each of the walkers takes.
# Use the solver to run MCMC
ml.del_noisemodel()
ml.solve(
solver=s,
initial=False,
fit_constant=False,
tmin="1990",
steps=100,
tune=True,
)
Fit report head Fit Statistics
==================================================
nfev nan EVP 88.10
nobs 351 R2 0.88
noise False RMSE 0.07
tmin 1990-01-01 00:00:00 AICc -1835.06
tmax 2005-10-14 00:00:00 BIC -1808.36
freq D Obj nan
freq_obs None ___
warmup 3650 days 00:00:00 Interp. No
Parameters (7 optimized)
==================================================
optimal initial vary
rch_A 0.476766 0.473048 True
rch_n 0.678931 0.674025 True
rch_a 304.906105 311.234331 True
rch_srmax 52.436214 75.363926 True
rch_lp 0.250000 0.250000 False
rch_ks 29.583133 50.997527 True
rch_gamma 2.473316 2.203450 True
rch_kv 1.979099 1.999647 True
rch_simax 2.000000 2.000000 False
constant_d 0.815720 0.000000 False
0%| | 0/100 [00:00<?, ?it/s]
/home/docs/checkouts/readthedocs.org/user_builds/pastas/envs/latest/lib/python3.14/site-packages/emcee/moves/red_blue.py:99: RuntimeWarning: invalid value encountered in scalar subtract
lnpdiff = f + nlp - state.log_prob[j]
2%|▏ | 2/100 [00:00<00:05, 18.54it/s]
4%|▍ | 4/100 [00:00<00:05, 16.08it/s]
6%|▌ | 6/100 [00:00<00:06, 14.09it/s]
8%|▊ | 8/100 [00:00<00:06, 13.45it/s]
10%|█ | 10/100 [00:00<00:07, 12.12it/s]
12%|█▏ | 12/100 [00:00<00:07, 11.58it/s]
14%|█▍ | 14/100 [00:01<00:07, 11.04it/s]
16%|█▌ | 16/100 [00:01<00:08, 10.43it/s]
18%|█▊ | 18/100 [00:01<00:08, 10.09it/s]
20%|██ | 20/100 [00:01<00:07, 10.58it/s]
22%|██▏ | 22/100 [00:01<00:07, 10.45it/s]
24%|██▍ | 24/100 [00:02<00:07, 10.34it/s]
26%|██▌ | 26/100 [00:02<00:07, 10.20it/s]
28%|██▊ | 28/100 [00:02<00:06, 10.36it/s]
30%|███ | 30/100 [00:02<00:06, 10.33it/s]
32%|███▏ | 32/100 [00:02<00:06, 10.27it/s]
34%|███▍ | 34/100 [00:03<00:06, 10.60it/s]
36%|███▌ | 36/100 [00:03<00:06, 10.11it/s]
38%|███▊ | 38/100 [00:03<00:06, 10.03it/s]
40%|████ | 40/100 [00:03<00:05, 10.81it/s]
42%|████▏ | 42/100 [00:03<00:05, 10.98it/s]
44%|████▍ | 44/100 [00:04<00:05, 10.89it/s]
46%|████▌ | 46/100 [00:04<00:05, 10.31it/s]
48%|████▊ | 48/100 [00:04<00:04, 10.43it/s]
50%|█████ | 50/100 [00:04<00:04, 10.47it/s]
52%|█████▏ | 52/100 [00:04<00:04, 10.45it/s]
54%|█████▍ | 54/100 [00:05<00:04, 10.07it/s]
56%|█████▌ | 56/100 [00:05<00:04, 9.64it/s]
57%|█████▋ | 57/100 [00:05<00:04, 9.58it/s]
58%|█████▊ | 58/100 [00:05<00:04, 9.55it/s]
59%|█████▉ | 59/100 [00:05<00:04, 9.42it/s]
61%|██████ | 61/100 [00:05<00:04, 9.54it/s]
62%|██████▏ | 62/100 [00:05<00:04, 9.47it/s]
63%|██████▎ | 63/100 [00:06<00:03, 9.44it/s]
64%|██████▍ | 64/100 [00:06<00:03, 9.33it/s]
65%|██████▌ | 65/100 [00:06<00:03, 9.28it/s]
66%|██████▌ | 66/100 [00:06<00:03, 9.24it/s]
67%|██████▋ | 67/100 [00:06<00:03, 9.42it/s]
69%|██████▉ | 69/100 [00:06<00:03, 9.78it/s]
71%|███████ | 71/100 [00:06<00:02, 10.31it/s]
73%|███████▎ | 73/100 [00:07<00:02, 9.96it/s]
74%|███████▍ | 74/100 [00:07<00:02, 9.84it/s]
76%|███████▌ | 76/100 [00:07<00:02, 10.04it/s]
78%|███████▊ | 78/100 [00:07<00:02, 10.07it/s]
80%|████████ | 80/100 [00:07<00:02, 9.97it/s]
81%|████████ | 81/100 [00:07<00:01, 9.96it/s]
82%|████████▏ | 82/100 [00:07<00:01, 9.95it/s]
83%|████████▎ | 83/100 [00:08<00:01, 9.79it/s]
84%|████████▍ | 84/100 [00:08<00:01, 9.79it/s]
85%|████████▌ | 85/100 [00:08<00:01, 9.70it/s]
87%|████████▋ | 87/100 [00:08<00:01, 9.73it/s]
89%|████████▉ | 89/100 [00:08<00:01, 9.74it/s]
90%|█████████ | 90/100 [00:08<00:01, 9.75it/s]
91%|█████████ | 91/100 [00:08<00:00, 9.53it/s]
92%|█████████▏| 92/100 [00:08<00:00, 9.45it/s]
94%|█████████▍| 94/100 [00:09<00:00, 9.65it/s]
95%|█████████▌| 95/100 [00:09<00:00, 9.63it/s]
97%|█████████▋| 97/100 [00:09<00:00, 10.03it/s]
99%|█████████▉| 99/100 [00:09<00:00, 10.16it/s]
100%|██████████| 100/100 [00:09<00:00, 10.25it/s]
3. Posterior parameter distributions#
The results from the MCMC analysis are stored in the sampler object, accessible through ml.solver.sampler variable. The object ml.solver.sampler.flatchain contains a Pandas DataFrame with \(n\) the parameter samples, where \(n\) is calculated as follows:
\(n = \frac{\left(\text{steps}-\text{burn}\right)\cdot\text{nwalkers}}{\text{thin}} \)
Corner.py#
Corner is a simple but great python package that makes creating corner graphs easy. A couple of lines of code suffice to create a plot of the parameter distributions and the covariances between the parameters.
# Corner plot of the results
fig = plt.figure(figsize=(8, 8))
labels = list(ml.parameters.index[ml.parameters.vary]) + list(
ml.solver.parameters.index[ml.solver.parameters.vary]
)
labels = [label.split("_")[1] for label in labels]
best = list(ml.parameters[ml.parameters.vary].optimal) + list(
ml.solver.parameters[ml.solver.parameters.vary].optimal
)
axes = corner.corner(
ml.solver.sampler.get_chain(flat=True, discard=50),
quantiles=[0.025, 0.5, 0.975],
labelpad=0.1,
show_titles=True,
title_kwargs=dict(fontsize=10),
label_kwargs=dict(fontsize=10),
max_n_ticks=3,
fig=fig,
labels=labels,
truths=best,
)
plt.show()
4. What happens to the walkers at each step?#
The walkers take steps in different directions for each step. It is expected that after a number of steps, the direction of the step becomes random, as a sign that an optimum has been found. This can be checked by looking at the autocorrelation, which should be insignificant after a number of steps. Below we just show how to obtain the different chains, the interpretation of which is outside the scope of this notebook.
fig, axes = plt.subplots(len(labels), figsize=(10, 7), sharex=True)
samples = ml.solver.sampler.get_chain(flat=True)
for i in range(len(labels)):
ax = axes[i]
ax.plot(samples[:, i], "k", alpha=0.5)
ax.set_xlim(0, len(samples))
ax.set_ylabel(labels[i])
ax.yaxis.set_label_coords(-0.1, 0.5)
axes[-1].set_xlabel("step number")
Text(0.5, 0, 'step number')
5. Plot some simulated time series to display uncertainty?#
We can now draw parameter sets from the chain and simulate the uncertainty in the head simulation.
# Plot results and uncertainty
ax = ml.plot(figsize=(10, 3))
plt.title(None)
chain = ml.solver.sampler.get_chain(flat=True, discard=50)
inds = np.random.randint(len(chain), size=100)
for ind in inds:
params = chain[ind]
p = ml.parameters.optimal.copy().to_numpy(copy=True)
p[ml.parameters.vary] = params[: ml.parameters.vary.sum()]
_ = ml.simulate(p, tmin="1990").plot(c="gray", alpha=0.1, zorder=-1)
plt.legend(["Measurements", "Simulation", "Ensemble members"], numpoints=3);