1. Statistiek van de windschuifspanning uit SEAS5

Python-versie van het R-script statistics-wind10-impr.Rmd (KNMI, februari 2026).

Dit notebook schat herhalingstijdwaarden (return values) van de windschuifspanning voor SEAS5-roosterpunten bij 7 kuststations (Vlissingen, Hoek van Holland, IJmuiden, Den Helder, West-Terschelling, Huibertgat, Delfzijl):

  1. inlezen van de windmetingen van de KNMI-stations;
  2. schatten van het model voor de extremale index uit de metingen;
  3. fitten van Generalised Weibull-staarten (GW) aan de SEAS5-windschuifspanning, omnidirectioneel en per richtingssector;
  4. schatten van de onzekerheid met een bootstrap, eerst zonder en daarna met modelfout.

De resultaten worden als .pkl-bestanden in output_path geschreven, met dezelfde namen en variabelen als de .RData-bestanden van het R-script.

Elk station krijgt precies de toevalsgetallen die het in de R-run krijgt (set.seed(449723), alle stations in de volgorde van R). Daarom geeft dit notebook dezelfde resultaten als het R-script, inclusief de bootstrap-trekkingen, ook als je maar één station of de stations in een andere volgorde doorrekent. Voorwaarde: nb en r_stations zijn gelijk aan die van de R-run.

Rekentijd: ongeveer 1 minuut per bootstrap-trekking per station (100 trekkingen × 7 stations ≈ een halve dag).

Volgend notebook: 2_production_wind.ipynb.

Instellingen

Pas deze zo nodig aan. In stations mag je elke selectie van stations zetten, in elke volgorde. r_stations is de stationslijst van de R-run: daaruit volgen de toevalsgetallen, dus die pas je normaal niet aan. De standaardwaarden van de mappen, van nb en van r_stations staan in kuststatistiek/settings.py.

from kuststatistiek import settings

input_path = settings.DATA_PATH  # map met de aangeleverde invoerdata
output_path = settings.OUTPUT_PATH  # map voor de resultaten
nb = settings.NB  # aantal bootstrap-trekkingen (R: nb <- 100)
r_stations = settings.WIND_STATIONS  # stationslijst van de R-run, in de volgorde van R

# stations die je wilt doorrekenen (bijvoorbeeld alleen ["hoekvanh"])
stations = [
    "vlissing",
    "hoekvanh",
    "ijmuiden",
    "denhelde",
    "westters",
    "huibertg",
    "delfzijl",
]

Voorbereiding

Laad de functies en de vaste instellingen. RRandom is een kopie van de toevalsgenerator van R, zodat de toevalsgetallen precies die van R zijn.

import numpy as np
import pandas as pd
from kuststatistiek.settings import (
    Paths,
    Bins,
    wind_settings,
    WIND_STATIONNAME,
    WIND_MEASSTATIONS,
    WIND_MEASSTATIONNAME,
    WIND_CSTATIONSYS5,
    RESOLUTIONFACTOR,
    PN,
)
from kuststatistiek.rrandom import RRandom
from kuststatistiek.rstream import wind_random_streams
from kuststatistiek.io.read_wind import (
    read_knmi_hourly,
    read_knmi_pothourly,
    read_seas5_wind,
)
from kuststatistiek.evtools import EI, fit_eimdl
from kuststatistiek.analysis import (
    fit_seas5_tails,
    seas5_blocks,
    bootstrap_seas5,
    model_error_draws,
)
from kuststatistiek.rutils import save_pkl, load_pkl, r_apply_sd
from kuststatistiek.plotting import plot_returnlevels, plot_frequencies
import matplotlib.pyplot as plt
from kuststatistiek.gw import assigncat
from matplotlib.ticker import FixedLocator, FormatStrFormatter

for station in stations:
    if station not in r_stations:
        raise ValueError(f"station {station} staat niet in r_stations")

paths = Paths(input_path=input_path, output_path=output_path)
WIND = wind_settings(nb=nb)  # constanten van het R-script (chunk 'fixed')
bins = Bins()  # richtingssectoren
rng = RRandom(WIND.seed)  # set.seed(449723)

save_pkl(
    paths.out("statistics-wind10settings.pkl"),
    stationsys5=r_stations,
    stationname=WIND_STATIONNAME,
    windstationname=WIND_MEASSTATIONNAME,
    cstationsys5=WIND_CSTATIONSYS5,
    freq=WIND.freq,
    EIvalue=WIND.EIvalue,
    delt=WIND.delt,
    factor=WIND.factor,
    resolutionfactor=RESOLUTIONFACTOR,
    pn=PN,
)

print(WIND)

Stap 1 – Windmetingen (R-chunk proc-meas2)

Lees de uurlijkse windmetingen van de KNMI-stations in (West-Terschelling (station 250): potentiële wind) en verwijder ontbrekende waarden. Net als in R wordt een heel klein toevalsgetal bij de windsnelheid opgeteld, zodat er geen gelijke waarden zijn.

Uitvoer: processed-windmeas-<station>.pkl

windmeas = {}
for station, name in zip(WIND_MEASSTATIONS, WIND_MEASSTATIONNAME):
    if station == 250:
        A = read_knmi_pothourly(station, paths.input_path)
    else:
        A = read_knmi_hourly(station, paths.input_path)
    winddir = A["data"][:, 0]
    windsp = A["data"][:, 1] * 0.1
    ok = ~(np.isnan(windsp) | np.isnan(winddir))
    dt_wind, winddir, windsp = A["date"][ok], winddir[ok], windsp[ok]
    Nm = len(dt_wind)
    windsp = windsp + (rng.runif(Nm) - 0.5) * 0.001
    windmeas[name] = dict(dt_wind=dt_wind, windsp=windsp, winddir=winddir, Nm=Nm)
    save_pkl(paths.out(f"processed-windmeas-{name}.pkl"), **windmeas[name])
    print(f"{name}: {Nm} uurwaarden")

Stap 2 – Model voor de extremaalindex (R-chunk eiall)

Schat de extremaalindex (het clusteren van extremen in de tijd) uit de wintermetingen van alle stations samen, en fit het model voor de extremaalindex als functie van de drempel. De uiteindelijk gehanteerde extremaalindex, EIvalue is gelijk aan 6.

Uitvoer: eimdl.pkl

ps, eifs = [], []
for name in WIND_MEASSTATIONNAME:
    m = windmeas[name]
    winter = pd.DatetimeIndex(m["dt_wind"]).month.isin([12, 1, 2])
    ei = EI(m["windsp"][winter], l=20, ngr=50)
    ps.append(ei["p"])
    eifs.append(ei["EIFS"])
eimdl = fit_eimdl(np.concatenate(ps), np.concatenate(eifs))
save_pkl(paths.out("eimdl.pkl"), eimdl=eimdl)
fig, ax = plt.subplots(figsize=(6, 6))

# metingen (uurwaarden), uit stap 2
for j, (p, eifs_station) in enumerate(zip(ps, eifs)):
    ax.plot(
        p[:49],
        eifs_station[:49],
        "s-",
        color="tab:blue",
        ms=2,
        lw=1,
        label="Measurements" if j == 0 else None,
    )

# SEAS5-windschuifspanning (6-uurwaarden, daarom gedeeld door 6)
for j, station in enumerate(r_stations):
    seas5 = read_seas5_wind(station, paths.input_path)
    winter = pd.DatetimeIndex(seas5["dt"]).month.isin([12, 1, 2])
    ei = EI(seas5["mstress"][winter], l=20, ngr=50)
    ax.plot(
        ei["p"][:49],
        ei["EIFS"][:49] / 6,
        color="black",
        lw=1,
        label="SEAS5 data" if j == 0 else None,
    )

# het model eimdl en de afgevlakte versie die voor de correctie wordt gebruikt
y = np.arange(0, 25.01, 0.1)
a, b = eimdl["coefficients"][1], eimdl["coefficients"][0] - np.log(WIND.EIvalue / 6)
ax.plot(
    np.exp(-y),
    np.exp(eimdl["coefficients"][0] + a * y),
    "--",
    color="tab:green",
    label="linear regression",
)
ax.plot(
    np.exp(-y),
    np.exp(b * (1 - np.tanh(y / (-b / a)))),
    ":",
    color="tab:orange",
    label="correctie met $EI_{lim}$",
)

ax.set(
    xscale="log",
    yscale="log",
    xlim=(0.6e-5, 1.6),
    ylim=(0.02 / 1.15, 1.15),
    xlabel="Sample fraction",
    ylabel="Extremal index / sampling interval [1/h]",
)
ax.yaxis.set_major_locator(FixedLocator([0.02, 0.05, 0.1, 0.2, 0.5, 1.0]))
ax.yaxis.set_major_formatter(FormatStrFormatter("%g"))
ax.yaxis.set_minor_formatter(FormatStrFormatter(""))
ax.set_box_aspect(1)
ax.grid(color="gray", linestyle="--", lw=0.5, alpha=0.6)
ax.legend(loc="lower left")
plt.show()

Maak figuren “Directionality of Extremes”

lc1 = bins.lcats - 1  # de 16 overlappende sectoren van 45 graden (zonder omni)
for j, naam in enumerate(WIND_STATIONNAME):
    if naam == "Delfzijl":
        seas5 = read_seas5_wind(WIND_CSTATIONSYS5[j], paths.input_path)
        meting = windmeas[WIND_MEASSTATIONNAME[j]]
        fig, ax = plt.subplots(figsize=(6, 6))
        # zwart: SEAS5-windschuifspanning (100000 hoogste waarden), blauw: gemeten windsnelheid
        for waarde, richting, nmax, nlabels, kleur in [
            (seas5["mstress"], seas5["dstress"], 100000, 5, "black"),
            (meting["windsp"], meting["winddir"], None, 4, "blue"),
        ]:
            N = len(waarde)
            volgorde = np.argsort(-waarde, kind="stable")[:nmax]  # van hoog naar laag
            cat = assigncat(richting[volgorde], bins.lbin[:lc1], bins.ubin[:lc1])
            for i in range(lc1):
                rang = (
                    np.flatnonzero(cat[:, i]) + 1
                )  # rangnummers van de waarden in sector i
                if len(rang) == 0:
                    continue
                ax.plot(
                    rang / N, np.arange(1, len(rang) + 1) / rang, color=kleur, lw=0.8
                )
                for k in np.unique(
                    np.round(
                        np.exp(np.arange(nlabels) * np.log(len(rang)) / (nlabels - 1))
                    ).astype(int)
                ):
                    ax.text(
                        rang[k - 1] / N,
                        k / rang[k - 1],
                        f"{bins.cats[i]:g}",
                        color=kleur,
                        fontsize=8,
                        fontweight="bold",
                        ha="center",
                        va="center",
                        clip_on=True,
                    )
        N5 = len(seas5["mstress"])
        ax.set(
            xscale="log",
            yscale="log",
            xlim=(0.6 / N5, 1.6e5 / N5),
            ylim=(0.6e-5, 1.6),
            title=naam,
            xlabel="Fraction exceeded",
            ylabel="Cond. prob. of category",
        )
        ax.grid(color="lightgray", linestyle=":")
        plt.show()

Toevalsgetallen van R per station

In R komen alle toevalsgetallen uit één reeks, die station na station wordt gebruikt. Hier wordt die reeks voor alle stations van r_stations nagespeeld (alleen het trekken, zonder fits; dit duurt ongeveer een halve minuut). Voor elk station en elke bootstrap-stap wordt bewaard waar de reeks van dat station begint. Zo krijgt elk station in stap 4 en 5 precies de toevalsgetallen van de R-run, welke stations je ook doorrekent.

streams = wind_random_streams(rng, r_stations, nb, paths.input_path)

Stap 3 – GW-staarten uit SEAS5 (R-chunk dir-es-seas5dcms5)

Fit de Generalised Weibull-staart aan de SEAS5-windschuifspanning, omnidirectioneel en per richtingssector.

Uitvoer: <station>_stats_wind.pkl

statdata = {}
for station in stations:
    seas5 = read_seas5_wind(station, paths.input_path)
    statdata[station] = fit_seas5_tails(
        seas5["mstress"], seas5["dstress"], WIND, bins, caseId=station
    )
    save_pkl(paths.out(f"{station}_stats_wind.pkl"), **statdata[station])
    print(f"{station}: GW-fit klaar")
for station in ["vlissing"]:
    naam = WIND_STATIONNAME[r_stations.index(station)]
    plot_returnlevels(
        statdata[station]["Qfreq0"],
        bins.cats0,
        WIND.freq,
        title=f"{naam} return values",
        ylabel="uncorrected SEAS5 wind stress [Pa]",
        Q0sd=None,
    )
    plt.show()
    plot_frequencies(
        statdata[station]["x"],
        statdata[station]["mu"],
        statdata[station]["Mu"],
        bins.cats,
        WIND.freq,
        title=naam,
        xlabel="transformed wind stress",
    )

Stap 4 – Bootstrap zonder modelonzekerheid (R-chunk dir-estimate-bootstrap1)

Trek nb bootstrap-steekproeven uit de SEAS5-data (er worden hele blokken data herbemonsterd) en herhaal de GW-fit voor elke steekproef. Dit geeft de statistische onzekerheid van de schattingen.

Uitvoer: <station>_stats_wind_bootdata.pkl (de steekproeven) en <station>_stats_wind_boot1.pkl (de resultaten)

# variabelen van stats_wind die worden overgenomen in boot1 en boot2
stats_keys = [
    "esGWdir",
    "esGW",
    "pbin0",
    "x",
    "mu",
    "Mu",
    "mu0",
    "Mu0",
    "qmu",
    "Qfreq",
    "Qfreq0",
]
boot_keys = ["Qbs", "Q0bs", "q0bs", "qbs", "Qsd", "Q0sd", "qsd"]

bootdata = {}
for station in stations:
    seas5 = read_seas5_wind(station, paths.input_path)
    blockno, blocks = seas5_blocks(seas5["dt"], streams[station]["bootstrap1"], nb)
    bs = bootstrap_seas5(
        seas5["mstress"],
        seas5["dstress"],
        blockno,
        blocks,
        WIND,
        bins,
        caseId=station,
        dir_threshold=WIND.pthreshold[WIND.mthresh - 1],
    )
    bootdata[station] = dict(
        theta0bs=bs["theta0bs"],
        theta0dirbs=bs["theta0dirbs"],
        blocks=blocks,
        blockno=blockno,
    )
    save_pkl(paths.out(f"{station}_stats_wind_bootdata.pkl"), **bootdata[station])

    s = statdata[station]
    save_pkl(
        paths.out(f"{station}_stats_wind_boot1.pkl"),
        **{k: s[k] for k in stats_keys},
        **{k: bs[k] for k in boot_keys},
        theta0bs=bs["theta0bs"],
        theta0sd=r_apply_sd(bs["theta0bs"], 1),
        theta0dirbs=bs["theta0dirbs"],
    )
    print(f"{station}: bootstrap zonder modelonzekerheid klaar")
for station in ["vlissing"]:
    naam = WIND_STATIONNAME[r_stations.index(station)]
    Q0sd = load_pkl(paths.out(f"{station}_stats_wind_boot1.pkl"))["Q0sd"]
    plot_returnlevels(
        statdata[station]["Qfreq0"],
        bins.cats0,
        WIND.freq,
        title=f"{naam} return values",
        ylabel="uncorrected SEAS5 wind stress [Pa]",
        Q0sd=Q0sd,
    )
    plt.show()

Stap 5 – Bootstrap met modelfout (R-chunk dir-estimate-bootstrap2)

Dezelfde bootstrap-steekproeven, maar nu wordt bij elke steekproef een toevallige modelfout opgeteld bij de vormparameter (standaardafwijking modelstd) en bij de schaal (scalestd). Deze resultaten worden gebruikt voor de tabellen.

Uitvoer: <station>_stats_wind_boot2.pkl

for station in stations:
    seas5 = read_seas5_wind(station, paths.input_path)
    bd = bootdata[station]
    rng_station = streams[station]["bootstrap2"]
    theta00bs, theta00dirbs = model_error_draws(
        bd["theta0bs"], bd["theta0dirbs"], WIND, rng_station
    )
    bs = bootstrap_seas5(
        seas5["mstress"],
        seas5["dstress"],
        bd["blockno"],
        bd["blocks"],
        WIND,
        bins,
        caseId=station,
        dir_threshold=WIND.pthreshold[WIND.mthresh - 1],
        modelerror={"theta00bs": theta00bs, "theta00dirbs": theta00dirbs},
        rng=rng_station,
    )
    s = statdata[station]
    save_pkl(
        paths.out(f"{station}_stats_wind_boot2.pkl"),
        **{k: s[k] for k in stats_keys},
        **{k: bs[k] for k in boot_keys},
        theta00bs=theta00bs,
        theta00sd=r_apply_sd(theta00bs, 1),
        theta00dirbs=theta00dirbs,
    )
    print(f"{station}: bootstrap met modelonzekerheid klaar")

Figuur (controle)

Herhalingstijdwaarden van de windschuifspanning per richting, voor enkele herhalingstijden, per station. (De overige figuren van het R-script zijn hier niet overgenomen.)

for station in ["vlissing"]:
    naam = WIND_STATIONNAME[r_stations.index(station)]
    Q0sd = load_pkl(paths.out(f"{station}_stats_wind_boot2.pkl"))["Q0sd"]
    plot_returnlevels(
        statdata[station]["Qfreq0"],
        bins.cats0,
        WIND.freq,
        title=f"{naam} return values",
        ylabel="uncorrected SEAS5 wind stress [Pa]",
        Q0sd=Q0sd,
    )
    plt.show()