aboutsummaryrefslogtreecommitdiff
path: root/scripts/prep.py
blob: 44f72aab46d22e69565f88899b65eaa0ff6453f7 (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
# /// script
# requires-python = ">=3.10"
# dependencies = ["numpy"]
# ///
"""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
"""

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

DWD = "https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/hourly/air_temperature/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

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


def fetch(url: str) -> bytes:
    path = CACHE / (url.rsplit("/", 1)[1] or "index.html")
    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 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)

    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)

    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)
    (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()