cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1541: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-09 06:36:15 +02:00
1 parent 05802d6f87
commit 94f46db8f8
19 files changed
+863 -60

No files matched your search

+49 -4
View File
@@ -24,6 +24,18 @@ like every command) with string args:
the battery's SoC bounds, which win (optimizer.py
Model.battery_plan). Kept with its schedule.
The binding (2026-11-09): a box that took a battery_plan stays bound to
that building after the plan ends ("battery_bound" in building.json: the
building, the level, since, the last plan's until). A bound battery's step
that no plan covers (the plan lapsed: the coordinator sent no renewal; or
beyond its 24 h within the box's 48 h) is self-consumption only: charged
from the house's PV surplus, discharged for the house's own use, never
charged from the grid or discharged into it for the box's own tariff
(optimizer.py Model.battery_plan, docs/methods.md A9.4). The battery
serves the building's flats, which the box's own plan cannot see. Ended
only when the box leaves that building (membership.json without it) or
the owner lifts a flexible battery plan by hand.
Rules: always within the flat's own floors (a cap below the comfort floor
of the owner or the tenant is refused: "floor"); a newer command for the
same control replaces the older; each is dropped at `until`. The level sits
@@ -60,6 +72,7 @@ PENALTY = { # EUR per unit across a building's request in the plan
# link checked (edge/link/gridorder.go): nobody overrides it; never a battery_plan
"emergency": {"load_limit": 500.0, "shift_request": 50.0, "thermostat_cap": 500.0},
}
BOUND_KEY = "battery_bound" # building.json: the binding of the battery to a building (kept after its plan ends)
SCHEDULE_STEP_S = 900 # a battery_plan's step: the plans' 15 minutes
SCHEDULE_MAX_W = 1e6 # |W| per step at most: a sanity bound on the numbers, not a battery's rating
@@ -69,9 +82,14 @@ class Building:
self.path, self.clock = os.path.join(state_dir, "building.json"), clock
self.membership_path = os.path.join(state_dir, "membership.json")
self.active: dict[str, dict] = {} # control -> the command's args (parsed)
# the building the battery is bound to (a battery_plan taken; kept after it ends: the module's doc)
self.bound: dict | None = None
try:
with open(self.path) as f:
self.active = {k: v for k, v in json.load(f).items() if k in CONTROLS}
raw = json.load(f)
self.active = {k: v for k, v in raw.items() if k in CONTROLS}
b = raw.get(BOUND_KEY)
self.bound = b if isinstance(b, dict) and b.get("building") else None
except (OSError, ValueError, AttributeError):
pass
self.drop_ended()
@@ -89,9 +107,21 @@ class Building:
def _save(self):
tmp = self.path + ".tmp"
with open(tmp, "w") as f:
json.dump(self.active, f)
json.dump({**self.active, **({BOUND_KEY: self.bound} if self.bound else {})}, f)
os.replace(tmp, self.path)
def battery_bound(self) -> dict | None:
"""The building the battery is bound to, or None (never bound, or the
box left that building: membership.json without it ends the binding)."""
if not self.bound:
return None
members = self.memberships()
if members is not None and str(self.bound["building"]) not in members:
self.bound = None
self._save()
return None
return self.bound
def drop_ended(self) -> list[dict]:
now = self.clock()
ended = [c for c in self.active.values() if now >= c["until"]]
@@ -165,22 +195,37 @@ class Building:
return False, f"floor: {cid}'s limit is {hi:g} °C, the cap {c['value']:g} °C"
old = self.active.get(c["control"])
self.active[c["control"]] = c
if c["control"] == "battery_plan":
b = self.bound if self.bound and self.bound.get("building") == c["building"] else {}
self.bound = {"building": c["building"], "level": c["level"], "since": b.get("since", int(self.clock())),
"until": c["until"], "id": c["id"]}
self._save()
replaced = f" (replaces {old['id']})" if old and old["id"] != c["id"] else ""
return True, f"{c['control']} {c['value']:g} {c['level']} until {time.strftime('%H:%M UTC', time.gmtime(c['until']))}{replaced}"
def lift(self, control: str):
"""The owner overrode a flexible request: it ends."""
"""The owner overrode a flexible request: it ends (a battery plan's
binding with it: the owner took the battery back)."""
if self.active.pop(control, None) is not None:
if control == "battery_plan":
self.bound = None
self._save()
def for_model(self, start: int, step_s: int, steps: int) -> dict:
"""The requests as the optimiser takes them: per step, or a window.
A battery_plan per model step (the slot at the step's middle; the
model may start after `from`: past slots skipped), None where the
command doesn't cover the step; from_step/to_step its covered span."""
command doesn't cover the step; from_step/to_step its covered span.
A bound battery (battery_bound) adds "battery_bound": {building,
level, until (the last plan's end), lapsed (no plan in force: it ended)}:
the steps no plan covers are self-consumption only."""
self.drop_ended()
out = {}
bound = self.battery_bound()
if bound:
out["battery_bound"] = {"building": bound["building"], "level": bound.get("level", "binding"),
"until": int(bound.get("until") or 0),
"lapsed": "battery_plan" not in self.active}
for ctl, c in self.active.items():
if ctl == "battery_plan":
ws, k_s = c.get("schedule") or [], int(c.get("step_s") or SCHEDULE_STEP_S)
+8
View File
@@ -342,6 +342,14 @@ class Controller:
log.info("weather forecast: %s", e)
state = self.model_state()
cands, net_load = state.pop("_cands", None) or {}, state.pop("_net_load", None)
# a battery bound to a building whose plan lapsed (building.py, A9.4): self-consumption only; said once
bound = (state.get("building") or {}).get("battery_bound") or {}
lapsed = bool(bound.get("lapsed"))
if lapsed and not getattr(self, "_bind_lapsed", False):
log.warning("building %s: its battery plan ended %s UTC and was not renewed: the battery runs in "
"self-consumption only (no grid charging) until the next one", bound.get("building"),
time.strftime("%d %b %H:%M", time.gmtime(bound.get("until") or 0)))
self._bind_lapsed = lapsed
plan = await solve(state, self.cfg.solve_timeout_s)
if "error" in plan:
self.plan_error = plan["error"]
+10 -3
View File
@@ -189,7 +189,10 @@ PARAMS = {
"heat_source": "electric", "source_options": {}, "cop_curve": [], "boiler_type": "",
"part_load_curve": [],
# a boiler's fuel (E15, branch heating-oil): gas | oil (heating oil EL); gas: every boiler before
"fuel": "gas"},
"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},
"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},
@@ -627,6 +630,10 @@ def _check_heat(cid: str, p: dict, ents: dict):
raise ValueError(f"control {cid}: a hybrid needs its source select and source_options for heat_pump and boiler")
if p.get("fuel", "gas") not in FUELS:
raise ValueError(f"control {cid}: fuel is one of {', '.join(FUELS)} (a boiler's)")
if p.get("combi") not in (None, True, False):
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)")
_check_part_load(cid, p)
@@ -878,10 +885,10 @@ def parse_inputs(raw: dict | None) -> Inputs:
if raw.get("heat") is not None:
h = raw["heat"]
if not isinstance(h, dict) or set(h) - {"source", "boiler_efficiency", "max_heat_w", "boiler_type",
"part_load_curve", "fuel"} or h.get("source") not in ("boiler", "district") \
"part_load_curve", "fuel", "combi"} or h.get("source") not in ("boiler", "district") \
or h.get("fuel", "gas") not in FUELS:
raise ValueError("inputs.heat: {source: boiler | district, boiler_efficiency, max_heat_w, boiler_type, "
"part_load_curve, fuel: gas | oil}")
"part_load_curve, fuel: gas | oil, combi}")
for k in ("boiler_efficiency", "max_heat_w"):
if k in h and (_num(h[k]) is None or float(h[k]) <= 0 or k == "boiler_efficiency" and float(h[k]) > 1):
raise ValueError(f"inputs.heat.{k}: a number above 0" + (" and at most 1" if k == "boiler_efficiency" else ""))
+4 -2
View File
@@ -237,9 +237,11 @@ class Executor:
continue # the thermostat's other control acts (switchover.py)
want, level, why = self.wanted(c, now)
acts = actions_for(c, want, self.col, level, why)
if why.startswith("building") and not any(a.channel == "climate" for a in acts):
if why.startswith("building") and "climate" in c.entities and not any(a.channel == "climate" for a in acts):
# the room is within the building's cap already: a change by
# hand still counts as an override of the cap
# hand still counts as an override of the cap (a room only: a
# battery following the building's battery plan has no climate,
# 2026-11-08 Sim Durlach: KeyError every round, no action at all)
self.guard.expect(c.id, c.entities["climate"], want["set"])
for a in acts:
done = await self._do(client, a, now)
+1 -1
View File
@@ -794,7 +794,7 @@ def heat_site(controls, devices: list, inputs, price_gas: list, price_heat: list
c = fuel[0]
facts, _, _ = c.heat_facts()
return {"from": c.id, "source": str(c.p("heat_source")), **facts, "space": not planned,
**{k: c.p(k) for k in ("boiler_type", "part_load_curve", "fuel") if c.p(k)}}
**{k: c.p(k) for k in ("boiler_type", "part_load_curve", "fuel", "combi") if c.p(k)}}
if heating:
hybrid = [c for c in heating if c.p("heat_source") == "hybrid" and c.id not in planned]
if hybrid and not planned:
+3
View File
@@ -206,6 +206,9 @@ def build(mapping, registries: dict, specs: dict, policy: dict, now: float, ev_p
v = (c.params or {}).get(k)
if v and k not in facts:
facts[k] = [list(x) for x in v] if k == "part_load_curve" else str(v)
# a combi boiler: the trainer's gas forecast adds its hot water (B14.4)
if (c.params or {}).get("combi") is True and (c.params or {}).get("heat_source") == "boiler":
facts["combi"] = True
if facts:
d["facts"] = facts
inv = {"v": 1, "made": int(now), "devices": out, "protection": prot}
+1
View File
@@ -195,6 +195,7 @@ NAMES = {
"carrier_electricity": {"en": "Electricity", "de": "Strom"},
"carrier_gas": {"en": "Gas", "de": "Gas"},
"carrier_heat": {"en": "Heat", "de": "Wärme"},
"carrier_oil": {"en": "Heating oil", "de": "Heizöl"},
"cs_prices": {"en": "Prices", "de": "Preise"},
"cs_costs": {"en": "Monthly cost", "de": "Monatskosten"},
"cs_savings": {"en": "Savings", "de": "Ersparnis"},
+203 -41
View File
@@ -115,7 +115,11 @@ following it) is a tracking target per step: the batteries' grid-side power
(their sum) at the building's W, each kWh off it at the request's penalty
(above any price, below the owner's floors and the SoC bounds, which win:
battery_plan). The battery's plan entries then say "building <id>: ..." and
stay setpoints (not the inverter's own self-consumption mode).
stay setpoints (not the inverter's own self-consumption mode). A battery
bound to a building (building.py battery_bound) charges beyond the
building's W only from the PV surplus, and where no plan covers a step
(lapsed, or beyond its 24 h) it is in self-consumption only: no grid
charging, no discharge into the grid, the inverter's own mode.
The owner's preferences (preferences.py, a device's "pref"): a room's
target per step from its schedule (in place of the occupied hours) at the
@@ -452,19 +456,44 @@ class Model:
the target, each W off it costing penalty x dt / 1000 (EUR per kWh
of deviation). A site with several batteries: their sum tracks it.
The SoC bounds and the owner's reserve (PENALTY_LIMIT, per % and
step) cost far more, so they win; no battery planned: nothing."""
bp = (self.s.get("building") or {}).get("battery_plan")
step) cost far more, so they win; no battery planned: nothing.
A battery bound to a building (state["building"]["battery_bound"],
A9.4): it charges more than the building's plan only from the
house's PV surplus (a reserve below its floor is refilled from PV,
from the grid only as far as the plan itself charges); a step no
plan covers (lapsed, or beyond its window) is self-consumption only:
charged from the PV surplus, discharged for the house's own use,
never from or into the grid for the box's own tariff."""
bld = self.s.get("building") or {}
bp, bound = bld.get("battery_plan"), bld.get("battery_bound")
bats = [v for kind, v in self.devices.values() if kind == "battery" and v]
if not bp or not bats:
if not bats or not (bp or bound):
return
ws = bp["schedule_w"]
for t in range(max(0, bp["from_step"]), min(self.T, bp["to_step"], len(ws))):
if ws[t] is None:
ws = bp["schedule_w"] if bp else []
a, b = (max(0, bp["from_step"]), min(self.T, bp["to_step"], len(ws))) if bp else (0, 0)
load, pv = self.s["load_w"], self.s["pv_w"]
for t in range(self.T):
w = ws[t] if a <= t < b else None
if w is None and not bound:
continue
pos = self.var(cost=bp["penalty"] * self.dt / 1000.0)
neg = self.var(cost=bp["penalty"] * self.dt / 1000.0)
net = sum((v["ch"][t] - v["dis"][t] for v in bats), start=Lin())
self.h.addConstr(net - pos + neg == float(ws[t]))
surplus, deficit = max(0.0, pv[t] - load[t]), max(0.0, load[t] - pv[t])
if w is not None:
pos = self.var(cost=bp["penalty"] * self.dt / 1000.0)
neg = self.var(cost=bp["penalty"] * self.dt / 1000.0)
self.h.addConstr(net - pos + neg == float(w))
if bound:
# above the building's W only from the PV surplus: never the box's own grid charging
self.h.addConstr(net <= max(float(w), 0.0) + surplus)
else:
# self-consumption only (no building plan covers the step)
self.h.addConstr(net <= surplus)
self.h.addConstr(net >= -deficit)
if bound and bound.get("lapsed"):
self.notes.append(f"the battery plan of building {bound['building']} ended "
f"{time.strftime('%d %b %H:%M UTC', time.gmtime(bound.get('until') or 0))} and was not renewed: "
"the battery runs in self-consumption only (no grid charging) until the next one")
def grid_order(self):
"""The grid operator's limit on the controllable consumers' draw."""
@@ -610,7 +639,7 @@ class Model:
switch_eur = float((self.s.get("params") or {})["heat.hybrid_switch_eur"]) if src == "hybrid" else 0.0
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, prev_u = [], [], [], None
els, gss, dhs, hxs, bxs, prev_u = [], [], [], [], [], None
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)
@@ -619,6 +648,12 @@ class Model:
ghi = self.s.get("ghi_w_m2") or [0.0] * self.T
pref = d.get("pref") # the owner's schedule and overrides (preferences.py)
cap = (self.s.get("building") or {}).get("thermostat_cap")
# a combi boiler (Kombitherme, 392; methods.md E6.6): one burner makes the rooms' heat
# and the hot water. Without a store of its own it heats the water as it is drawn, first: the rooms
# get what is left of its most heat in each step (the hot-water forecast; without one the rooms keep
# all of it, noted). With a store (a dhw_tank whose heater is this boiler: shares_with) the store is
# its own device: its draws come from the store, and the burner's heat is shared (dhw_tank)
combi = combi_dhw(self, d["id"], p, src) if not cooling else None
for t in range(self.T):
terms = [] # (W of heat per W of input, the input)
pw = pg = ph = None
@@ -634,6 +669,8 @@ class Model:
if src in ("boiler", "hybrid"):
pg, bterms = sup.variables(t)
terms += bterms
# the burner's heat alone (a hybrid's heat pump apart): what a store it heats shares (dhw_tank)
bxs.append(sum((k * v for k, v in bterms), start=Lin()))
if src == "district":
ph, hterms = sup.variables(t)
terms += hterms
@@ -650,6 +687,9 @@ class Model:
gss.append(pg)
dhs.append(ph)
heat = sum((k * v for k, v in terms), start=Lin())
hxs.append(heat)
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
tt = self.var(-50.0, 80.0)
sign = -1.0 if cooling else 1.0
@@ -710,7 +750,7 @@ class Model:
self.devices[d["id"]] = ("cooling" if cooling else "heating",
{"temp": temps, "power": els, "gas": gss, "district": dhs, "src": src,
"fuel": boiler_fuel(p) if src in ("boiler", "hybrid") else None,
"cops": cops, "eff": eff,
"cops": cops, "eff": eff, "heat": hxs, "qmax": qmax, "burner": bxs,
"pmax": {"electric": pmax, "heat_pump": pmax, "hybrid": pmax, "boiler": gmax,
"district": qmax}[src], "switched": switched,
# the shift envelope (electric sources only): Wh of electricity per K at the mean COP
@@ -825,7 +865,17 @@ class Model:
if heater == "heat_pump":
cops = [cop_at(p, self.s["t_out"][t]) if p.get("cop_curve") else float(p["cop"]) for t in range(self.T)]
sup = HeatSupply(self, d["id"], p, heater) if heater in ("boiler", "district") else None
shared = None
shared = burner = None
if heater == "boiler" and p.get("shares_with"):
# its boiler is the rooms' boiler (a combi, a system boiler or a hybrid's gas boiler with a
# store): one burner, the store's heat and the rooms' heat from that burner together
# at most its heat output (a hybrid's heat pump is not the burner: its heat is not counted)
kind, rv = self.devices.get(p["shares_with"], (None, None))
if kind == "heating" and rv and rv.get("src") in ("boiler", "hybrid") and rv.get("qmax") and rv.get("burner"):
burner = (rv["burner"], rv["qmax"])
else:
self.note(f"{d['id']}: its boiler's room control {p['shares_with']} is not planned or has no boiler: "
"the tank's boiler planned alone")
if heater == "heat_pump" and p.get("shares_with"):
kind, rv = self.devices.get(p["shares_with"], (None, None))
if kind == "heating" and rv and rv.get("power"):
@@ -864,6 +914,8 @@ class Model:
else:
ph, terms = sup.variables(t)
q = sum((k * v for k, v in terms), start=Lin())
if burner is not None and t < len(burner[0]):
self.h.addConstr(q + burner[0][t] <= burner[1])
# never below the cold water's (or a colder room's) temperature
e_lb = min(0.0, e0, cw * (room - t_cw))
e = self.var(e_lb, highspy.kHighsInf)
@@ -893,6 +945,7 @@ class Model:
"cw": cw, "t_cw": t_cw, "room": room, "ua": ua, "phi": phi, "p0": p0, "e0": e0, "emin": emin, "emax": emax,
"lo_c": lo_c, "hi_c": hi_c, "heater": heater, "pmax": pmax, "cops": cops, "switched": switched,
"eff": sup.curve["full"] if heater == "boiler" else None, "e_leg": e_leg, "window": window,
"qmax": sup.qmax if sup else None,
"src": "electric" if heater in ("element", "heat_pump") else heater})
def cover(self, d, room_ids):
@@ -975,6 +1028,35 @@ class Model:
# what one W of heat from a source takes as input and costs (price, CO2,
# part load). Today the demand is met when it is demanded:
# HeatSupply.delivered is the one place that says so.
def is_combi(p: dict) -> bool:
"""A combi boiler (Kombitherme, 392): the heating control's
param combi (the mapping's, from the device or its owner): one burner
for the rooms and the hot water. A store is a device of its own (a
dhw_tank whose heater is this boiler, shares_with): combi_dhw."""
return p.get("combi") is True or str(p.get("combi") or "").lower() in ("true", "yes", "1")
def combi_dhw(m: "Model", cid: str, p: dict, src: str) -> list[float] | None:
"""A combi boiler's hot water per step (W of heat, the site's hot-water
forecast dhw_w), which it makes first (methods.md E6.6): the rooms'
heat is capped at its most heat less it. None for any other source, for
a combi that heats a store of its own (a dhw_tank with heater boiler and
shares_with this control: the store takes the draws, the burner is shared
there), or without a forecast (noted: the rooms keep its
whole output)."""
if src != "boiler" or not is_combi(p):
return None
for t in m.s.get("devices") or []:
tp = t.get("params") or {}
if t.get("kind") == "dhw_tank" and str(tp.get("heater") or "") == "boiler" and tp.get("shares_with") == cid:
return None
q = heat_demand(m.s, "dhw", m.T)
if q is None:
m.note(f"{cid}: a combi boiler without a hot-water forecast: its rooms keep its whole output (no hot-water meter)")
return None
return [max(0.0, float(v)) for v in q]
HEAT_DEMANDS = {"space": "heat_w", "dhw": "dhw_w"} # the model bundle's series (B13, B16)
@@ -1447,6 +1529,24 @@ def term_at(c: dict, t: int) -> dict | None:
return per[t] if 0 <= t < len(per) else None
def contract_energy(m, x, c, vars_, paid_):
"""A market contract's steps in the plan with energy used or paid:
(step, kWh used, kWh paid, the step's price ct). A take-or-pay
contract's paid energy is at least its minimum, used or not."""
for t, v in sorted(vars_.items()):
e = max(x(v), 0.0) * m.dt / 1000.0
pay = max(x(paid_[t]) * m.dt / 1000.0, e) if t in paid_ else e
if pay < 1e-6:
continue
yield t, e, pay, (term_at(c, t) or c)["price_ct"]
def contract_eur(c, e, pay, price) -> float:
"""What a contract's step costs (EUR; < 0 received): bought, the kWh
paid at its price; sold, the kWh delivered at its price."""
return pay * price / 100.0 if c["direction"] == "buys" else -e * price / 100.0
def market_plan(s, m, x) -> list[dict]:
"""Per contract in the plan (shadow): the planned energy per step and in
all (kWh), what is paid, and what it saves against the grid: bought,
@@ -1460,20 +1560,14 @@ def market_plan(s, m, x) -> list[dict]:
pi, pe = s["price_import"], s["price_export"]
for c, vars_, paid_ in getattr(m, "contracts", []):
steps, kwh, paid_kwh, cost, vs = [], 0.0, 0.0, 0.0, 0.0
for t, v in sorted(vars_.items()):
e = max(x(v), 0.0) * m.dt / 1000.0
pay = max(x(paid_[t]) * m.dt / 1000.0, e) if t in paid_ else e
if pay < 1e-6:
continue
price = (term_at(c, t) or c)["price_ct"]
for t, e, pay, price in contract_energy(m, x, c, vars_, paid_):
steps.append({"t": s["start"] + t * s["step_s"], "kwh": round(e, 4), "paid_kwh": round(pay, 4)})
kwh += e
paid_kwh += pay
cost += contract_eur(c, e, pay, price)
if c["direction"] == "buys":
cost += pay * price / 100.0
vs += (e * pi[t] - pay * price) / 100.0
else:
cost -= e * price / 100.0
vs += e * (price - (pe[t] or 0.0)) / 100.0 # an unpriced export: worth nothing
out.append({"id": c["id"], "name": c.get("name", ""), "direction": c["direction"], "price_ct": c["price_ct"],
"steps": steps, "planned_kwh": round(kwh, 4), "paid_kwh": round(paid_kwh, 4),
@@ -1774,14 +1868,22 @@ def _entry(d, kind, v, t, x, s, pi, grid_w=(1e9, 1e9)):
net = _round(net, 50.0)
surplus = s["pv_w"][t] - s["load_w"][t]
grid = net > max(0.0, surplus) + 50
bp = (s.get("building") or {}).get("battery_plan")
bld = s.get("building") or {}
bp, bound = bld.get("battery_plan"), bld.get("battery_bound")
target = bp["schedule_w"][t] if bp and t < len(bp["schedule_w"]) else None
if target is not None:
# the building's plan for its battery (Model.battery_plan): a setpoint, not the own mode
why = f"building {bp['building']}: its battery plan ({target:+.0f} W)"
if abs(net - target) > GRID_ZERO_W:
why += ", within your battery's limits and reserve"
why += (", more from the PV surplus to your battery's reserve" if bound and net > target and net > 0
else ", within your battery's limits and reserve")
return {"set": net, "grid": grid, "why": why}
if bound:
# bound to a building without its plan for this step (A9.4): the inverter's own self-consumption
end = time.strftime("%d %b %H:%M UTC", time.gmtime(bound.get("until") or 0))
why = (f"building {bound['building']}: its battery plan ended {end}, not renewed" if bound.get("lapsed")
else f"building {bound['building']}: no battery plan after {end}")
return {"set": net, "grid": False, "auto": True, "why": why + ": self-consumption only, no grid charging"}
if not s.get("priced", True):
# no tariff: the battery in its own mode, unless the owner's
# reserve needs charging from the grid
@@ -1973,21 +2075,56 @@ def _tank_input_w(v, t, heat_w: float) -> tuple[str, float]:
def tank_baseline(m, v) -> float:
"""The tank without the plan (EUR): its own thermostat holding the
comfort's least, the same draw and the standing loss there, each W of
heat at its carrier's mean price over the horizon."""
comfort's least from the same start, the same draw and the standing
loss, each W of heat at its carrier's mean price over the horizon
(tank_baseline_steps summed)."""
return sum(sum(eur) for eur in tank_baseline_steps(m, v).values())
def tank_thermostat_heat(m, v) -> list[float]:
"""The heat (W per step) the tank's own thermostat gives without the
plan: from the plan's own start E_0 (the heat in it now), the same
balance as Model.dhw_tank, E_t = phi E_(t-1) + dt (q_t - D_t - P0),
heating only when E would fall below the comfort's least E_min, at most
the heater's output (an element's or heat pump's W x COP, a boiler's or
heat station's max_heat_w). A tank above its least coasts down as the
plan's does: the heat already in it is not a saving of the plan (until
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)."""
e, dt, out = v["e0"], m.dt, []
for t in range(m.T):
need = (v["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:
cap = v.get("qmax") or math.inf
q = min(max(0.0, need), cap)
e = v["phi"] * e + dt * (q - v["draw"][t] - v["p0"])
out.append(q)
return out
def tank_baseline_steps(m, v) -> dict:
"""tank_baseline per carrier and step: {carrier: [EUR per step]}, the
carriers with a price only (step_costs' base side, so the split's base
is baseline()): the thermostat's heat (tank_thermostat_heat) as its
heater's input at the carrier's mean price."""
s = m.s
eur = 0.0
out = {}
heat = tank_thermostat_heat(m, v)
for carrier in ("electricity", "gas", "heat"):
ps = [p for p in [_carrier_price(s, carrier, t) for t in range(m.T)] if p is not None]
if not ps:
continue
mean = sum(ps) / len(ps)
eur = [0.0] * m.T
for t in range(m.T):
heat = v["draw"][t] + v["ua"] * (v["lo_c"] - v["room"])
c, w = _tank_input_w(v, t, max(0.0, heat))
c, w = _tank_input_w(v, t, heat[t])
if c == carrier:
eur += m.eur_wh(t, mean) * w
return eur
eur[t] += m.eur_wh(t, mean) * w
out[carrier] = eur
return out
def storage_report(s, m, x) -> dict:
@@ -2045,6 +2182,8 @@ def storage_report(s, m, x) -> dict:
"temp_c": round(float(st["temp_c"]), 1), "stored_kwh": round(v["e0"] / 1000.0, 2),
"usable_kwh": round(max(0.0, v["e0"] - v["emin"]) / 1000.0, 2), "min_temp_c": round(v["lo_c"], 1),
"max_temp_c": round(v["hi_c"], 1), "grossanlage": bool(p.get("grossanlage")),
# its cold water and room (°C): the building plan composes a central boiler's store with them (C2.12)
"room_c": round(float(v["room"]), 1), "cold_water_c": round(float(v["t_cw"]), 1),
"idle_loss_kwh": round(sum(loss) / 1000.0, 3), "idle_loss_kwh_24h": round(sum(loss[:n24]) / 1000.0, 3),
"idle_loss_eur_24h": round(eur, 3) if m.priced else None,
"draw_kwh_24h": round(sum(v["draw"][:n24]) * m.dt / 1000.0, 3),
@@ -2117,6 +2256,9 @@ def heat_outlook(s, m) -> dict | None:
if src == "boiler":
out["efficiency"] = sup.eff
out["part_load"] = sup.curve["from"]
if is_combi(site) and "dhw" in lines:
# a combi (392): its hot water, as drawn or into its store (E6.6)
out["combi"] = True
return out
@@ -2220,19 +2362,30 @@ def step_costs(s, m, x) -> dict | None:
would cost without it, at the same prices (EUR; costs.py books the step
of each quarter-hour as the household's saving by the plan, methods.md
A12):
electricity plan: the meter's import less its feed-in at the step's
prices; without: the house's net load at those prices (no
battery) and the planned devices' electric energy of the
step at the horizon's mean import price (a car's at the
mean of its as-soon-as-possible steps), as baseline()
electricity plan: the grid's import less its feed-in at the step's
prices, and the market's contracts in the step (a
tenant-power flat's energy bought from its building at the
offer's price of that slot, a sale at its price; as
energy_of, market_plan); without: the house's net load at
the grid's prices (no battery) and the planned devices'
electric energy of the step at the horizon's mean import
price (a car's at the mean of its as-soon-as-possible
steps, a tank's by its own thermostat), as baseline()
gas, heat the heating's gas or district heat of the step at its
price, against the same energy at the horizon's mean price
A step's saving can be negative (a battery charging now for later). The
market's contracts are not in it. None without a tariff."""
(a tank's: its own thermostat's, tank_baseline_steps)
Summed over the steps and carriers, plan is cost_eur and base
baseline_eur, each less the heat outlook (a fixed term in both): the
split's saving is the plan's own. A step's saving can be
negative (a battery charging now for later). None without a tariff."""
if not m.priced:
return None
T, pi, pe = m.T, s["price_import"], s["price_export"]
el_plan = [m.eur_wh(t, pi[t]) * x(m.gin[t]) - m.eur_wh(t, pe[t]) * x(m.gout[t]) for t in range(T)]
for c, vars_, paid_ in getattr(m, "contracts", []):
for t, e, pay, price in contract_energy(m, x, c, vars_, paid_):
el_plan[t] += contract_eur(c, e, pay, price)
tanks = {d: tank_baseline_steps(m, v) for d, (kind, v) in m.devices.items() if kind == "dhw_tank" and v}
el_base = []
for t in range(T):
net = s["load_w"][t] - s["pv_w"][t]
@@ -2246,7 +2399,7 @@ def step_costs(s, m, x) -> dict | None:
continue
mp = sum(ps) / len(ps)
plan_c, base_c, used = [0.0] * T, [0.0] * T, False
for kind, v in m.devices.values():
for d, (kind, v) in m.devices.items():
if kind not in ("heating", "dhw_tank") or not v:
continue
if col == "gas" and (v.get("fuel") or "gas") != carrier:
@@ -2255,19 +2408,28 @@ def step_costs(s, m, x) -> dict | None:
if var is not None and t < len(prices) and prices[t] is not None:
used = True
plan_c[t] += m.eur_wh(t, prices[t]) * x(var)
base_c[t] += m.eur_wh(t, mp) * x(var)
if kind == "heating":
base_c[t] += m.eur_wh(t, mp) * x(var)
if kind == "dhw_tank" and carrier in tanks[d]:
# without the plan: the tank's own thermostat (baseline's tank_baseline)
used = used or any(tanks[d][carrier])
for t, eur in enumerate(tanks[d][carrier]):
base_c[t] += eur
if used:
out[carrier] = {"plan": plan_c, "base": base_c}
for kind, v in m.devices.values():
for d, (kind, v) in m.devices.items():
if not v:
continue
if kind == "battery" and v.get("p0"):
for t in range(T):
el_base[t] += m.eur_wh(t, mean) * v["p0"]
if kind in ("heating", "cooling", "dhw_tank"):
if kind in ("heating", "cooling"):
for t in range(T):
if v["power"][t] is not None:
el_base[t] += m.eur_wh(t, mean) * x(v["power"][t])
elif kind == "dhw_tank":
for t, eur in enumerate(tanks[d].get("electricity") or []):
el_base[t] += eur
elif kind == "ev":
wh = sum(m.dt * x(p) for p in v["power"] if p is not None)
# as soon as it can charge: from now, an expected session from its arrival
+60 -4
View File
@@ -14,11 +14,29 @@ of the electricity saving is load shifting and off-peak buying (battery,
car, appliances). Gas and district heat are the heating's alone.
{"electricity": {"plan_eur", "base_eur", "heating_eur"},
"gas": {"plan_eur", "base_eur"}, "heat": {"plan_eur", "base_eur"}}
"gas": {"plan_eur", "base_eur"[, "why", "note"]}, "heat": {...}, "oil": {...}}
base_eur − plan_eur summed over the carriers is the plan's saving without
the market's contracts (cost_eur carries them, step_costs does not). None
without a tariff (no step costs)."""
Gas, heating oil and district heat whose saving rounds to 0.00 EUR carry
why (a code) and note (in words) instead of a bare 0 (2026-11-09, the
owner: "we still have no saving from gas/oil?"; methods E14):
not_used the carrier is priced, the plan makes no heat with it (a
hybrid's heat pump made all of it)
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)
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
base_eur − plan_eur summed over the carriers is the plan's own saving,
baseline_eur − cost_eur: the plan's electricity carries the market's
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)."""
def saving_parts(s: dict, m, x, steps: dict | None) -> dict | None:
@@ -38,4 +56,42 @@ def saving_parts(s: dict, m, x, steps: dict | None) -> dict | None:
if p is not None:
heating += m.eur_wh(t, mean - pi[t]) * x(p)
out["electricity"]["heating_eur"] = round(heating, 4)
for carrier in HEAT_CARRIERS:
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)
return out
HEAT_CARRIERS = {"gas": ("price_gas", "gas"), "oil": ("price_oil", "heating oil"), "heat": ("price_heat", "district heat")}
ZERO_EUR = 0.005 # a saving that rounds to 0.00 EUR
def zero_why(s: dict, m, carrier: str, part: dict | None) -> dict | None:
"""Why a heat carrier's saving is 0 in this plan ({why, note}; module
docstring), None where it has a saving or is not there at all."""
key, words = HEAT_CARRIERS[carrier]
if part is None:
# not in the plan: a heating control or tank on it refused for want of its price
for r in (s.get("refused") or {}).values():
if f"{carrier}_price" in (r.get("missing") or []):
return {"why": "not_planned", "note": f"its heating is not planned: {r.get('why') or 'refused'}"}
return None
if abs(part["base_eur"] - part["plan_eur"]) >= ZERO_EUR:
return None
hybrid = any(kind == "heating" and v and v.get("src") == "hybrid" and (v.get("fuel") or "gas") == carrier
for kind, v in m.devices.values())
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 ""
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}
ps = [p for p in (s.get(key) or [])[:m.T] if p is not 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 "")
+ tail}
return {"why": "not_shifted", "note": f"the {words} price varies, but the heat was needed when it was made" + tail}
+84
View File
@@ -106,3 +106,87 @@ def test_shift_envelope_has_the_capacity():
sh = optimizer.plan(house([b]), 20)["flex"]["shift"]
d = next(x for x in sh["devices"] if x["kind"] == "battery")
assert d["cap_wh"] == 10000 and d["max_wh"] == 9000
# -- the binding (A9.4, 2026-11-09: Durlach's box charged from the grid at its own tariff once its plan ended; Mitte's
# box charged 2150 W from the grid to its 10 % reserve against the building's 0 W) ---------------------------------
def bound_state(tmp_path, s, ws, frm=START, now=START):
"""The state as the controller makes it with a battery_plan taken at frm and the clock at now."""
clock = Clock(frm)
b = Building(str(tmp_path), clock)
ok, why = b.take(b.parse({"v": "1", "id": "p1", "building": "house-7", "level": "binding",
"control": "battery_plan", "value": str(ws[0]), "from": str(frm),
"until": str(frm + 900 * len(ws)), "why": "the building's plan",
"schedule": ",".join(str(w) for w in ws), "step_s": "900"}), [])
assert ok, why
clock.t = now
s["building"] = Building(str(tmp_path), clock).for_model(now, 900, s["steps"]) # as after a restart
return s
def pv_day(s):
"""PV 3 kW from 09:00 to 15:00 UTC on each day of the horizon (house: 400 W)."""
s["pv_w"] = [3000.0 if 9 <= (k // 4) % 24 < 15 else 0.0 for k in range(s["steps"])]
return s
def no_grid_charging(s, p):
return all(w <= max(0.0, s["pv_w"][t] - s["load_w"][t]) + 1 for t, w in enumerate(p))
def test_binding_kept_after_the_plan_ends(tmp_path):
s = bound_state(tmp_path, house([battery(soc=50)]), [0] * 4, now=START + 3600)
assert "battery_plan" not in s["building"]
assert s["building"]["battery_bound"] == {"building": "house-7", "level": "binding", "until": START + 3600, "lapsed": True}
# membership.json without that building ends it
(tmp_path / "membership.json").write_text('{"buildings": ["other"]}')
assert "battery_bound" not in Building(str(tmp_path), Clock(START + 3600)).for_model(START + 3600, 900, 8)
assert '"battery_bound"' not in (tmp_path / "building.json").read_text()
def test_lapsed_plan_is_self_consumption_never_grid_charging(tmp_path):
# the house's own plan would charge in the cheap night (test_optimizer) and sell at the peak; bound and lapsed:
# charged only from the PV surplus, discharged only for the house, every entry the inverter's own mode
s = bound_state(tmp_path, pv_day(house([battery(soc=50)])), [0] * 4, frm=START - 3600, now=START)
assert s["building"]["battery_bound"]["lapsed"] and "battery_plan" not in s["building"]
p, _ = solved(s)["battery"]
assert no_grid_charging(s, p)
assert all(w >= -max(0.0, s["load_w"][t] - s["pv_w"][t]) - 1 for t, w in enumerate(p))
assert any(w > 100 for w in p) # it does take the PV surplus
plan = optimizer.plan(s, 20)
e = plan["devices"]["battery"]
assert e and all(x.get("auto") and not x["grid"] for x in e)
assert e[0]["why"].startswith("building house-7: its battery plan ended") and "no grid charging" in e[0]["why"]
assert any("not renewed" in n for n in plan.get("notes", []))
def test_beyond_the_window_self_consumption(tmp_path):
# a plan for the first 2 h (0 W): the box's 48 h after it are self-consumption only, not its own arbitrage
s = bound_state(tmp_path, pv_day(house([battery(soc=50)])), [0] * 8)
p, _ = solved(s)["battery"]
assert no_grid_charging(s, p)
later = [x for x in optimizer.plan(s, 20)["devices"]["battery"] if x["t"] >= START + 8 * 900]
assert later and all(x.get("auto") and not x["grid"] for x in later)
assert "no battery plan after" in later[0]["why"]
def test_reserve_refilled_from_pv_not_the_grid(tmp_path):
# Sim Mitte (2026-11-08): 5 % with the owner's floor at 10 %, the building's 0 W through the night: no grid
# charging to the reserve; the PV surplus refills it once the sun is up
s = bound_state(tmp_path, pv_day(house([battery(soc=5, floor=10)])), [0] * 96)
p, soc = solved(s)["battery"]
assert all(w <= 1 for w in p[:36]) # 00:00-09:00 UTC: no PV, nothing charged
assert no_grid_charging(s, p)
assert max(soc[36:60]) >= 1000 - 1 # back at its 10 % from the PV
e = optimizer.plan(s, 20)["devices"]["battery"]
assert not any(x["grid"] for x in e)
assert any("PV surplus to your battery's reserve" in x["why"] for x in e)
def test_the_building_may_charge_from_the_grid(tmp_path):
# the plan itself charges 2 kW at night: followed (the building's choice, it sees the flats)
s = bound_state(tmp_path, house([battery(soc=5, floor=10)]), [2000] * 4 + [0] * 92)
p, _ = solved(s)["battery"]
assert p[:4] == pytest.approx([2000] * 4, abs=1)
assert all(w <= 1 for w in p[4:36])
+39 -1
View File
@@ -179,4 +179,42 @@ def test_battery_plan_for_model_alignment(tmp_path):
r = b2.for_model(START, 900, 10)["battery_plan"]
assert r["schedule_w"] == [None] * 3 + [-3000.0] * 4 + [None] * 3
assert (r["from_step"], r["to_step"], r["penalty"]) == (3, 7, 5.0)
assert b2.for_model(START + 7 * 900, 900, 10) == {} # nothing of it left in this window
# nothing of it left in this window: only the binding (A9.4), not lapsed while the plan is in force
assert b2.for_model(START + 7 * 900, 900, 10) == {"battery_bound": {"building": "house-7", "level": "binding",
"until": START + 7 * 900, "lapsed": False}}
def test_battery_binding_survives_and_lifts(tmp_path):
clock = Clock(1_800_000_000.0)
b = Building(str(tmp_path), clock)
a = {"v": "1", "id": "p1", "building": "b1", "level": "flexible", "control": "battery_plan", "value": "0",
"from": "1800000000", "until": "1800003600", "schedule": ",".join(["0"] * 4), "step_s": "900"}
assert b.take(b.parse(a), [])[0]
assert b.bound["building"] == "b1" and b.bound["until"] == 1800003600
clock.t = 1800003600 + 1
m = Building(str(tmp_path), clock).for_model(1800003600, 900, 4)
assert m == {"battery_bound": {"building": "b1", "level": "flexible", "until": 1800003600, "lapsed": True}}
# a newer plan of the same building keeps the binding's start; the owner lifting a flexible one ends it
b = Building(str(tmp_path), clock)
since = b.bound["since"]
assert b.take(b.parse({**a, "id": "p2", "from": "1800003600", "until": "1800007200"}), [])[0]
assert b.bound["since"] == since and b.bound["id"] == "p2"
assert b.for_model(1800003600, 900, 4)["battery_bound"]["lapsed"] is False
b.lift("battery_plan")
assert Building(str(tmp_path), clock).bound is None
def test_battery_follows_the_building_plan_in_the_executor(tmp_path, mapping, consent): # noqa: F811
"""A battery whose plan entry names the building (its battery plan) is set like any other: the cap's
override bookkeeping is for a room's climate only (2026-11-08, Sim Durlach's box: KeyError 'climate' on
every round from the first battery plan on, so it kept charging 3 kW from the grid for its own earlier plan)."""
clk = Clock(START + 600)
g = mk_guard(mapping, consent, clock=clk)
col = Collector()
states(col, switch__grid_charge=("off",), number__batt_power=("2500",), climate__living=("heat", {"temperature": 21}))
ex = Executor(mapping.controls, g, col, lambda *a: asyncio.sleep(0), clock=clk, building=Building(str(tmp_path), clk))
ex.plan = {"made": clk.t, "devices": {"battery": [{"t": START, "set": 0.0, "grid": False,
"why": "building house-7: its battery plan (+0 W)"}]}}
ha = FakeHA()
asyncio.run(ex.tick(ha, auto=True))
assert ("number", "set_value", "number.batt_power", {"value": 0.0}) in ha.calls
+182
View File
@@ -0,0 +1,182 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""A combi boiler (Kombitherme, 392, docs/methods.md E6.6): one
burner for the rooms and the hot water. Without a store of its own it makes
the water as it is drawn, the hot water first:
in each step the rooms get the boiler's most heat less the hot water (the
site's hot-water forecast); without a forecast they keep all of it (noted).
The hot water's gas is the heat outlook's (an unshiftable demand at the gas
price), marked as the combi's. With a store (a dhw_tank whose heater is the
boiler, shares_with) the store is a device of its own: it takes the draws,
the burner is shared, nothing refuses. A hybrid's gas boiler heating a
store: the same rule, the store's heat and the boiler's heat for the rooms
within the boiler's output (its heat pump apart)."""
import pytest
highspy = pytest.importorskip("highspy")
from cantabile_edge import optimizer # noqa: E402
from test_heat_sources import house, room # noqa: E402
def combi_house(dhw_w, combi=True, qmax=9000.0, temp=17.0):
r = room("boiler", temp=temp, boiler_efficiency=0.9, max_heat_w=qmax, **({"combi": True} if combi else {}))
s = house([r], gas=12.0)
s["t_out"] = [-10.0] * s["steps"] # a cold day: the rooms want the whole output
if dhw_w is not None:
s["dhw_w"] = dhw_w if isinstance(dhw_w, list) else [dhw_w] * s["steps"]
s["heat_site"] = {"from": "heating", "source": "boiler", "boiler_efficiency": 0.9, "max_heat_w": qmax,
"space": False, **({"combi": True} if combi else {})}
return s
def room_heat(s):
m = optimizer.Model(optimizer._prepare(s))
m.solve(20)
val = m.h.getSolution().col_value
v = m.devices["heating"][1]
return [val[g.index] * 0.9 for g in v["gas"]], m
def test_the_hot_water_first():
# 6 kW of hot water drawn in steps 28..31 (07:00-08:00 UTC): the rooms get at most 3 kW there
dhw = [0.0] * 96
for k in range(28, 32):
dhw[k] = 6000.0
heat, _ = room_heat(combi_house(dhw))
for k in range(28, 32):
assert heat[k] <= 3000.0 + 1, (k, heat[k])
assert max(heat) > 3000.0 + 1 # elsewhere the whole output is there
def test_a_plain_boiler_is_not_capped():
dhw = [6000.0] * 96
heat, _ = room_heat(combi_house(dhw, combi=False))
assert max(heat) > 3000.0 + 1
def test_without_a_hot_water_forecast_noted():
heat, m = room_heat(combi_house(None))
assert max(heat) > 3000.0 + 1
assert any("combi boiler without a hot-water forecast" in n for n in m.notes), m.notes
def test_the_outlook_marks_the_combis_hot_water():
p = optimizer.plan(combi_house([500.0] * 96), 20)
o = p["heat_outlook"]
assert o["combi"] is True and "dhw" in o["lines"]
assert o["lines"]["dhw"]["heat_kwh"] == pytest.approx(12.0, abs=0.05) # 0.5 kW for 24 h
assert p["cost_parts"]["heat_outlook_eur"] == o["eur"]
assert optimizer.is_combi({"combi": "true"}) and not optimizer.is_combi({})
def test_the_mapping_checks_combi():
from cantabile_edge import controls
controls._check_heat("h", {"heat_source": "boiler", "combi": True}, {})
with pytest.raises(ValueError, match="combi is a boiler's"):
controls._check_heat("h", {"heat_source": "heat_pump", "combi": True}, {})
with pytest.raises(ValueError, match="true or false"):
controls._check_heat("h", {"heat_source": "boiler", "combi": "maybe"}, {})
# ---- a combi and a store: two devices (the owner, 2026-11-08: "model it, don't refuse")
def combi_with_store(dhw_w=6000.0):
from test_storage import tank
s = combi_house([0.0] * 96)
t = tank(heater="boiler", temp=47.0, power=9000.0, channels=("water_heater",), shares_with="heating")
hour = lambda k: (k // 4 + 1) % 24 # noqa: E731
draw = [dhw_w if hour(k) == 19 else 0.0 for k in range(s["steps"])]
t["draw_w"] = draw
s["dhw_w"] = draw # the site's forecast: the store's draws
s["devices"].append(t)
return s
def test_a_combi_with_a_store_reserves_nothing_the_store_takes_the_draws():
s = combi_with_store()
m = optimizer.Model(optimizer._prepare(s))
assert optimizer.combi_dhw(m, "heating", s["devices"][0]["params"], "boiler") is None
m.solve(30)
val = m.h.getSolution().col_value
x = lambda v: val[v.index] # noqa: E731
room, store = m.devices["heating"][1], m.devices["tank"][1]
for t in range(s["steps"]):
# one burner: the store's heat and the rooms' together at most its 9 kW
assert optimizer.tank_heat(store, t, x) + x(room["gas"][t]) * 0.9 <= 9000.0 + 1.0, t
assert sum(x(u) for u in store["unmet"]) * 0.25 < 5.0 # the store gives the draws (Wh short)
def test_a_store_of_its_own_burner_is_not_shared():
s = combi_with_store()
s["devices"][1]["params"].pop("shares_with")
m = optimizer.Model(optimizer._prepare(s))
# no store names this combi: it makes the water as drawn again (the forecast reserved)
assert optimizer.combi_dhw(m, "heating", s["devices"][0]["params"], "boiler") is not None
def test_nothing_refuses_a_combi_with_a_store():
from cantabile_edge import controls
controls._check_heat("heating", {"heat_source": "boiler", "combi": True}, {})
controls._check_tank("tank", {"heater": "boiler", "shares_with": "heating"})
p = optimizer.plan(combi_with_store(), 30)
assert "heating" in p["devices"] and "tank" in p["devices"], p.get("notes")
assert not any("refus" in str(n).lower() for n in p.get("notes") or []), p.get("notes")
# ---- a hybrid's gas boiler with a store (the owner, 2026-11-08: "yes"; backlog 392 follow-up): the same rule
def hybrid_with_store(imp=60.0):
from test_heat_sources import house, room
from test_storage import tank
r = room("hybrid", temp=17.0, boiler_efficiency=0.9, max_heat_w=9000.0)
s = house([r], imp=imp, gas=12.0)
s["t_out"] = [-10.0] * s["steps"] # a cold day: the rooms want the whole output
t = tank(heater="boiler", temp=47.0, power=9000.0, channels=("water_heater",), shares_with="heating")
hour = lambda k: (k // 4 + 1) % 24 # noqa: E731
t["draw_w"] = [6000.0 if hour(k) == 19 else 0.0 for k in range(s["steps"])]
s["devices"].append(t)
return s
def test_a_hybrids_boiler_shares_its_burner_with_its_store():
s = hybrid_with_store() # electricity dear: the rooms on the boiler
m = optimizer.Model(optimizer._prepare(s))
m.solve(30)
assert not any("is not planned" in n for n in m.notes), m.notes
val = m.h.getSolution().col_value
x = lambda v: val[v.index] # noqa: E731
room, store = m.devices["heating"][1], m.devices["tank"][1]
assert room["src"] == "hybrid" and len(room["burner"]) == s["steps"]
assert sum(x(g) for g in room["gas"]) > 0 # the boiler heats the rooms
for t in range(s["steps"]):
# one burner: the store's heat and the rooms' boiler heat together at most its 9 kW
assert optimizer.tank_heat(store, t, x) + x(room["gas"][t]) * 0.9 <= 9000.0 + 1.0, t
assert sum(x(u) for u in store["unmet"]) * 0.25 < 5.0 # the store gives the draws
def test_a_hybrids_heat_pump_is_not_the_stores_burner():
s = hybrid_with_store(imp=10.0) # electricity cheap: the rooms on the heat pump
m = optimizer.Model(optimizer._prepare(s))
m.solve(30)
val = m.h.getSolution().col_value
x = lambda v: val[v.index] # noqa: E731
room, store = m.devices["heating"][1], m.devices["tank"][1]
for t in range(s["steps"]):
# the bound holds the boiler's heat alone: the heat pump's (COP x W) is not in it
assert optimizer.tank_heat(store, t, x) + x(room["gas"][t]) * 0.9 <= 9000.0 + 1.0, t
hp_heat = [x(room["power"][t]) * 3.0 for t in range(s["steps"])]
st_heat = [optimizer.tank_heat(store, t, x) for t in range(s["steps"])]
assert sum(hp_heat) > 0 and sum(st_heat) > 0
p = optimizer.plan(hybrid_with_store(imp=10.0), 30)
assert "heating" in p["devices"] and "tank" in p["devices"], p.get("notes")
assert not any("refus" in str(n).lower() for n in p.get("notes") or []), p.get("notes")
def test_a_store_naming_a_heat_pump_room_plans_its_boiler_alone():
from test_heat_sources import house, room
from test_storage import tank
s = house([room("heat_pump", temp=19.0)], gas=12.0)
s["devices"].append(tank(heater="boiler", temp=50.0, power=9000.0, channels=("water_heater",), shares_with="heating"))
m = optimizer.Model(optimizer._prepare(s))
m.solve(30)
assert any("its boiler's room control heating is not planned or has no boiler" in n for n in m.notes), m.notes
+11
View File
@@ -295,3 +295,14 @@ def test_a_failing_view_leaves_the_dashboard(tmp_path, monkeypatch):
views = dashboards.dashboard(h)["views"]
bad = next(v for v in views if v["path"] == "costs")
assert "ha-alert" in json.dumps(bad) and "overview" in [v["path"] for v in views]
def test_every_carrier_has_its_name_in_both_languages():
# the costs and savings sections name each carrier by names.name("carrier_" + c): a missing one fails
# the whole section on the box (heating oil had none until 2026-11-09: oil homes showed no costs)
for c in costs.CARRIERS:
for lang in ("en", "de"):
assert names.NAMES["carrier_" + c].get(lang), (c, lang)
from cantabile_edge import optimizer
for facts in ({"fuel": "oil"}, {"fuel": "gas"}, {}):
assert optimizer.boiler_fuel(facts) in costs.CARRIERS, facts
+202
View File
@@ -47,3 +47,205 @@ def test_no_tariff_no_parts():
s["price_export"] = [None] * len(s["price_export"])
p = optimizer.plan(s, 20)
assert p.get("saving_parts") is None
# -- the split adds up to the plan's own saving (a tenant-power flat's split) ---------------------
from test_market_plan import contract, house as market_house # noqa: E402
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"]
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)
assert sum(x["base_eur"] for x in sp.values()) == pytest.approx(p["baseline_eur"] - outlook, abs=0.02)
# and per step (costs.py books step 0 of each quarter-hour): the same sums
se = p["steps_eur"]
for c, x in sp.items():
assert sum(se[c]["plan"]) == pytest.approx(x["plan_eur"], abs=1e-3)
def test_a_tenant_power_flat_prices_what_it_buys_from_its_building():
# GGV / Mieterstrom: the building's offer at 20 ct against the grid's 30, priced per slot
terms = [{"price_ct": 18.0 + (t % 4), "guaranteed_w": 0.0, "minimum_wh": 0.0, "max_w": 600.0} for t in range(16)]
c = contract("buys", 20.0, max_w=600, a=0, b=16)
c["terms"] = terms
p = optimizer.plan(market_house([c]), 10)
el = p["saving_parts"]["electricity"]
assert p["market"][0]["planned_kwh"] > 0
# the building's energy is in the plan's electricity, never 0 for a flat that buys
assert el["plan_eur"] == pytest.approx(p["cost_eur"], abs=0.02)
assert saved(el) == pytest.approx(p["market"][0]["vs_grid_eur"], abs=0.02)
assert_adds_up(p)
@pytest.mark.parametrize("c,kw", [
(contract("buys", 40.0, max_w=1000, minimum_wh=100.0), {}), # take-or-pay: the minimum paid
(contract("buys", 1.0, max_w=5000), {"load": 300.0}), # below the feed-in, never resold
(contract("sells", 15.0, max_w=1500), {"load": 500.0, "pv": 2500.0}), # §42c: the surplus sold to the pool
])
def test_the_markets_contracts_in_the_split(c, kw):
assert_adds_up(optimizer.plan(market_house([c], **kw), 10))
def test_a_plain_grid_house_adds_up():
p = optimizer.plan(house([battery(), heating()]), 20)
assert "market" not in p
assert_adds_up(p)
@pytest.mark.parametrize("src,extra,prices", [
("boiler", {"boiler_efficiency": 0.9, "max_heat_w": 9000}, {"gas": [10.0 + (k % 8) for k in range(96)]}),
("district", {"max_heat_w": 6000}, {"heat": [11.0 + (k % 5) for k in range(96)]}),
("boiler", {"boiler_efficiency": 0.9, "max_heat_w": 9000, "fuel": "oil"}, {}),
])
def test_a_gas_or_heat_site_adds_up(src, extra, prices):
s = heat_house([room(src, **extra)], imp=[20.0 + (k % 12) for k in range(96)], **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_adds_up(p)
@pytest.mark.parametrize("heater,key", [("element", None), ("boiler", "price_gas"), ("district", "price_heat")])
def test_a_hot_water_tank_adds_up(heater, key):
s = house([tank(heater=heater, temp=47.0, power=10000.0 if key else 3000.0,
channels=("water_heater",) if key else ("switch",))])
if key:
s[key] = [10.0 + (k % 6) for k in range(s["steps"])]
s["devices"][0]["draw_w"] = evening_draw(s)
assert_adds_up(optimizer.plan(s, 30))
def test_a_tenant_power_flat_with_district_heat_adds_up():
# Sim Berlin 5's shape: the building's offer for electricity, district heat for the rooms
s = heat_house([room("district", max_heat_w=6000)], heat=11.0)
s["market"] = [contract("buys", 22.0, max_w=3000, a=0, b=96)]
p = optimizer.plan(s, 20)
assert p["saving_parts"]["electricity"]["plan_eur"] > 0
assert_adds_up(p)
# -- gas, heating oil and district heat: a saving where the plan has a lever, else 0 with its reason (2026-11-09) ---
# The owner: "we still have no saving from gas/oil?" The baseline counts the plan's own heat at the horizon's mean
# price (A12.2): at one price every quarter-hour there is nothing to move in time, so 0 exactly, and the split says
# why instead of a bare 0; where the price varies the plan heats in the cheaper hours and the carrier shows it.
N = 96
def oil(s, price=11.0):
s["price_oil"] = [price] * N
return s
def combi_store(t0):
st = tank(heater="boiler", temp=t0, power=9000.0, channels=("water_heater",), shares_with="heating")
s = heat_house([room("boiler", boiler_efficiency=0.9, max_heat_w=9000, combi=True), st], gas=12.0)
s["devices"][1]["draw_w"] = evening_draw(s, 6000.0)
return s
def combi(s):
s["dhw_w"] = evening_draw(s, 6000.0)
return s
@pytest.mark.parametrize("name,s,carrier", [
("gas boiler", lambda: heat_house([room("boiler", boiler_efficiency=0.9, max_heat_w=9000)], gas=12.0), "gas"),
("condensing boiler on its part-load curve", lambda: heat_house([room(
"boiler", boiler_efficiency=0.88, max_heat_w=10000, part_load_curve=[[0.3, 1.094], [1.0, 1.0]])], gas=12.0), "gas"),
("combi", lambda: combi(heat_house([room("boiler", boiler_efficiency=0.9, max_heat_w=9000, combi=True)], gas=12.0)), "gas"),
("combi with a store, started warm", lambda: combi_store(47.0), "gas"),
("oil boiler", lambda: oil(heat_house([room("boiler", boiler_efficiency=0.9, max_heat_w=9000, fuel="oil")])), "oil"),
("district heat (Sim Durlach's 9.315 ct)", lambda: heat_house([room("district", max_heat_w=6000)], heat=9.315), "heat"),
("district heat, dynamic power", lambda: heat_house([room("district", max_heat_w=6000)],
imp=[20.0 + (k % 12) for k in range(N)], heat=9.315), "heat"),
])
def test_one_price_saves_nothing_and_says_why(name, s, carrier):
p = optimizer.plan(s(), 30)
part = p["saving_parts"][carrier]
assert saved(part) == pytest.approx(0, abs=0.005), name
assert part["plan_eur"] > 0
assert part["why"] == "flat_price"
assert "nothing to move in time" in part["note"] and "ct/kWh" in part["note"]
assert_adds_up(p)
@pytest.mark.parametrize("carrier,s", [
("gas", lambda: heat_house([room("boiler", boiler_efficiency=0.9, max_heat_w=9000)], gas=[10.0 + (k % 8) for k in range(N)])),
("heat", lambda: heat_house([room("district", max_heat_w=6000)], heat=[11.0 + (k % 5) for k in range(N)])),
])
def test_a_varying_price_saves_on_the_carrier(carrier, s):
# the lever the plan has on gas and district heat: heat (pre-heat) in the cheaper quarter-hours
p = optimizer.plan(s(), 30)
part = p["saving_parts"][carrier]
assert saved(part) > 0.1
assert "why" not in part
assert_adds_up(p)
@pytest.mark.parametrize("fuel", ["gas", "oil"])
def test_a_hybrid_on_its_heat_pump_used_no_gas_and_says_so(fuel):
# heat pump 30/3 = 10 ct per kWh of heat against the boiler's 12/0.9 = 13.3: the heat pump all the time
s = heat_house([room("hybrid", boiler_efficiency=0.9, max_heat_w=9000, **({"fuel": "oil"} if fuel == "oil" else {}))],
imp=30.0, gas=12.0)
if fuel == "oil":
oil(s, 12.0)
p = optimizer.plan(s, 30)
part = p["saving_parts"][fuel]
assert part["plan_eur"] == part["base_eur"] == 0
assert part["why"] == "not_used"
assert "heat pump made all the heat" in part["note"] and "choice between heat pump and boiler" in part["note"]
def test_a_heating_refused_for_its_gas_price_says_so():
# a gas-boiler home without a gas tariff: the heating refused, no gas part at all
s = house([battery()])
s["refused"] = {"heating": {"why": "no gas price for now", "kind": "heating", "missing": ["gas_price"]}}
sp = optimizer.plan(s, 20)["saving_parts"]
assert sp["gas"] == {"plan_eur": 0.0, "base_eur": 0.0, "why": "not_planned",
"note": "its heating is not planned: no gas price for now"}
assert "oil" not in sp and "heat" not in sp
@pytest.mark.parametrize("heater,key", [("element", None), ("boiler", "price_gas"), ("district", "price_heat")])
def test_a_tank_started_warm_saves_nothing_at_one_price(heater, key):
# the baseline's thermostat starts from the same stored heat as the plan: before 2026-11-09 it held the
# least from the first step and a tank at 55 °C over its 45 showed 0.75 EUR (element) saved at one price
s = house([tank(heater=heater, temp=55.0, power=10000.0 if key else 3000.0,
channels=("water_heater",) if key else ("power",))])
s["price_import"] = [30.0] * s["steps"] # one price on every carrier
if key:
s[key] = [12.0] * s["steps"]
s["devices"][0]["draw_w"] = evening_draw(s)
p = optimizer.plan(s, 30)
carrier = {"price_gas": "gas", "price_heat": "heat"}.get(key, "electricity")
assert saved(p["saving_parts"][carrier]) == pytest.approx(0, abs=0.005)
assert p["baseline_eur"] - p["cost_eur"] == pytest.approx(0, abs=0.01)
assert_adds_up(p)
def test_a_tank_still_saves_where_power_is_cheaper():
s = house([tank(temp=55.0, channels=("power",))]) # 12 ct at night, 28 by day, 40 at the evening peak
s["devices"][0]["draw_w"] = evening_draw(s)
p = optimizer.plan(s, 30)
assert saved(p["saving_parts"]["electricity"]) > 0.05
assert_adds_up(p)
def test_the_thermostat_from_a_warm_start_coasts_then_holds_its_least():
s = house([tank(temp=55.0, channels=("power",))])
s["devices"][0]["draw_w"] = evening_draw(s)
m = optimizer.Model(optimizer._prepare(s))
m.solve(30)
v = m.devices["tank"][1]
q = optimizer.tank_thermostat_heat(m, v)
first = next(t for t, w in enumerate(q) if w > 0)
assert first > 0 and all(w == 0 for w in q[:first]) # it coasts down from 55 °C first
# then it holds the least: the draw and the loss at 45 °C in an 18 °C room
later = [t for t in range(first + 8, len(q)) if v["draw"][t] == 0]
assert q[later[-1]] == pytest.approx(v["ua"] * (v["lo_c"] - v["room"]), rel=1e-6)
+2
View File
@@ -191,6 +191,8 @@ def test_s5_standing_loss_in_the_first_step():
p = optimizer.plan(s, 30)
st = p["storage"]["tank"]
assert st["standby_w"] == pytest.approx(70.0, abs=0.1) and st["idle_loss_kwh_24h"] > 1.0
# its cold water and room, for the building plan's store (C2.12)
assert st["room_c"] == pytest.approx(18.0) and st["cold_water_c"] == pytest.approx(10.0)
def test_an_element_stores_pv_surplus_at_noon_not_at_night():