diff --git a/README.md b/README.md index 40a7122..f4b248a 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Settings → Add-ons → Add-on store → ⋮ → Repositories, add `https://git.setti.solutions/Daniel/cantabile-ha-addons`, then install the add-on. The Supervisor pulls the prebuilt images (`git.setti.solutions/daniel/cantabile-ha--:`, -named by `image:` in each `config.yaml`); this version: `0.1.1919`, arch amd64. +named by `image:` in each `config.yaml`); this version: `0.1.2019`, arch amd64. ## Layout diff --git a/cantabile_edge/config.yaml b/cantabile_edge/config.yaml index 43c7148..c2d9f91 100644 --- a/cantabile_edge/config.yaml +++ b/cantabile_edge/config.yaml @@ -3,7 +3,7 @@ # the Hub's, wrapped by addon-run (Dockerfile). The image is prebuilt, # per arch (README.md: building it from src/). name: Cantabile Edge Agent -version: "0.1.1919" +version: "0.1.2019" slug: cantabile_edge description: Plans your home's energy with Cantabile and, with your consent, runs the devices you choose. url: https://cantabile.cloud diff --git a/cantabile_eebus/config.yaml b/cantabile_eebus/config.yaml index d96bd49..f43b787 100644 --- a/cantabile_eebus/config.yaml +++ b/cantabile_eebus/config.yaml @@ -4,7 +4,7 @@ # Assistant that isn't a Cantabile Hub. Devices are paired on its page # (ingress), by their SKI. name: Cantabile EEBUS -version: "0.1.1919" +version: "0.1.2019" slug: cantabile_eebus description: Pairs with EEBUS devices (the grid operator's control box, heat pumps, wallboxes, inverters), shows them in Home Assistant under Cantabile's names and hands the grid operator's §14a limit to the Cantabile agent; every control with its protection. url: https://cantabile.cloud diff --git a/cantabile_modbus/config.yaml b/cantabile_modbus/config.yaml index 83ccd82..71bf937 100644 --- a/cantabile_modbus/config.yaml +++ b/cantabile_modbus/config.yaml @@ -4,7 +4,7 @@ # Home Assistant that isn't a Cantabile Hub. Devices come from the options; # the page (ingress) shows them and each control's protection. name: Cantabile Modbus bridge -version: "0.1.1919" +version: "0.1.2019" slug: cantabile_modbus description: Reads inverters, meters, relays and circuits by Cantabile's device profiles (Modbus, or Home Assistant's own entities) and shows them in Home Assistant, each control with its protection. url: https://cantabile.cloud diff --git a/src/edge/cantabile_edge/battery_core.py b/src/edge/cantabile_edge/battery_core.py new file mode 100644 index 0000000..4f78125 --- /dev/null +++ b/src/edge/cantabile_edge/battery_core.py @@ -0,0 +1,510 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The building battery's one algorithm (the owner's of 2026-11-12; docs/methods.md D17). Pure: no database. + +One formulation of the battery, used by the tenant power plan (mieterstrom._optimise: Mieterstrom, GGV, §42c, the +48 h proposal whose dispatch is the battery's plan, C6.2), by the building plan without tenant power (core.plan, C2: +the same Block over 48 h, its floors per slot and refill_by) and by the battery ROI over a real year +(battery_roi: the same block and the same objective at the year's prices, in rolling 48 h horizons, plan()). The box +carries a byte-identical copy (edge cantabile_edge/battery_core.py: building/test_boxmodel.py checks it) for the +rules (window, discharge_kw) and the check of its own MILP against plan() (A2.3a). The owner's rules, each a term here: + +1. Forecast-driven: one optimisation over the horizon's forecasts (day-ahead prices, PV, loads); no time windows, + no fixed rules, no cycle limit: the optimiser decides when and how often to charge and discharge. +2. Charging: the PV surplus always; PV while the loads could use it (the time shift) only up to a share of each + slot's PV (Parameters battery.pv_share_pct, per building) and only where it pays; grid kWh only for GGV and §42c, + never Mieterstrom (law; mieterstrom.charging_mode), and only where they pay: a grid kWh bought at b and sold at + v later earns v − b/η − wear, the objective's own terms, so the optimiser buys none where that is ≤ 0. +3. Either side's prices vary the value: the discharge is valued at each slot's own price (the tenants' rule price + per slot, the residual or the site's own purchase per slot), the grid kWh at the site's own purchase per slot; + nothing assumes a flat price. +4. Wear (Parameters battery.wear_ct, per kWh cycled) on every kWh discharged, whatever it serves; the idle loss + (standby P⁰ and self-discharge λ, design storage-losses.md S.2) in the charge balance; what of it the grid supplies + (the BMS's valves) is money in plan() at the slot's purchase. +5. The window: the floor (the battery's own minimum, its box's published floor, and the building's reserve + battery.plan_reserve_pct) and the top (the battery's maximum and battery.plan_max_soc_pct); the charge and the + discharge each at their own power (the battery's facts; where they give one power, the discharge at + battery.discharge_ratio_pct of it). +6. The discharge serves every load in one objective (the flats or members, the plant's own use: common areas, the + building heat pump), each at its own value; no fixed priority. No battery feed-in where grid kWh may be in it. +7. Grid orders: a binding limit on the import is a constraint of the plan (the caller's import-limit row; the + battery's grid kWh count on it, and none are bought while a §14a order dims): it overrides the prices and may + force a discharge. +8. A flat's own battery (and a house's) is its box's (edge optimizer, for the household's money, with the same rules: + wear, reserve and top, the discharge power; not the PV share, a building's concept); the plan sees it in the + flat's published plan (its import after its own battery) and the building battery never charges it (the caller's + caps). +""" +from __future__ import annotations + +import math +from dataclasses import dataclass, field +from typing import Callable + +INF = math.inf +RESERVE_EUR_KWH = 1.0 # engineering-parameters.md: per kWh under the battery's floor and slot when it starts below it (C6.5) +STANDBY_GRID_EUR_KWH = 1.0 # the idle loss's valves: no money (the BMS draws its idle loss directly) +VALVE_UNDER = 1e-3 # ENG: with grid kWh the valves sit this share below the horizon's cheapest grid kWh (a tie-break, not money) +END_GRID_GAP = 1e-3 # ENG: the grid pool's end value this share below the horizon's cheapest grid kWh (never bought to keep) + + +# The Parameters page's suggested values of the battery rows (fleet migrations-parameters.sql; test_boxmodel checks +# they match). Used only where a row did not arrive (the owner, 2026-11-12: "fall back to suggested, with alarm"): +# the plan goes on with these and the missing row is reported as a data gap naming it. +SUGGESTED_ROWS = {"battery.wear_ct": 3.0, "battery.pv_share_pct": 50.0, "battery.discharge_ratio_pct": 65.0, + "battery.plan_reserve_pct": 10.0, "battery.plan_max_soc_pct": 95.0} + + +def suggested_gap(missing: list) -> dict: + """The data gap for rows planned with their suggested values: why, missing, where.""" + vals = ", ".join(f"{k} {SUGGESTED_ROWS[k]:g}" for k in missing) + return {"why": "Parameters " + ("rows" if len(missing) > 1 else "row") + " missing: planned with the suggested " + + ("values " if len(missing) > 1 else "value ") + vals, + "missing": list(missing), "where": "the admin Parameters page (Battery)", "fallback": "suggested"} + +# ---- the owner's rows: the battery's window and powers ------------------------------------------------------------ + +def pv_share(pct) -> float | None: + """The time shift's cap as a share of each slot's PV (battery.pv_share_pct, %); None where not resolved (no cap: + the tests' old model).""" + if pct is None or (isinstance(pct, float) and math.isnan(pct)): + return None + return min(max(float(pct), 0.0), 100.0) / 100.0 + + +def discharge_kw(charge_kw: float, discharge: float | None, ratio_pct) -> float: + """The battery's discharge power (kW): its own fact where known, else ratio_pct (battery.discharge_ratio_pct) of + its one rated power; without the row, that power both ways (a fact of the battery, not a guess).""" + if discharge is not None and discharge > 0: + return float(discharge) + if ratio_pct is None or (isinstance(ratio_pct, float) and math.isnan(ratio_pct)): + return charge_kw + return charge_kw * min(max(float(ratio_pct), 1.0), 400.0) / 100.0 + + +def window(min_pct: float, max_pct: float, reserve_pct=None, top_pct=None) -> tuple[float, float]: + """The plan's charge window (% of capacity): the battery's own [min, max] narrowed by the building's reserve + (battery.plan_reserve_pct: the floor at least it) and top (battery.plan_max_soc_pct: the top at most it); never + an empty window (a top under the floor keeps the floor).""" + lo, hi = float(min_pct), float(max_pct) + if reserve_pct is not None and not (isinstance(reserve_pct, float) and math.isnan(reserve_pct)): + lo = max(lo, float(reserve_pct)) + if top_pct is not None and not (isinstance(top_pct, float) and math.isnan(top_pct)): + hi = min(hi, float(top_pct)) + return lo, max(lo, hi) + + +# ---- the battery's columns and rows in one model -------------------------------------------------------------------- + +@dataclass +class Block: + """The battery in an LP/MILP (HiGHS columns through the caller's add/row): its charge from the PV (CH; the part + beyond the surplus CT, the time shift, at most pv_share of the slot's PV), its discharges (DI to the loads the + caller balances, DO to the plant's own use, XB fed in where no grid kWh may be in it), the grid pool (CQ charged at + the site's purchase, Q its charge, DQ to the loads, DOq to the own use), the charge E, the idle loss (LB from the + cells, LG/LBq/LQ the BMS's valves: no money), the reserve's shortfall UF (a start under the floor), and the end + values. add(lb, ub, eur) -> column (eur: the owner's money per unit, maximised); row(lb, ub, cols, vals).""" + add: Callable + row: Callable + bat: object # mieterstrom.Battery (kwh, kw, dis_kw, efficiency, lo, hi, start, wear_ct, idle loss) + n: int + pv: list # the PV per slot (kWh) + room: list # the PV the loads leave per slot (kWh; ≤ 0: none): the surplus + surplus_only: bool = False # "surplus": the PV's pool takes only the surplus (no time shift) + share: float | None = None # the time shift's cap (share of the slot's PV); None: no cap + shift: bool = True # the time shift's columns (CT) and rows: where the PV may be stored beyond the surplus + charge_eur: float = 0.0 # per PV kWh charged (Mieterstrom: −Zuschlag, the caller counts it on all PV) + grid_eur: list | None = None # per grid kWh charged, per slot (−purchase); None: no grid kWh + grid_blocked: list | None = None # per slot: a §14a order dims (no grid kWh) + grey_to_loads: bool = True # the grid pool may serve the loads (GGV, §42c); else only the own use + feed_eur: list | None = None # per kWh of the battery's PV fed in, per slot (feed-in − wear − unpaid); None: none + feed_cap: float = INF + own_load: list | None = None # the plant's own use per slot (kWh); None: none modelled + own_eur: list | None = None # its purchase price per slot (€/kWh): what a kWh from the battery saves there + end_eur: float = 0.0 # a kWh left at the end (€/kWh, D5.17) + green_start: float | None = None # the start's PV part with a grid pool (None: all of it) + valve: Callable = None # the valves' price (base €/kWh -> €/kWh) + idle_eur: list | None = None # per slot: what a kWh of idle loss from the grid costs (€/kWh, the purchase): + # the valves' price in the objective instead of valve's tie-break; None: valve (no money) + floor: list | None = None # the floor per slot (kWh; the box's per step, C2); None: the battery's lo in every slot + refill_by: int | None = None # a start under the floor back at it from this slot on, refilled where the plan finds it + # cheapest (the building plan's C6.5); None: the reserve's penalty (UF), the proposal's + exclusive: bool = True # charge or discharge in a slot, not both: a binary per slot (Z; the caller makes them + # integer: integers()). Without it an LP may pass PV through the battery in one slot + # (found 2026-11-12 on a GGV test building: PV charged and the plant's own use served from the + # battery at once in 50 quarter-hours, around the flats-first bound of the PV to the own use) + CH: list = field(default_factory=list) + DI: list = field(default_factory=list) + CT: list = field(default_factory=list) + E: list = field(default_factory=list) + XB: list = field(default_factory=list) + DO: list = field(default_factory=list) + CQ: list = field(default_factory=list) + Q: list = field(default_factory=list) + DQ: list = field(default_factory=list) + DOq: list = field(default_factory=list) + UF: list = field(default_factory=list) + LB: list = field(default_factory=list) + LG: list = field(default_factory=list) + LBq: list = field(default_factory=list) + LQ: list = field(default_factory=list) + Z: list = field(default_factory=list) # 1: the slot may charge, 0: discharge (exclusive) + lo: dict = field(default_factory=dict) # column -> a new lower bound (the caller applies: set_bounds) + hi: dict = field(default_factory=dict) + const_eur: float = 0.0 # the start's charge at the end value (taken off: the gain counts the change) + + def __post_init__(self): + b, n, add = self.bat, self.n, self.add + self.pch, self.pdis = charge_slot_kwh(b), discharge_slot_kwh(b) + self.ec = math.sqrt(b.efficiency) + wear = b.wear_ct / 100 + valve = self.valve or (lambda base: base) + grid = self.grid_eur is not None + pch, pdis = self.pch, self.pdis + self.CH = [add(0, min(pch, max(0.0, self.room[t])) if self.surplus_only else pch, self.charge_eur) for t in range(n)] + self.DI = [add(0, pdis, -wear) for t in range(n)] + if self.shift and not self.surplus_only: + # the time shift (CT_t ≥ CH_t − room⁺_t): at most the share of the slot's PV, and what it stores comes out again + cap = [pch if self.share is None else min(pch, self.share * max(0.0, self.pv[t])) for t in range(n)] + self.CT = [add(0, cap[t]) for t in range(n)] + self.E = [add(self.base_lo(t), b.hi) for t in range(n)] + if self.feed_eur is not None and not grid: + self.XB = [add(0, min(pdis, self.feed_cap), self.feed_eur[t]) for t in range(n)] + has_own = self.own_load is not None and self.own_eur is not None + if has_own: + self.DO = [add(0, min(pdis, self.own_load[t]), self.own_eur[t] - wear) for t in range(n)] + if grid: + dims = self.grid_blocked or [] + self.CQ = [add(0, 0.0 if t < len(dims) and dims[t] else pch, self.grid_eur[t]) for t in range(n)] + self.Q = [add(0, b.hi) for t in range(n)] + if self.grey_to_loads: + self.DQ = [add(0, pdis, -wear) for t in range(n)] + if has_own: + self.DOq = [add(0, min(pdis, self.own_load[t]), self.own_eur[t] - wear) for t in range(n)] + for t in range(n): # E is the PV's part now: the floor and the top hold for both together (soc_row) + self.lo[self.E[t]] = 0.0 + if self.below(): + # a start below the floor (C6.5): the charge may sit between the start (less its loss) and the floor, each kWh + # under the floor and slot at RESERVE_EUR_KWH (no money): refilled at the first PV the plant can spare (from + # the grid at once where grid kWh are allowed: a real cost, as a hybrid inverter's forced charge); with + # refill_by (the building plan) back at the floor from that slot on, wherever the plan finds it cheapest + if not grid: + for t in range(n): + self.lo[self.E[t]] = self.floor_at(t) + if self.refill_by is None: + self.UF = [add(0, self.base_lo(t), -RESERVE_EUR_KWH) for t in range(n)] + self.p0, self.phi = b.standby_kwh(), b.phi() + if self.p0 > 0: + self.LB = [add(0, self.p0) for t in range(n)] + self.LG = [add(0, self.p0, -self.valve_eur(t, valve)) for t in range(n)] + if grid: + self.LBq = [add(0, self.p0) for t in range(n)] + if self.phi < 1.0: + # the self-discharge at the floor where nothing can charge (night): the BMS holds the floor, the same valve + self.LQ = [add(0, (1.0 - self.phi) * b.hi, -self.valve_eur(t, valve)) for t in range(n)] + self.g0 = b.start + if self.exclusive: + self.Z = [add(0, 1) for t in range(n)] + if self.Q: # the start's PV part where known, else none of it (never shared as PV): D5.19 + self.g0 = min(b.start, max(0.0, self.green_start or 0.0)) + + def valve_eur(self, t: int, valve: Callable) -> float: + """The valves' price in slot t (€/kWh): the purchase where given (idle_eur: real money, plan() counts it), else + the tie-break (valve: no money).""" + if self.idle_eur is not None: + return max(0.0, self.idle_eur[min(t, len(self.idle_eur) - 1)]) + return valve(STANDBY_GRID_EUR_KWH) + + def base_lo(self, t: int) -> float: + """The floor in slot t (kWh): the caller's per slot, else the battery's own; never above its top.""" + if self.floor: + return min(float(self.floor[min(t, len(self.floor) - 1)]), self.bat.hi) + return self.bat.lo + + def below(self) -> bool: + """The start below the first slot's floor (C6.5).""" + return self.base_lo(0) - self.bat.start > 1e-9 + + def floor_at(self, t: int) -> float: + """The charge's lower bound in slot t: the floor; a start below it may stay under it (never under the start less + its loss), with refill_by only before that slot.""" + f = self.base_lo(t) + if self.below() and (self.refill_by is None or t < self.refill_by): + return min(f, self.bat.start * self.bat.phi() ** (t + 1)) + return f + + # the end value (the caller sets the columns' money: add() took 0 for E and Q) + def end_values(self, cheapest_grid_eur: float | None = None) -> dict[int, float]: + """{column: €/kWh} for the last charge of each pool: the end value; the grid pool's never at or above the + horizon's cheapest grid kWh (no grid kWh is bought only to be kept). const_eur: the start at the same rate.""" + out = {} + if not self.n: + return out + out[self.E[-1]] = self.end_eur + if self.Q: + v = self.end_eur + if cheapest_grid_eur is not None: + v = min(v, max(0.0, cheapest_grid_eur) * (1 - END_GRID_GAP)) + out[self.Q[-1]] = v + self.const_eur = -self.end_eur * self.bat.start + return out + + def outs(self, t: int) -> list[int]: + """Every discharge column of slot t (to the loads, the own use, the feed-in).""" + return [cs[t] for cs in (self.DI, self.DQ, self.DO, self.DOq, self.XB) if cs] + + def all_outs(self) -> list[int]: + return [c for cs in (self.DI, self.DQ, self.DO, self.DOq, self.XB) for c in cs] + + def soc_row(self, t: int): + """The charge (S.2): e_t − φ e_{t−1} − ηc·charge + discharge/ηd + ℓᵇ_t = 0 (e_{−1} the start), ℓᵇ + ℓᵍ = P⁰. + With grid kWh (D5.19) two pools, the PV's e and the grid's q, each with its own charge, discharge and loss, + their sum within the floor and the top; the charges together at most the charge power, the discharges at + most the discharge power.""" + b, row, ec, phi = self.bat, self.row, self.ec, self.phi + c2, v2, rhs = [self.E[t], self.CH[t], self.DI[t]], [1.0, -ec, 1.0 / ec], 0.0 + for cs in (self.DO, self.XB): + if cs: + c2.append(cs[t]) + v2.append(1.0 / ec) + if t > 0: + c2.append(self.E[t - 1]) + v2.append(-phi) + else: + rhs = phi * self.g0 + if self.LB: + c2.append(self.LB[t]) + v2.append(1.0) + row(self.p0, self.p0, [self.LB[t], self.LG[t]] + ([self.LBq[t]] if self.LBq else []), + [1.0, 1.0] + ([1.0] if self.LBq else [])) + if self.LQ and not self.Q: + c2.append(self.LQ[t]) + v2.append(-1.0) + row(rhs, rhs, c2, v2) + if self.Q: + c3, v3 = [self.Q[t], self.CQ[t]], [1.0, -ec] + for cs in (self.DQ, self.DOq): + if cs: + c3.append(cs[t]) + v3.append(1.0 / ec) + rq = 0.0 + if t > 0: + c3.append(self.Q[t - 1]) + v3.append(-phi) + else: + rq = phi * (b.start - self.g0) + if self.LBq: + c3.append(self.LBq[t]) + v3.append(1.0) + if self.LQ: + c3.append(self.LQ[t]) + v3.append(-1.0) + row(rq, rq, c3, v3) + row(self.floor_at(t), b.hi, [self.E[t], self.Q[t]], [1.0, 1.0]) + row(-INF, self.pch, [self.CH[t], self.CQ[t]], [1.0, 1.0]) + outs = self.outs(t) + if len(outs) > 1: + row(-INF, self.pdis, outs, [1.0] * len(outs)) + if self.Z: + # charge or discharge, not both: Σ charge ≤ P^ch z, Σ discharge ≤ P^dis (1 − z) + ins = [self.CH[t]] + ([self.CQ[t]] if self.CQ else []) + row(-INF, 0.0, ins + [self.Z[t]], [1.0] * len(ins) + [-self.pch]) + row(-INF, self.pdis, outs + [self.Z[t]], [1.0] * len(outs) + [self.pdis]) + + def idle_grid(self, x: list, t: int) -> float: + """The idle loss the grid supplies in slot t (kWh, the valves LG and LQ: the standby and the self-discharge the + BMS draws while the cells are at the floor), from a solution x. plan() counts it at the slot's purchase, and prices the valves at it in the objective too (idle_eur), so the dispatch avoids what it costs.""" + return sum(max(0.0, x[cs[t]]) for cs in (self.LG, self.LQ) if cs) + + def integers(self) -> list[int]: + """The columns the caller makes integer (the exclusivity's binaries).""" + return list(self.Z) + + def reserve_rows(self): + """Under the floor (C6.5): E_t (+ Q_t) + UF_t ≥ the floor.""" + for t, u in enumerate(self.UF): + self.row(self.base_lo(t), INF, [self.E[t], u] + ([self.Q[t]] if self.Q else []), [1.0, 1.0] + ([1.0] if self.Q else [])) + + def shift_rows(self): + """The time shift's charge (beyond the surplus) comes out again: CT_t ≥ CH_t − room⁺_t, η ΣCT ≤ Σ discharge (never + PV spent on the battery's own idle loss, which the floor's valves hold).""" + if not self.CT: + return + for t in range(self.n): + self.row(-max(0.0, self.room[t]), INF, [self.CT[t], self.CH[t]], [1.0, -1.0]) + outs = self.all_outs() + self.row(-INF, 0, self.CT + outs, [self.bat.efficiency] * self.n + [-1.0] * len(outs)) + + def feed_rows(self, EX: list[int], cap: float): + """The feed-in limit holds for the PV and the battery together.""" + if self.XB: + for t in range(self.n): + self.row(-INF, max(0.0, cap), [EX[t], self.XB[t]], [1.0, 1.0]) + + +def charge_slot_kwh(b, slot_h: float = 0.25) -> float: + """The charge power over one slot (kWh).""" + return max(0.0, b.kw) * getattr(b, "slot_h", slot_h) + + +def discharge_slot_kwh(b, slot_h: float = 0.25) -> float: + """The discharge power over one slot (kWh): its own where the battery has one, else the charge power's.""" + d = getattr(b, "dis_kw", None) + return max(0.0, d if d is not None and d > 0 else b.kw) * getattr(b, "slot_h", slot_h) + + +# ---- the same algorithm at fixed prices: one horizon (the ROI's, and a check of the plan's) --------------------------- + +@dataclass +class Horizon: + """One horizon's inputs at fixed prices per slot (kWh; ct net per kWh). value_ct: what a kWh delivered to the loads + (flats, members) from the PV or the battery earns the owner (GGV the rule's price net of VAT, §42c the same less + the service fee, Mieterstrom the residual it saves); direct_ct: extra on PV used directly (Mieterstrom: the + Zuschlag); own_ct: the plant's own use's purchase; feed_ct: the feed-in (0 at a §51 slot); grid_ct: a grid kWh + into the battery (None: none allowed); import_cap: the import limit per slot (None: none).""" + pv: list + load: list + value_ct: list + feed_ct: list + own: list | None = None + own_ct: list | None = None + direct_ct: list | None = None + grid_ct: list | None = None + import_cap: list | None = None + unpaid: list | None = None + buy_ct: list | None = None # the site's purchase per slot (ct): what a kWh the idle loss draws from the grid costs; + # None: grid_ct, else own_ct, else value_ct (Mieterstrom: the residual) + + +class Lp: + """A small column/row builder for HiGHS (maximising the owner's money).""" + + def __init__(self): + self.lb, self.ub, self.c = [], [], [] + self.rows: list[tuple[float, float, list[int], list[float]]] = [] + self.ints: list[int] = [] + + def add(self, lb: float, ub: float, eur: float = 0.0) -> int: + self.lb.append(lb), self.ub.append(ub), self.c.append(eur) + return len(self.c) - 1 + + def row(self, lb, ub, cols, vals): + self.rows.append((lb, ub, list(cols), list(vals))) + + def solve(self, lo: dict | None = None, hi: dict | None = None, money: dict | None = None): + import highspy + import numpy as np + for k, v in (lo or {}).items(): + self.lb[k] = v + for k, v in (hi or {}).items(): + self.ub[k] = v + for k, v in (money or {}).items(): + self.c[k] = v + h = highspy.Highs() + h.setOptionValue("output_flag", False) + h.setOptionValue("random_seed", 0) + nc = len(self.c) + inf = highspy.kHighsInf + clip = lambda v: inf if v == INF else (-inf if v == -INF else v) # noqa: E731 + h.addVars(nc, np.array([clip(v) for v in self.lb]), np.array([clip(v) for v in self.ub])) + h.changeColsCost(nc, np.arange(nc, dtype=np.int32), -np.array(self.c, dtype=float)) + if self.ints: + h.changeColsIntegrality(len(self.ints), np.array(self.ints, dtype=np.int32), np.ones(len(self.ints), dtype=np.uint8)) + if self.rows: + starts, idx, val, lbs, ubs = [], [], [], [], [] + for lb, ub, cs, vs in self.rows: + starts.append(len(idx)) + idx += cs + val += vs + lbs.append(clip(lb)) + ubs.append(clip(ub)) + h.addRows(len(self.rows), np.array(lbs), np.array(ubs), len(idx), np.array(starts, dtype=np.int32), + np.array(idx, dtype=np.int32), np.array(val, dtype=float)) + h.run() + st = h.modelStatusToString(h.getModelStatus()) + if st != "Optimal": + raise RuntimeError(f"battery plan: {st}") + return list(h.getSolution().col_value) + + +def plan(hz: Horizon, bat=None, *, wear_ct: float = 0.0, share: float | None = None, end_ct: float = 0.0, + grey_to_loads: bool = True, surplus_only: bool = False, battery_feed: bool = True, z_ct: float = 0.0) -> dict: + """The owner's dispatch over one horizon at fixed prices (the same Block and terms as the plan's MILP at its fixed + prices): per slot the PV used directly (DU ≤ the load), by the own use (PO), fed in (EX), curtailed (CU), charged + (CH), the battery's discharges and grid kWh; the owner's money (€) over the horizon without the end value, and the + series. bat None: no battery. wear_ct only labels the battery's (bat.wear_ct is used).""" + n = len(hz.pv) + lp = Lp() + own = hz.own if hz.own is not None and hz.own_ct is not None else None + direct = hz.direct_ct or [0.0] * n + DU = [lp.add(0, max(0.0, hz.load[t]), (hz.value_ct[t] + direct[t]) / 100) for t in range(n)] + PO = [lp.add(0, max(0.0, own[t]), hz.own_ct[t] / 100) for t in range(n)] if own else [] + EX = [lp.add(0, max(0.0, hz.pv[t]), (hz.feed_ct[t] - (0.01 if hz.unpaid and hz.unpaid[t] else 0.0)) / 100) for t in range(n)] + CU = [lp.add(0, max(0.0, hz.pv[t])) for t in range(n)] + blk = None + if bat is not None: + room = [hz.pv[t] - hz.load[t] - (own[t] if own else 0.0) for t in range(n)] + grid = hz.grid_ct is not None + g_min = min(hz.grid_ct) / 100 if grid and hz.grid_ct else None + blk = Block(lp.add, lp.row, bat, n, list(hz.pv), room, surplus_only=surplus_only, share=share, + charge_eur=-z_ct / 100, grid_eur=[-hz.grid_ct[t] / 100 for t in range(n)] if grid else None, + grey_to_loads=grey_to_loads, + feed_eur=[(hz.feed_ct[t] - bat.wear_ct - (0.01 if hz.unpaid and hz.unpaid[t] else 0.0)) / 100 for t in range(n)] + if battery_feed else None, + own_load=list(own) if own else None, own_eur=[hz.own_ct[t] / 100 for t in range(n)] if own else None, + end_eur=end_ct / 100, green_start=bat.start, + idle_eur=[v / 100 for v in (hz.buy_ct or hz.grid_ct or hz.own_ct or hz.value_ct)], + valve=(lambda base: base if g_min is None else min(base, max(0.0, g_min) * (1 - VALVE_UNDER)))) + # the battery's money on the delivered kWh: the loads' value (DI, DQ), the own use's (DO, DOq: in Block) + for t in range(n): + lp.c[blk.DI[t]] += hz.value_ct[t] / 100 + if blk.DQ: + lp.c[blk.DQ[t]] += hz.value_ct[t] / 100 + lp.ints += blk.integers() + blk.reserve_rows() + if own: + for t in range(n): + cs = [c[t] for c in (PO, blk.DO, blk.DOq) if c] + lp.row(-INF, own[t], cs, [1.0] * len(cs)) + blk.shift_rows() + blk.feed_rows(EX, INF) + for t in range(n): + # the PV: used directly, by the own use, fed in, curtailed, charged + cols = [DU[t], EX[t], CU[t]] + ([PO[t]] if PO else []) + ([blk.CH[t]] if blk else []) + lp.row(hz.pv[t], hz.pv[t], cols, [1.0] * len(cols)) + if blk: + # the loads: at most their use from the PV and the battery together + cs = [DU[t], blk.DI[t]] + ([blk.DQ[t]] if blk.DQ else []) + lp.row(-INF, max(0.0, hz.load[t]), cs, [1.0] * len(cs)) + blk.soc_row(t) + if hz.import_cap is not None and hz.import_cap[t] is not None: + # the import: the loads and the own use less what the PV and the battery give them, plus grid kWh + imp = [DU[t], blk.DI[t]] + ([blk.DQ[t]] if blk.DQ else []) + ([PO[t]] if PO else []) \ + + [c[t] for c in (blk.DO, blk.DOq) if c] + base = hz.load[t] + (own[t] if own else 0.0) + cols, vals = imp + ([blk.CQ[t]] if blk.CQ else []), [-1.0] * len(imp) + ([1.0] if blk.CQ else []) + lp.row(-INF, hz.import_cap[t] - base, cols, vals) + money = blk.end_values(g_min) if blk else {} + x = lp.solve(blk.lo if blk else None, blk.hi if blk else None, money) + v = lambda cs: [max(0.0, x[c]) for c in cs] if cs else [0.0] * n # noqa: E731 + out = {"direct": v(DU), "own_pv": v(PO), "export": v(EX), "curtail": v(CU)} + groups = [DU, PO, EX, CU] + if blk: + out.update(charge=v(blk.CH), discharge=v(blk.DI), grid_charge=v(blk.CQ), grey_discharge=v(blk.DQ), own_discharge=v(blk.DO), + own_grey=v(blk.DOq), battery_export=v(blk.XB), + soc=[x[blk.E[t]] + (x[blk.Q[t]] if blk.Q else 0.0) for t in range(n)]) + groups += [blk.CH, blk.DI, blk.CQ, blk.DQ, blk.DO, blk.DOq, blk.XB] + # the owner's money per slot (€; the end value is no money); the idle loss the grid supplies (the valves) at the + # slot's purchase (before 2026-11-12 at no money, the ROI ~3 % optimistic with a 20 W, 0.3 %/h battery) + eur_t = [0.0] * n + for cs in groups: + for t, c in enumerate(cs): + eur_t[t] += lp.c[c] * x[c] + if blk: + buy = hz.buy_ct or hz.grid_ct or hz.own_ct or hz.value_ct + idle = [blk.idle_grid(x, t) for t in range(n)] + for t in range(n): + eur_t[t] -= idle[t] * buy[t] / 100 + out["idle_grid"] = idle + out["eur_t"] = eur_t + out["eur"] = sum(eur_t) + return out diff --git a/src/edge/cantabile_edge/bundles.py b/src/edge/cantabile_edge/bundles.py index 00c4339..3fe9ae3 100644 --- a/src/edge/cantabile_edge/bundles.py +++ b/src/edge/cantabile_edge/bundles.py @@ -82,6 +82,17 @@ Model v1 (the forecasts' data; the ML in ml/ is a placeholder, 2026-10-28): from the site's ev_plug forecast, the car's departure and energy where it reports none (inputs.ev_session). Only from a model for this site; malformed sessions are left out (ev_sessions_error), the rest stays. + - "zones" (2026-11-12, methods.md B17, G2; fleet mlforecast.go from + ml_zones, fitted or on the prior only): {"home": {"model": "2r2c", + "power": thermal | electric, "r_i_k_per_kw", "r_e_k_per_kw", + "c_air_kwh_per_k", "c_mass_kwh_per_k", "c_eff_kwh_per_k", + "ua_w_per_k", "tau_fast_h", "tau_slow_h", "solar_kind": ghi | facts, + "solar_m2" | "solar_factor", "gain_w", "el_gain_share"?, "occ_gain_w"?, + "cool_eer"?}}: the flat's air and mass (its daily check passed); and + per room "subzone" {"basis", "share", ...}: the room's share of the + flat's heat. The plan's rooms take it (zone_rc, inputs._room_rc; G2 in + the plan, backlog 473); a zone out of range is left out (zone_rc says + why), the rest of the bundle stays. A malformed series or room refuses the whole bundle. """ import json @@ -161,6 +172,8 @@ SERIES_MAX = 400 # a model's series: steps of 900 s (~4 days) ROOM_R = (0.5, 200.0) # K/kW ROOM_C = (0.1, 100.0) # kWh/K ROOM_SUFFIX = re.compile(r"_(heating|cooling|heat|cool)$") +ZONE_R = (0.05, 200.0) # K/kW, a zone's R_i and R_e (the fit's bounds, thermal.r_*: 0.1-100, with margin) +ZONE_C = (0.01, 500.0) # kWh/K, a zone's C_air, C_mass (thermal.c_*: 0.05-20, 0.5-200, with margin) # a room's fitted gains (Finding B6-a), as the planner takes them: outside # these the fit's artefact (a negative sun, a gain above any home's) is cut ROOM_GAIN_W = (-2000.0, 5000.0) # W of heat, internal (people, appliances) @@ -518,6 +531,18 @@ class Bundles: own = (t.get("tenant") or {}).get("own_import") return dict(m, own_known=isinstance(own, list) and any(_finite(x) for x in own)) + def gas_conversion(self, ts: float, now: float | None = None) -> float | None: + """kWh per m³ of gas (Brennwert Hs × Zustandszahl Z of the billing period) at ts, from the bundle + in force now (optional "gas_kwh_per_m3": [{from, to, kwh_per_m3, hs, z}], unix seconds; fleet + climateprices.go: the gas grid operator's published values or the site's own). None: no period + covers ts, or no bundle: a gas meter in m³ then books no kWh (never a default).""" + t = self._valid(ts if now is None else now) + for p in (t.get("gas_kwh_per_m3") or []) if t is not None else []: + if isinstance(p, dict) and _finite(p.get("from")) and _finite(p.get("to")) and _finite(p.get("kwh_per_m3")) \ + and p["from"] <= ts < p["to"] and p["kwh_per_m3"] > 0: + return float(p["kwh_per_m3"]) + return None + def fixed_charges(self, now: float) -> dict | None: """The fixed charges per carrier the bundle carries (optional "fixed": {"electricity": {"eur_month": gross €/month, "incomplete": @@ -782,6 +807,56 @@ class Bundles: "gain_w": [_clip(x, ROOM_GAIN_W) for x in g] if isinstance(g, list) else _clip(g, ROOM_GAIN_W), "solar_m2": _clip(r.get("solar_m2") or 0.0, ROOM_SOLAR_M2)} + def zone_rc(self, control_id: str = "", area: str = "", only_one: bool = False, + now: float | None = None) -> tuple[dict | None, str]: + """The flat's 2R2C (the bundle's "zones", methods.md B17) for a + heating or cooling control (G2 in the plan): the room's share of the + flat's heat (its "subzone" share; the site's only heating or cooling + control: all of it, 1; neither: not used). (zone, why not) with zone + {"r_i", "r_e" (K/kW), "c_a", "c_m" (kWh/K), "share", "share_src", + "power", "gain_w", "solar_m2", "solar_kind", "el_gain_share", + "occ_gain_w", "cool_eer"}: the zone's own values; the plan scales + them by the share (a room is that share of the flat with the flat's + time constants: inputs._room_rc).""" + m = self.model.get() + now = time.time() if now is None else now + if m is None or m.get("site") != self.site or (m.get("expires") and m["expires"] <= now): + return None, "" + z = (m.get("zones") or {}).get("home") + if not isinstance(z, dict): + return None, "" + vals = {} + for key, name, lo_hi in (("r_i_k_per_kw", "r_i", ZONE_R), ("r_e_k_per_kw", "r_e", ZONE_R), + ("c_air_kwh_per_k", "c_a", ZONE_C), ("c_mass_kwh_per_k", "c_m", ZONE_C)): + v = z.get(key) + if not _finite(v) or not lo_hi[0] <= v <= lo_hi[1]: + return None, f"the flat's model: {key} {v!r} outside {lo_hi[0]:g}-{lo_hi[1]:g} (left out)" + vals[name] = float(v) + if z.get("power", "thermal") not in ("thermal", "electric"): + return None, "the flat's model: power neither thermal nor electric (left out)" + rooms = m.get("rooms") or {} + key = next((k for k in (control_id, ROOM_SUFFIX.sub("", control_id or ""), area or "") + if k and k in rooms), None) + sub = (rooms.get(key) or {}).get("subzone") if key else None + share, src = None, "" + if only_one: + share, src = 1.0, "the site's only heating or cooling control" + elif isinstance(sub, dict) and _finite(sub.get("share")) and 0 < sub["share"] <= 1: + share, src = float(sub["share"]), f"its sub-zone's share ({sub.get('basis') or '?'})" + if share is None: + return None, "the flat's model: the room's share of the flat's heat is not known" + + def num(k, lo_hi): + v = z.get(k) + return _clip(v, lo_hi) if _finite(v) else 0.0 + ghi = (z.get("solar_kind") or "ghi") == "ghi" + out = dict(vals, share=share, share_src=src, power=z.get("power") or "thermal", + solar_kind=z.get("solar_kind") or "ghi", gain_w=num("gain_w", ROOM_GAIN_W), + solar_m2=num("solar_m2", ROOM_SOLAR_M2) if ghi else 0.0, + el_gain_share=num("el_gain_share", (0.0, 1.0)), occ_gain_w=num("occ_gain_w", (0.0, 2000.0)), + cool_eer=num("cool_eer", (0.0, 20.0)) or None) + return out, "" + def model_id(self) -> str: m = self.model.get() return m.get("id", "") if m else "" diff --git a/src/edge/cantabile_edge/comfort.py b/src/edge/cantabile_edge/comfort.py new file mode 100644 index 0000000..fb32f15 --- /dev/null +++ b/src/edge/cantabile_edge/comfort.py @@ -0,0 +1,288 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The comfort band (docs/methods.md G5 in the plan; backlog 473): instead of +one target per room, a band per step from EN 16798-1 and the household. + + - the band's edges: EN 16798-1's design values for heated and cooled homes + (the lower edge in heating, the upper in cooling, per category), and its + adaptive line where the running mean outdoor temperature is warm enough + (theta_comf = slope x theta_rm + intercept, the band's edges at + category offsets from it); + - the running mean outdoor temperature theta_rm: the daily means of the + past days (the box's history "t_out") and of the forecast's days, + weighted alpha^(i-1) (EN 16798-1 B.2.2, alpha 0.8); + - the category by the household's choice per flat (comfort, balanced, + saving: preferences "comfort"), else the Parameters page's default; + - the cost per K·h outside: asymmetric (too cold, too warm), times the + choice's factor, weighted by the probability that someone is home (the + occupancy forecast's share over the occupied threshold, capped at 1); + sleeping hours with their own offset; "warm by arrival": the step + someone comes home costs more per K missed; + - the household's tolerance learnt from its overrides (Tolerance): the + mean of (its own setpoint - the plan's) shrunk toward 0 (the category: + the similar homes' prior until the cloud sends one) by prior_n. + +Every number is a Parameters row (ROWS) sent in the tariff bundle's params; +a row missing takes its suggested value and the plan's refused names it +(the owner's rule for missing rows, 2026-11-12: planned with the suggested +value, an alarm).""" +from __future__ import annotations + +import json +import math +import os +from datetime import datetime, timezone +from zoneinfo import ZoneInfo + +STEP_S = 900 + +# the Parameters page's rows (fleet migrations-climate-plan.sql), suggested values and their sources in +# docs/parameters.md "Comfort band" +SUGGESTED_ROWS = { + # EN 16798-1:2019 Annex B, Table B.6 (residential, living spaces: heating ≥, cooling ≤ per category) and the + # adaptive band's offsets (B.2.2: upper +2/+3/+4 K, lower -3/-4/-5 K for I/II/III) + "comfort.band_categories": {"I": {"heat_min_c": 21.0, "cool_max_c": 25.5, "upper_k": 2.0, "lower_k": 3.0}, + "II": {"heat_min_c": 20.0, "cool_max_c": 26.0, "upper_k": 3.0, "lower_k": 4.0}, + "III": {"heat_min_c": 18.0, "cool_max_c": 27.0, "upper_k": 4.0, "lower_k": 5.0}}, + # EN 16798-1 B.2.2: theta_comf = 0.33 theta_rm + 18.8; the upper edge for theta_rm 10-30 °C, the lower 15-30 °C + "comfort.adaptive_line": {"slope": 0.33, "intercept_c": 18.8, "upper_from_c": 10.0, "lower_from_c": 15.0, "to_c": 30.0}, + "comfort.running_mean_alpha": 0.8, # EN 16798-1 B.2.2 + "comfort.mode_categories": {"comfort": "I", "balanced": "II", "saving": "III"}, + "comfort.mode_cost_factor": {"comfort": 2.0, "balanced": 1.0, "saving": 0.5}, + "comfort.default_mode": "balanced", + "comfort.value_eur_per_kh": 2.0, # the existing row: too cold (heating) / too warm (cooling) + "comfort.warm_eur_per_kh": 1.0, # the other side: too warm while heating, too cold while cooling + "comfort.arrival_eur_per_k": 5.0, + "comfort.sleep": {"from": "22:00", "to": "06:00", "offset_k": -1.0}, + "comfort.tolerance": {"prior_n": 5.0, "max_k": 2.0, "days": 28.0}, +} +ROWS = tuple(SUGGESTED_ROWS) +MODES = ("comfort", "balanced", "saving") + + +def rows(box_params: dict | None) -> tuple[dict, list[str]]: + """The band's rows from the tariff bundle's params, each checked; a row + missing or malformed takes its suggested value. (rows, missing).""" + bp = box_params or {} + out, missing = {}, [] + for k, sug in SUGGESTED_ROWS.items(): + v = bp.get(k) + if not _ok(k, v): + out[k] = sug + missing.append(k) + else: + out[k] = v + return out, missing + + +def _num(v) -> float | None: + if isinstance(v, bool): + return None + try: + x = float(v) + except (TypeError, ValueError): + return None + return x if math.isfinite(x) else None + + +def _ok(key: str, v) -> bool: + if v is None: + return False + if key == "comfort.band_categories": + return isinstance(v, dict) and bool(v) and all( + isinstance(c, dict) and all(_num(c.get(f)) is not None for f in ("heat_min_c", "cool_max_c", "upper_k", "lower_k")) + for c in v.values()) + if key == "comfort.adaptive_line": + return isinstance(v, dict) and all(_num(v.get(f)) is not None for f in ("slope", "intercept_c", "upper_from_c", + "lower_from_c", "to_c")) + if key == "comfort.mode_categories": + return isinstance(v, dict) and all(isinstance(v.get(m), str) for m in MODES) + if key == "comfort.mode_cost_factor": + return isinstance(v, dict) and all((_num(v.get(m)) or -1) >= 0 for m in MODES) + if key == "comfort.default_mode": + return v in MODES + if key == "comfort.sleep": + return isinstance(v, dict) and _hhmm(v.get("from")) is not None and _hhmm(v.get("to")) is not None \ + and _num(v.get("offset_k")) is not None + if key == "comfort.tolerance": + return isinstance(v, dict) and all((_num(v.get(f)) or -1) >= 0 for f in ("prior_n", "max_k", "days")) + if key == "comfort.running_mean_alpha": + x = _num(v) + return x is not None and 0 <= x < 1 + x = _num(v) + return x is not None and x >= 0 + + +def _hhmm(v) -> int | None: + try: + h, m = str(v).split(":") + x = int(h) * 60 + int(m) + except (ValueError, AttributeError): + return None + return x if 0 <= x <= 1440 else None + + +def gap(missing: list[str]) -> dict: + """The data gap for rows planned with their suggested values (as the battery's, battery_core.suggested_gap).""" + return {"why": "Parameters " + ("rows" if len(missing) > 1 else "row") + " missing: comfort band planned with the " + "suggested " + ("values" if len(missing) > 1 else "value") + " (" + ", ".join(missing) + ")", + "missing": list(missing), "where": "the admin Parameters page (Comfort)", "fallback": "suggested", + "kind": "comfort", "name": "Comfort band"} + + +# ---- the running mean outdoor temperature ----------------------------------------------------------------- + +def daily_means(start: int, tz: str, past: list[float | None], past_start: int, forecast: list[float] | None, + min_slots: int = 48) -> dict[str, float]: + """Local day -> its mean outdoor temperature: the history's quarter + hours (past, from past_start) and the forecast's (from start); a day + with fewer than min_slots values is left out.""" + zone = ZoneInfo(tz or "UTC") + acc: dict[str, list[float]] = {} + for k, v in enumerate(past or []): + if v is not None: + d = datetime.fromtimestamp(past_start + k * STEP_S, timezone.utc).astimezone(zone).date().isoformat() + acc.setdefault(d, []).append(float(v)) + for k, v in enumerate(forecast or []): + if v is not None: + d = datetime.fromtimestamp(start + k * STEP_S, timezone.utc).astimezone(zone).date().isoformat() + acc.setdefault(d, []).append(float(v)) + return {d: sum(v) / len(v) for d, v in acc.items() if len(v) >= min_slots} + + +def running_mean(days: dict[str, float], day: str, alpha: float, n: int = 7) -> float | None: + """theta_rm for a local day: the mean of the n days before it weighted + alpha^(i-1) (EN 16798-1 B.2.2's series), over the days there are.""" + prev = sorted((d for d in days if d < day), reverse=True)[:n] + if not prev: + return None + w = [alpha ** i for i in range(len(prev))] + return sum(wi * days[d] for wi, d in zip(w, prev)) / sum(w) + + +def edges(r: dict, category: str, theta_rm: float | None, cooled: bool) -> tuple[float, float]: + """The band's (lower, upper) °C for a category and running mean: + EN 16798-1's design values, the adaptive line where theta_rm is in its + range (the upper edge only in a home without cooling).""" + cats = r["comfort.band_categories"] + c = cats.get(category) or cats.get("II") or next(iter(cats.values())) + line = r["comfort.adaptive_line"] + lo, hi = float(c["heat_min_c"]), float(c["cool_max_c"]) + if theta_rm is not None: + rm = min(theta_rm, float(line["to_c"])) + comf = float(line["slope"]) * rm + float(line["intercept_c"]) + if theta_rm >= float(line["lower_from_c"]): + lo = comf - float(c["lower_k"]) + if theta_rm >= float(line["upper_from_c"]) and not cooled: + hi = comf + float(c["upper_k"]) + return lo, max(hi, lo) + + +# ---- the household's tolerance, learnt from its overrides ------------------------------------------------- + +class Tolerance: + """The inhabitants' changes by hand to a planned room's setpoint (the + guard's overrides, E18): kept in /comfort-tolerance.json for + comfort.tolerance's days. shift() is the room's learnt offset of the + band's edge it cares about (heating: the lower, cooling: the upper).""" + + def __init__(self, state_dir: str | None): + self.path = os.path.join(state_dir, "comfort-tolerance.json") if state_dir else None + self.events: list[dict] = [] + if self.path: + try: + with open(self.path) as f: + self.events = [e for e in json.load(f) if isinstance(e, dict)] + except (OSError, ValueError, TypeError): + self.events = [] + + def record(self, control: str, kind: str, agent_set, value, at: float): + a, v = _num(agent_set), _num(value) + if a is None or v is None or not (5.0 <= a <= 35.0 and 5.0 <= v <= 35.0) or kind not in ("heating", "cooling"): + return False + self.events.append({"control": control, "kind": kind, "agent_set": a, "value": v, "at": int(at)}) + self.events = self.events[-500:] + self.save() + return True + + def save(self): + if not self.path: + return + tmp = self.path + ".tmp" + try: + with open(tmp, "w") as f: + json.dump(self.events, f) + os.replace(tmp, self.path) + except OSError: + pass + + def shift(self, control: str, kind: str, now: float, r: dict) -> tuple[float, int]: + """(K, n): the mean difference (the inhabitant's setpoint - the + plan's) over the last days, shrunk toward 0 by n / (n + prior_n), + within ± max_k. Heating: + raises the lower edge; cooling: - lowers + the upper.""" + t = r["comfort.tolerance"] + cut = now - float(t["days"]) * 86400 + d = [e["value"] - e["agent_set"] for e in self.events + if e.get("control") == control and e.get("kind") == kind and e.get("at", 0) >= cut] + if not d: + return 0.0, 0 + n = len(d) + k = float(t["prior_n"]) + x = sum(d) / (n + k) # = mean x n/(n+k): toward the prior 0 + m = float(t["max_k"]) + return max(-m, min(m, x)), n + + +# ---- the band per step for a room ---------------------------------------------------------------------- + +def presence_weight(occupied: list, share: list | None, min_share: float | None) -> list[float]: + """The probability someone is home per step: the forecast's share over + the occupied threshold, capped at 1 (a step at the threshold is home); + where there is no share (presence now, the fixed hours) the 0/1.""" + out = [] + for t, o in enumerate(occupied): + s = share[t] if share and t < len(share) else None + if s is None or not min_share: + out.append(1.0 if o else 0.0) + else: + out.append(max(0.0, min(1.0, float(s) / float(min_share)))) + return out + + +def room_band(r: dict, kind: str, mode: str, start: int, tz: str, steps: int, weights: list[float], + rm_by_day: dict[str, float | None], setback_c: float, cooled: bool, + shift_k: float = 0.0) -> dict: + """Per step: lo, hi (°C), w_lo, w_hi (EUR per K·h), floor (the setback + in heating, the setup in cooling: held whoever is home, at the cold + side's cost), arrive (EUR per K extra at a step someone comes home).""" + zone = ZoneInfo(tz or "UTC") + category = r["comfort.mode_categories"].get(mode) or r["comfort.mode_categories"]["balanced"] + factor = float(r["comfort.mode_cost_factor"].get(mode, 1.0)) + cold, warm = float(r["comfort.value_eur_per_kh"]), float(r["comfort.warm_eur_per_kh"]) + sl = r["comfort.sleep"] + s_from, s_to, s_off = _hhmm(sl["from"]), _hhmm(sl["to"]), float(sl["offset_k"]) + arr = float(r["comfort.arrival_eur_per_k"]) + out = {"lo": [], "hi": [], "w_lo": [], "w_hi": [], "floor": [], "arrive": [], "category": category, + "mode": mode, "shift_k": round(shift_k, 2), "w_floor": cold} + for t in range(steps): + lt = datetime.fromtimestamp(start + (t + 1) * STEP_S, timezone.utc).astimezone(zone) + lo, hi = edges(r, category, rm_by_day.get(lt.date().isoformat()), cooled) + m = lt.hour * 60 + lt.minute + asleep = (s_from <= m or m < s_to) if s_from > s_to else (s_from <= m < s_to) + if asleep: + lo += s_off if kind == "heating" else 0.0 + hi -= s_off if kind == "cooling" else 0.0 + if kind == "heating": + lo += shift_k + else: + hi += shift_k + w = weights[min(t + 1, len(weights) - 1)] if weights else 1.0 + prev = weights[t] if weights else 1.0 + # heating: below lo is the cold side; cooling: above hi is the warm (the paid) side + out["lo"].append(round(lo, 2)) + out["hi"].append(round(max(hi, lo), 2)) + out["w_lo"].append(round((cold if kind == "heating" else warm) * factor * w, 4)) + out["w_hi"].append(round((warm if kind == "heating" else cold) * factor * w, 4)) + out["floor"].append(float(setback_c)) + out["arrive"].append(round(arr * factor, 4) if (prev < 0.5 <= w) else 0.0) + return out diff --git a/src/edge/cantabile_edge/controller.py b/src/edge/cantabile_edge/controller.py index edc232a..75abf84 100644 --- a/src/edge/cantabile_edge/controller.py +++ b/src/edge/cantabile_edge/controller.py @@ -47,7 +47,7 @@ import time from . import inputs as inputs_mod from .building import Building from .bundles import Bundles -from . import shades, steady +from . import comfort, shades, steady from .evphases import EvPhases from .executor import Executor, building_msg from .gridorder import GridOrders @@ -129,6 +129,9 @@ class Controller: self.executor = Executor(self.controls, self.guard, self.col, self._publish, stale_s=cfg.plan_stale_s, clock=clock, building=self.building) self.executor.shade_moves = shades.Moves(cfg.state_dir) # what each shade was last moved for + # the household's tolerance learnt from its changes by hand (comfort.py, methods.md G5) + self.tolerance = comfort.Tolerance(cfg.state_dir) + self.executor.on_override = self._learn_override self.col.observers.append(self._observe) self.client = None self.tz = "UTC" @@ -243,6 +246,9 @@ class Controller: ours = moves.ours(c.id, inputs_mod.cover_position(self.col, c.entities["cover"])) if ours: ctx["ours"] = ours + if self.guard.overridden(c.id): + # moved by hand: the plan keeps it there while the guard keeps off it (G3: the override wins) + ctx["held_until"] = self.guard._t(c.id).override_until out[c.id] = ctx return out @@ -329,7 +335,8 @@ class Controller: grid_order=self.gridorders.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS), grid_max_w=getattr(self.cfg, "grid_max_w", None), ev_phases=self.ev_phases(), presence=self.presence_entities(), - storefit=self.storefit) + storefit=self.storefit, + comfort_ctx={"mode": self.prefs.comfort_mode(), "tolerance": self.tolerance}) # the owner's preferences per step (preferences.py) return self.prefs.apply(state, {c.id: c for c in controls}, self.col, now) @@ -628,6 +635,10 @@ class Controller: now = self.clock() self.history.add("load_w", inputs_mod.base_load(self.col, self.inputs), now) self.history.add("pv_w", self.col.total(self.inputs.pv_power), now) + try: + self.sample_climate(now) + except Exception as e: # never stops the actions + log.warning("climate history: %s", e) if self.sample_ev_phases(now) and self.gridorders.active(): self._merge_limits() # a learned count: the order's current bound again try: @@ -797,6 +808,31 @@ class Controller: changed |= self.evphases.sample(c.id, p, a, float(c.p("voltage")), now) return changed + def _learn_override(self, ev: dict): + """A change by hand to a planned room's setpoint (the guard's + override): into the household's tolerance (comfort.Tolerance, G5). + Only a thermostat's setpoint against the plan's own (not a + command's).""" + c = next((x for x in self.controls if x.id == ev.get("control")), None) + if c is None or c.kind not in ("heating", "cooling") or ev.get("level", "plan") != "plan": + return + if ev.get("entity") != c.entities.get("climate"): + return + self.tolerance.record(c.id, c.kind, ev.get("agent_set"), ev.get("value"), ev.get("at") or self.clock()) + + # -- the climate's history: the comfort band's running mean, the flat's mass (G2, G5) ---- + def sample_climate(self, now: float): + """The outdoor temperature now ("t_out") and each heating or cooling + control's room temperature ("room:") into the history (8 days): + the comfort band's running mean outdoor temperature (comfort.py) and + the flat's mass now (inputs.mass_start).""" + self.history.add("t_out", inputs_mod.outdoor_now(self.col, self.inputs), now) + for c in self.controls: + if c.kind in ("heating", "cooling"): + t = inputs_mod.device_state(c, self.col, now).get("temp_c") + if t is not None: + self.history.add(f"room:{c.id}", float(t), now) + # -- what the box learns of its stores (storefit.py) --------------------------- def sample_stores(self, now: float): """A reading of each battery (its SoC, its own power, the PV, its diff --git a/src/edge/cantabile_edge/controls.py b/src/edge/cantabile_edge/controls.py index c0c50a3..eb97bfc 100644 --- a/src/edge/cantabile_edge/controls.py +++ b/src/edge/cantabile_edge/controls.py @@ -136,6 +136,9 @@ ENTITIES = { "standby": ("sensor", "input_number")}, "heating": {"climate": ("climate",), "switch": ("switch", "input_boolean"), "temp": ("sensor",), "source": ("select", "input_select"), + # a combi boiler's hot-water comfort mode (keeps its heat exchanger warm; methods.md G7): a switch, + # or a select with params.dhw_comfort_options {"on":