aboutsummaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorLouis <louis@dnge.de>2026-11-08 15:20:31 +0100
committerLouis <louis@dnge.de>2026-11-08 15:20:31 +0100
commit5a956f1c82b10f4283fa8bbfd52fd9c6c2a39bd9 (patch)
tree8527285fffe0cf92438766ae2273178c63c392b7 /scripts
parent618b26b81fe2bb6fb33cb9a1924c16e44bf45399 (diff)
downloaddeckungsanteil-main.tar.gz
Add Panasonic Aquarea, hot water and PV, step-by-step layoutHEADmain
- Panasonic Aquarea J (WH-MDC05/07/09J3E5) and L (WH-WDG05/07/09LE5) monobloc capacity and COP tables from the service manuals. - Optional hot water (daily demand charged 11-15 h MEZ with priority over heating) and PV with battery from DWD 10-minute global/diffuse irradiation, each switched on separately; surplus fed in or curtailed. - Inputs in five steps with the key figures always visible on top and the matching chart beside each step; full results in the last step. - Bisect the bivalence point so no hour at exactly that temperature is left uncovered (seen with 1 K bins). - Average the duration curve between sample points instead of picking single hours, which showed hot water hours as spikes. - Make the hidden attribute override label display rules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'scripts')
-rw-r--r--scripts/prep.py180
1 files changed, 177 insertions, 3 deletions
diff --git a/scripts/prep.py b/scripts/prep.py
index 44f72aa..1c6c87b 100644
--- a/scripts/prep.py
+++ b/scripts/prep.py
@@ -1,6 +1,6 @@
# /// script
# requires-python = ">=3.10"
-# dependencies = ["numpy"]
+# dependencies = ["numpy", "pandas"]
# ///
"""Build the weather data for the web app from DWD open data and GeoNames.
@@ -9,6 +9,9 @@ Output (web/data/):
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
@@ -22,8 +25,10 @@ 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
@@ -32,13 +37,26 @@ 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:
- path = CACHE / (url.rsplit("/", 1)[1] or "index.html")
+ # 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())
@@ -124,6 +142,150 @@ def load_station(sid: str, zip_name: str) -> np.ndarray:
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)."""
@@ -167,6 +329,7 @@ def read_postcodes() -> dict:
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()
@@ -192,6 +355,16 @@ def main():
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"]))
@@ -199,7 +372,8 @@ def main():
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)
+ 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=(",", ":")))