cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1541: full source
This commit is contained in:
1 parent
05802d6f87
commit
94f46db8f8
19 files changed
+863
-60
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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 ""))
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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"},
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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}
|
||||
Reference in new issue
Block a user