Ensemble Predictions#

R.A. Collenteur, Eawag, 2025

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.

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.

Note: Collenteur et al. (In submission) Ensemble groundwater predictions (EGP) in alluvial aquifers in Switzerland.

0. Import Python Packages#

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. Load data#

Below the head and meteorological data is loaded for the well in Gossau, Switzerland.

head = pd.read_csv("data_forecast/heads.csv", index_col=0, parse_dates=True).squeeze()
prec = pd.read_csv("data_forecast/prec.csv", index_col=0, parse_dates=True).squeeze()
evap = pd.read_csv("data_forecast/evap.csv", index_col=0, parse_dates=True).squeeze()
temp = pd.read_csv("data_forecast/temp.csv", index_col=0, parse_dates=True).squeeze()

ps.plots.series(
    head,
    [prec, evap, temp],
    tmin="2004",
    tmax="2014",
    titles=False,
    labels=["Head\n[m]", "Prec.\n[mm/d]", "Evap.\n[mm/d]", "Temp.\n[C]"],
    table=True,
)
plt.tight_layout()
../_images/089b951e49afe91385d753733d1d7d95161022beb254154966ffb4092c29cf2b.png

2. Make Pastas Model#

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.

ml = ps.Model(head)
ml.add_stressmodel(
    ps.RechargeModel(
        prec=prec,
        evap=evap,
        rfunc=ps.Gamma(),
        recharge=ps.rch.FlexModel(snow=True),
        temp=temp,
        name="rch",
    )
)

ml.set_parameter("rch_tt", vary=False)
ml.solve(
    tmin="2004", tmax="2014-02-01", report=True, fit_constant=False, freq_obs="10D"
)
ml.add_noisemodel(ps.ArNoiseModel())
ml.set_parameter("rch_srmax", vary=False)
ml.solve(
    tmin="2004", tmax="2014-02-01", initial=False, fit_constant=False, freq_obs="10D"
)
Fit report solver                   Fit Statistics
==================================================
nfev     39                     EVP          80.91
nobs     370                    R2            0.81
noise    False                  RMSE          0.21
tmin     2004-01-01 00:00:00    AICc      -1141.69
tmax     2014-02-01 00:00:00    BIC       -1110.78
freq     D                      Obj            nan
freq_obs 10D                    ___               
warmup   3650 days 00:00:00     Interp.         No

Parameters (8 optimized)
==================================================
               optimal     initial   vary
rch_A         0.459717    0.405356   True
rch_n         1.262505    1.000000   True
rch_a        19.925832   10.000000   True
rch_srmax    72.381681  250.000000   True
rch_lp        0.250000    0.250000  False
rch_ks       34.242699  100.000000   True
rch_gamma     7.900861    2.000000   True
rch_kv        1.097896    1.000000   True
rch_simax     2.000000    2.000000  False
rch_tt        0.000000    0.000000  False
rch_k         5.480565    2.000000   True
constant_d  637.514503    0.000000  False
Fit report solver                   Fit Statistics
==================================================
nfev     25                     EVP          79.79
nobs     370                    R2            0.80
noise    True                   RMSE          0.22
tmin     2004-01-01 00:00:00    AICc      -1409.07
tmax     2014-02-01 00:00:00    BIC       -1378.16
freq     D                      Obj            nan
freq_obs 10D                    ___               
warmup   3650 days 00:00:00     Interp.         No

Parameters (8 optimized)
==================================================
                optimal    initial   vary
rch_A          0.451171   0.459717   True
rch_n          1.098610   1.262505   True
rch_a         24.987812  19.925832   True
rch_srmax     72.381681  72.381681  False
rch_lp         0.250000   0.250000  False
rch_ks        32.706503  34.242699   True
rch_gamma      5.529732   7.900861   True
rch_kv         1.042877   1.097896   True
rch_simax      2.000000   2.000000  False
rch_tt         0.000000   0.000000  False
rch_k          5.713167   5.480565   True
constant_d   637.471223   0.000000  False
noise_alpha   32.274961  10.000000   True

Visualize the model results#

ml.plots.results();
../_images/ce96545867365d6790b7a24c226df5e090998eb183c8b531a0e136de5a7cab22.png

3. Prepare the forecast ensembles#

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). The value of that dictionary should be a dictionary as well with the key the name of the stress argument, provided to the stressmodel and the value the pandas.DataFrame with the ensemble time series.

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.

fc = {
    "rch": {
        "prec": pd.read_csv(
            "data_forecast/ensemble_prec.csv", index_col=0, parse_dates=True
        ),
        "evap": pd.read_csv(
            "data_forecast/ensemble_evap.csv", index_col=0, parse_dates=True
        ),
        "temp": pd.read_csv(
            "data_forecast/ensemble_temp.csv", index_col=0, parse_dates=True
        ),
    }
}

fig, axes = plt.subplots(1, 3, figsize=(10, 3))
names = ["Cum. Precipitation", "Cum. Evaporation", "Temperature"]
for i, (key, name) in enumerate(zip(fc["rch"], names)):
    series = fc["rch"][key]
    data = series.cumsum() if "Cum" in name else series
    data.plot(legend=False, ax=axes[i], color="k", alpha=0.7, title=name)
../_images/d6ea5c7eab9dabcba1d9a0c828f50aea4125bf15c68013071b05cce5f7f77b99.png

4. Compute GWL forecasts#

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.

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:

  1. corrected using the last GWL measurement and the fitted noisemodel, and

  2. the variance of the error is computed using the noise and the noisemodel.

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.

# Draw parameter sets
params = ml.solver.get_parameter_sample(n=10)
params[:2]
array([[ 4.48067860e-01,  1.10021423e+00,  2.49878279e+01,
         7.23816809e+01,  2.50000000e-01,  3.36701593e+01,
         5.54967257e+00,  1.01203951e+00,  2.00000000e+00,
         8.69420365e-27,  5.26478521e+00,  6.37471223e+02,
         3.53644965e+01],
       [ 4.45109629e-01,  1.08534604e+00,  2.49877636e+01,
         7.23816809e+01,  2.50000000e-01,  3.47386473e+01,
         5.63608479e+00,  1.09008322e+00,  2.00000000e+00,
        -4.99229999e-26,  5.12381984e+00,  6.37471223e+02,
         3.12453408e+01]])
# Generate the forecast
df_nopp = ps.forecast.forecast(ml, fc, p=params, post_process=False)
df_pp = ps.forecast.forecast(ml, fc, p=params, post_process=True)

df_pp.head()
ensemble_member 0 ... 50
param_member 0 1 2 3 4 ... 5 6 7 8 9
forecast mean var mean var mean var mean var mean var ... mean var mean var mean var mean var mean var
2014-01-02 638.030830 0.002747 638.029757 0.002842 638.034491 0.003004 638.033168 0.002916 638.030159 0.002800 ... 638.030341 0.002796 638.033510 0.002829 638.028777 0.002740 638.029655 0.002852 638.035424 0.003031
2014-01-03 638.024535 0.005344 638.022820 0.005507 638.029878 0.005787 638.028031 0.005640 638.023502 0.005445 ... 638.026904 0.005427 638.031550 0.005494 638.025118 0.005336 638.025745 0.005528 638.034338 0.005838
2014-01-04 638.017448 0.007797 638.015128 0.008007 638.024376 0.008366 638.022034 0.008186 638.016049 0.007942 ... 638.021848 0.007903 638.027925 0.008003 638.019475 0.007796 638.020401 0.008039 638.031613 0.008438
2014-01-05 638.010762 0.010116 638.007884 0.010352 638.019124 0.010755 638.016384 0.010565 638.009088 0.010299 ... 638.076681 0.010232 638.085712 0.010366 638.077794 0.010126 638.069748 0.010396 638.086816 0.010845
2014-01-06 638.026192 0.012307 638.023266 0.012552 638.034126 0.012969 638.034087 0.012788 638.025969 0.012525 ... 638.125329 0.012424 638.137844 0.012590 638.126734 0.012333 638.113702 0.012608 638.135856 0.013074

5 rows × 1020 columns

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.

5. Compute the overall mean and variance#

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.

fig, axes = plt.subplots(1, 2, figsize=(10.0, 4.0), sharey=True, layout="tight")

suptitles = ["Without post-processing", "With post-processing"]

for i, (df, label) in enumerate(zip([df_nopp, df_pp], ["No PP", "PP"])):
    mean, var = ps.forecast.get_overall_mean_and_variance(df)
    std = np.sqrt(var)

    ax = axes[i]
    ml.oseries.series_original.loc[df.index].plot(
        ax=ax, marker=".", color="k", linestyle="None", zorder=100
    )

    mean.plot(ax=ax, alpha=0.5, zorder=100)
    ax.plot(mean, color="k", label="Mean")
    ax.fill_between(
        mean.index,
        mean - std * 1.96,
        mean + std * 1.96,
        color="k",
        alpha=0.2,
        label="1 std",
    )

    df.loc[:, (slice(None), slice(None), "mean")].plot(
        color="gray", legend=False, ax=ax
    )
    ax.set_title(suptitles[i], x=0.01, y=0.93, ha="left", va="top")

axes[-1].legend(
    ["Observations", "Mean forecast", "Ensemble Members", "95% Prediction interval"],
    loc="lower right",
    ncol=2,
    bbox_to_anchor=(1.0, 1.0),
    frameon=False,
)

axes[0].set_ylabel("Head [m]")
/tmp/ipykernel_1100/696467994.py:15: UserWarning: This axis already has a converter set and is updating to a potentially incompatible converter
  ax.plot(mean, color="k", label="Mean")
/home/docs/checkouts/readthedocs.org/user_builds/pastas/envs/dev/lib/python3.14/site-packages/pandas/plotting/_matplotlib/core.py:997: UserWarning: This axis already has a converter set and is updating to a potentially incompatible converter
  return ax.plot(*args, **kwds)
/tmp/ipykernel_1100/696467994.py:15: UserWarning: This axis already has a converter set and is updating to a potentially incompatible converter
  ax.plot(mean, color="k", label="Mean")
/home/docs/checkouts/readthedocs.org/user_builds/pastas/envs/dev/lib/python3.14/site-packages/pandas/plotting/_matplotlib/core.py:997: UserWarning: This axis already has a converter set and is updating to a potentially incompatible converter
  return ax.plot(*args, **kwds)
Text(0, 0.5, 'Head [m]')
../_images/79042c351caa17278b2423d914d6a2c7a821b9ffaea4b043584d4fc34fe915cc.png

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.