cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1919: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-12 13:44:54 +00:00
1 parent b24675fe9c
commit c0a6f8a579
21 files changed
+1055 -47

No files matched your search

+30
View File
@@ -30,6 +30,13 @@ Tariff v1 (agreed with the cloud side, 2026-10-28):
heat: g/kWh or null, basis: direct | lifecycle, electricity_source:
words}; co2() reads them (the planner weighs them by the Parameters
page's co2.planner_eur_per_t, docs/methods.md A2).
Weather (fleet sitewx.go, 2026-11-12; an older agent ignores it):
"weather" {"source", "station", "cell": [lat, lon] (0.1°), "hours":
[{"end": unix, the hour's end, "temp": °C|null, "cloud": %|null}]}: the
DWD forecast (MOSMIX through Bright Sky) for the site's own 0.1° cell over
the plan's horizon, never another site's. weather_forecast() gives it in
the form of HA's weather forecast; the plan's outdoor temperature and sky
where the mapping has no weather entity (inputs.outdoor_temperature).
Model v1 (the forecasts' data; the ML in ml/ is a placeholder, 2026-10-28):
{"v":1, "kind":"model", "id", "site" (or "*"), "issued", "expires"?,
@@ -431,6 +438,29 @@ class Bundles:
p = t.get("params")
return {k: v for k, v in p.items() if isinstance(k, str)} if isinstance(p, dict) else {}
def weather_forecast(self, now: float) -> list[dict]:
"""The tariff bundle's weather for the site's cell as HA's weather
forecast reads ([{"datetime": the hour's start, ISO, "temperature",
"cloud_coverage"}], inputs._hourly), the hours not yet over; [] without
a valid tariff bundle or without weather in it (nothing held past the
bundle's expiry)."""
t = self._valid(now)
w = (t or {}).get("weather")
if not isinstance(w, dict) or not isinstance(w.get("hours"), list):
return []
out = []
for h in w["hours"]:
if not isinstance(h, dict) or not _finite(h.get("end")) or h["end"] <= now:
continue
rec = {"datetime": datetime.fromtimestamp(int(h["end"]) - 3600, timezone.utc).isoformat()}
for k, name in (("temp", "temperature"), ("cloud", "cloud_coverage")):
v = h.get(k)
if _finite(v) and (k != "temp" or -60 <= v <= 60) and (k != "cloud" or 0 <= v <= 100):
rec[name] = float(v)
if len(rec) > 1:
out.append(rec)
return sorted(out, key=lambda r: r["datetime"])
def _valid(self, now: float) -> dict | None:
t = self.tariff.get()
if t is None or t.get("site") not in (self.site, None, "") or now >= int(t.get("expires", 0) or 0):
+13 -1
View File
@@ -192,7 +192,11 @@ PARAMS = {
"fuel": "gas",
# a combi boiler (Kombitherme; E6.6): the same burner makes the hot water as it is
# drawn, first (the rooms get what is left); the device's or its owner's fact, never assumed
"combi": False},
"combi": False,
# a hybrid's bivalence point as its own controller is set (°C: the boiler below it): the device's
# or installer's; None: the Parameters page's heat.hybrid_bivalent_c, assumed (only the savings'
# source lever reads it, heatlevers.py)
"bivalent_c": None},
"cooling": {"comfort_c": 25.0,
"setup_c": 28.0, "min_switch_s": 600.0, "internal_gain_w": 0.0, "solar_m2": 0.0,
"hold_mode_s": 1800.0, "hold_set_s": 900.0, "min_gain_ct": 1.0},
@@ -209,6 +213,9 @@ PARAMS = {
# sheet's; inputs.tank_inputs passes them to the plan; 2026-11-09: refused as unknown before)
"dhw_tank": {"legionella": "device", "shares_with": "", "sg_options": {}, "cop_curve": [], "boiler_type": "",
"part_load_curve": [],
# the store's own thermostat setpoint without Cantabile (°C; the device's or installer's); None:
# the Parameters page's dhw.thermostat_setpoint_c, assumed (the savings' store lever, heatlevers.py)
"thermostat_c": None,
"min_switch_s": 600.0, "hold_mode_s": 1800.0, "hold_set_s": 900.0, "min_gain_ct": 1.0},
}
@@ -637,6 +644,9 @@ def _check_heat(cid: str, p: dict, ents: dict):
raise ValueError(f"control {cid}: combi is true or false (a combi boiler: its hot water as it is drawn)")
if p.get("combi") and src != "boiler":
raise ValueError(f"control {cid}: combi is a boiler's (heat_source boiler)")
if p.get("bivalent_c") is not None and (_num(p["bivalent_c"]) is None or not -30 <= float(p["bivalent_c"]) <= 20
or src != "hybrid"):
raise ValueError(f"control {cid}: bivalent_c is a hybrid's bivalence point, °C (-30 to 20)")
_check_part_load(cid, p)
@@ -753,6 +763,8 @@ def _check_tank(cid: str, p: dict):
SG-Ready options for states "1".."4", a COP curve as heating's."""
if "heater" in p and p["heater"] not in TANK_HEATERS:
raise ValueError(f"control {cid}: heater is one of {', '.join(TANK_HEATERS)}")
if p.get("thermostat_c") is not None and (_num(p["thermostat_c"]) is None or not 20 <= float(p["thermostat_c"]) <= 95):
raise ValueError(f"control {cid}: thermostat_c is the store's own setpoint, °C (20 to 95)")
_check_part_load(cid, p)
if "erp_class" in p and p["erp_class"] not in ERP_CLASSES:
raise ValueError(f"control {cid}: erp_class is one of {', '.join(ERP_CLASSES)}")
+418
View File
@@ -0,0 +1,418 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The heating levers the plan's baseline does not count (docs/methods.md
E14 "Heating levers"; the owner, 2026-11-09: "we still have
no saving from gas/oil?").
The plan's baseline (optimizer.baseline, A12.2) counts each heat input as
the plan itself uses it, at the horizon's mean price: it shows only heat
moved to cheaper hours, and at one gas, oil or district heat price nothing.
What the plan changes besides the hour is the quantity: less heat while
nobody is home, a boiler at a better load, a heat pump at a better COP, a
hybrid's source, a store held cooler. Each lever here has its stated
counterfactual (what the house would do without Cantabile) and is the
difference in each carrier's input over the plan's horizon (kWh: gas and
heating oil on Hs, electricity, district heat), priced at the carrier's
mean price over the horizon (EUR), so it never overlaps the time shift the
baseline counts (that is the existing split's). Positive: the plan uses
less.
setback a room thermostat on the household's fixed day program
(comfort from savings.thermostat_comfort_from_h to _to_h, its
setback otherwise; the Parameters page) against the same
thermostat on the plan's targets (comfort while someone is
home, by the presence now and the learnt presence): the heat
the presence saves. Not in use: the owner's own schedule
drives the room (a thermostat would follow it too), or no
presence is known (the plan uses the same fixed hours).
part_load a boiler heating rooms, on its part-load curve (E6.4):
the gas or oil per kWh of heat a thermostat holding the plan's targets would burn (full output on every
recovery) against the plan's own, times the plan's heat. Not
measured: no curve (boiler_type or part_load_curve), an
on/off boiler (full load either way).
cop_timing a heat pump heating rooms, whose COP follows the
outside temperature (cop_curve): the electricity per kWh of
heat of the thermostat holding the plan's targets against the
plan's (heat made in the warmer hours). Not measured: one COP.
source a hybrid: its own controller holding the plan's targets,
the boiler below its bivalence point, the heat pump at or
above it (the device's bivalent_c, else the Parameters page's
heat.hybrid_bivalent_c, assumed), against the plan's choice
of source, its timing and its part load, each input at its
mean price. Not measured: no bivalence point.
store a hot-water store's own thermostat at its setpoint (the
device's thermostat_c, else the Parameters page's
dhw.thermostat_setpoint_c, assumed) against the same
thermostat at the plan's least (the baseline's): the standing
loss the plan avoids (the heat stored at the horizon's end
taken off). Not measured: no setpoint.
{lever: {"eur", "carriers": {carrier: {"kwh", "eur"}}, "note"}
| {"why", "note"}} (why: not measured or not in use)
A lever that does not apply to the home (no device of its kind) is left
out. A store's firing and hours are not levers: its baseline is its own
thermostat (A13), so the plan's saving (base - plan) counts them already;
only its setpoint (store) lies beyond that baseline. With the plan's saving
(the plan's inputs at the mean price against the same inputs at each step's
price: the time shift) and each lever (a quantity at the mean price) the
parts add up without overlap (achieved levers are inside
with and without). Electricity's quarter-hours of a hybrid's or heat pump's heat are at
the mean import price here; their time shift stays the existing lever's.
"""
import math
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
PROGRAM_FROM_KEY = "savings.thermostat_comfort_from_h" # the Parameters page's (via the tariff bundle)
PROGRAM_TO_KEY = "savings.thermostat_comfort_to_h"
BIVALENT_KEY = "heat.hybrid_bivalent_c"
SETPOINT_KEY = "dhw.thermostat_setpoint_c"
LEVERS = ("setback", "part_load", "cop_timing", "source", "store")
PRICE_KEYS = {"electricity": "price_import", "gas": "price_gas", "oil": "price_oil", "heat": "price_heat"}
def _num(v) -> float | None:
if isinstance(v, bool):
return None
try:
x = float(v)
except (TypeError, ValueError):
return None
return x if math.isfinite(x) else None
def mean_prices(s: dict, T: int) -> dict:
"""Per carrier the mean of its prices over the horizon (ct/kWh), the carriers with a price."""
out = {}
for c, key in PRICE_KEYS.items():
ps = [p for p in (s.get(key) or [])[:T] if p is not None]
if ps:
out[c] = sum(ps) / len(ps)
return out
class Acc:
"""Wh per carrier, then kWh and EUR at the carriers' mean prices."""
def __init__(self):
self.wh: dict[str, float] = {}
def add(self, carrier: str, wh: float):
self.wh[carrier] = self.wh.get(carrier, 0.0) + wh
def result(self, means: dict, note: str) -> dict:
"""{"eur", "carriers", "note"}; not measured where a carrier has no price."""
out, total = {}, 0.0
for c, wh in sorted(self.wh.items()):
if c not in means:
return not_measured("no_price", f"no {c} price over the plan's horizon")
eur = wh / 1000.0 * means[c] / 100.0
out[c] = {"kwh": round(wh / 1000.0, 3), "eur": round(eur, 4)}
total += eur
return {"eur": round(total, 4), "carriers": out, "note": note}
def not_measured(why: str, note: str) -> dict:
return {"why": why, "note": note}
# ---- rooms
def heat_of(v: dict, t: int, x) -> float:
"""The plan's heat into the room in step t (W)."""
return sum(k * x(var) for k, var in v["hterms"][t])
def gains_k(s: dict, v: dict, x, T: int) -> list[float]:
"""Per step the room's other heat (its internal and solar gains, the
covers' as planned) in kelvin, from the plan's own temperatures:
T_t = (1 - a) T_(t-1) + a T_out,t + k (Q_t + G_t), so G_t k = T_t - (1 -
a) T_(t-1) - a T_out,t - k Q_t (the thermal model, A2.6, exactly)."""
a, k, prev, out = v["a"], v["k"], v["t0"], []
for t in range(T):
tt = x(v["temp"][t])
out.append(tt - (1 - a) * prev - a * s["t_out"][t] - k * heat_of(v, t, x))
prev = tt
return out
def heat_cap(v: dict, t: int) -> float:
"""The most heat the room's source gives in step t (W)."""
src = v["src"]
if src in ("electric", "heat_pump"):
return v["elmax"] * v["cops"][t]
if src == "hybrid":
return max(v["elmax"] * v["cops"][t], v["qmax"])
cap = v["qmax"]
if v.get("combi") is not None and t < len(v["combi"]):
cap = max(cap - v["combi"][t], 0.0) # a combi makes the hot water first (E6.6)
return cap
def thermostat(s: dict, v: dict, targets: list[float], gk: list[float], T: int) -> tuple[list[float], float]:
"""A thermostat holding targets (°C per step) with the room's model, its
gains and its source's most heat, from the plan's own start: per step
the heat (W), and the temperature at the end. No pre-heating: it heats
when the room would fall below the target, as much as that takes."""
a, k, temp, out = v["a"], v["k"], v["t0"], []
for t in range(T):
free = (1 - a) * temp + a * s["t_out"][t] + gk[t]
q = min(max(0.0, (targets[t] - free) / k), heat_cap(v, t)) if k > 0 else 0.0
temp = free + k * q
out.append(q)
return out, temp
def plan_targets(v: dict, T: int) -> list[float]:
"""The plan's heating target per step (the band's lower bound: comfort while someone is home, the
setback otherwise, the owner's musts and schedule)."""
return [v["band"][t][0] for t in range(T)]
def program_targets(s: dict, v: dict, T: int, frm: float, to: float) -> list[float]:
"""The fixed day program per step: comfort from frm to to (local hours), the setback otherwise, inside
the room's bounds; a step's target is the next step's (the plan's own rule, Model.room)."""
zone = ZoneInfo(s.get("tz") or "UTC")
out = []
for t in range(T):
ts = s["start"] + min(t + 1, T - 1) * s["step_s"]
h = datetime.fromtimestamp(ts, timezone.utc).astimezone(zone)
hour = h.hour + h.minute / 60.0
on = frm <= hour < to if frm <= to else (hour >= frm or hour < to)
out.append(min(max(v["comfort"] if on else v["other"], v["lo"]), v["hi"]))
return out
def inputs_w(v: dict, t: int, q: float, rule) -> dict:
"""The inputs (W per carrier) that make q W of heat in step t: a heat pump's electricity by its COP, a
boiler's fuel on its curve (HeatSupply.input_w), district heat as it is; a hybrid by rule(t) ->
"heat_pump" | "boiler" (the heat pump up to its output, the rest from the boiler, and the reverse)."""
if q <= 0:
return {}
src = v["src"]
if src in ("electric", "heat_pump"):
return {"electricity": q / max(v["cops"][t], 1e-9)}
if src == "district":
return {"heat": q}
if src == "boiler":
return {v["fuel"] or "gas": v["sup"].input_w(q)}
hp_cap, out = v["elmax"] * v["cops"][t], {}
if rule(t) == "heat_pump":
hp = min(q, hp_cap)
boiler = q - hp
else:
boiler = min(q, v["qmax"])
hp = min(q - boiler, hp_cap)
if hp > 0:
out["electricity"] = hp / max(v["cops"][t], 1e-9)
if boiler > 0:
out[v["fuel"] or "gas"] = v["sup"].input_w(boiler)
return out
def plan_inputs_wh(v: dict, x, T: int, dt: float) -> dict:
"""The plan's own inputs over the horizon (Wh per carrier)."""
out = {}
for col, carrier in (("power", "electricity"), ("gas", v.get("fuel") or "gas"), ("district", "heat")):
wh = sum(x(var) for var in (v.get(col) or [])[:T] if var is not None) * dt
if wh:
out[carrier] = out.get(carrier, 0.0) + wh
return out
def cheaper_rule(v: dict, means: dict):
"""A hybrid's source per step for a thermostat that knows the prices: the cheaper heat at the mean prices."""
fuel = v.get("fuel") or "gas"
def rule(t):
el, fu = means.get("electricity"), means.get(fuel)
if el is None:
return "boiler"
if fu is None:
return "heat_pump"
hp = el / max(v["cops"][t], 1e-9)
bo = fu / max(v["sup"].curve["full"] or 1e-9, 1e-9)
return "heat_pump" if hp <= bo else "boiler"
return rule
def setback(s, m, x, rooms, means, gks) -> dict | None:
"""The heat the presence saves against a thermostat's fixed day program (module docstring)."""
if not rooms:
return None
occ = (s.get("sources") or {}).get("occupancy") or {}
if all(v["pref"] for _, v in rooms):
return not_measured("owner_schedule", "the rooms follow the household's own schedule: a thermostat would "
"follow it too, so the plan saves no heat by presence")
if occ.get("source") == "fixed_hours" and not occ.get("presence_now"):
return not_measured("no_presence", "no presence is known (no presence source, or none learnt yet): the plan "
"heats by the same fixed hours a thermostat's program would")
params = s.get("params") or {}
frm, to = _num(params.get(PROGRAM_FROM_KEY)), _num(params.get(PROGRAM_TO_KEY))
if frm is None or to is None or not (0 <= frm <= 24 and 0 <= to <= 24):
return not_measured("no_parameter", f"the Parameters page's {PROGRAM_FROM_KEY} and {PROGRAM_TO_KEY} (the "
"thermostat's day program without Cantabile) did not reach the box")
acc, T, dt = Acc(), m.T, m.dt
for _, v in rooms:
if v["pref"]:
continue
qa, ta = thermostat(s, v, program_targets(s, v, T, frm, to), gks[id(v)], T)
qb, tb = thermostat(s, v, plan_targets(v, T), gks[id(v)], T)
# the heat the presence saves (the program's room still holding heat at the end is not used: taken off),
# converted at the plan's own inputs per kWh of heat: the quantity alone; how the heat is made (a
# boiler's load, a heat pump's hour, a hybrid's source) is the other levers'
dheat = (sum(qa) - sum(qb)) * dt - ((ta - tb) * dt / v["k"] if v["k"] > 0 else 0.0)
conv = plan_inputs_wh(v, x, T, dt)
heat = sum(heat_of(v, t, x) for t in range(T)) * dt
if heat <= 0 or not conv:
# no heat in the plan: the conversion of the thermostat's own heat (the cheaper source for a hybrid)
rule, conv, heat = cheaper_rule(v, means), {}, 0.0
for q in (qb, qa):
for t in range(T):
for c, w in inputs_w(v, t, q[t], rule).items():
conv[c] = conv.get(c, 0.0) + w * dt
heat = sum(q) * dt
if heat > 0:
break
if heat <= 0:
continue # no heat needed in the horizon either way
for c, wh in conv.items():
acc.add(c, dheat * wh / heat)
return acc.result(means, f"against a thermostat's day program, comfort {frm:g}-{to:g} h")
def part_load(s, m, x, rooms, tanks, means, gks) -> dict | None:
"""A boiler room's fuel per kWh of heat: a thermostat's firing against the plan's (module docstring). A
boiler-heated store is not here: its baseline is its own thermostat already (A13, tank_baseline), so the
plan's saving counts its firing (no double counting once the levers are in with / without)."""
boilers = [(d, v) for d, v in rooms if v["src"] == "boiler"]
if not boilers:
return None
acc, T, dt, measured, why = Acc(), m.T, m.dt, False, None
for d, v in boilers:
curve = v["sup"].curve or {}
if v.get("switched"):
why = why or ("on_off", "an on/off boiler runs at full load with and without the plan")
continue
if not curve.get("segs"):
why = why or ("no_curve", "no part-load curve: the boiler's type or its datasheet's curve is needed "
"(mapping boiler_type or part_load_curve; methods E6.4)")
continue
qb = thermostat(s, v, plan_targets(v, T), gks[id(v)], T)[0]
qp = [heat_of(v, t, x) for t in range(T)]
heat_b, heat_p = sum(qb), sum(qp)
fuel_b = sum(v["sup"].input_w(q) for q in qb)
fuel_p = sum(x(var) for var in v["gas"][:T] if var is not None)
measured = True
if heat_b <= 0 or heat_p <= 0:
continue
acc.add(v.get("fuel") or "gas", (heat_p * fuel_b / heat_b - fuel_p) * dt)
if not measured:
return not_measured(*why)
return acc.result(means, "against a thermostat firing the boiler as the heat is needed, on the same curve")
def cop_timing(s, m, x, rooms, tanks, means, gks) -> dict | None:
"""A heat pump room's electricity per kWh of heat: a thermostat's hours against the plan's (module docstring).
A heat pump store is not here: its baseline is its own thermostat at each step's COP already (A13), so the
plan's saving counts its hours (no double counting)."""
pumps = [(d, v) for d, v in rooms if v["src"] == "heat_pump"]
if not pumps:
return None
acc, T, dt, measured = Acc(), m.T, m.dt, False
for d, v in pumps:
cops = v["cops"][:T]
if not cops or max(cops) - min(cops) < 1e-9:
continue
qb = thermostat(s, v, plan_targets(v, T), gks[id(v)], T)[0]
qp = [heat_of(v, t, x) for t in range(T)]
heat_b, heat_p = sum(qb), sum(qp)
el_b = sum(q / max(cops[t], 1e-9) for t, q in enumerate(qb))
el_p = sum(x(var) for var in v["power"][:T] if var is not None)
measured = True
if heat_b <= 0 or heat_p <= 0:
continue
acc.add("electricity", (heat_p * el_b / heat_b - el_p) * dt)
if not measured:
return not_measured("one_cop", "one COP at every hour (no cop_curve): the hour a heat pump runs does not "
"change its electricity per kWh of heat")
return acc.result(means, "against a thermostat running the heat pump as the heat is needed, at that hour's COP")
def source(s, m, x, rooms, means, gks) -> dict | None:
"""A hybrid's choice of source against its own controller's bivalence point (module docstring)."""
hybrids = [(d, v) for d, v in rooms if v["src"] == "hybrid"]
if not hybrids:
return None
acc, T, dt, srcs = Acc(), m.T, m.dt, set()
biv_par = _num((s.get("params") or {}).get(BIVALENT_KEY))
for _, v in hybrids:
own = _num(v.get("bivalent_c"))
biv = own if own is not None else biv_par
if biv is None:
return not_measured("no_bivalent", "the hybrid's bivalence point is not known (the device's bivalent_c, "
f"or the Parameters page's {BIVALENT_KEY})")
srcs.add(f"{biv:g} °C, " + ("the device's" if own is not None else "assumed (Parameters page)"))
def rule(t, biv=biv):
return "boiler" if s["t_out"][t] < biv else "heat_pump"
qb = thermostat(s, v, plan_targets(v, T), gks[id(v)], T)[0]
cf = {}
for t in range(T):
for c, w in inputs_w(v, t, qb[t], rule).items():
cf[c] = cf.get(c, 0.0) + w * dt
pl = plan_inputs_wh(v, x, T, dt)
for c in set(cf) | set(pl):
acc.add(c, cf.get(c, 0.0) - pl.get(c, 0.0))
return acc.result(means, "against the hybrid's own controller: the boiler below its bivalence point ("
+ "; ".join(sorted(srcs)) + "), the heat pump above")
def store(s, m, x, tanks, means) -> dict | None:
"""The standing loss a store's own thermostat at its setpoint has over the plan's least (module docstring)."""
from .optimizer import _tank_input_w, tank_thermostat
if not tanks:
return None
par = _num((s.get("params") or {}).get(SETPOINT_KEY))
acc, T, dt, srcs = Acc(), m.T, m.dt, set()
for _, v in tanks:
own = _num(v.get("thermostat_c"))
sp = own if own is not None else par
if sp is None:
return not_measured("no_setpoint", "the store's own thermostat setpoint without Cantabile is not known "
f"(the device's thermostat_c, or the Parameters page's {SETPOINT_KEY})")
set_c = min(sp, v["hi_c"])
srcs.add(f"{set_c:g} °C, " + ("the device's" if own is not None else "assumed (Parameters page)"))
if set_c <= v["lo_c"] + 1e-9:
continue
hs, es = tank_thermostat(m, v, v["cw"] * (set_c - v["t_cw"]))
hm, em = tank_thermostat(m, v)
heat = sum(hs) * dt - sum(hm) * dt - (es - em) # the extra standing loss, Wh of heat
mid = T // 2
carrier, w = _tank_input_w(v, mid, 1.0)
if v["heater"] == "boiler":
carrier = v.get("fuel") or "gas" # a boiler store's own fuel (gas or heating oil)
acc.add(carrier, heat * w)
return acc.result(means, "against the store's own thermostat at its setpoint (" + "; ".join(sorted(srcs)) + ")")
def heat_levers(s: dict, m, x) -> dict | None:
"""The heating levers of this plan (module docstring); None without a priced plan or any heating."""
if not m.priced:
return None
T = m.T
rooms = [(d, v) for d, (kind, v) in m.devices.items() if kind == "heating" and v and "hterms" in v]
tanks = [(d, v) for d, (kind, v) in m.devices.items() if kind == "dhw_tank" and v and "sup" in v]
if not rooms and not tanks:
return None
means = mean_prices(s, T)
gks = {id(v): gains_k(s, v, x, T) for _, v in rooms}
out = {}
for name, got in (("setback", setback(s, m, x, rooms, means, gks)),
("part_load", part_load(s, m, x, rooms, tanks, means, gks)),
("cop_timing", cop_timing(s, m, x, rooms, tanks, means, gks)),
("source", source(s, m, x, rooms, means, gks)),
("store", store(s, m, x, tanks, means))):
if got is not None:
out[name] = got
return out or None
+56 -15
View File
@@ -151,6 +151,34 @@ def _hourly(forecast: list[dict], key: str, start: int, steps: int) -> list[floa
return out
def outdoor_temperature(start: int, col: Collector, inputs, ha_forecast: list[dict] | None,
fleet_forecast: list[dict] | None) -> tuple[list[float] | None, str]:
"""The outdoor temperature per step and where it is from (the plan's
sources.outdoor, methods.md A1.4): "ha_entity" (the mapping's weather
entity's forecast), else "fleet_forecast" (fleet's DWD forecast for the
site's cell, bundles.weather_forecast), either "+sensor_bias" where an
outdoor sensor reads now (the forecast moved by the difference, fading
over 6 hours); else "sensor_now" or "ha_entity_now" (that value held);
else (None, "none"): no stand-in."""
measured = col.value(inputs.outside_temp) if inputs.outside_temp else None
t_out, src = _hourly(ha_forecast or [], "temperature", start, STEPS), "ha_entity"
if t_out is None:
t_out, src = _hourly(fleet_forecast or [], "temperature", start, STEPS), "fleet_forecast"
if t_out is not None:
if measured is not None:
# a thermometer outside says better than the forecast what it is now
bias = measured - t_out[0]
t_out = [v + bias * max(0.0, 1 - k / 24) for k, v in enumerate(t_out)]
src += "+sensor_bias"
return t_out, src
if measured is not None:
return [measured] * STEPS, "sensor_now"
now_out = number(col.attr(inputs.weather, "temperature")) if inputs.weather else None
if now_out is not None:
return [now_out] * STEPS, "ha_entity_now"
return None, "none"
def watts(col: Collector, eid: str) -> float | None:
"""A power sensor's value in W (HA's kW converted)."""
v = col.value(eid)
@@ -935,20 +963,15 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
net_load = got[0] if got[1].startswith("model") else None
else:
net_load = load
t_out = _hourly(weather_forecast or [], "temperature", start, STEPS)
t_src = "weather forecast"
measured = col.value(inputs.outside_temp) if inputs.outside_temp else None
if t_out is not None and measured is not None:
# a thermometer outside says better than the forecast what it is
# now: the forecast moved by the difference, fading over 6 hours
bias = measured - t_out[0]
t_out = [v + bias * max(0.0, 1 - k / 24) for k, v in enumerate(t_out)]
t_src = "weather forecast, from the outdoor sensor now"
# the outdoor temperature (methods.md A1.4): the mapping's weather entity's forecast, else
# fleet's forecast for the site's own cell (the tariff bundle's "weather", DWD MOSMIX), each
# moved by an outdoor sensor where there is one; else the sensor's (or the entity's) value
# now, held; else none: no number stands in (rooms are not planned, a quiet note)
fwx = bundles.weather_forecast(now) if hasattr(bundles, "weather_forecast") else []
t_out, t_src = outdoor_temperature(start, col, inputs, weather_forecast, fwx)
if t_out is None:
now_out = col.value(inputs.outside_temp)
if now_out is None and inputs.weather:
now_out = number(col.attr(inputs.weather, "temperature"))
t_out, t_src = [now_out if now_out is not None else 10.0] * STEPS, ("now" if now_out is not None else "default")
notes.append("no outdoor temperature (no weather entity, no forecast from the platform for the site's "
"location, no outdoor sensor): rooms are not planned, they follow their schedule")
peak = max(pv) if pv else 0.0
if peak > 100:
sun = [max(0.0, p / peak) for p in pv]
@@ -1018,6 +1041,12 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
fallback.append({"id": c.id, "kind": c.kind, "params": params, "state": st, "bounds": bounds,
"channels": sorted(c.writable())})
continue
if t_out is None:
# no outdoor temperature: the room model has no outside to lose heat to. Not a
# refusal (nothing to enter in the mapping): its fallback schedule, the plan's note
fallback.append({"id": c.id, "kind": c.kind, "params": params, "state": st, "bounds": bounds,
"channels": sorted(c.writable())})
continue
if c.kind == "heating" and hasattr(c, "heat_facts"):
facts, _, fsrc = c.heat_facts()
params.update(facts)
@@ -1054,6 +1083,15 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
if "note" in got:
notes.append(got["note"])
continue
if t_out is None and params.get("cop_curve") and str(params.get("heater")) == "heat_pump":
# its COP by the outside temperature: none known. The device's one COP where it
# has one, else not planned (its own thermostat)
if params.get("cop") is None:
notes.append(f"{c.id}: hot-water tank not planned: its heat pump's COP follows the outdoor "
"temperature and there is none; its own thermostat meanwhile")
continue
params["cop_curve"] = []
got["src"] = dict(got["src"], cop="its one COP (no outdoor temperature for the curve)")
tank_src[c.id] = got["src"]
extra = {"draw_w": got["draw_w"]}
b = c.bounds("temp_c", (extra_limits or {}).get(c.id)) # with a Großanlage's floor (tank_facts)
@@ -1062,6 +1100,9 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
"state": st, "bounds": bounds,
"channels": sorted(c.writable()), **extra})
clouds = _hourly(weather_forecast or [], "cloud_coverage", start, STEPS)
sky_src = "weather forecast"
if clouds is None and fwx:
clouds, sky_src = _hourly(fwx, "cloud_coverage", start, STEPS), "fleet forecast"
sky = [max(0.0, min(1.0, 1 - c / 100.0)) for c in clouds] if clouds else [1.0] * STEPS
ghi, ghi_src = irradiance(start, location, sky, sun if peak > 100 else None)
# the heat outlook (space heat no room plans, hot water), CO2 (methods A2): the forecasts and factors
@@ -1077,8 +1118,8 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
"priced_steps": getattr(prices, "priced_steps", STEPS)},
"load_w": load, "pv_w": pv, "t_out": t_out, "sun": sun, "occupied": occupied, "sky": sky,
"ghi_w_m2": ghi, "location": location or {},
"sources": {"load": load_src, "pv": pv_src, "t_out": t_src, "model": bundles.model_id(),
"sky": "weather forecast" if clouds else "clear", "rooms": rooms_src, "ghi": ghi_src,
"sources": {"load": load_src, "pv": pv_src, "outdoor": t_src, "model": bundles.model_id(),
"sky": sky_src if clouds else "clear", "rooms": rooms_src, "ghi": ghi_src,
"rooms_cop": cop_src, "rooms_band": band_src,
"ev_phases": phases_src,
# occupied steps per source (presence now, learnt, fixed hours) and why (B16)
+49 -5
View File
@@ -171,6 +171,9 @@ SPILL_EUR_KWH = 1e-3 # EUR per kWh of PV curtailed (ENG: never curtail whil
# above NO_PRICE_EUR_KWH so export wins over spill without a tariff)
END_VALUE_KEY = "battery.end_value_pct" # the Parameters page's (via the tariff bundle's params): % of the
# mean feed-in price a kWh left in the battery at the end is worth
WEAR_KEY = "battery.wear_ct" # the Parameters page's (via the tariff bundle's params): net ct per kWh a battery
# discharges, its ageing per kWh cycled (the owner's battery algorithm, 2026-11-12:
# in every decision, as the building's battery_core); a device's own wear_ct wins
END_VALUE_GAP_CT = 0.5 # ct/kWh: the end value at least this far below the cheapest import price (ENG: never
# buy grid energy into the battery only to keep it; building/mieterstrom.py's twin)
GRID_MAX_W = 43470.0 # W: the site's connection when the state does not say (state["grid_max_w"],
@@ -546,6 +549,21 @@ class Model:
self._end_v = max(0.0, v)
return self._end_v
def wear(self, p: dict) -> tuple[float, str]:
"""The battery's wear (ct per kWh discharged) and where it came from: the device's own wear_ct, else the
Parameters page's battery.wear_ct (state["params"]); 0 without a tariff (nothing is priced) or without
either (as before 2026-11-12: "none")."""
if not self.priced:
return 0.0, "none"
for raw, src in ((p.get("wear_ct"), "device"), ((self.s.get("params") or {}).get(WEAR_KEY), "parameter")):
try:
v = float(raw)
except (TypeError, ValueError):
continue
if math.isfinite(v) and v >= 0:
return v, src
return 0.0, "none"
def battery(self, d):
p, st, b = d["params"], d["state"], d["bounds"]
cap = max(1.0, float(p["capacity_wh"]))
@@ -566,6 +584,10 @@ class Model:
lam_h = max(0.0, float(p.get("self_discharge_pct_month") or 0.0)) / 100.0 / HOURS_PER_MONTH
phi = (1.0 - lam_h) ** self.dt
grid_side = p.get("standby_in_load") is False
wear_ct, wear_src = self.wear(p)
wear_eur = wear_ct / 100.0 * self.dt / 1000.0 # EUR per W discharged over a step
self.wear_used = getattr(self, "wear_used", {})
self.wear_used[d["id"]] = {"ct": wear_ct, "src": wear_src}
lbs, lgs = [], []
for t in range(self.T):
lo_t = lo_pct
@@ -573,7 +595,7 @@ class Model:
lo_t = min(max(lo_pct, pref["floor_pct"][t]), hi_pct)
floors.append(lo_t)
c = self.var(0.0, max_ch, cost=self.use_cost(t))
x = self.var(0.0, max_dis, cost=self.use_cost(t))
x = self.var(0.0, max_dis, cost=self.use_cost(t) + wear_eur)
z = self.var(0.0, 1.0, integer=True)
self.h.addConstr(c - max_ch * z <= 0)
self.h.addConstr(x + max_dis * z <= max_dis)
@@ -640,6 +662,7 @@ class Model:
t_out = self.s["t_out"]
cops = [cop_at(p, t_out[t]) if p.get("cop_curve") else cop for t in range(self.T)]
els, gss, dhs, hxs, bxs, prev_u = [], [], [], [], [], None
hts, occs = [], [] # per step the heat's terms; the occupancy the target used
if src == "hybrid" and st.get("source") in ("heat_pump", "boiler"):
prev_u = 1.0 if st["source"] == "heat_pump" else 0.0 # the source now: a change from it counts
a = self.dt / (r * c)
@@ -688,6 +711,7 @@ class Model:
dhs.append(ph)
heat = sum((k * v for k, v in terms), start=Lin())
hxs.append(heat)
hts.append(list(terms))
if combi is not None:
self.h.addConstr(heat <= max(qmax - combi[t], 0.0))
main = pw if pw is not None else pg if pg is not None else ph
@@ -702,6 +726,7 @@ class Model:
self.h.addConstr(tt - (1 - a) * prev - sign * self.dt / c / 1000.0 * heat
- self.dt / c / 1000.0 * gain == a * self.s["t_out"][t] + self.dt / c / 1000.0 * fixed)
occ = self.s["occupied"][t + 1] if t + 1 < self.T else self.s["occupied"][t]
occs.append(occ)
want, must = (comfort if occ else other), None
if pref:
want, must = pref["target"][t], pref["must"][t]
@@ -755,7 +780,13 @@ class Model:
"district": qmax}[src], "switched": switched,
# the shift envelope (electric sources only): Wh of electricity per K at the mean COP
"keep": 1 - a, "wh_per_k": 1000.0 * c / (sum(cops) / len(cops)) if cops and min(cops) > 0 else 0.0,
"band": band})
"band": band,
# for the heating levers the baseline does not count (heatlevers.py, E14): the
# room's model, the heat's terms per step, its source's conversion and facts
"a": a, "k": self.dt / c / 1000.0, "t0": t0, "hterms": hts, "sup": sup,
"elmax": pmax, "combi": combi, "comfort": comfort, "other": other,
"lo": lo, "hi": hi, "pref": bool(pref), "occ": occs,
"bivalent_c": p.get("bivalent_c")})
def hourly(self, v) -> list[float]:
"""A number, or 24 by local hour, per step."""
@@ -948,7 +979,9 @@ class Model:
"qmax": sup.qmax if sup else None,
# a boiler-heated tank's fuel (gas or heating oil: the plan's series, plan_series)
"fuel": sup.carrier if heater == "boiler" and sup else None,
"src": "electric" if heater in ("element", "heat_pump") else heater})
"src": "electric" if heater in ("element", "heat_pump") else heater,
# for the store's lever (heatlevers.py): its heater's conversion, its own setpoint without the plan
"sup": sup, "thermostat_c": p.get("thermostat_c")})
def cover(self, d, room_ids):
p, b = d["params"], d["bounds"]
@@ -1289,6 +1322,8 @@ def plan(s: dict, time_limit: float = 30.0) -> dict:
v_ct = m.end_value()
out["battery_end"] = {"value_ct": round(v_ct, 2), "store_eur": round(sum(
v_ct / 100.0 * (x(b["soc"][-1]) - b["soc0"]) / 1000.0 for b in bats), 2)}
# the wear on every kWh discharged (the owner's battery algorithm, 2026-11-12) and where it came from
out["battery_wear"] = getattr(m, "wear_used", {})
if parts is not None:
out["cost_parts"] = parts # cost_eur by carrier, the heat outlook a fixed term of its own
if outlook is not None:
@@ -2162,9 +2197,18 @@ def tank_thermostat_heat(m, v) -> list[float]:
2026-11-09 the baseline held E_min from the first step, and a tank
started warm showed its stored heat as saved: 0.75 EUR per plan for
300 L at 55 °C over a 45 °C least, at one price)."""
return tank_thermostat(m, v)[0]
def tank_thermostat(m, v, emin: float | None = None) -> tuple[list[float], float]:
"""tank_thermostat_heat holding emin (Wh above the cold water; None:
the comfort's least E_min): (the heat per step, W; the stored heat at
the horizon's end, Wh). The store's lever (heatlevers.py) holds the
store's own setpoint with it."""
e, dt, out = v["e0"], m.dt, []
emin = v["emin"] if emin is None else emin
for t in range(m.T):
need = (v["emin"] - v["phi"] * e) / dt + v["draw"][t] + v["p0"]
need = (emin - v["phi"] * e) / dt + v["draw"][t] + v["p0"]
if v["heater"] in ("element", "heat_pump"):
cap = v["pmax"] * v["cops"][t] if v["pmax"] else math.inf
else:
@@ -2172,7 +2216,7 @@ def tank_thermostat_heat(m, v) -> list[float]:
q = min(max(0.0, need), cap)
e = v["phi"] * e + dt * (q - v["draw"][t] - v["p0"])
out.append(q)
return out
return out, e
def tank_baseline_steps(m, v) -> dict:
+17 -5
View File
@@ -24,8 +24,8 @@ owner: "we still have no saving from gas/oil?"; methods E14):
flat_price one price at every step of the horizon: the plan's heat costs
the same whenever it is made, there is nothing to move in time
(the baseline counts the plan's own heat at the mean price,
A12.2; a lower room temperature is not counted as a saving,
E14; a hybrid's choice of source is not counted either)
A12.2; a lower room temperature and a hybrid's choice of source
are counted apart, heat_levers below)
not_shifted the price varies, but the heat lies where it is needed
not_planned the heating or tank on it was refused (its refusal's why: e.g.
no gas price); 0 in plan and base, nothing of it is planned
@@ -49,7 +49,14 @@ contracts (a tenant-power flat's energy bought from its building at the
offer's price per slot, GGV §42b / Mieterstrom §42a / §42c; before, only the
grid meter was priced and such a flat showed electricity 0.00 against a
baseline of its whole load). None without a tariff (no step
costs)."""
costs).
heat_levers (2026-11-12): what the plan saves on heat that
the baseline cannot show (a lower room temperature while nobody is home, a
boiler's part load, a heat pump's COP by the hour, a hybrid's source, a
store held cooler), each against its stated counterfactual, apart from the
carriers above (heatlevers.py)."""
from .heatlevers import heat_levers
def saving_parts(s: dict, m, x, steps: dict | None) -> dict | None:
@@ -77,6 +84,11 @@ def saving_parts(s: dict, m, x, steps: dict | None) -> dict | None:
why = zero_why(s, m, carrier, out.get(carrier))
if why is not None:
out.setdefault(carrier, {"plan_eur": 0.0, "base_eur": 0.0}).update(why)
# the heating levers the baseline does not count, each against its own counterfactual, apart from the
# carriers' saving above (heatlevers.py; methods E14 "Heating levers")
levers = heat_levers(s, m, x)
if levers:
out["heat_levers"] = levers
return out
@@ -101,7 +113,7 @@ def zero_why(s: dict, m, carrier: str, part: dict | None) -> dict | None:
col = "district" if carrier == "heat" else "gas"
rooms = any(kind == "heating" and v and any(c is not None for c in v.get(col) or [])
and (carrier == "heat" or (v.get("fuel") or "gas") == carrier) for kind, v in m.devices.values())
tail = "; a hybrid's choice between heat pump and boiler is not counted as a saving" if hybrid else ""
tail = "; a hybrid's choice between heat pump and boiler is counted apart (the heating levers)" if hybrid else ""
if abs(part["plan_eur"]) < ZERO_EUR and abs(part["base_eur"]) < ZERO_EUR:
return {"why": "not_used", "note": (f"the heat pump made all the heat in this plan: no {words} used" if hybrid
else f"no {words} used in this plan") + tail}
@@ -109,7 +121,7 @@ def zero_why(s: dict, m, carrier: str, part: dict | None) -> dict | None:
if ps and max(ps) - min(ps) < 1e-9:
return {"why": "flat_price", "note": f"one {words} price ({ps[0]:.2f} ct/kWh) at every hour of the plan: its heat "
"costs the same whenever it is made, nothing to move in time"
+ ("; a lower room temperature is not counted as a saving" if rooms else "")
+ ("; a lower room temperature is counted apart (the heating levers)" if rooms else "")
+ tail}
return {"why": "not_shifted", "note": f"the {words} price varies, but the heat was needed when it was made" + tail}
+2 -1
View File
@@ -172,7 +172,8 @@ def schedule(d: dict, s: dict, ctx: dict | None = None) -> dict:
priced = [x for x in prices if x is not None]
mean = sum(priced) / len(priced) if priced else 0.0
sky = s.get("sky") or [1.0] * T
t_out = s.get("t_out") or [10.0] * T
# no outdoor temperature (inputs.outdoor_temperature: none): no step is warm, every step cold
t_out = s.get("t_out") or []
occupied = s.get("occupied") or [1] * T
temp, setpoint = ctx.get("temp_c"), ctx.get("setpoint_c")
pos0 = st.get("position_pct")