cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.2019: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-12 21:05:22 +00:00
1 parent c0a6f8a579
commit 5168a4a590
27 files changed
+2815 -126

No files matched your search

+359 -90
View File
@@ -143,6 +143,7 @@ import highspy
from highspy.highs import highs_linear_expression as Lin
from .controls import ERP_TEST_DT_K, HOURS_PER_MONTH, cop_at, ev_volts, gas_segments, part_load, relative_efficiency
from . import battery_core
from .evphases import words as phase_words
from .storefit import WATER_WH_PER_L_K
from .plansplit import saving_parts
@@ -164,6 +165,8 @@ CHANGE_EUR_KW = 0.002 # EUR per kW a device's power changes from one step to
# plans (equal prices would otherwise give any order, and a charger or
# boiler must not be switched back and forth)
CLOSED_EUR = 0.00002 # EUR per step for a closed cover: open when nothing is at stake
COVER_MOVE_EUR = 0.01 # EUR per full travel of a cover the plan places on its window's facts (ENG, G3: no
# flapping between nearly equal positions; a move a few W of sun pays for is still made)
MARKET_MAX_W = 100000.0 # W: a contract without a maximum, and the meter's import/export switch
NO_PRICE_EUR_KWH = 1e-4 # EUR per kWh through the meter and per kWh a device uses, without a tariff
# only (ENG: a tie-break toward the least energy, not a price)
@@ -189,6 +192,9 @@ RELAY_STEPS = 4 # steps: a tank element's relay is on or off for a w
STORE_TIE_EUR_WH = 1e-8 # EUR per Wh held above the floor per step, only for a battery with a standby (ENG: a
# tie-break, 0.1 ct per kWh and day: with a flat price, charging the standby ahead or
# step by step costs the same; the plan holds the floor instead of a buffer)
REFILL_STEPS = 48 # steps: a battery that starts under the plan's reserve (above its top) is back inside it
# within 12 h, at the steps the plan finds cheapest, or later where its power needs longer
# (ENG, A2.3a; the building plan's REFILL_SLOTS, C6.5): never at once from the grid by force
STANDBY_GRID_EUR_KWH = 1.0 # EUR per kWh of a battery's standby drawn from the grid where the battery could give it
# (ENG, A2.3 S.2: above any price, so the standby comes from the cells while they hold
# charge, as it does physically; the grid only where the battery cannot: a valve)
@@ -576,6 +582,23 @@ class Model:
soc, prev, ch, dis = [], soc0, [], []
pref = d.get("pref") # the owner's reserve per step (preferences.py)
floors = []
# the plan's reserve and top (the owner's battery algorithm, A2.3a: the Parameters rows battery.plan_reserve_pct
# and battery.plan_max_soc_pct, inputs.battery_rows): the battery's own window narrowed by them (the shared
# battery_core.window); a start under the reserve (or above the top) stays outside until refill_k / drain_k,
# moved back where the plan finds it cheapest, never at once by force
wlo, whi = battery_core.window(lo_pct, hi_pct, p.get("plan_reserve_pct"), p.get("plan_max_soc_pct"))
s0 = 100.0 * soc0 / cap
refill_k = drain_k = 0
if s0 < wlo - 1e-9 and wlo > lo_pct:
per = max_ch * eff * self.dt / cap * 100.0 # % a step at full charge
refill_k = max(REFILL_STEPS, math.ceil((wlo - s0) / per) + 1) if per > 0 else self.T
if s0 > whi + 1e-9 and whi < hi_pct:
per = max_dis / eff * self.dt / cap * 100.0
drain_k = max(REFILL_STEPS, math.ceil((s0 - whi) / per) + 1) if per > 0 else self.T
self.window_used = getattr(self, "window_used", {})
self.window_used[d["id"]] = {"floor_pct": round(wlo, 2), "top_pct": round(whi, 2),
"reserve_pct": p.get("plan_reserve_pct"), "max_soc_pct": p.get("plan_max_soc_pct"),
"max_discharge_w": round(max_dis), "refill_steps": refill_k, "drain_steps": drain_k}
# the idle loss (A2.3, S.2): the system's standby p0 (W) from the battery while it holds charge
# (lb), from the grid only where it cannot (lg: a valve at STANDBY_GRID_EUR_KWH, into the house's
# balance only where the mapping says the load does not hold it); the cells' self-discharge as
@@ -590,9 +613,11 @@ class Model:
self.wear_used[d["id"]] = {"ct": wear_ct, "src": wear_src}
lbs, lgs = [], []
for t in range(self.T):
lo_t = lo_pct
base_lo = max(lo_pct, min(wlo, s0)) if t < refill_k else wlo
hi_t = min(hi_pct, max(whi, s0)) if t < drain_k else whi
lo_t = base_lo
if pref and not (pref.get("off") is not None and pref["group"][t] == pref["off"]):
lo_t = min(max(lo_pct, pref["floor_pct"][t]), hi_pct)
lo_t = min(max(base_lo, pref["floor_pct"][t]), hi_pct)
floors.append(lo_t)
c = self.var(0.0, max_ch, cost=self.use_cost(t))
x = self.var(0.0, max_dis, cost=self.use_cost(t) + wear_eur)
@@ -614,7 +639,7 @@ class Model:
else:
self.h.addConstr(e - phi * prev - self.dt * eff * c + self.dt / eff * x == 0)
self.h.addConstr(e + under >= lo_t / 100.0 * cap)
self.h.addConstr(e - over <= hi_pct / 100.0 * cap)
self.h.addConstr(e - over <= hi_t / 100.0 * cap)
self.flows[t] += [(-1, c), (1, x)]
soc.append(e)
ch.append(c)
@@ -628,8 +653,8 @@ class Model:
self.cost.append((-v_ct / 100.0 / 1000.0, prev))
self.smooth([c - x for c, x in zip(ch, dis)])
self.devices[d["id"]] = ("battery", {"ch": ch, "dis": dis, "soc": soc, "cap": cap, "max_dis": max_dis,
"floor_wh": lo_pct / 100.0 * cap, "floors": floors,
"max_ch": max_ch, "eff": eff, "soc0": soc0, "hi_wh": hi_pct / 100.0 * cap,
"floor_wh": wlo / 100.0 * cap, "floors": floors,
"max_ch": max_ch, "eff": eff, "soc0": soc0, "hi_wh": whi / 100.0 * cap,
"p0": p0, "phi": phi, "lam_h": lam_h, "lb": lbs, "lg": lgs,
"grid_side": grid_side, "in_load": p.get("standby_in_load")})
@@ -670,6 +695,25 @@ class Model:
solar = float(p.get("solar_m2") or 0.0)
ghi = self.s.get("ghi_w_m2") or [0.0] * self.T
pref = d.get("pref") # the owner's schedule and overrides (preferences.py)
# the comfort band (comfort.py, G5): only without the owner's schedule, which wins
cband = d.get("band") if not pref else None
# the flat's air and mass (2R2C, B17; G2 in the plan): the room as its share of the flat
zone = p.get("zone")
ad = bd = None
mprev = None
zgain = [0.0] * self.T
if zone:
ad, bd = rc2_discrete(zone, self.dt)
mprev = zone.get("theta_m0")
if mprev is None:
mprev = (zone["r_e"] * t0 + zone["r_i"] * self.s["t_out"][0]) / (zone["r_i"] + zone["r_e"])
load = self.s.get("load_w") or [0.0] * self.T
pres = self.s.get("presence_w") or [float(o) for o in self.s["occupied"]]
# the household's electricity and the people as heat (the fit's shares; the room's share of them)
zgain = [float(zone.get("el_gain_share") or 0.0) * max(0.0, float(load[t] if t < len(load) else 0.0))
+ float(zone.get("occ_gain_w") or 0.0) * float(pres[t] if t < len(pres) else 0.0)
for t in range(self.T)]
masses, targets = [], []
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
@@ -718,21 +762,42 @@ class Model:
tt = self.var(-50.0, 80.0)
sign = -1.0 if cooling else 1.0
covers = gains(t)
gain = sum((g * gx for g, gx in covers), start=Lin())
# the fit's (B6): its internal gain, and its sun where no cover carries it
fixed = internal[t] + (solar * ghi[t] if not covers and t < len(ghi) else 0.0)
# T[t+1] = T[t] (1 - a) + a T_out + dt/C (± heat/1000 + sun gain/1000 + fixed gains/1000);
# heat: COP x electric W, efficiency x gas W, district W (module docstring)
self.h.addConstr(tt - (1 - a) * prev - sign * self.dt / c / 1000.0 * heat
- self.dt / c / 1000.0 * gain == a * self.s["t_out"][t] + self.dt / c / 1000.0 * fixed)
gain = sum((g * gx for g, gx in covers if gx is not None), start=Lin())
# the fit's (B6): its internal gain, and its sun where no cover carries it; a window's fixed part (G3)
fixed = internal[t] + (solar * ghi[t] if not covers and t < len(ghi) else 0.0) + zgain[t] \
+ sum(g for g, gx in covers if gx is None)
if zone:
# the air and the mass, exact over the step (B17.4): x_t = Ad x_(t-1) + Bd [T_out, heat into the air in kW]
mm = self.var(-50.0, 80.0)
k_air, k_m = bd[0][1] / 1000.0, bd[1][1] / 1000.0
self.h.addConstr(tt - ad[0][0] * prev - ad[0][1] * mprev - sign * k_air * heat - k_air * gain
== bd[0][0] * self.s["t_out"][t] + k_air * fixed)
self.h.addConstr(mm - ad[1][0] * prev - ad[1][1] * mprev - sign * k_m * heat - k_m * gain
== bd[1][0] * self.s["t_out"][t] + k_m * fixed)
masses.append(mm)
mprev = mm
else:
# T[t+1] = T[t] (1 - a) + a T_out + dt/C (± heat/1000 + sun gain/1000 + fixed gains/1000);
# heat: COP x electric W, efficiency x gas W, district W (module docstring)
self.h.addConstr(tt - (1 - a) * prev - sign * self.dt / c / 1000.0 * heat
- self.dt / c / 1000.0 * gain == a * self.s["t_out"][t] + self.dt / c / 1000.0 * fixed)
occ = self.s["occupied"][t + 1] if t + 1 < self.T else self.s["occupied"][t]
occs.append(occ)
want, must = (comfort if occ else other), None
if cband:
# the band's edge the room keeps (heating: the lower, cooling: the upper) where someone may be
# home, else the setback (setup); the plan's target for the words and the envelope
edge = cband["lo"][t] if not cooling else cband["hi"][t]
w_edge = cband["w_lo"][t] if not cooling else cband["w_hi"][t]
want = edge if w_edge > 0 else cband["floor"][t]
occ = 1 if w_edge > 0 else 0
occs[-1] = occ
if pref:
want, must = pref["target"][t], pref["must"][t]
if pref.get("off") is not None and pref["group"][t] == pref["off"]:
want, must = pref["base"][t], None # pref_costs: the plan without this group
target = min(max(want, lo), hi)
targets.append(target)
capped = bool(cap) and cap["from_step"] <= t < cap["to_step"]
# heating: from its target (and must) up to its upper bound (under a building's cap); cooling mirrored
if cooling:
@@ -751,13 +816,29 @@ class Model:
self.h.addConstr(tt - cross <= mv)
else:
self.h.addConstr(tt + cross >= mv)
miss = self.var(cost=COMFORT_EUR_KH * self.dt)
under = self.var(cost=PENALTY_LIMIT)
over = self.var(cost=PENALTY_LIMIT)
if cooling:
self.h.addConstr(tt - miss <= target)
if cband:
# G5: the K·h outside the band, each side at its cost weighted by the presence (and the step
# someone comes home at its own); the setback (setup) held whoever is home
b_lo = min(max(cband["lo"][t], lo), hi)
b_hi = min(max(cband["hi"][t], lo), hi)
cold = self.var(cost=cband["w_lo"][t] * self.dt + (cband["arrive"][t] if not cooling else 0.0))
warm = self.var(cost=cband["w_hi"][t] * self.dt + (cband["arrive"][t] if cooling else 0.0))
self.h.addConstr(tt + cold >= b_lo)
self.h.addConstr(tt - warm <= b_hi)
back = min(max(cband["floor"][t], lo), hi)
miss = self.var(cost=cband.get("w_floor", COMFORT_EUR_KH) * self.dt)
if cooling:
self.h.addConstr(tt - miss <= back)
else:
self.h.addConstr(tt + miss >= back)
else:
self.h.addConstr(tt + miss >= target)
miss = self.var(cost=COMFORT_EUR_KH * self.dt)
if cooling:
self.h.addConstr(tt - miss <= target)
else:
self.h.addConstr(tt + miss >= target)
self.h.addConstr(tt + under >= lo)
self.h.addConstr(tt - over <= hi)
if capped:
@@ -786,7 +867,9 @@ class Model:
"a": a, "k": self.dt / c / 1000.0, "t0": t0, "hterms": hts, "sup": sup,
"elmax": pmax, "combi": combi, "comfort": comfort, "other": other,
"lo": lo, "hi": hi, "pref": bool(pref), "occ": occs,
"bivalent_c": p.get("bivalent_c")})
"bivalent_c": p.get("bivalent_c"),
# G2, G5: the mass per step (a zone), the target per step, the band in use
"mass": masses, "targets": targets, "banded": bool(cband), "zone": bool(zone)})
def hourly(self, v) -> list[float]:
"""A number, or 24 by local hour, per step."""
@@ -925,8 +1008,38 @@ class Model:
e_leg = cw * (t_leg - t_cw)
due = int(leg["due_step"])
window = list(range(0, min(self.T, due if due > 0 else self.T)))
# hot water as a reserve (hotwater.py, G7): the floor per step (the draw temperature at the forecast
# draws, the idle floor between them; a Großanlage the law's, hard), the owner's preferences (107)
floor_c = [min(max(float(v), 0.0), hi_c) for v in (d.get("floor_c") or [lo_c] * self.T)[:self.T]]
floor_c += [lo_c] * (self.T - len(floor_c))
if p.get("law_floor_c") is not None:
floor_c = [max(v, min(lo_c, hi_c)) for v in floor_c]
law = p.get("law_floor_c") is not None
pref = d.get("pref")
pmin = [None] * self.T # the owner's "must" per step (°C)
if pref:
for t in range(self.T):
c_t = pref["floor"][t]
if pref.get("off") is not None and pref["group"][t] == pref["off"]:
continue # pref_costs: the plan without this group
if c_t is not None:
floor_c[t] = max(floor_c[t], min(float(c_t), hi_c))
if pref["must"][t] is not None:
pmin[t] = min(float(pref["must"][t]), hi_c)
# a heat pump's COP by the tank's temperature (hotwater.cop_factor): below the draw temperature at its
# COP there, the heat stored above it at the maximum's (linear: the growth of the energy above it)
layers = None
if heater == "heat_pump" and not switched:
from .hotwater import cop_factor
r = {"dhw.hp_cop_drop_pct_per_k": float(p.get("hp_cop_drop_pct_per_k") or 0.0),
"dhw.hp_cop_ref_c": float(p.get("hp_cop_ref_c") or 0.0)}
mid_c = min(max(float(p["min_temp_c"]), t_cw + 1.0), hi_c)
f_lo, f_hi = cop_factor(p, mid_c, r), cop_factor(p, hi_c, r)
if f_hi < f_lo - 1e-6 and mid_c < hi_c - 0.5:
layers = (cw * (mid_c - t_cw), f_lo, f_hi, mid_c)
es, pws, gss, dhs, heats, unmet, prev = [], [], [], [], [], [], e0
lsum = Lin()
y_prev = max(0.0, e0 - layers[0]) if layers is not None else 0.0
for t in range(self.T):
terms, pw, pg, ph = [], None, None, None
if heater in ("element", "heat_pump"):
@@ -937,7 +1050,15 @@ class Model:
y = self.var(0.0, 1.0, integer=True)
self.h.addConstr(pw - pmax * y == 0)
self.flows[t].append((-1, pw))
terms.append((cops[t], pw))
if layers is not None:
# the heat at the draw temperature's COP, less the extra electricity the heat stored above
# it takes (x: (1/COP_hi - 1/COP_lo) per Wh the energy above the draw temperature grows, net
# of its standing loss; linear, no binary: G7)
x_el = self.var(0.0, pmax)
self.h.addConstr(x_el - pw <= 0)
terms += [(cops[t] * layers[1], pw), (-cops[t] * layers[1], x_el)]
else:
terms.append((cops[t], pw))
if shared is not None and shared[0][t] is not None:
self.h.addConstr(pw + shared[0][t] <= max(shared[1], pmax))
elif heater == "boiler":
@@ -951,11 +1072,26 @@ class Model:
e_lb = min(0.0, e0, cw * (room - t_cw))
e = self.var(e_lb, highspy.kHighsInf)
u = self.var(0.0, max(draw[t], 0.0), cost=short) # the draw not given
w = self.var(cost=short) # Wh under the comfort
# Wh under the floor: the short cost; a Großanlage's floor is the law's (PENALTY_LIMIT per K and step)
w = self.var(cost=PENALTY_LIMIT / cw if law else short)
over = self.var(cost=PENALTY_LIMIT / cw) # Wh above the maximum (a hot start)
self.h.addConstr(e - phi * prev - self.dt * q - self.dt * u == -self.dt * (draw[t] + p0))
self.h.addConstr(e + w >= emin)
self.h.addConstr(e + w >= cw * (floor_c[t] - t_cw))
self.h.addConstr(e - over <= emax)
if pmin[t] is not None:
wm = self.var(cost=MUST_EUR_K / cw) # the owner's must (107)
self.h.addConstr(e + wm >= cw * (pmin[t] - t_cw))
if layers is not None:
# y: the energy above the draw temperature (Wh, at its least: a tie cost); its growth over a
# step (the part its standing loss does not take) is heat made above it, at the upper COP
y = self.var(cost=STORE_TIE_EUR_WH)
self.h.addConstr(y - e >= -layers[0])
k_el = (1.0 / (cops[t] * layers[2]) - 1.0 / (cops[t] * layers[1])) / self.dt
if isinstance(y_prev, float): # the first step: the energy above it now
self.h.addConstr(x_el - k_el * y >= -k_el * phi * y_prev)
else:
self.h.addConstr(x_el - k_el * y + k_el * phi * y_prev >= 0)
y_prev = y
if e_leg is not None and t in window and t % LEGIONELLA_EVERY == 0:
lt = self.var(0.0, 1.0, integer=True)
self.h.addConstr(e - (e_leg - e_lb) * lt >= e_lb)
@@ -974,14 +1110,19 @@ class Model:
self.devices[d["id"]] = ("dhw_tank", {
"e": es, "power": pws, "gas": gss, "district": dhs, "heat": heats, "unmet": unmet, "draw": draw,
"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,
"lo_c": lo_c, "hi_c": hi_c, "heater": heater, "pmax": pmax, "switched": switched,
# the COP the reports and the thermostat's baseline take: at the draw temperature where the plan
# has the heat pump's two layers (the baseline's thermostat holds that temperature)
"cops": [c_ * layers[1] for c_ in cops] if layers is not None else cops,
"eff": sup.curve["full"] if heater == "boiler" else None, "e_leg": e_leg, "window": window,
"qmax": sup.qmax if sup else None,
# a boiler-heated tank's fuel (gas or heating oil: the plan's series, plan_series)
"fuel": sup.carrier if heater == "boiler" and sup else None,
"src": "electric" if heater in ("element", "heat_pump") else heater,
# for the store's lever (heatlevers.py): its heater's conversion, its own setpoint without the plan
"sup": sup, "thermostat_c": p.get("thermostat_c")})
"sup": sup, "thermostat_c": p.get("thermostat_c"),
# G7: the floor per step, the heat pump's two layers (E at the draw temperature, the COP factors)
"floor_c": floor_c, "law": law, "layers": layers, "pref": bool(pref)})
def cover(self, d, room_ids):
p, b = d["params"], d["bounds"]
@@ -1000,8 +1141,14 @@ class Model:
if p.get("room") not in room_ids:
self.devices[d["id"]] = ("cover", None)
return
win = d.get("window")
xs = []
for t in range(self.T):
if win and t < win["hold_steps"] and win.get("hold_pos") is not None:
# moved by hand: where the inhabitant put it while the guard keeps off it (G3: the override wins)
hp = min(max(win["hold_pos"], 0.0), 1.0)
xs.append(self.var(hp, hp))
continue
x = self.var(lo, hi)
closed_any = self.var(cost=CLOSED_EUR)
self.h.addConstr(closed_any + x >= hi)
@@ -1009,8 +1156,24 @@ class Model:
if daylight:
closed = self.var(cost=LIGHT_EUR)
self.h.addConstr(closed + x >= hi)
if win and xs:
# G3: no move in the owner's quiet hours; each move costs a little (no flapping)
if self._quiet(t, p):
self.h.addConstr(x - xs[-1] == 0)
else:
mv = self.var(cost=COVER_MOVE_EUR)
self.h.addConstr(mv - x + xs[-1] >= 0)
self.h.addConstr(mv + x - xs[-1] >= 0)
xs.append(x)
self.devices[d["id"]] = ("cover", {"pos": xs, "gain_w": float(p["gain_w"]), "room": p["room"]})
self.devices[d["id"]] = ("cover", {"pos": xs, "gain_w": float(p["gain_w"]), "room": p["room"],
**({"window": win} if win else {})})
def _quiet(self, t: int, p: dict) -> bool:
"""A step in a cover's quiet hours (its params quiet_from..quiet_to, local), as A7's rules."""
from .shades import quiet
zone = ZoneInfo(self.s.get("tz") or "UTC")
lt = datetime.fromtimestamp(self.s["start"] + t * self.s["step_s"], timezone.utc).astimezone(zone)
return quiet(lt, str(p.get("quiet_from", "22:00")), str(p.get("quiet_to", "07:00")))
# -- solve -------------------------------------------------------------
def solve(self, time_limit: float):
@@ -1026,11 +1189,23 @@ class Model:
if k == "battery":
self.battery(d)
elif k in ("heating", "cooling"):
def gains(t, room=d["id"]):
t0_room = (d.get("state") or {}).get("temp_c")
def gains(t, room=d["id"], t0_room=t0_room):
# (W per unit open, the cover's position), or (W, None): a fixed gain
out = []
for cid, (kind, v) in self.devices.items():
if kind == "cover" and v and v["room"] == room:
out.append((v["gain_w"] * v.get("sun", s["sun"])[t], v["pos"][t]))
w = v.get("window")
if w:
# G3: the sun through the window after the cover (a closed one keeps its
# shade_factor out), a closed shutter's lower loss (h_sh x (the room now - outside))
sun = w["sun_w"][t] if t < len(w["sun_w"]) else 0.0
dk = max(0.0, float(t0_room) - s["t_out"][t]) if t0_room is not None else 0.0
out.append((sun * w["shade_factor"] - w["h_sh"] * dk, v["pos"][t]))
out.append((sun * (1.0 - w["shade_factor"]) + w["h_sh"] * dk, None))
else:
out.append((v["gain_w"] * v.get("sun", s["sun"])[t], v["pos"][t]))
return out
self.room(d, k == "cooling", gains)
elif k == "ev":
@@ -1056,6 +1231,35 @@ class Model:
return self.h.modelStatusToString(status)
def rc2_discrete(z: dict, dt: float) -> tuple[list, list]:
"""The 2R2C's exact discrete form over dt hours (methods.md B17.4):
x = [air, mass], u = [T_out (°C), heat into the air (kW)];
A = [[-1/(R_i C_a), 1/(R_i C_a)], [1/(R_i C_m), -(1/R_i + 1/R_e)/C_m]],
B = [[0, 1/C_a], [1/(R_e C_m), 0]]; Ad = exp(A dt), Bd = A^-1 (Ad - I) B.
A's eigenvalues are real, negative and distinct (an RC network), so
exp by its eigen-decomposition. (Ad, Bd) as nested lists."""
ri, re_, ca, cm = float(z["r_i"]), float(z["r_e"]), float(z["c_a"]), float(z["c_m"])
a11, a12 = -1.0 / (ri * ca), 1.0 / (ri * ca)
a21, a22 = 1.0 / (ri * cm), -(1.0 / ri + 1.0 / re_) / cm
tr, det = a11 + a22, a11 * a22 - a12 * a21
disc = math.sqrt(max(tr * tr / 4.0 - det, 0.0))
l1, l2 = tr / 2.0 + disc, tr / 2.0 - disc
e1, e2 = math.exp(l1 * dt), math.exp(l2 * dt)
if abs(l1 - l2) < 1e-12:
f0, f1 = e1 * (1 - l1 * dt), e1 * dt # repeated root: exp(A dt) = e (I + (A - l I) dt)
else:
f1 = (e1 - e2) / (l1 - l2) # Sylvester: exp(A dt) = f0 I + f1 A
f0 = (l1 * e2 - l2 * e1) / (l1 - l2)
ad = [[f0 + f1 * a11, f1 * a12], [f1 * a21, f0 + f1 * a22]]
# A^-1 (Ad - I)
inv = [[a22 / det, -a12 / det], [-a21 / det, a11 / det]]
m = [[ad[0][0] - 1.0, ad[0][1]], [ad[1][0], ad[1][1] - 1.0]]
g = [[inv[i][0] * m[0][j] + inv[i][1] * m[1][j] for j in range(2)] for i in range(2)]
b = [[0.0, 1.0 / ca], [1.0 / (re_ * cm), 0.0]]
bd = [[g[i][0] * b[0][j] + g[i][1] * b[1][j] for j in range(2)] for i in range(2)]
return ad, bd
# -- heat: what is demanded, and what a source's heat costs (docs/methods.md A2.16, E6) -------
# Two clean halves, so a store can later sit between them (backlog 329: the
# hot-water tank, demand -> tank -> heater): heat_demand says what heat a
@@ -1323,7 +1527,17 @@ def plan(s: dict, time_limit: float = 30.0) -> dict:
out["battery_end"] = {"value_ct": round(v_ct, 2), "store_eur": round(sum(
v_ct / 100.0 * (x(b["soc"][-1]) - b["soc0"]) / 1000.0 for b in bats), 2)}
# the wear on every kWh discharged (the owner's battery algorithm, 2026-11-12) and where it came from
out["battery_wear"] = getattr(m, "wear_used", {})
# the wear's EUR over the horizon per battery: a cost of the plan's own, NOT in cost_eur nor baseline_eur (both
# are the energy bought and sold; the baseline has no battery): the saving baseline − cost stays on one basis,
# the wear apart beside it
wear = {}
for bid, w in (getattr(m, "wear_used", {}) or {}).items():
v = m.devices.get(bid, (None, None))[1]
kwh = sum(x(d) for d in v["dis"]) * m.dt / 1000.0 if v else 0.0
wear[bid] = {**w, "kwh": round(kwh, 3), "eur": round(kwh * w["ct"] / 100.0, 3)}
out["battery_wear"] = wear
# the plan's window and discharge power per battery (the Parameters rows, A2.3a)
out["battery_window"] = getattr(m, "window_used", {})
if parts is not None:
out["cost_parts"] = parts # cost_eur by carrier, the heat outlook a fixed term of its own
if outlook is not None:
@@ -1430,6 +1644,21 @@ def pref_feedback(s, m, x) -> list[dict]:
out.append(f)
elif kind == "ev":
out.append(_ev_feedback(s, d, pref, v, x, m))
elif kind == "dhw_tank" and v:
# the owner's hot-water times (107): the tank's least planned temperature in each block
for gi, g in enumerate(pref["groups"]):
ts = [t for t in range(T) if pref["group"][t] == gi]
f = {"control": d["id"], "group": g["group"], "kind": "dhw_tank", "how": g["how"], "label": g["text"]}
if not ts:
out.append(dict(f, met=None, detail="not in the next 48 h"))
continue
temps = [tank_temp(v, t, x) for t in ts]
worst = min(range(len(ts)), key=lambda k: temps[k])
met = temps[worst] >= g["c"] - TOL_K
f.update(met=met, min_c=round(min(temps), 1))
if not met:
f["detail"] = f"{temps[worst]:.0f} °C at {_when(s, start + (ts[worst] + 1) * step)}"
out.append(f)
return out
@@ -1536,7 +1765,7 @@ def pref_costs(s, energy: float, deadline: float) -> dict:
n = 0
for i, d in enumerate(s["devices"]):
pref = d.get("pref")
if not pref or d["kind"] not in ("heating", "cooling", "battery"):
if not pref or d["kind"] not in ("heating", "cooling", "battery", "dhw_tank"):
continue
for gi, g in enumerate(pref["groups"]):
if g["how"] != "must" or gi not in pref["group"]:
@@ -1774,6 +2003,9 @@ def shift_envelope(m, x) -> dict | None:
"soc_wh": round(v["soc0"]), "lo_wh": [round(v["floors"][t] / 100.0 * v["cap"]) for t in range(n)],
"max_wh": round(v["hi_wh"]), "cap_wh": round(v["cap"]),
"ch_w": round(v["max_ch"]), "dis_w": round(v["max_dis"]),
# where the discharge power came from (mapping | device | owner | ratio: the
# Parameters row on the one rated power), so the building takes it as the box's
"dis_src": ((src.get("battery") or {}).get(d["id"]) or {}).get("max_discharge_w"),
"eta": round(v["eff"], 4), "end_wh": round(_x(x, v["soc"][n - 1])),
# its idle loss (S.2) and where it came from, for the building's own plan (C2.7)
"standby_w": round(v.get("p0", 0.0), 1), "loss_pct_h": round(v.get("lam_h", 0.0) * 100.0, 6),
@@ -1805,11 +2037,11 @@ def shift_envelope(m, x) -> dict | None:
continue # an on/off boiler: all or nothing, not a band of power
if v.get("src", "electric") not in ("electric", "heat_pump"):
continue # gas, district heat or a hybrid's choice: no electricity to shift as planned
if rooms.get(d["id"]) not in ("mapping", "model", "box model") or \
cops.get(d["id"]) not in ("mapping", "electric fit", "electric heater") or v["wh_per_k"] <= 0:
if rooms.get(d["id"]) not in ("mapping", "model", "box model", "zone 2r2c") or \
cops.get(d["id"]) not in ("mapping", "electric fit", "electric heater", "zone fit") or v["wh_per_k"] <= 0:
continue # no fit or no COP: the heat it can hold is not known
if not d.get("pref") and bands.get(d["id"]) != "mapping":
continue # no band of the owner's
if not d.get("pref") and bands.get(d["id"]) != "mapping" and not str(bands.get(d["id"]) or "").startswith("en16798"):
continue # no band of the owner's (or EN 16798-1's, G5)
p = [_x(x, v["power"][t]) for t in range(n)]
temps = [_x(x, v["temp"][t]) for t in range(n)]
k, sign = v["wh_per_k"], (-1.0 if kind == "cooling" else 1.0)
@@ -1860,7 +2092,7 @@ def _charge_why(pi, t) -> str:
def _key(e) -> tuple:
"""What makes a plan entry a change: a battery's self-consumption is one
state whatever its power (it follows the house); a hybrid's source."""
return ("auto",) if e.get("auto") else (e["set"], e.get("grid"), e.get("source"))
return ("auto",) if e.get("auto") else (e["set"], e.get("grid"), e.get("source"), e.get("dhw_comfort"))
def boiler_fuel(p: dict) -> str:
@@ -2014,67 +2246,86 @@ def _entry(d, kind, v, t, x, s, pi, grid_w=(1e9, 1e9)):
"self-consumption: PV surplus into the battery"}
return {"set": net, "grid": grid, "why": why}
if kind in ("heating", "cooling"):
temp = x(v["temp"][t])
pw = _inputs_w(v, t, x)
src = v.get("src", "electric")
# the price that buys the heat now, for the words
fuel = v.get("fuel") or "gas"
pr = {"boiler": s.get("price_" + fuel), "district": s.get("price_heat")}.get(src) or pi
pr_t = pr[t] if t < len(pr) else None
source = None
if src == "hybrid":
hp_w, gas_w = x(v["power"][t]), x(v["gas"][t])
source = "heat_pump" if hp_w >= gas_w and hp_w > 50 else "boiler" if gas_w > 50 else None
if source == "boiler":
pr_t = (s.get("price_" + fuel) or [None] * (t + 1))[t]
ahead = s["occupied"][min(t + 4, s["steps"] - 1)]
pref = d.get("pref")
if pref:
# a schedule: "someone home" is a target above the setback ahead
# (below the setup, cooling); its target in place of comfort/setback
sign = -1 if kind == "cooling" else 1
tg, k0 = pref["target"], max(t - 1, 0)
occ = sign * (tg[k0] - pref["base"][k0]) > 0
ahead = any(sign * (tg[k] - tg[k0]) > 0 for k in range(t, min(t + 4, len(tg))))
if kind == "heating" and v["switched"] and src != "hybrid":
on = pw > 0.5 * v["pmax"]
why = ("pre-heat before someone is home" if on and not occ and ahead else
"keep the room warm" if on else "off: warm enough or away")
return {"set": "on" if on else "off", "why": why}
# the room may dip below a floor in the model (soft, so there is always
# a plan), but a setpoint never asks for it: clamped into the bounds
# (the guard would refuse it; the sim's run showed 19.5 under a 20 floor)
lo, hi = d["bounds"]["temp_c"][0], d["bounds"]["temp_c"][1]
target = min(max(_round(temp, 0.5), math.ceil(lo * 2) / 2), math.floor(hi * 2) / 2)
if kind == "cooling":
if pw < 50:
return {"set": "off", "why": "off: cool enough or away"}
return {"set": target, "why": "pre-cool before someone is home" if not occ and ahead else "keep cool"}
if pw < 50:
# no heat planned: the thermostat at what the room must keep (the
# comfort or setback target in the bounds), not at the room's
# predicted temperature, which a thermostat holds by heating; the
# room never cooled as planned, every next plan started from it
# again (a replay of a munich-1 day: kept at 24 °C all evening)
occ1 = s["occupied"][min(t + 1, s["steps"] - 1)]
p = d["params"]
want = float(p["comfort_c"]) if occ1 else float(p["setback_c"])
if pref:
want = float(pref["target"][t])
if pref["must"][t] is not None:
want = max(want, float(pref["must"][t]))
floor_t = min(max(math.floor(want * 2) / 2, math.ceil(lo * 2) / 2), math.floor(hi * 2) / 2)
return {"set": min(target, floor_t), "why": "setback: away or night" if not occ else "warm enough"}
what = {"boiler": "heating oil" if fuel == "oil" else "gas", "district": "heat"}.get(
src if src != "hybrid" else (source or ""), "power")
e = {"set": target, "why": f"pre-heat while {what} is cheap ({pr_t:.1f} ct)"
if not occ and ahead and pr_t is not None else "keep the room warm"}
if source:
e["source"] = source
e["why"] += "; " + ("the heat pump: its heat is cheaper now" if source == "heat_pump" else "the boiler: its heat is cheaper now")
e = _room_entry(d, kind, v, t, x, s, pi)
cc = d.get("dhw_comfort")
if e is not None and cc and t < len(cc):
# a combi boiler's comfort mode (G7): on while someone is home and awake, else off
e["dhw_comfort"] = "on" if cc[t] else "off"
return e
if kind == "dhw_tank":
return _tank_entry(d, v, t, x, s, pi)
return _entry_rest(d, kind, v, t, x, s, pi)
def _room_entry(d, kind, v, t, x, s, pi):
"""_entry for a heating or cooling room (its setpoint, a switched boiler's on/off, a hybrid's source)."""
occ = s["occupied"][t]
temp = x(v["temp"][t])
pw = _inputs_w(v, t, x)
src = v.get("src", "electric")
# the price that buys the heat now, for the words
fuel = v.get("fuel") or "gas"
pr = {"boiler": s.get("price_" + fuel), "district": s.get("price_heat")}.get(src) or pi
pr_t = pr[t] if t < len(pr) else None
source = None
if src == "hybrid":
hp_w, gas_w = x(v["power"][t]), x(v["gas"][t])
source = "heat_pump" if hp_w >= gas_w and hp_w > 50 else "boiler" if gas_w > 50 else None
if source == "boiler":
pr_t = (s.get("price_" + fuel) or [None] * (t + 1))[t]
ahead = s["occupied"][min(t + 4, s["steps"] - 1)]
pref = d.get("pref")
if pref:
# a schedule: "someone home" is a target above the setback ahead
# (below the setup, cooling); its target in place of comfort/setback
sign = -1 if kind == "cooling" else 1
tg, k0 = pref["target"], max(t - 1, 0)
occ = sign * (tg[k0] - pref["base"][k0]) > 0
ahead = any(sign * (tg[k] - tg[k0]) > 0 for k in range(t, min(t + 4, len(tg))))
if kind == "heating" and v["switched"] and src != "hybrid":
on = pw > 0.5 * v["pmax"]
why = ("pre-heat before someone is home" if on and not occ and ahead else
"keep the room warm" if on else "off: warm enough or away")
return {"set": "on" if on else "off", "why": why}
# the room may dip below a floor in the model (soft, so there is always
# a plan), but a setpoint never asks for it: clamped into the bounds
# (the guard would refuse it; the sim's run showed 19.5 under a 20 floor)
lo, hi = d["bounds"]["temp_c"][0], d["bounds"]["temp_c"][1]
target = min(max(_round(temp, 0.5), math.ceil(lo * 2) / 2), math.floor(hi * 2) / 2)
if kind == "cooling":
if pw < 50:
return {"set": "off", "why": "off: cool enough or away"}
return {"set": target, "why": "pre-cool before someone is home" if not occ and ahead else "keep cool"}
if pw < 50:
# no heat planned: the thermostat at what the room must keep (the
# comfort or setback target in the bounds), not at the room's
# predicted temperature, which a thermostat holds by heating; the
# room never cooled as planned, every next plan started from it
# again (a replay of a munich-1 day: kept at 24 °C all evening)
occ1 = s["occupied"][min(t + 1, s["steps"] - 1)]
p = d["params"]
want = float(p["comfort_c"]) if occ1 else float(p["setback_c"])
if v.get("banded") and t < len(v.get("targets") or []):
want = float(v["targets"][t]) # the band's edge or the setback (G5)
occ = bool(v["occ"][t])
if pref:
want = float(pref["target"][t])
if pref["must"][t] is not None:
want = max(want, float(pref["must"][t]))
floor_t = min(max(math.floor(want * 2) / 2, math.ceil(lo * 2) / 2), math.floor(hi * 2) / 2)
return {"set": min(target, floor_t), "why": "setback: away or night" if not occ else "warm enough"}
what = {"boiler": "heating oil" if fuel == "oil" else "gas", "district": "heat"}.get(
src if src != "hybrid" else (source or ""), "power")
e = {"set": target, "why": f"pre-heat while {what} is cheap ({pr_t:.1f} ct)"
if not occ and ahead and pr_t is not None else "keep the room warm"}
if source:
e["source"] = source
e["why"] += "; " + ("the heat pump: its heat is cheaper now" if source == "heat_pump" else "the boiler: its heat is cheaper now")
return e
def _entry_rest(d, kind, v, t, x, s, pi):
"""_entry for an EV and a cover."""
if kind == "ev":
if v.get("expected"):
return None # not plugged in: a forecast load, no command (inputs.ev_session)
@@ -2098,6 +2349,24 @@ def _entry(d, kind, v, t, x, s, pi, grid_w=(1e9, 1e9)):
rule = (sch.get("rule") or [""] * (t + 1))[t]
# the rule it moves for: the executor keeps it for the next plans (shades.Moves)
return {"set": sch["set"][t], "why": sch["why"][t], **({"rule": rule} if rule else {})}
if kind == "cover" and v.get("window"):
# G3: placed by the plan on its window's sun and loss
w = v["window"]
pos = _round(100 * x(v["pos"][t]), 10.0)
if t < w["hold_steps"]:
return {"set": None, "why": "moved by hand: kept"}
sun = w["sun_w"][t] if t < len(w["sun_w"]) else 0.0
if pos < 100 and sun > 50:
why = "shade: keep the sun's heat out"
elif sun > 50:
why = "open: the sun's heat in"
elif pos < 100 and w["h_sh"] > 0:
why = "closed: keep the heat in"
elif pos < 100:
why = "closed"
else:
why = "open"
return {"set": pos, "why": why}
if kind == "cover":
pos = _round(100 * x(v["pos"][t]), 10.0)
sun = s["sun"][t]