cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.650: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-04 03:22:07 +02:00
1 parent 85edd56ec8
commit 3edd015039
20 files changed
+2021 -35

No files matched your search

+206
View File
@@ -0,0 +1,206 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""A building's PV forecast from a weather forecast (docs/mieterstrom-ggv.md
§4): irradiance → plane of array → kWp × performance ratio.
The weather comes from fleet's weather_forecasts (weather.go: DWD's MOSMIX
through Bright Sky, hourly): `solar` is the global horizontal irradiation
of the hour *ending* at the record's timestamp (kWh/m²), plus cloud cover
(%) and the air temperature (°C). Per 15-minute slot:
1. the hour's irradiation spread over its quarter-hours by the sun's
height (sin of the elevation at each quarter's middle);
2. global → beam + diffuse with Erbs' correlation on the clearness index;
3. plane of array (tilt, azimuth): beam × cos(incidence) + isotropic sky
diffuse + ground reflection (albedo 0.2);
4. P = kWp × POA / 1000 W/m² × PR × (1 − 0.4 %/K × (T_cell − 25 °C)),
T_cell = T_air + 25 K × POA / 800 W/m².
Without irradiation (no forecast, or a station without it) a clear-sky
model (Haurwitz) dimmed by the cloud cover (Kasten–Czeplak). Without any
weather the climate: Haurwitz's clear-sky shape scaled so each day's
energy is PVGIS's mean daily yield of that month at the site and
orientation (`climatology`: pvgis.monthly_yield_per_kwp, kWh per kWp per
month; PVGIS's 14 % system loss stands for PR 0.85, so the yield is scaled
by pr / 0.85). Only where PVGIS can't be had either, the last resort: a
clear sky dimmed by 60 % cloud, which takes only 13 % off (about 1.9 times
November's climate in Berlin; methods.md B3-a), noted by the caller.
Units: W/m², kWh per slot, degrees."""
from __future__ import annotations
import calendar
import math
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
SLOT = timedelta(minutes=15)
@dataclass
class Hour:
"""A weather record: the hour ending at `end` (UTC)."""
end: datetime
solar_kwh_m2: float | None = None
cloud_pct: float | None = None
temp_c: float | None = None
def sun_position(t: datetime, lat: float, lon: float) -> tuple[float, float]:
"""(elevation, azimuth) in degrees; azimuth from north, clockwise
(180 = south). NOAA's simple formulas, good to about a degree."""
t = t.astimezone(timezone.utc)
doy = t.timetuple().tm_yday
hour = t.hour + t.minute / 60 + t.second / 3600
g = 2 * math.pi / 365 * (doy - 1 + (hour - 12) / 24)
decl = (0.006918 - 0.399912 * math.cos(g) + 0.070257 * math.sin(g) - 0.006758 * math.cos(2 * g)
+ 0.000907 * math.sin(2 * g) - 0.002697 * math.cos(3 * g) + 0.00148 * math.sin(3 * g))
eqt = 229.18 * (0.000075 + 0.001868 * math.cos(g) - 0.032077 * math.sin(g) - 0.014615 * math.cos(2 * g)
- 0.040849 * math.sin(2 * g))
tst = hour * 60 + eqt + 4 * lon
ha = math.radians(tst / 4 - 180)
la = math.radians(lat)
cz = math.sin(la) * math.sin(decl) + math.cos(la) * math.cos(decl) * math.cos(ha)
cz = max(-1.0, min(1.0, cz))
zen = math.acos(cz)
elev = 90 - math.degrees(zen)
sz = math.sin(zen)
if sz < 1e-9:
return elev, 180.0
ca = (math.sin(decl) - math.sin(la) * cz) / (math.cos(la) * sz)
az = math.degrees(math.acos(max(-1.0, min(1.0, ca))))
if ha > 0:
az = 360 - az
return elev, az
def extraterrestrial(t: datetime) -> float:
doy = t.timetuple().tm_yday
return 1367 * (1 + 0.033 * math.cos(2 * math.pi * doy / 365))
def erbs_diffuse_fraction(kt: float) -> float:
if kt <= 0.22:
return 1 - 0.09 * kt
if kt <= 0.8:
return 0.9511 - 0.1604 * kt + 4.388 * kt ** 2 - 16.638 * kt ** 3 + 12.336 * kt ** 4
return 0.165
def clear_sky_ghi(elev: float) -> float:
"""Haurwitz: W/m² on the horizontal."""
s = math.sin(math.radians(elev))
return 1098 * s * math.exp(-0.057 / s) if s > 0.01 else 0.0
def cloud_dimmed(ghi_clear: float, cloud_pct: float) -> float:
"""Kasten–Czeplak: G = G_clear × (1 − 0.75 × N^3.4), N the cover 0..1."""
n = max(0.0, min(1.0, cloud_pct / 100))
return ghi_clear * (1 - 0.75 * n ** 3.4)
def poa(ghi: float, t: datetime, lat: float, lon: float, tilt: float, azimuth: float, albedo: float = 0.2) -> float:
"""Plane-of-array irradiance (W/m²) from the global horizontal at t."""
elev, az = sun_position(t, lat, lon)
if elev <= 0 or ghi <= 0:
return 0.0
se = math.sin(math.radians(elev))
g0 = extraterrestrial(t) * se
kt = max(0.0, min(1.0, ghi / g0)) if g0 > 0 else 0.0
dhi = erbs_diffuse_fraction(kt) * ghi
beam_h = ghi - dhi
b, ts = math.radians(tilt), math.radians(elev)
cos_inc = math.cos(b) * se + math.sin(b) * math.cos(ts) * math.cos(math.radians(az - azimuth))
beam = beam_h / se * max(cos_inc, 0.0) if elev > 2 else 0.0
if elev <= 2:
dhi = ghi # near the horizon: all of it as diffuse
return max(0.0, beam + dhi * (1 + math.cos(b)) / 2 + ghi * albedo * (1 - math.cos(b)) / 2)
def power_kw(poa_w: float, kwp: float, pr: float, temp_c: float | None) -> float:
if poa_w <= 0:
return 0.0
t_cell = (temp_c if temp_c is not None else 10.0) + 25 * poa_w / 800
derate = max(0.75, min(1.05, 1 - 0.004 * (t_cell - 25)))
return kwp * poa_w / 1000 * pr * derate
CLIMATE_PR = 0.85 # the PR PVGIS's 14 % system loss stands for
FALLBACK_CLOUD = 60.0 # the last resort without weather and without PVGIS
def clear_day_kwh(day: datetime, lat: float, lon: float, tilt: float, azimuth: float) -> float:
"""The clear-sky (Haurwitz, undimmed) energy of 1 kWp at PR 1 over a UTC
day (96 slots, 10 °C air): the shape's total, for scaling it to a day's
climate. Europe's daylight lies inside the UTC day."""
d0 = day.astimezone(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
e = 0.0
for k in range(96):
mid = d0 + SLOT * k + SLOT / 2
ghi = clear_sky_ghi(sun_position(mid, lat, lon)[0])
e += power_kw(poa(ghi, mid, lat, lon, tilt, azimuth), 1.0, 1.0, None) * 0.25
return e
def climate_day_kwh(day: datetime, climatology: list[float], kwp: float, pr: float) -> float:
"""A day's expected energy (kWh) from PVGIS's monthly yield per kWp:
the month's yield over its days, times kWp, times pr / 0.85."""
d = day.astimezone(timezone.utc)
return climatology[d.month - 1] / calendar.monthrange(d.year, d.month)[1] * kwp * pr / CLIMATE_PR
def forecast(start: datetime, n: int, hours: list[Hour], lat: float, lon: float, kwp: float,
tilt: float = 30, azimuth: float = 180, pr: float = 0.85,
climatology: list[float] | None = None) -> tuple[list[float], str]:
"""kWh per 15-minute slot from `start` (UTC) for n slots, and what it was
made from: "irradiance", "cloud" (some slots from the cloud cover, or a
mix), "climatology" (no weather at all: the clear-sky shape at PVGIS's
mean daily yield of the month; `climatology` = 12 × kWh per kWp per
month at this site and orientation), or "clear-sky" (no weather and no
climatology: the last resort, 60 % cloud)."""
by_end = {h.end.astimezone(timezone.utc).replace(minute=0, second=0, microsecond=0): h for h in hours}
clim = climatology if climatology and len(climatology) == 12 else None
day_scale: dict = {}
out, kinds = [], set()
for k in range(n):
s = start + k * SLOT
mid = s + SLOT / 2
hour_end = (s.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)).astimezone(timezone.utc)
h = by_end.get(hour_end)
if h is not None and h.solar_kwh_m2 is not None:
# the hour's mean irradiance, shaped over its quarters by the sun's height
quarters = [hour_end - timedelta(hours=1) + SLOT * q + SLOT / 2 for q in range(4)]
sines = [max(0.0, math.sin(math.radians(sun_position(q, lat, lon)[0]))) for q in quarters]
mine = max(0.0, math.sin(math.radians(sun_position(mid, lat, lon)[0])))
ghi = h.solar_kwh_m2 * 1000 * (4 * mine / sum(sines)) if sum(sines) > 0 else 0.0
kinds.add("irradiance")
elif clim is not None and (h is None or h.cloud_pct is None):
# no weather: the clear sky's shape, scaled to the month's mean day
day = mid.astimezone(timezone.utc).date()
if day not in day_scale:
shape = clear_day_kwh(mid, lat, lon, tilt, azimuth)
day_scale[day] = climate_day_kwh(mid, clim, kwp, pr) / shape if shape > 0 else 0.0
kinds.add("climatology")
ghi = clear_sky_ghi(sun_position(mid, lat, lon)[0])
p = power_kw(poa(ghi, mid, lat, lon, tilt, azimuth), 1.0, 1.0, None) * day_scale[day]
out.append(round(p * 0.25, 4))
continue
else:
cloud = h.cloud_pct if h is not None and h.cloud_pct is not None else FALLBACK_CLOUD
kinds.add("cloud" if h is not None and h.cloud_pct is not None else "clear-sky")
ghi = cloud_dimmed(clear_sky_ghi(sun_position(mid, lat, lon)[0]), cloud)
p = power_kw(poa(ghi, mid, lat, lon, tilt, azimuth), kwp, pr, h.temp_c if h is not None else None)
out.append(round(p * 0.25, 4))
kind = next(iter(kinds)) if len(kinds) == 1 else "cloud"
return out, kind
# ---- the inverter's AC limit ------------------------------------------------
#
# The calibration to the plant (its metered history: shading, soiling, a
# wrong kWp, the inverter) is pvcalib.py, one implementation for the
# trainer and the Mieterstrom / GGV pricing.
def clip(pv: list[float], ac_kw: float) -> list[float]:
"""kWh per slot at most the inverter's AC limit (0: none)."""
return [min(v, ac_kw * 0.25) for v in pv] if ac_kw > 0 else list(pv)