cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1919: full source
This commit is contained in:
1 parent
b24675fe9c
commit
c0a6f8a579
21 files changed
+1055
-47
No files matched your search
@@ -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):
|
||||
|
||||
@@ -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)}")
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -77,7 +77,8 @@ def test_model_state_plans_on_the_base_load(tmp_path):
|
||||
from cantabile_edge import optimizer
|
||||
m = site_mapping(tmp_path, [gauge("sensor.hp", "heatpump.power")], [heater()])
|
||||
col = Collector()
|
||||
watts(col, sensor__load=6400, sensor__hp=4000, sensor__living_temp=15)
|
||||
watts(col, sensor__load=6400, sensor__hp=4000, sensor__living_temp=15, sensor__out=-5)
|
||||
m.inputs.outside_temp = "sensor.out" # an outdoor temperature: the room is planned (methods A1.4)
|
||||
ctl = [Control("living", "heating", {"climate": "climate.living", "temp": "sensor.living_temp"}, True,
|
||||
{"max_power_w": 4000.0, "comfort_c": 22.0, "setback_c": 22.0,
|
||||
# the installer's room (never the built-in R/C)
|
||||
@@ -141,8 +142,10 @@ def test_bundle_carries_the_gains(tmp_path):
|
||||
hp = Control("living", "heating", {"climate": "climate.living"}, True, {"cop": 3.0, "max_power_w": 2000.0})
|
||||
b = room_model(tmp_path, gain_w=100.0, solar_m2=2.0, power="electric")
|
||||
col = Collector()
|
||||
col.on_entities({"a": {"climate.living": {"s": "heat", "a": {"current_temperature": 20.0}}}})
|
||||
s = model_state(START, [hp], site_mapping(tmp_path, [], []).inputs, col, b, None, "UTC", None,
|
||||
col.on_entities({"a": {"climate.living": {"s": "heat", "a": {"current_temperature": 20.0}}, "sensor.out": {"s": "5", "a": {}}}})
|
||||
mi = site_mapping(tmp_path, [], []).inputs
|
||||
mi.outside_temp = "sensor.out" # an outdoor temperature: the room is planned (methods A1.4)
|
||||
s = model_state(START, [hp], mi, col, b, None, "UTC", None,
|
||||
location={"latitude": 52.5, "longitude": 13.4})
|
||||
p = s["devices"][0]["params"]
|
||||
assert (p["internal_gain_w"], p["solar_m2"]) == (300.0, 6.0) and s["sources"]["rooms"]["living"] == "model"
|
||||
|
||||
@@ -64,3 +64,22 @@ def test_no_export_price_values_the_end_at_zero():
|
||||
s["params"] = {"battery.end_value_pct": 100}
|
||||
m, _, _ = solve(s)
|
||||
assert m.end_value() == 0 and m.end_note.startswith("no export price")
|
||||
|
||||
|
||||
def test_the_wear_counts_on_every_kwh_discharged():
|
||||
"""The owner's battery algorithm (2026-11-12): the flat's own battery weighs its wear (battery.wear_ct from the
|
||||
bundle's params, a device's own wear_ct first) on every kWh it discharges, as the building's battery_core: a spread
|
||||
smaller than the wear after the round trip is not cycled."""
|
||||
s = house([battery(soc=20)])
|
||||
n = s["steps"]
|
||||
s["price_import"] = [20.0 if k % 96 < 24 else 24.0 for k in range(n)] # a 4 ct spread
|
||||
s["price_export"] = [0.0] * n
|
||||
s["params"] = {"battery.end_value_pct": 0}
|
||||
m0, _, _ = solve(s)
|
||||
s["params"] = {"battery.end_value_pct": 0, "battery.wear_ct": 10}
|
||||
m, soc, soc0 = solve(s)
|
||||
assert m.wear_used["battery"] == {"ct": 10.0, "src": "parameter"}
|
||||
assert optimizer.plan(s, 20)["battery_wear"]["battery"]["ct"] == 10.0
|
||||
out = lambda m_: sum(m_.h.getSolution().col_value[x.index] for x in m_.devices["battery"][1]["dis"]) # noqa: E731
|
||||
assert max(soc) <= soc0 + 50 # nothing bought to cycle at a loss
|
||||
assert out(m) <= out(m0) + 1e-6
|
||||
@@ -170,7 +170,7 @@ def test_the_sites_heat_source():
|
||||
assert "heat_outlook" not in p
|
||||
|
||||
|
||||
INPUTS = SimpleNamespace(load_power="", outside_temp="", weather="", sun="", presence=[])
|
||||
INPUTS = SimpleNamespace(load_power="", outside_temp="sensor.outside", weather="", sun="", presence=[]) # 5 °C (A1.4)
|
||||
|
||||
|
||||
def bundles(tmp_path):
|
||||
@@ -189,7 +189,8 @@ def bundles(tmp_path):
|
||||
def test_the_model_state_fetches_the_heat_forecasts(tmp_path):
|
||||
b = bundles(tmp_path)
|
||||
col = Collector()
|
||||
col.on_entities({"a": {"climate.heating": {"s": "heat", "a": {"current_temperature": 20.0, "temperature": 20.0}}}})
|
||||
col.on_entities({"a": {"climate.heating": {"s": "heat", "a": {"current_temperature": 20.0, "temperature": 20.0}},
|
||||
"sensor.outside": {"s": "5", "a": {}}}})
|
||||
# no R/C: the room is refused; its boiler's facts give the outlook of the space heat and the hot water
|
||||
c = parse_controls([{"id": "heating", "kind": "heating", "entities": {"climate": "climate.heating"},
|
||||
"params": {"heat_source": "boiler", "boiler_efficiency": 0.9, "max_heat_w": 9000}}], set())[0]
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The heating levers the plan's baseline does not count (heatlevers.py;
|
||||
docs/methods.md E14 "Heating levers"): each against its
|
||||
stated counterfactual, per carrier in kWh and EUR at the mean price, apart
|
||||
from the carriers' saving; not measured or not in use in words, never 0."""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
highspy = pytest.importorskip("highspy")
|
||||
from cantabile_edge import controls, heatlevers, optimizer # noqa: E402
|
||||
from test_heat_sources import house, room # noqa: E402
|
||||
from test_part_load import PARAMS as PART_LOAD # noqa: E402
|
||||
from test_storage import evening_draw, tank # noqa: E402
|
||||
|
||||
PROGRAM = {heatlevers.PROGRAM_FROM_KEY: 6, heatlevers.PROGRAM_TO_KEY: 22}
|
||||
LEARNT = {"occupancy": {"source": "learnt", "presence_now": 4, "fixed_hours": 0}}
|
||||
|
||||
|
||||
def local_hour(k):
|
||||
return (k // 4 + 1) % 24 # START is 01:00 Berlin (CET)
|
||||
|
||||
|
||||
def away_by_day(s):
|
||||
"""Someone home 6-8 and 17-22 only (learnt presence): away during the working day."""
|
||||
s["occupied"] = [1 if 6 <= local_hour(k) < 8 or 17 <= local_hour(k) < 22 else 0 for k in range(s["steps"])]
|
||||
s["sources"] = dict(LEARNT)
|
||||
return s
|
||||
|
||||
|
||||
def levers(s, limit=20):
|
||||
p = optimizer.plan(s, limit)
|
||||
return p, (p.get("saving_parts") or {}).get("heat_levers") or {}
|
||||
|
||||
|
||||
def carriers_add_up(lv):
|
||||
assert sum(c["eur"] for c in lv["carriers"].values()) == pytest.approx(lv["eur"], abs=1e-3)
|
||||
|
||||
|
||||
# ---- setback: presence against a thermostat's day program
|
||||
|
||||
def boiler_house(**kw):
|
||||
s = house([room("boiler", boiler_efficiency=0.9, max_heat_w=9000, **kw)], gas=12.0)
|
||||
s["params"] = {**s["params"], **PROGRAM}
|
||||
return s
|
||||
|
||||
|
||||
def test_setback_saves_gas_while_nobody_is_home_at_one_price():
|
||||
p, lv = levers(away_by_day(boiler_house()))
|
||||
sb = lv["setback"]
|
||||
assert "why" not in sb
|
||||
assert set(sb["carriers"]) == {"gas"}
|
||||
gas = sb["carriers"]["gas"]
|
||||
assert gas["kwh"] > 1.0 # 9 h a day at the setback instead of comfort
|
||||
assert gas["eur"] == pytest.approx(gas["kwh"] * 0.12, abs=1e-3) # at the gas price (one price)
|
||||
carriers_add_up(sb)
|
||||
# the carriers' own saving stays 0 at one price: the lever is apart, never inside it
|
||||
assert p["saving_parts"]["gas"]["why"] == "flat_price"
|
||||
assert p["baseline_eur"] - p["cost_eur"] == pytest.approx(0, abs=0.02)
|
||||
|
||||
|
||||
def test_setback_is_zero_where_presence_matches_the_program():
|
||||
s = boiler_house()
|
||||
s["sources"] = dict(LEARNT) # learnt, but home exactly 6-22: the program's hours
|
||||
_, lv = levers(s)
|
||||
assert lv["setback"]["eur"] == pytest.approx(0, abs=0.01)
|
||||
|
||||
|
||||
def test_setback_against_district_heat_and_a_heat_pump():
|
||||
s = away_by_day(house([room("district", max_heat_w=6000)], heat=11.0))
|
||||
s["params"] = {**s["params"], **PROGRAM}
|
||||
_, lv = levers(s)
|
||||
assert set(lv["setback"]["carriers"]) == {"heat"} and lv["setback"]["carriers"]["heat"]["kwh"] > 1.0
|
||||
s = away_by_day(house([room("heat_pump")], imp=30.0))
|
||||
s["params"] = {**s["params"], **PROGRAM}
|
||||
_, lv = levers(s)
|
||||
el = lv["setback"]["carriers"]["electricity"]
|
||||
assert el["kwh"] > 0.3 and el["eur"] == pytest.approx(el["kwh"] * 0.30, abs=1e-3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change,why", [
|
||||
(lambda s: s.update(sources={"occupancy": {"source": "fixed_hours", "presence_now": 0}}), "no_presence"),
|
||||
(lambda s: s["params"].pop(heatlevers.PROGRAM_TO_KEY), "no_parameter"),
|
||||
])
|
||||
def test_setback_not_in_use_says_why(change, why):
|
||||
s = away_by_day(boiler_house())
|
||||
change(s)
|
||||
_, lv = levers(s)
|
||||
assert lv["setback"]["why"] == why and lv["setback"]["note"]
|
||||
assert "eur" not in lv["setback"] # never a 0 for what is not measured
|
||||
|
||||
|
||||
def test_setback_with_the_owners_schedule_is_not_presence():
|
||||
s = away_by_day(boiler_house())
|
||||
m = optimizer.Model(optimizer._prepare(s))
|
||||
m.solve(20)
|
||||
val = m.h.getSolution().col_value
|
||||
x = lambda v: val[v.index] # noqa: E731
|
||||
for _, (kind, v) in m.devices.items():
|
||||
if kind == "heating":
|
||||
v["pref"] = True # the room follows the owner's schedule (preferences.apply)
|
||||
got = heatlevers.heat_levers(m.s, m, x)
|
||||
assert got["setback"]["why"] == "owner_schedule"
|
||||
|
||||
|
||||
# ---- part load: a boiler on its curve
|
||||
|
||||
def test_part_load_needs_a_curve():
|
||||
s = away_by_day(boiler_house())
|
||||
_, lv = levers(s)
|
||||
assert lv["part_load"]["why"] == "no_curve"
|
||||
|
||||
|
||||
def test_part_load_condensing_boiler_saves_by_modulating():
|
||||
s = away_by_day(boiler_house(boiler_type="condensing"))
|
||||
s["params"] = {**s["params"], **PART_LOAD}
|
||||
p, lv = levers(s, 30)
|
||||
pl = lv["part_load"]
|
||||
assert "why" not in pl and set(pl["carriers"]) == {"gas"}
|
||||
# the thermostat's recovery fires the burner at full output (its worst point on a condensing curve)
|
||||
assert pl["carriers"]["gas"]["kwh"] > 0
|
||||
# bounded by the curve: at most the full-load vs best-point difference (1.094) of the plan's gas
|
||||
gas_kwh = p["gas_eur"] / 0.12
|
||||
assert pl["carriers"]["gas"]["kwh"] < gas_kwh * (1 - 1 / 1.094) + 0.01
|
||||
|
||||
|
||||
def test_part_load_on_off_boiler_runs_at_full_load_either_way():
|
||||
s = away_by_day(boiler_house(boiler_type="condensing"))
|
||||
s["params"] = {**s["params"], **PART_LOAD}
|
||||
s["devices"][0]["channels"] = ["switch"]
|
||||
_, lv = levers(s, 30)
|
||||
assert lv["part_load"]["why"] == "on_off"
|
||||
|
||||
|
||||
# ---- COP timing: a heat pump by the hour's outside temperature
|
||||
|
||||
def warm_afternoon(s):
|
||||
s["t_out"] = [-4.0 + 10.0 * max(0.0, 1 - abs(local_hour(k) - 15) / 6) for k in range(s["steps"])]
|
||||
return s
|
||||
|
||||
|
||||
def test_cop_timing_heat_pump_heats_in_the_warm_hours():
|
||||
s = warm_afternoon(away_by_day(house([room("heat_pump", cop_curve=[[-7, 2.0], [2, 3.0], [7, 4.0]])], imp=30.0)))
|
||||
s["params"] = {**s["params"], **PROGRAM}
|
||||
_, lv = levers(s, 30)
|
||||
ct = lv["cop_timing"]
|
||||
assert "why" not in ct and set(ct["carriers"]) == {"electricity"}
|
||||
assert ct["carriers"]["electricity"]["kwh"] >= -0.01
|
||||
|
||||
|
||||
def test_cop_timing_with_one_cop_is_not_measured():
|
||||
s = away_by_day(house([room("heat_pump")], imp=30.0))
|
||||
_, lv = levers(s)
|
||||
assert lv["cop_timing"]["why"] == "one_cop"
|
||||
|
||||
|
||||
# ---- source: a hybrid against its own bivalence point
|
||||
|
||||
def hybrid_house(**kw):
|
||||
s = away_by_day(house([room("hybrid", boiler_efficiency=0.9, max_heat_w=9000, **kw)], imp=30.0, gas=12.0))
|
||||
s["params"] = {**s["params"], **PROGRAM}
|
||||
return s
|
||||
|
||||
|
||||
def test_source_hybrid_below_its_bivalence_point_would_burn_gas():
|
||||
# 0 °C outside, bivalence 2 °C: its own controller burns gas (13.3 ct of heat); the plan's heat pump 10 ct
|
||||
s = hybrid_house()
|
||||
s["params"][heatlevers.BIVALENT_KEY] = 2.0
|
||||
_, lv = levers(s)
|
||||
src = lv["source"]
|
||||
assert "why" not in src and "assumed" in src["note"]
|
||||
assert src["carriers"]["gas"]["kwh"] > 1.0 # gas not burnt
|
||||
assert src["carriers"]["electricity"]["kwh"] < 0 # electricity used instead
|
||||
assert src["eur"] > 0
|
||||
carriers_add_up(src)
|
||||
|
||||
|
||||
def test_source_the_devices_bivalence_point_wins():
|
||||
s = hybrid_house(bivalent_c=-5.0) # 0 °C is above it: the controller runs the heat pump too
|
||||
s["params"][heatlevers.BIVALENT_KEY] = 2.0
|
||||
_, lv = levers(s)
|
||||
assert "the device's" in lv["source"]["note"]
|
||||
assert abs(lv["source"]["carriers"].get("gas", {}).get("kwh", 0.0)) < 0.5
|
||||
|
||||
|
||||
def test_source_without_a_bivalence_point_is_not_measured():
|
||||
_, lv = levers(hybrid_house())
|
||||
assert lv["source"]["why"] == "no_bivalent"
|
||||
|
||||
|
||||
def test_bivalent_c_is_a_hybrids_and_checked():
|
||||
ok = {"heat_source": "hybrid", "source_options": {"heat_pump": "hp", "boiler": "gas"}, "bivalent_c": -3}
|
||||
controls._check_heat("h", ok, {"climate": "climate.x", "source": "select.s"})
|
||||
with pytest.raises(ValueError):
|
||||
controls._check_heat("h", {**ok, "bivalent_c": "cold"}, {"climate": "climate.x", "source": "select.s"})
|
||||
with pytest.raises(ValueError):
|
||||
controls._check_heat("h", {"heat_source": "boiler", "bivalent_c": 0}, {"climate": "climate.x"})
|
||||
|
||||
|
||||
# ---- store: the standing loss of a store's own setpoint
|
||||
|
||||
def store_house(**kw):
|
||||
s = house([tank(heater="boiler", temp=47.0, power=10000.0, channels=("water_heater",), **kw)])
|
||||
s["price_gas"] = [12.0] * s["steps"]
|
||||
s["devices"][0]["draw_w"] = evening_draw(s)
|
||||
return s
|
||||
|
||||
|
||||
def test_store_held_at_its_setpoint_loses_more():
|
||||
s = store_house()
|
||||
s["params"] = {**s["params"], heatlevers.SETPOINT_KEY: 60.0}
|
||||
p, lv = levers(s, 30)
|
||||
st = lv["store"]
|
||||
assert "why" not in st and set(st["carriers"]) == {"gas"}
|
||||
# UA 1.556 W/K × 15 K (60 against the least 45) for 24 h ≈ 0.56 kWh of heat, ÷ 0.9 ≈ 0.62 kWh of gas
|
||||
assert st["carriers"]["gas"]["kwh"] == pytest.approx(70.0 / 45.0 * 15.0 * 24 / 1000 / 0.9, rel=0.15)
|
||||
assert "assumed" in st["note"]
|
||||
|
||||
|
||||
def test_store_without_a_setpoint_is_not_measured_and_at_its_least_is_zero():
|
||||
_, lv = levers(store_house())
|
||||
assert lv["store"]["why"] == "no_setpoint"
|
||||
s = store_house(thermostat_c=45.0) # the device's own setpoint is the plan's least
|
||||
s["params"] = {**s["params"], heatlevers.SETPOINT_KEY: 60.0}
|
||||
_, lv = levers(s, 30)
|
||||
assert lv["store"]["eur"] == 0 and "the device's" in lv["store"]["note"]
|
||||
|
||||
|
||||
def test_a_stores_firing_and_hours_are_the_plans_saving_not_a_lever():
|
||||
"""A store's baseline is its own thermostat (A13): the plan's saving counts its boiler's firing and its heat
|
||||
pump's hours already, so part_load and cop_timing leave stores out (the achieved levers are
|
||||
inside with and without, never counted twice)."""
|
||||
s = store_house(part_load_curve=[[0.3, 1.094], [1.0, 1.0]])
|
||||
s["params"] = {**s["params"], heatlevers.SETPOINT_KEY: 60.0}
|
||||
p, lv = levers(s, 30)
|
||||
assert "part_load" not in lv and "store" in lv
|
||||
s = warm_afternoon(house([tank(heater="heat_pump", temp=47.0, channels=("water_heater",),
|
||||
cop_curve=[[-7, 2.0], [2, 3.0], [7, 4.0]])], imp=30.0))
|
||||
s["devices"][0]["draw_w"] = evening_draw(s)
|
||||
p, lv = levers(s, 30)
|
||||
assert "cop_timing" not in lv
|
||||
assert p["saving_parts"]["electricity"]["base_eur"] >= p["saving_parts"]["electricity"]["plan_eur"] - 1e-6
|
||||
|
||||
|
||||
def test_thermostat_c_is_checked():
|
||||
controls._check_tank("t", {"heater": "boiler", "thermostat_c": 60})
|
||||
with pytest.raises(ValueError):
|
||||
controls._check_tank("t", {"heater": "boiler", "thermostat_c": 5})
|
||||
|
||||
|
||||
# ---- the shape
|
||||
|
||||
def test_no_heating_no_levers_and_the_split_stays_small():
|
||||
from test_optimizer import battery, house as el_house
|
||||
p = optimizer.plan(el_house([battery()]), 20)
|
||||
assert "heat_levers" not in (p.get("saving_parts") or {})
|
||||
s = hybrid_house()
|
||||
s["params"][heatlevers.BIVALENT_KEY] = 2.0
|
||||
p, lv = levers(s)
|
||||
assert set(lv) == {"setback", "source"} # no part-load curve given: not a boiler room alone
|
||||
# fleet keeps saving_parts up to 8 KiB (plans.go savingPartsMax)
|
||||
assert len(json.dumps(p["saving_parts"])) < 8 << 10
|
||||
@@ -127,7 +127,8 @@ def test_room_matching(tmp_path):
|
||||
assert put(tmp_path, model()).room_rc("bedroom") is None
|
||||
|
||||
|
||||
INPUTS = SimpleNamespace(load_power="", outside_temp="", weather="", sun="", presence=[])
|
||||
# an outdoor sensor: the rooms are planned (methods A1.4; without any outdoor temperature they follow their schedule)
|
||||
INPUTS = SimpleNamespace(load_power="", outside_temp="sensor.outside", weather="", sun="", presence=[])
|
||||
|
||||
|
||||
def heating(cid, **params):
|
||||
@@ -136,9 +137,10 @@ def heating(cid, **params):
|
||||
|
||||
|
||||
def warm(*ids):
|
||||
"""A collector where each climate reports its room at 20 °C."""
|
||||
"""A collector where each climate reports its room at 20 °C, and it is 5 °C outside."""
|
||||
col = Collector()
|
||||
col.on_entities({"a": {f"climate.{i}": {"s": "heat", "a": {"current_temperature": 20.0}} for i in ids}})
|
||||
col.on_entities({"a": {**{f"climate.{i}": {"s": "heat", "a": {"current_temperature": 20.0}} for i in ids},
|
||||
"sensor.outside": {"s": "5", "a": {}}}})
|
||||
return col
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The plan's outdoor temperature (docs/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"), either moved by an outdoor sensor; else
|
||||
the sensor's or the entity's value now, held; else none. No number stands in
|
||||
(the 10 °C default is gone): the rooms then follow their schedule, a quiet
|
||||
note, never a refusal."""
|
||||
import inspect
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from cantabile_edge import inputs as inputs_mod
|
||||
from cantabile_edge import shades
|
||||
from cantabile_edge.bundles import Bundles
|
||||
from cantabile_edge.controls import Control
|
||||
from cantabile_edge.inputs import STEPS, Collector, model_state, outdoor_temperature
|
||||
|
||||
from test_control_parts import SITE
|
||||
|
||||
START = 1793232000 # 2026-10-29 00:00 UTC
|
||||
|
||||
|
||||
def inputs(outside="", weather=""):
|
||||
return SimpleNamespace(load_power="", outside_temp=outside, weather=weather, sun="", presence=[])
|
||||
|
||||
|
||||
def col(**ents):
|
||||
c = Collector()
|
||||
c.on_entities({"a": {k: {"s": str(v[0]), "a": v[1]} for k, v in ents.items()}})
|
||||
return c
|
||||
|
||||
|
||||
def ha_forecast(temp=4.0, hours=49):
|
||||
return [{"datetime": datetime.fromtimestamp(START + h * 3600, timezone.utc).isoformat(),
|
||||
"temperature": temp + h * 0.0, "cloud_coverage": 50} for h in range(hours)]
|
||||
|
||||
|
||||
def tariff(tmp_path, weather=None, site=SITE, expires=None):
|
||||
t = {"v": 1, "kind": "tariff", "id": "t1", "site": site, "issued": START, "start": START, "step_s": 900,
|
||||
"steps": STEPS, "expires": expires or START + STEPS * 900, "currency": "EUR", "unit": "ct/kWh",
|
||||
"import": [30.0] * STEPS, "export": [8.0] * STEPS, "estimated": [], "other": {}, "sources": []}
|
||||
if weather is not None:
|
||||
t["weather"] = weather
|
||||
(tmp_path / "tariff.json").write_text(json.dumps(t))
|
||||
return Bundles(str(tmp_path), SITE)
|
||||
|
||||
|
||||
def fleet_weather(temp=-2.0, hours=52, cloud=80.0):
|
||||
return {"source": "DWD MOSMIX (Bright Sky)", "station": "BERLIN-TEMPELHOF", "cell": [52.5, 13.4],
|
||||
"hours": [{"end": START + (h + 1) * 3600, "temp": temp + h, "cloud": cloud} for h in range(hours)]}
|
||||
|
||||
|
||||
# -- the bundle's weather ----------------------------------------------------------------
|
||||
def test_bundle_weather_in_ha_form(tmp_path):
|
||||
b = tariff(tmp_path, fleet_weather())
|
||||
fc = b.weather_forecast(START)
|
||||
assert len(fc) == 52 and fc[0] == {"datetime": "2026-10-29T00:00:00+00:00", "temperature": -2.0,
|
||||
"cloud_coverage": 80.0}
|
||||
# the hours already over are left out
|
||||
assert b.weather_forecast(START + 2 * 3600)[0]["temperature"] == 0.0
|
||||
|
||||
|
||||
def test_bundle_weather_none(tmp_path):
|
||||
assert tariff(tmp_path).weather_forecast(START) == [] # no weather in it
|
||||
assert tariff(tmp_path, fleet_weather(), site="cd" * 16).weather_forecast(START) == [] # another site's
|
||||
assert tariff(tmp_path, fleet_weather(), expires=START + 60).weather_forecast(START + 120) == [] # expired
|
||||
assert Bundles(str(tmp_path / "none"), SITE).weather_forecast(START) == []
|
||||
# implausible values are not taken
|
||||
bad = {"hours": [{"end": START + 3600, "temp": 99.0, "cloud": 140.0}, {"end": "x", "temp": 1.0}]}
|
||||
assert tariff(tmp_path, bad).weather_forecast(START) == []
|
||||
|
||||
|
||||
# -- the sources -------------------------------------------------------------------------
|
||||
def test_ha_entity_first():
|
||||
fleet = [{"datetime": "2026-10-29T00:00:00+00:00", "temperature": -9.0}]
|
||||
t, src = outdoor_temperature(START, col(), inputs(weather="weather.home"), ha_forecast(4.0), fleet)
|
||||
assert src == "ha_entity" and t == [4.0] * STEPS
|
||||
|
||||
|
||||
def test_fleet_forecast_without_an_entity(tmp_path):
|
||||
fc = tariff(tmp_path, fleet_weather()).weather_forecast(START)
|
||||
t, src = outdoor_temperature(START, col(), inputs(), None, fc)
|
||||
assert src == "fleet_forecast" and t[0] == -2.0 and t[4] == -1.0 and len(t) == STEPS
|
||||
|
||||
|
||||
def test_sensor_bias_on_either_forecast(tmp_path):
|
||||
c = col(**{"sensor.out": (1.0, {})})
|
||||
fc = tariff(tmp_path, fleet_weather()).weather_forecast(START)
|
||||
t, src = outdoor_temperature(START, c, inputs(outside="sensor.out"), None, fc)
|
||||
assert src == "fleet_forecast+sensor_bias" and t[0] == 1.0 # -2 moved by +3 now
|
||||
assert t[24] == fc[6]["temperature"] # faded out after 6 h
|
||||
t, src = outdoor_temperature(START, c, inputs(outside="sensor.out", weather="weather.home"), ha_forecast(4.0), fc)
|
||||
assert src == "ha_entity+sensor_bias" and t[0] == 1.0 and t[30] == 4.0
|
||||
|
||||
|
||||
def test_now_held_without_a_forecast():
|
||||
c = col(**{"sensor.out": (7.5, {}), "weather.home": ("cloudy", {"temperature": 3.0})})
|
||||
assert outdoor_temperature(START, c, inputs(outside="sensor.out"), None, []) == ([7.5] * STEPS, "sensor_now")
|
||||
assert outdoor_temperature(START, c, inputs(weather="weather.home"), [], []) == ([3.0] * STEPS, "ha_entity_now")
|
||||
|
||||
|
||||
def test_none_without_any_weather():
|
||||
assert outdoor_temperature(START, col(), inputs(), None, []) == (None, "none")
|
||||
|
||||
|
||||
def test_no_ten_degrees_anywhere():
|
||||
# the old stand-in (10 °C at every step) is gone from the plan's inputs and the shades' rules
|
||||
assert "10.0] * STEPS" not in inspect.getsource(inputs_mod)
|
||||
assert "[10.0] * T" not in inspect.getsource(shades)
|
||||
|
||||
|
||||
# -- the plan ----------------------------------------------------------------------------
|
||||
def room(cid="living"):
|
||||
return Control(cid, "heating", {"climate": f"climate.{cid}"}, True,
|
||||
{"max_power_w": 2000.0, "r_k_per_kw": 10.0, "c_kwh_per_k": 3.0})
|
||||
|
||||
|
||||
def warm(cid="living", **more):
|
||||
return col(**{f"climate.{cid}": ("heat", {"current_temperature": 20.0, "temperature": 20.0}), **more})
|
||||
|
||||
|
||||
def test_plan_without_outdoor_temperature(tmp_path):
|
||||
s = model_state(START, [room()], inputs(), warm(), tariff(tmp_path), None, "UTC", None)
|
||||
assert s["t_out"] is None and s["sources"]["outdoor"] == "none" and "t_out" not in s["sources"]
|
||||
# the room follows its schedule: not planned, and not refused (nothing to enter: a quiet note)
|
||||
assert s["devices"] == [] and [d["id"] for d in s["fallback"]] == ["living"] and s["refused"] == {}
|
||||
assert any("no outdoor temperature" in n for n in s["notes"])
|
||||
|
||||
|
||||
def test_plan_on_the_fleet_forecast(tmp_path):
|
||||
s = model_state(START, [room()], inputs(), warm(), tariff(tmp_path, fleet_weather()), None, "UTC", None)
|
||||
assert s["sources"]["outdoor"] == "fleet_forecast" and s["t_out"][0] == -2.0
|
||||
assert [d["id"] for d in s["devices"]] == ["living"] and s["fallback"] == []
|
||||
assert s["sources"]["sky"] == "fleet forecast" and abs(s["sky"][0] - 0.2) < 1e-9
|
||||
assert not any("no outdoor temperature" in n for n in s["notes"])
|
||||
|
||||
|
||||
def test_plan_entity_over_fleet(tmp_path):
|
||||
c = warm(**{"sensor.out": (0.0, {})})
|
||||
s = model_state(START, [room()], inputs(outside="sensor.out", weather="weather.home"), c,
|
||||
tariff(tmp_path, fleet_weather()), None, "UTC", ha_forecast(4.0))
|
||||
assert s["sources"]["outdoor"] == "ha_entity+sensor_bias" and s["t_out"][0] == 0.0
|
||||
assert s["sources"]["sky"] == "weather forecast"
|
||||
|
||||
|
||||
def test_shades_without_outdoor_temperature():
|
||||
# the shades' rules take no temperature as "cold" (winter gains, closed at night), as before
|
||||
cover = {"id": "c", "kind": "cover", "params": {}, "state": {"position_pct": 100}, "bounds": {}}
|
||||
s = {"start": START, "step_s": 900, "steps": 8, "tz": "UTC", "t_out": None, "occupied": [1] * 8,
|
||||
"price_import": [None] * 8, "location": {"latitude": 52.5, "longitude": 13.4}}
|
||||
out = shades.schedule(cover, s, {})
|
||||
assert len(out["set"]) == 8
|
||||
@@ -71,6 +71,9 @@ def flat(tmp_path, src, drop=()):
|
||||
"steps": 192, "expires": START + 192 * 900, "currency": "EUR", "unit": "ct/kWh",
|
||||
"import": [32.0] * 192, "export": [8.0] * 192, "gas": [12.7] * 192, "heat": [None] * 192,
|
||||
"estimated": [], "other": {}, "sources": [], "params": {"heat.hybrid_switch_eur": 0.05}}
|
||||
# the site's weather as fleet sends it (no weather entity in the mapping: methods A1.4)
|
||||
bundle["weather"] = {"source": "DWD", "cell": [52.4, 9.7], "hours": [{"end": START + (h + 1) * 3600, "temp": 3.0, "cloud": 50}
|
||||
for h in range(52)]}
|
||||
(tmp_path / "tariff.json").write_text(json.dumps(bundle))
|
||||
cfg = Config(site_id=SITE, mapping=str(tmp_path / "mapping.yaml"), state_dir=str(tmp_path), dashboards=False,
|
||||
train=False)
|
||||
@@ -93,6 +96,7 @@ def test_model_state_past_the_tariffs_end(tmp_path, src):
|
||||
assert s["price_import"][0] == 32.0 and s["price_import"][-1] is None # the horizon's tail unpriced
|
||||
assert s["price_heat"] == [None] * 192 and s["price_gas"][0] == 12.7
|
||||
assert s["refused"] == {} # the heating is planned
|
||||
assert s["sources"]["outdoor"] == "fleet_forecast" and s["t_out"][0] == 3.0 # the bundle's weather
|
||||
shade = next(d for d in s["devices"] if d["id"] == "shades_living")
|
||||
assert len(shade["schedule"]["set"]) == s["steps"]
|
||||
|
||||
|
||||
@@ -15,9 +15,14 @@ def saved(part):
|
||||
return part["base_eur"] - part["plan_eur"]
|
||||
|
||||
|
||||
def carriers(p):
|
||||
"""The split by carrier, without the heating levers (apart: heatlevers.py, test_heatlevers.py)."""
|
||||
return {k: v for k, v in (p.get("saving_parts") or {}).items() if k != "heat_levers"}
|
||||
|
||||
|
||||
def test_parts_add_up_to_the_plan_and_its_baseline():
|
||||
p = optimizer.plan(house([battery(), heating()]), 20)
|
||||
sp = p["saving_parts"]
|
||||
sp = carriers(p)
|
||||
assert set(sp) == {"electricity"}
|
||||
assert sum(x["plan_eur"] for x in sp.values()) == pytest.approx(p["cost_eur"], abs=0.02)
|
||||
assert sum(x["base_eur"] for x in sp.values()) == pytest.approx(p["baseline_eur"], abs=0.02)
|
||||
@@ -35,7 +40,7 @@ def test_battery_alone_has_no_heating_share():
|
||||
|
||||
def test_gas_is_the_heatings_and_a_flat_gas_price_saves_nothing_in_time():
|
||||
p = optimizer.plan(heat_house([room("boiler", boiler_efficiency=0.9, max_heat_w=9000)], gas=12.0), 20)
|
||||
sp = p["saving_parts"]
|
||||
sp = carriers(p)
|
||||
assert sp["gas"]["plan_eur"] == pytest.approx(p["gas_eur"], abs=0.02)
|
||||
assert saved(sp["gas"]) == pytest.approx(0, abs=0.001) # the same price every quarter-hour
|
||||
assert sum(x["base_eur"] for x in sp.values()) == pytest.approx(p["baseline_eur"], abs=0.02)
|
||||
@@ -57,7 +62,7 @@ from test_storage import evening_draw, tank # noqa: E402
|
||||
def assert_adds_up(p):
|
||||
"""The parts' saving is the plan's own (baseline − cost; the heat outlook is in both, a fixed term),
|
||||
and the parts' plan and base are cost_eur and baseline_eur without it."""
|
||||
sp = p["saving_parts"]
|
||||
sp = carriers(p)
|
||||
outlook = (p.get("heat_outlook") or {}).get("eur", 0.0)
|
||||
assert sum(saved(x) for x in sp.values()) == pytest.approx(p["baseline_eur"] - p["cost_eur"], abs=0.02)
|
||||
assert sum(x["plan_eur"] for x in sp.values()) == pytest.approx(p["cost_eur"] - outlook, abs=0.02)
|
||||
@@ -107,7 +112,7 @@ def test_a_gas_or_heat_site_adds_up(src, extra, prices):
|
||||
if extra.get("fuel") == "oil":
|
||||
s["price_oil"] = [11.0] * s["steps"]
|
||||
p = optimizer.plan(s, 20)
|
||||
assert set(p["saving_parts"]) - {"electricity"}
|
||||
assert set(carriers(p)) - {"electricity"}
|
||||
assert_adds_up(p)
|
||||
|
||||
|
||||
|
||||
@@ -23,7 +23,8 @@ from test_model_series import model, put
|
||||
|
||||
START = 1793232000 # 2026-10-29 00:00 UTC, a Thursday (01:00 in Berlin)
|
||||
TZ = "Europe/Berlin"
|
||||
INPUTS = SimpleNamespace(load_power="", outside_temp="", weather="", sun="", presence=[])
|
||||
# an outdoor sensor: a room with its facts is planned (methods A1.4)
|
||||
INPUTS = SimpleNamespace(load_power="", outside_temp="sensor.outside", weather="", sun="", presence=[])
|
||||
|
||||
|
||||
class Clock:
|
||||
@@ -43,8 +44,8 @@ def room(cid="living", kind="heating", ents=None, limits=None, **params):
|
||||
|
||||
def col(temps: dict | None = None):
|
||||
c = Collector()
|
||||
c.on_entities({"a": {f"climate.{k}": {"s": "heat", "a": {"current_temperature": v, "temperature": 20.0}}
|
||||
for k, v in (temps or {}).items()}})
|
||||
c.on_entities({"a": {**{f"climate.{k}": {"s": "heat", "a": {"current_temperature": v, "temperature": 20.0}}
|
||||
for k, v in (temps or {}).items()}, "sensor.outside": {"s": "5", "a": {}}}})
|
||||
return c
|
||||
|
||||
|
||||
|
||||
@@ -407,7 +407,7 @@ def test_model_state_gives_each_shade_its_schedule(site):
|
||||
d = next(x for x in s["devices"] if x["id"] == "curtain")
|
||||
assert any(v == 30 for v in d["schedule"]["set"]) and s["sky"][0] == 1.0
|
||||
# a thermometer outside: the forecast moved to what it measures now
|
||||
assert s["t_out"][0] == 31.0 and s["t_out"][30] == 25.0 and "outdoor sensor" in s["sources"]["t_out"]
|
||||
assert s["t_out"][0] == 31.0 and s["t_out"][30] == 25.0 and s["sources"]["outdoor"] == "ha_entity+sensor_bias"
|
||||
|
||||
|
||||
def test_optimizer_takes_the_schedule():
|
||||
|
||||
Reference in new issue
Block a user