{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Frequentist uncertainty vs. Bayesian uncertainty analysis\n", "*Mark Bakker, TU Delft & Raoul Collenteur, Hydroconsult, February, 2025 (last updated May 2026)*\n", "\n", "In this notebook, the fit and uncertainty are compared for Pastas models solved with least squares (frequentist uncertainty) and with MCMC (Bayesian uncertainty). Besides Pastas the following Python Packages have to be installed to run this notebook:\n", "\n", "- [emcee](https://emcee.readthedocs.io)\n", "- [corner](https://corner.readthedocs.io)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import corner\n", "import emcee\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import pandas as pd\n", "\n", "import pastas as ps\n", "\n", "ps.set_log_level(\"ERROR\")\n", "ps.show_versions()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. A 'regular' Pastas Model\n", "The first step is to create a Pastas Model with a linear `RechargeModel` and a `Gamma` response function to simulate the effect of precipitation and evaporation on the heads. The AR1 noise model is used. We first estimate the model parameters using the standard least-squares approach." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "head = pd.read_csv(\n", " \"data/B32C0639001.csv\", parse_dates=[\"date\"], index_col=\"date\"\n", ").squeeze()\n", "head = head[\"1990\":] # use data from 1990 on for this example\n", "\n", "evap = pd.read_csv(\"data/evap_260.csv\", index_col=0, parse_dates=[0]).squeeze()\n", "rain = pd.read_csv(\"data/rain_260.csv\", index_col=0, parse_dates=[0]).squeeze()\n", "\n", "ml1 = ps.Model(head)\n", "ps.ArNoiseModel(ml1)\n", "\n", "rm = ps.RechargeModel(\n", " ml1, rain, evap, recharge=ps.rch.Linear(), rfunc=ps.Gamma(), name=\"rch\"\n", ")\n", "\n", "ml1.solve()\n", "\n", "ax = ml1.plots.results(figsize=(8, 4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The diagnostics show that the noise meets the statistical requirements for uncertainty analysis reasonably well. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ml1.plots.diagnostics();" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ml1.parameters" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The estimated least squares parameters and standard errors are stored for later reference" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ls_params = ml1.parameters[[\"optimal\", \"stderr\"]].copy()\n", "ls_params.rename(columns={\"optimal\": \"ls_opt\", \"stderr\": \"ls_sig\"}, inplace=True)\n", "ls_params" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute prediction interval Pastas\n", "pi = ml1.solver.prediction_interval(n=1000)\n", "ax = ml1.plot(figsize=(10, 3))\n", "ax.fill_between(pi.index, pi.iloc[:, 0], pi.iloc[:, 1], color=\"lightgray\")\n", "ax.legend([\"Observations\", \"Simulation\", \"95% Prediction interval\"], ncol=3, loc=2)\n", "pi_pasta = np.mean(pi[0.975] - pi[0.025])\n", "print(f\"Mean prediction interval width: {pi_pasta:.3f} m\")\n", "print(f\"Prediction interval coverage probability: {ps.stats.picp(head, pi): .3f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Use the EmceeSolver\n", "\n", "We will now use MCMC to estimate the model parameters and their uncertainties. The `EmceeSolve` solver wraps the [Emcee](https://lmfit.github.io/lmfit-py/fitting.html#lmfit.minimizer.Minimizer.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.\n", "\n", "We start by making a `pastas` model with a linear recharge model and a Gamma response function. No noise model is added, as this is taken care of in the likelihood function. The model is solved using the regular solve (least squares) to have a good estimate of the starting values of the parameters." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ml2 = ps.Model(head)\n", "rm = ps.RechargeModel(\n", " ml2, rain, evap, recharge=ps.rch.Linear(), rfunc=ps.Gamma(), name=\"rch\"\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ml2.parameters" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To set up the `EmceeSolve` solver, a number of decisions need to be made:\n", "\n", "- Select a (log) likelihood function\n", "- Select the priors of the parameters\n", "- Select the number of steps and thinning\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2a. Create the solver instance\n", "\n", "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 `objfunction`. More advanced options are to parallelize the MCMC algorithm (`parallel=True`), and to set a backend to store the results. Here's an example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "parameters" ] }, "outputs": [], "source": [ "NUM_STEPS = 10" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Choose the objective function\n", "ln_prob = ps.objective.likelihood.GaussianLikelihoodAr1()\n", "\n", "# Create the EmceeSolver with some settings\n", "s = ps.solver.Emcee(\n", " model=ml2,\n", " nwalkers=20,\n", " nsteps=NUM_STEPS,\n", " moves=emcee.moves.DEMove(),\n", " objfunction=ln_prob,\n", " progress_bar=True,\n", " parallel=False,\n", ")\n", "ml2.parameters" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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. \n", "\n", "Depending on the likelihood function, a number of additional parameters need to be inferred. These parameters are added to the Pastas Model instance. Using the `set_parameter` method of the model, these parameters can be changed. In this example where we use the `GaussianLikelihoodAr1` function, the $\\sigma^2$ and $\\phi$ are estimated; the unknown standard deviation of the errors and the autoregressive parameter." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2b. Priors\n", "\n", "The first step is to select the priors of the parameters. This is done by using the `ml.set_parameter` method and the `dist` argument (from distribution). Any distribution from `scipy.stats` can be chosen (https://docs.scipy.org/doc/scipy/tutorial/stats/continuous.html), for example `uniform`, `norm`, or `lognorm`. Here, we select normal distributions for the priors. \n", "\n", "Currently, `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 `sigma` 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.\n", "\n", "