{ "cells": [ { "cell_type": "markdown", "id": "fa0b630a-9017-45c6-b640-8404be2987ea", "metadata": {}, "source": [ "# Ensemble Predictions\n", "*R.A. Collenteur, Eawag, 2025*\n", "\n", "This notebook shows how to use Pastas and meteorological ensemble forecasts to generate ensemble groundwater predictions (EGPs). The goal is to forecast the groundwater levels for a well in Switzerland (Gossau), one month ahead. Meteorological ensemble forecasts of the ECMWF with 51 ensemble members are used as data input. These members represent the uncertainty in the meteorological input data. \n", "\n", "The Pastas model is calibrated on 10 years of head data prior to the start of the forecast, using meteorological data provided by MeteoSwiss. In this example, meteorological forecasts are used, but it is straightforward to extend this to other input data such as ensembles of pumping forecasts.\n", "\n", "
\n", "Note:\n", "Collenteur et al. (In submission) Ensemble groundwater predictions (EGP) in alluvial aquifers in Switzerland.\n", "
\n", "\n", "## 0. Import Python Packages" ] }, { "cell_type": "code", "execution_count": null, "id": "19440a46-a262-4d52-a158-13e429c75402", "metadata": {}, "outputs": [], "source": [ "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(\"INFO\")\n", "ps.show_versions()" ] }, { "cell_type": "markdown", "id": "0542d01e-dd78-400e-a98e-6fc396632376", "metadata": {}, "source": [ "## 1. Load data\n", "\n", "Below the head and meteorological data is loaded for the well in Gossau, Switzerland.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "525b28c7", "metadata": {}, "outputs": [], "source": [ "head = pd.read_csv(\"data_forecast/heads.csv\", index_col=0, parse_dates=True).squeeze()\n", "prec = pd.read_csv(\"data_forecast/prec.csv\", index_col=0, parse_dates=True).squeeze()\n", "evap = pd.read_csv(\"data_forecast/evap.csv\", index_col=0, parse_dates=True).squeeze()\n", "temp = pd.read_csv(\"data_forecast/temp.csv\", index_col=0, parse_dates=True).squeeze()\n", "\n", "ps.plots.series(\n", " head,\n", " [prec, evap, temp],\n", " tmin=\"2004\",\n", " tmax=\"2014\",\n", " titles=False,\n", " labels=[\"Head\\n[m]\", \"Prec.\\n[mm/d]\", \"Evap.\\n[mm/d]\", \"Temp.\\n[C]\"],\n", " table=True,\n", ")\n", "plt.tight_layout()" ] }, { "cell_type": "markdown", "id": "91af6feb-4a58-4343-a414-c087b99877cc", "metadata": {}, "source": [ "## 2. Make Pastas Model\n", "\n", "We now make a Pastas model to simulate the heads for this monitoring well in Gossau. Only meterological data, which is also available as forecast data, is used to model the groundwater levels. A nonlinear recharge model including a snow module is applied to compute the recharge. The model is calibrated on weekly groundwater level data in the period 2004-2014." ] }, { "cell_type": "code", "execution_count": null, "id": "c1e495e1-ab59-44de-944f-073acc435d75", "metadata": {}, "outputs": [], "source": [ "ml = ps.Model(head)\n", "ml.add_stressmodel(\n", " ps.RechargeModel(\n", " prec,\n", " evap,\n", " rfunc=ps.Gamma(),\n", " recharge=ps.rch.FlexModel(snow=True),\n", " temp=temp,\n", " name=\"rch\",\n", " )\n", ")\n", "\n", "ml.set_parameter(\"rch_tt\", vary=False)\n", "ml.solve(\n", " tmin=\"2004\", tmax=\"2014-02-01\", report=True, fit_constant=False, freq_obs=\"10D\"\n", ")\n", "ml.add_noisemodel(ps.ArNoiseModel())\n", "ml.set_parameter(\"rch_srmax\", vary=False)\n", "ml.solve(\n", " tmin=\"2004\", tmax=\"2014-02-01\", initial=False, fit_constant=False, freq_obs=\"10D\"\n", ")" ] }, { "cell_type": "markdown", "id": "91166fa7", "metadata": {}, "source": [ "### Visualize the model results" ] }, { "cell_type": "code", "execution_count": null, "id": "594149a1", "metadata": {}, "outputs": [], "source": [ "ml.plots.results();" ] }, { "cell_type": "markdown", "id": "f272f5f3", "metadata": {}, "source": [ "## 3. Prepare the forecast ensembles\n", "\n", "Now that we have a calibrated Pastas model, we can prepare the forecast data used to generate the groundwater ensemble predictions. The forecast data should be prepared carefully as a dictionary. For each stressmodel, one item in the dictionary should be provided where the `key` is the stressmodel name (i.e., same as in `ml.stressmodels`) and the `value` a list or dictionary of `pandas.DataFrames`. \n", "\n", "Each `DataFrame` should have the same `DateimeIndex` with the dates of the forecasts of the input data. It should also have the same number of columns, where each column represents an ensemble member (i.e., the precipitation and evaporation data need the same number of members). All these properties are internally checked by the internal method `ps.forecast._check_forecast_data` and an error is raised if something is wrong." ] }, { "cell_type": "code", "execution_count": null, "id": "c16fbbcf", "metadata": {}, "outputs": [], "source": [ "fc = {\n", " \"rch\": {\n", " \"rech\": pd.read_csv(\n", " \"data_forecast/ensemble_prec.csv\", index_col=0, parse_dates=True\n", " ),\n", " \"evap\": pd.read_csv(\n", " \"data_forecast/ensemble_evap.csv\", index_col=0, parse_dates=True\n", " ),\n", " \"temp\": pd.read_csv(\n", " \"data_forecast/ensemble_temp.csv\", index_col=0, parse_dates=True\n", " ),\n", " }\n", "}\n", "\n", "fig, axes = plt.subplot_mosaic([list(fc[\"rch\"].keys())], figsize=(9.5, 3.5))\n", "for k, series in fc[\"rch\"].items():\n", " series = series.cumsum() if k != \"temp\" else series\n", " title = \"Cumulative \" + k.capitalize() if k != \"temp\" else k.capitalize()\n", " series.plot(legend=False, ax=axes[k], color=\"k\", alpha=0.7, title=title)" ] }, { "cell_type": "markdown", "id": "9882721b-f850-4685-bdd8-6c21b1e7a525", "metadata": {}, "source": [ "## 4. Compute GWL forecasts\n", "\n", "We can now generate the forecasts of the groundwater levels using the calibrated model. We can include the parameter uncertainty, by drawing multiple parameter sets (i.e., $N$ parameter sets). The model is run with each of the $N$ parameter sets for all $M$ ensemble member sets (i.e., set of precipitation, evaporation and temperature), resulting in $N$ x $M$ forecasts. \n", "\n", "For each individual forecast the mean forecast and the variance of the error or noise is returned, depending on whether or not `post_process` is `True` or `False`. If `True`, the forecast is:\n", "\n", "1) corrected using the last GWL measurement and the fitted noisemodel, and \n", "2) the variance of the error is computed using the noise and the noisemodel. \n", "\n", "If `False`, the forecast is not corrected and the variance of the residuals is returned. Thus, for each combination of a forecast of the ensemble members and the parameter sets a mean forecast and the variance of theb forecast is returned. These can be used to compute a prediction interval." ] }, { "cell_type": "code", "execution_count": null, "id": "e30662ba", "metadata": {}, "outputs": [], "source": [ "# Draw parameter sets\n", "params = ml.solver.get_parameter_sample(n=10)\n", "params[:2]" ] }, { "cell_type": "code", "execution_count": null, "id": "99adb0a5-5b8a-4e96-a028-b73a65a4ecf7", "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Generate the forecast\n", "df_nopp = ps.forecast.forecast(ml, fc, p=params, post_process=False)\n", "df_pp = ps.forecast.forecast(ml, fc, p=params, post_process=True)\n", "\n", "df_pp.head()" ] }, { "cell_type": "markdown", "id": "f8af66ef", "metadata": {}, "source": [ "The returned variable `df` is a DataFrame containing the ensemble groundwater predictions. The columns of `df` are a `MultiIndex` with the first row the $M$ ensemble members (i.e., a single meteorological forecast), the second row the $N$ parameter sets, and the third row three columns with the mean prediction and the variance of the error that can be used to construct the prediction interval. \n", "\n", "## 5. Compute the overall mean and variance\n", "\n", "The forecast method returns a matrix with with $N$ x $M$ forecasts of the mean and variance. From these, we can compute the mean forecast over all ensembles and parameter sets easily. For the variance, which we use to compute the (for example) the 95\\% prediction interval, we apply the law of total variance. The forecast method provides a convenience method to do this: `ps.forecast.get_overall_mean_and_variance`. The method takes the output dataframe `df` and returns two `pandas.Series` with the overall mean and the variance." ] }, { "cell_type": "code", "execution_count": null, "id": "1f264932", "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, 2, figsize=(10.0, 4.0), sharey=True, layout=\"tight\")\n", "\n", "suptitles = [\"Without post-processing\", \"With post-processing\"]\n", "\n", "for i, (df, label) in enumerate(zip([df_nopp, df_pp], [\"No PP\", \"PP\"])):\n", " mean, var = ps.forecast.get_overall_mean_and_variance(df)\n", " std = np.sqrt(var)\n", "\n", " ax = axes[i]\n", " ml.oseries.series.loc[df.index].plot(\n", " ax=ax, marker=\".\", color=\"k\", linestyle=\"None\", zorder=100\n", " )\n", "\n", " mean.plot(ax=ax, alpha=0.5, zorder=100)\n", " ax.plot(mean, color=\"k\", label=\"Mean\")\n", " ax.fill_between(\n", " mean.index,\n", " mean - std * 1.96,\n", " mean + std * 1.96,\n", " color=\"k\",\n", " alpha=0.2,\n", " label=\"1 std\",\n", " )\n", "\n", " df.loc[:, (slice(None), slice(None), \"mean\")].plot(\n", " color=\"gray\", legend=False, ax=ax\n", " )\n", " ax.set_title(suptitles[i], x=0.01, y=0.93, ha=\"left\", va=\"top\")\n", "\n", "axes[-1].legend(\n", " [\"Observations\", \"Mean forecast\", \"Ensemble Members\", \"95% Prediction interval\"],\n", " loc=\"lower right\",\n", " ncol=2,\n", " bbox_to_anchor=(1.0, 1.0),\n", " frameon=False,\n", ")\n", "\n", "axes[0].set_ylabel(\"Head [m]\")" ] }, { "cell_type": "markdown", "id": "db1f7e16", "metadata": {}, "source": [ "In the figure above we see the two ensemble predictions, without (left) and with (right) post-processing. What we can see is that the prediction intervals widen over time when using the post/processing, whereas without it, these remain more stable and only widen due to the increased uncertainty in the ensemble members. In general, we can see that the largest part of the uncertainty is due to the uncertainty in the input data, as visible bz the mean forecasts of the ensemble members (the grey lines) covering a large part of the prediction intervals.\n" ] } ], "metadata": { "kernelspec": { "display_name": "pastas (3.13.5)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.5" } }, "nbformat": 4, "nbformat_minor": 5 }