aboutsummaryrefslogtreecommitdiff
path: root/scripts/prep.py
blob: 1c6c87b0572d2c0ab93739b1ad8d0bf209c8309f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# /// script
# requires-python = ">=3.10"
# dependencies = ["numpy", "pandas"]
# ///
"""Build the weather data for the web app from DWD open data and GeoNames.

Output (web/data/):
  stations.json   station metadata, valid years, estimated Norm-Außentemperatur
  plz.json        postcode -> [place, lat, lon, station id, distance km]
  t/<id>.bin      int16 hourly temperatures in 0.1 °C, YEARS x 8760 (Feb 29 dropped),
                  MISSING for invalid years
  pv/<id>.bin     uint16 hourly PV yield in Wh per kWp (before the module temperature
                  correction), YEARS x 8760, PV_MISSING for invalid years; hour i is the
                  interval from hour i to i+1 UTC
"""

import io
import json
import math
import re
import sys
import urllib.request
import zipfile
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import numpy as np
import pandas as pd

DWD = "https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/hourly/air_temperature/historical/"
DWD_SOLAR = "https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/10_minutes/solar/historical/"
GEONAMES = "https://download.geonames.org/export/zip/DE.zip"
YEARS = list(range(2007, 2026))
HOURS = 8760
MISSING = -32768
MAX_MISSING_SHARE = 0.03  # a year with more gaps is dropped
MAX_GAP_HOURS = 72  # a longer single gap also drops the year
MIN_YEARS = 10  # a station needs this many valid years to be used

# PV generator: south, 30° tilt, ground albedo 0.2, 14 % system losses (as PVGIS)
PV_TILT = math.radians(30)
PV_ALBEDO = 0.2
PV_LOSSES = 0.14
PV_MISSING = 65535
# irradiation gaps are filled from the surrounding days, so it may have more of them
SOLAR_MAX_MISSING_SHARE = 0.10
SOLAR_MAX_GAP_HOURS = 168
SOLAR_FILL_DAYS = 10
PV_MAX_DISTANCE = 100  # km between temperature and solar station

ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "web" / "data"
CACHE = ROOT / ".cache"


def fetch(url: str) -> bytes:
    # directory listings are cached under their directory names
    name = url.rsplit("/", 1)[1] or re.sub(r"\W+", "_", url.split("/CDC/")[-1]) + "index.html"
    path = CACHE / name
    if not path.exists():
        with urllib.request.urlopen(url, timeout=120) as r:
            path.write_bytes(r.read())
    return path.read_bytes()


def read_station_list() -> dict:
    text = fetch(DWD + "TU_Stundenwerte_Beschreibung_Stationen.txt").decode("latin1")
    stations = {}
    for line in text.splitlines()[2:]:
        parts = line.split()
        if len(parts) < 8:
            continue
        sid, von, bis, elev, lat, lon = parts[:6]
        # name may contain spaces; Bundesland and Abgabe are the last two fields
        name = " ".join(parts[6:-2])
        stations[sid] = dict(id=sid, von=int(von), bis=int(bis), elev=int(elev),
                             lat=float(lat), lon=float(lon), name=name, land=parts[-2])
    return stations


def zip_names() -> dict:
    html = fetch(DWD).decode()
    names = {}
    for m in re.finditer(r'href="(stundenwerte_TU_(\d{5})_\d{8}_\d{8}_hist\.zip)"', html):
        names[m.group(2)] = m.group(1)
    return names


def hour_index(year: int) -> dict:
    """Map (month, day, hour) of a non-leap year to the hour index 0..8759."""
    idx, i = {}, 0
    for month, days in enumerate([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 1):
        for day in range(1, days + 1):
            for hour in range(24):
                idx[(month, day, hour)] = i
                i += 1
    return idx


HOUR_INDEX = hour_index(2001)


def fill_year(values: np.ndarray) -> np.ndarray | None:
    """Interpolate gaps linearly, or return None if the year is too incomplete."""
    missing = np.isnan(values)
    if missing.mean() > MAX_MISSING_SHARE:
        return None
    if missing.any():
        # longest run of missing values
        edges = np.diff(np.concatenate([[0], missing.astype(int), [0]]))
        runs = np.flatnonzero(edges == -1) - np.flatnonzero(edges == 1)
        if runs.max() > MAX_GAP_HOURS:
            return None
        x = np.arange(HOURS)
        values = values.copy()
        values[missing] = np.interp(x[missing], x[~missing], values[~missing])
    return values


def load_station(sid: str, zip_name: str) -> np.ndarray:
    data = np.full((len(YEARS), HOURS), np.nan)
    with zipfile.ZipFile(io.BytesIO(fetch(DWD + zip_name))) as z:
        product = next(n for n in z.namelist() if n.startswith("produkt_tu_stunde"))
        lines = z.read(product).decode("latin1").splitlines()[1:]
    for line in lines:
        f = line.split(";")
        stamp = f[1].strip()
        year = int(stamp[:4])
        if year < YEARS[0] or year > YEARS[-1]:
            continue
        key = (int(stamp[4:6]), int(stamp[6:8]), int(stamp[8:10]))
        if key not in HOUR_INDEX:  # Feb 29
            continue
        t = float(f[3])
        if t > -999:
            data[year - YEARS[0], HOUR_INDEX[key]] = t
    out = np.full((len(YEARS), HOURS), MISSING, dtype=np.int16)
    for y in range(len(YEARS)):
        filled = fill_year(data[y])
        if filled is not None:
            out[y] = np.round(filled * 10).astype(np.int16)
    return out


def solar_zip_names() -> dict:
    """Station id -> 10-minute solar archives that overlap YEARS."""
    html = fetch(DWD_SOLAR).decode()
    names = {}
    for m in re.finditer(r'href="(10minutenwerte_SOLAR_(\d{5})_(\d{8})_(\d{8})_hist\.zip)"', html):
        if int(m.group(4)[:4]) >= YEARS[0] and int(m.group(3)[:4]) <= YEARS[-1]:
            names.setdefault(m.group(2), []).append(m.group(1))
    return names


def read_solar_stations() -> dict:
    text = fetch(DWD_SOLAR + "zehn_min_sd_Beschreibung_Stationen.txt").decode("latin1")
    stations = {}
    for line in text.splitlines()[2:]:
        parts = line.split()
        if len(parts) < 8:
            continue
        sid, lat, lon = parts[0], float(parts[4]), float(parts[5])
        stations[sid] = dict(id=sid, lat=lat, lon=lon, name=" ".join(parts[6:-2]))
    return stations


# day of the non-leap year (0..364) for each month and day, -1 for Feb 29
_DAY = np.full((13, 32), -1)
for (_m, _d, _h), _i in HOUR_INDEX.items():
    _DAY[_m, _d] = _i // 24


def load_solar(zip_names: list) -> tuple:
    """Hourly global and diffuse irradiation in Wh/m², YEARS x HOURS, NaN where missing.
    The 10-minute sums (J/cm²) are stamped at the end of their interval in UTC."""
    ghi = np.zeros(len(YEARS) * HOURS)
    dhi = np.zeros(len(YEARS) * HOURS)
    n_g = np.zeros(len(YEARS) * HOURS)
    n_d = np.zeros(len(YEARS) * HOURS)
    for name in zip_names:
        with zipfile.ZipFile(io.BytesIO(fetch(DWD_SOLAR + name))) as z:
            product = next(n for n in z.namelist() if n.startswith("produkt_zehn_min"))
            df = pd.read_csv(z.open(product), sep=";", usecols=[1, 3, 4], skipinitialspace=True)
        stamp = pd.to_datetime(df.iloc[:, 0].astype(str), format="%Y%m%d%H%M") - pd.Timedelta(minutes=10)
        year = stamp.dt.year.to_numpy()
        day = _DAY[stamp.dt.month.to_numpy(), stamp.dt.day.to_numpy()]
        keep = (year >= YEARS[0]) & (year <= YEARS[-1]) & (day >= 0)
        idx = ((year - YEARS[0]) * HOURS + day * 24 + stamp.dt.hour.to_numpy())[keep]
        for col, total, count in ((2, ghi, n_g), (1, dhi, n_d)):
            v = df.iloc[:, col].to_numpy(dtype=float)[keep]
            ok = v >= 0
            np.add.at(total, idx[ok], v[ok])
            np.add.at(count, idx[ok], 1)
    j_per_cm2 = 10000 / 3600  # J/cm² -> Wh/m²
    # an hour needs all six 10-minute values
    ghi = np.where(n_g == 6, ghi * j_per_cm2, np.nan).reshape(len(YEARS), HOURS)
    dhi = np.where(n_d == 6, dhi * j_per_cm2, np.nan).reshape(len(YEARS), HOURS)
    return ghi, dhi


def fill_solar_year(values: np.ndarray) -> np.ndarray | None:
    """Fill missing hours with the mean of the same hour within ±SOLAR_FILL_DAYS, or
    return None if the year is too incomplete."""
    missing = np.isnan(values)
    if missing.mean() > SOLAR_MAX_MISSING_SHARE:
        return None
    if not missing.any():
        return values
    edges = np.diff(np.concatenate([[0], missing.astype(int), [0]]))
    if (np.flatnonzero(edges == -1) - np.flatnonzero(edges == 1)).max() > SOLAR_MAX_GAP_HOURS:
        return None
    days = values.reshape(-1, 24)
    out = days.copy()
    for d, h in zip(*np.nonzero(np.isnan(days))):
        window = days[max(0, d - SOLAR_FILL_DAYS):d + SOLAR_FILL_DAYS + 1, h]
        out[d, h] = np.nanmean(window) if np.isfinite(window).any() else 0
    return out.ravel()


def pv_yield(year: int, lat: float, lon: float, ghi: np.ndarray, dhi: np.ndarray) -> np.ndarray:
    """PV yield in Wh/kWp per hour from horizontal global and diffuse irradiation, with
    the Hay-Davies model for the tilted plane. The sun position is taken at mid-hour.
    Missing diffuse values (NaN) are estimated with the Erbs correlation."""
    days = np.array([(np.datetime64(f"{year}-{m:02d}-{d:02d}") - np.datetime64(f"{year}-01-01")).astype(int)
                     for (m, d, h) in HOUR_INDEX if h == 0])
    doy = np.repeat(days, 24) + 1
    hour = np.tile(np.arange(24) + 0.5, len(days))
    g = 2 * math.pi / 365 * (doy - 1 + (hour - 12) / 24)
    decl = (0.006918 - 0.399912 * np.cos(g) + 0.070257 * np.sin(g) - 0.006758 * np.cos(2 * g)
            + 0.000907 * np.sin(2 * g) - 0.002697 * np.cos(3 * g) + 0.00148 * np.sin(3 * g))
    eot = 229.18 * (0.000075 + 0.001868 * np.cos(g) - 0.032077 * np.sin(g)
                    - 0.014615 * np.cos(2 * g) - 0.040849 * np.sin(2 * g))  # minutes
    omega = np.radians((hour * 60 + eot + 4 * lon) / 4 - 180)  # hour angle
    phi = math.radians(lat)
    cosz = np.sin(phi) * np.sin(decl) + np.cos(phi) * np.cos(decl) * np.cos(omega)
    # angle of incidence on a south-facing plane tilted by PV_TILT
    cosi = (np.sin(phi - PV_TILT) * np.sin(decl)
            + np.cos(phi - PV_TILT) * np.cos(decl) * np.cos(omega))
    up = cosz > 0.035  # sun more than 2° above the horizon
    i0 = 1367 * (1 + 0.033 * np.cos(2 * math.pi * doy / 365))
    kt = np.where(up, np.clip(ghi / (i0 * np.maximum(cosz, 0.087)), 0, 1), 0)
    erbs = np.where(kt <= 0.22, 1 - 0.09 * kt,
                    np.where(kt <= 0.8, 0.9511 - 0.1604 * kt + 4.388 * kt**2 - 16.638 * kt**3
                             + 12.336 * kt**4, 0.165))
    dhi = np.minimum(np.where(np.isnan(dhi), erbs * ghi, dhi), ghi)
    beam = np.where(up, ghi - dhi, 0)
    diffuse = np.where(up, dhi, ghi)
    rb = np.where(up, np.maximum(cosi, 0) / np.maximum(cosz, 0.087), 0)
    ai = np.where(up, np.clip(beam / np.maximum(cosz, 0.087) / i0, 0, 1), 0)  # anisotropy index
    poa = (beam * rb + diffuse * (ai * rb + (1 - ai) * (1 + math.cos(PV_TILT)) / 2)
           + ghi * PV_ALBEDO * (1 - math.cos(PV_TILT)) / 2)
    return poa * (1 - PV_LOSSES)  # 1 kWp delivers 1 kW at 1000 W/m²


def build_pv(stations: dict) -> list:
    """Write pv/<id>.bin for every solar station with global irradiation and return their
    metadata with the valid years."""
    names = solar_zip_names()
    candidates = [stations[sid] for sid in names if sid in stations]
    print(f"{len(candidates)} candidate solar stations", file=sys.stderr)

    def work(s):
        return s, load_solar(names[s["id"]])

    used = []
    with ThreadPoolExecutor(4) as pool:
        for i, (s, (ghi, dhi)) in enumerate(pool.map(work, candidates), 1):
            out = np.full((len(YEARS), HOURS), PV_MISSING, dtype=np.uint16)
            years = []
            for y, year in enumerate(YEARS):
                g = fill_solar_year(ghi[y])
                if g is None:
                    continue
                # diffuse: measured where available, otherwise estimated in pv_yield
                d = dhi[y]
                if np.isnan(d).mean() > SOLAR_MAX_MISSING_SHARE:
                    continue
                out[y] = np.round(pv_yield(year, s["lat"], s["lon"], g, d)).astype(np.uint16)
                years.append(year)
            print(f"\r{i}/{len(candidates)} {s['name'][:30]:30} {len(years)} years",
                  end="", file=sys.stderr)
            if years:
                out.tofile(OUT / "pv" / f"{s['id']}.bin")
                used.append(dict(id=s["id"], name=s["name"], lat=s["lat"], lon=s["lon"], years=years))
    print(f"\n{len(used)} solar stations with global irradiation", file=sys.stderr)
    return used


def norm_outdoor_temp(series: np.ndarray) -> float | None:
    """Estimate the Norm-Außentemperatur as in DIN EN 12831: the lowest two-day
    mean reached or undercut 10 times in 20 years (counted in days)."""
    valid = [y for y in range(len(YEARS)) if series[y, 0] != MISSING]
    means = []
    for a, b in zip(valid, valid[1:]):
        if b != a + 1:
            continue
        # winter from July of year a to June of year b
        winter = np.concatenate([series[a, 181 * 24:], series[b, :181 * 24]]) / 10
        daily = winter.reshape(-1, 24).mean(axis=1)
        means.append((daily[1:] + daily[:-1]) / 2)
    if len(means) < 5:
        return None
    winters = len(means)
    means = np.sort(np.concatenate(means))
    return round(float(means[winters * 10 // 20]), 1)


def haversine(lat1, lon1, lat2, lon2) -> float:
    p1, p2 = math.radians(lat1), math.radians(lat2)
    a = (math.sin((p2 - p1) / 2) ** 2
         + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2)
    return 12742 * math.asin(math.sqrt(a))


def read_postcodes() -> dict:
    with zipfile.ZipFile(io.BytesIO(fetch(GEONAMES))) as z:
        text = z.read("DE.txt").decode("utf-8")
    sums = {}
    for line in text.splitlines():
        f = line.split("\t")
        plz, place, lat, lon = f[1], f[2], float(f[9]), float(f[10])
        s = sums.setdefault(plz, [place, 0.0, 0.0, 0])
        s[1] += lat
        s[2] += lon
        s[3] += 1
    return {plz: (place, lat / n, lon / n) for plz, (place, lat, lon, n) in sums.items()}


def main():
    CACHE.mkdir(exist_ok=True)
    (OUT / "t").mkdir(parents=True, exist_ok=True)
    (OUT / "pv").mkdir(parents=True, exist_ok=True)

    stations = read_station_list()
    zips = zip_names()
    candidates = [s for sid, s in stations.items()
                  if sid in zips and s["von"] <= 20120101 and s["bis"] >= 20240101]
    print(f"{len(candidates)} candidate stations", file=sys.stderr)

    def work(s):
        series = load_station(s["id"], zips[s["id"]])
        return s, series

    used = []
    with ThreadPoolExecutor(8) as pool:
        for i, (s, series) in enumerate(pool.map(work, candidates), 1):
            years = [YEARS[y] for y in range(len(YEARS)) if series[y, 0] != MISSING]
            print(f"\r{i}/{len(candidates)} {s['name'][:30]:30} {len(years)} years",
                  end="", file=sys.stderr)
            if len(years) < MIN_YEARS:
                continue
            series.tofile(OUT / "t" / f"{s['id']}.bin")
            used.append(dict(id=s["id"], name=s["name"], land=s["land"], lat=s["lat"],
                             lon=s["lon"], elev=s["elev"], years=years,
                             tnorm=norm_outdoor_temp(series)))
    print(f"\n{len(used)} stations with at least {MIN_YEARS} valid years", file=sys.stderr)

    # per temperature station and year the nearest solar station with data for that year
    pv = build_pv(read_solar_stations())
    for s in used:
        s["pv"] = []
        for year in YEARS:
            near = [(haversine(s["lat"], s["lon"], p["lat"], p["lon"]), p["id"]) for p in pv
                    if year in p["years"]]
            near = [n for n in near if n[0] <= PV_MAX_DISTANCE]
            s["pv"].append(min(near)[1] if near else None)

    plz = {}
    for code, (place, lat, lon) in sorted(read_postcodes().items()):
        best = min(used, key=lambda s: haversine(lat, lon, s["lat"], s["lon"]))
        plz[code] = [place, round(lat, 4), round(lon, 4), best["id"],
                     round(haversine(lat, lon, best["lat"], best["lon"]), 1)]
    print(f"{len(plz)} postcodes", file=sys.stderr)

    meta = dict(years=YEARS, hours=HOURS, missing=MISSING, stations=used, pvMissing=PV_MISSING,
                pvStations=[dict(id=p["id"], name=p["name"], lat=p["lat"], lon=p["lon"]) for p in pv])
    (OUT / "stations.json").write_text(json.dumps(meta, ensure_ascii=False))
    (OUT / "plz.json").write_text(json.dumps(plz, ensure_ascii=False, separators=(",", ":")))


if __name__ == "__main__":
    main()