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, R. A., Bogner, K., Zappa, M., Schirmer, M., and Moeck, C.: An ensemble groundwater prediction (EGP) system to forecast groundwater levels in alluvial aquifers in Switzerland, EGUsphere [preprint], https://doi.org/10.5194/egusphere-2025-4653, 2025

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.1.0b
Python     : 3.14.6
Numpy      : 2.5.4
Pandas     : 3.1.1
Scipy      : 1.18.1
Matplotlib : 3.11.2
Numba      : 0.68.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/29933c5e5e9d511fd8dc3869a3d1ade28b131710247d29f2545cc5097c52626a.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)
ps.RechargeModel(
    model=ml,
    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"
)
ps.ArNoiseModel(model=ml)
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 Gossau                   Fit Statistics
==================================================
nfev     35                     EVP          80.20
nobs     370                    R2            0.80
noise    False                  RMSE          0.21
tmin     2004-01-01 00:00:00    AICc      -1128.15
tmax     2014-02-01 00:00:00    BIC       -1097.24
freq     D                      Obj           8.39
freq_obs 10D                    ___               
warmup   3650 days 00:00:00     Interp.         No

Parameters (8 optimized)
==================================================
               optimal     initial   vary
rch_A         0.455846    0.405356   True
rch_n         1.202549    1.000000   True
rch_a        20.351633   10.000000   True
rch_srmax    65.517598  250.000000   True
rch_lp        0.250000    0.250000  False
rch_ks       28.798922  100.000000   True
rch_gamma     4.945030    2.000000   True
rch_kv        1.100261    1.000000   True
rch_simax     2.000000    2.000000  False
rch_tt        0.000000    0.000000  False
rch_k         5.601201    2.000000   True
constant_d  637.489858    0.000000  False
Fit report Gossau                   Fit Statistics
==================================================
nfev     28                     EVP          79.55
nobs     370                    R2            0.80
noise    True                   RMSE          0.22
tmin     2004-01-01 00:00:00    AICc      -1413.94
tmax     2014-02-01 00:00:00    BIC       -1383.03
freq     D                      Obj           3.88
freq_obs 10D                    ___               
warmup   3650 days 00:00:00     Interp.         No

Parameters (8 optimized)
==================================================
                optimal    initial   vary
rch_A          0.463802   0.455846   True
rch_n          1.102283   1.202549   True
rch_a         25.512864  20.351633   True
rch_srmax     65.517598  65.517598  False
rch_lp         0.250000   0.250000  False
rch_ks        32.368384  28.798922   True
rch_gamma      4.879745   4.945030   True
rch_kv         1.077235   1.100261   True
rch_simax      2.000000   2.000000  False
rch_tt         0.000000   0.000000  False
rch_k          5.725627   5.601201   True
constant_d   637.453135   0.000000  False
noise_alpha   33.525950  10.000000   True

Visualize the model results#

ml.plots.results();
../_images/9a024c1a3b59b0a80c4ca1fd94c5b615aabd68abdeb9013842a9ba715b4150e2.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/b161f8c1f4f50bb24ac167ff035fd0c21cb58b5e7e68c3e8ac29d8ffd5ad88bc.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.44383986e-01,  1.13196437e+00,  2.57546872e+01,
         6.55175980e+01,  2.49999998e-01,  3.64344966e+01,
         4.73803030e+00,  9.31109481e-01,  2.00000000e+00,
         1.17230087e-25,  5.29160239e+00,  6.37453135e+02,
         2.55205135e+01],
       [ 4.76201924e-01,  1.10822678e+00,  2.61576273e+01,
         6.55175980e+01,  2.50000001e-01,  3.35172614e+01,
         4.66510756e+00,  1.12165239e+00,  2.00000000e+00,
        -1.81336111e-25,  6.35085496e+00,  6.37453135e+02,
         2.51600022e+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.033103 0.003048 638.031777 0.003009 638.027818 0.002821 638.030781 0.003160 638.030626 0.002872 ... 638.036598 0.002970 638.030790 0.002761 638.034651 0.002842 638.028494 0.002696 638.034544 0.002963
2014-01-03 638.027971 0.005866 638.025657 0.005788 638.019797 0.005466 638.024161 0.006052 638.023941 0.005549 ... 638.036750 0.005734 638.027507 0.005363 638.034665 0.005533 638.024453 0.005253 638.033645 0.005723
2014-01-04 638.022005 0.008471 638.018569 0.008355 638.011038 0.007945 638.016747 0.008699 638.016441 0.008045 ... 638.034543 0.008306 638.022547 0.007815 638.031721 0.008081 638.018599 0.007678 638.030639 0.008292
2014-01-05 638.016315 0.010880 638.011914 0.010726 638.002669 0.010268 638.009870 0.011121 638.009346 0.010370 ... 638.101434 0.010699 638.074431 0.010125 638.103989 0.010492 638.077356 0.009976 638.088459 0.010685
2014-01-06 638.031492 0.013108 638.026575 0.012915 638.014769 0.012446 638.027726 0.013338 638.024895 0.012538 ... 638.158111 0.012925 638.119640 0.012302 638.160061 0.012775 638.125563 0.012156 638.136158 0.012914

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]")
Text(0, 0.5, 'Head [m]')
../_images/6269a9b2cdd76def41ffa811ae1c129edc33a54282e45366d77a80e4866f1bc2.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.