cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.2019: full source
This commit is contained in:
1 parent
c0a6f8a579
commit
5168a4a590
27 files changed
+2815
-126
No files matched your search
@@ -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
|
||||
@@ -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 ""
|
||||
@@ -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 <state dir>/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
|
||||
@@ -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:<id>") 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
|
||||
|
||||
@@ -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": <option>, "off": <option>}
|
||||
"dhw_comfort": ("switch", "input_boolean", "select", "input_select"),
|
||||
# read only: the boiler's own rated efficiency (%; heat_facts)
|
||||
"efficiency": ("sensor", "input_number")},
|
||||
"cooling": {"climate": ("climate",), "temp": ("sensor",)},
|
||||
@@ -155,7 +158,7 @@ ENTITIES = {
|
||||
"standby_loss": ("sensor", "input_number")},
|
||||
}
|
||||
WRITES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover", "source",
|
||||
"water_heater", "power", "sg_ready"}
|
||||
"water_heater", "power", "sg_ready", "dhw_comfort"}
|
||||
NEEDED = {"battery": (("charge_from_grid", "setpoint"),), "heating": (("climate", "switch"),),
|
||||
"cooling": (("climate",),), "ev": (("switch",),), "cover": (("cover",),),
|
||||
"dhw_tank": (("water_heater", "switch", "power", "sg_ready"),)}
|
||||
@@ -193,6 +196,9 @@ PARAMS = {
|
||||
# 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,
|
||||
# its comfort mode as a select: {"on": <the comfort option>, "off": <the eco option>} (G7; a switch
|
||||
# needs none)
|
||||
"dhw_comfort_options": {},
|
||||
# a hybrid's bivalence point as its own controller is set (°C: the boiler below it): the device's
|
||||
# or installer's; None: the Parameters page's heat.hybrid_bivalent_c, assumed (only the savings'
|
||||
# source lever reads it, heatlevers.py)
|
||||
@@ -216,6 +222,9 @@ PARAMS = {
|
||||
# the store's own thermostat setpoint without Cantabile (°C; the device's or installer's); None:
|
||||
# the Parameters page's dhw.thermostat_setpoint_c, assumed (the savings' store lever, heatlevers.py)
|
||||
"thermostat_c": None,
|
||||
# a heat pump's COP over the tank's temperature [[°C, factor of its rated COP], ...] (the device's
|
||||
# data sheet; methods.md G7): else the Parameters page's dhw.hp_cop_drop_pct_per_k
|
||||
"cop_tank_curve": [],
|
||||
"min_switch_s": 600.0, "hold_mode_s": 1800.0, "hold_set_s": 900.0, "min_gain_ct": 1.0},
|
||||
}
|
||||
|
||||
@@ -233,7 +242,13 @@ FACTS = {"battery": ("capacity_wh", "max_charge_w", "max_discharge_w", "efficien
|
||||
# a hot-water tank's facts (tank_facts; docs/methods.md A13)
|
||||
"dhw_tank": ("heater", "volume_l", "max_power_w", "max_heat_w", "cop", "boiler_efficiency", "standby_w",
|
||||
"ua_w_k", "erp_class", "min_temp_c", "max_temp_c", "room_temp_c", "cold_water_c", "top_share",
|
||||
"legionella_temp_c", "legionella_interval_h", "grossanlage")}
|
||||
"legionella_temp_c", "legionella_interval_h", "grossanlage",
|
||||
# the largest pipe run's volume (L; DVGW W 551: above 3 L a large system; methods.md G7)
|
||||
"pipe_volume_l"),
|
||||
# a window's facts behind a cover (methods.md G3 in the plan; the installer's, the device's or the
|
||||
# owner's, never assumed): its glass area (m²), g-value (0-1), the share of the sun the closed cover
|
||||
# keeps out (0-1), the window's U (W/m²K) and the factor a closed shutter leaves of it (0-1)
|
||||
"cover": ("window_m2", "g_value", "shade_factor", "window_u", "closed_u_factor")}
|
||||
# facts that may be 0 (a battery without idle loss), facts that are no numbers
|
||||
ZERO_OK = {"standby_w", "self_discharge_pct_month"}
|
||||
TEXT_FACTS = {"heater", "erp_class", "grossanlage"}
|
||||
@@ -270,6 +285,7 @@ CLASS_LIMITS_KEY = "dhw.erp_class_limits" # law: Regulation (EU) 812/201
|
||||
CLASS_ASSUMED_KEY = "dhw.erp_class_assumed" # the class a tank without its loss is planned with (D)
|
||||
GROSS_VOLUME_KEY = "de.dvgw_w551_volume_l" # law: a tank above it is a Großanlage
|
||||
GROSS_FLOOR_KEY = "de.dvgw_w551_min_outlet_c" # law: a Großanlage's outlet at least this
|
||||
GROSS_PIPE_KEY = "de.dvgw_w551_pipe_volume_l" # law: more than this in a pipe run is a Großanlage too
|
||||
SHORT_KEY = "dhw.short_eur_kwh" # EUR per kWh of hot water short of the comfort
|
||||
# EN 15332 / EN 12897: the standing loss S is measured at 65 °C water in a 20 °C room, so UA = S / 45 K
|
||||
# (the standard's test condition, not a tunable)
|
||||
@@ -535,10 +551,14 @@ class Control:
|
||||
out["max_temp_c"], src["max_temp_c"] = dev_hi, "device"
|
||||
# a Großanlage (DVGW W 551): the mapping's or the owner's word, else its volume above the law's
|
||||
g = p.get("grossanlage")
|
||||
pipe = _num(p.get("pipe_volume_l")) # the installer's: the largest pipe run's volume (L)
|
||||
if isinstance(g, bool):
|
||||
out["grossanlage"], src["grossanlage"] = g, "mapping"
|
||||
elif _num(own.get("tank_grossanlage")):
|
||||
out["grossanlage"], src["grossanlage"] = True, "owner"
|
||||
elif pipe is not None and _num(bp.get(GROSS_PIPE_KEY)) is not None and pipe > float(bp[GROSS_PIPE_KEY]):
|
||||
# DVGW W 551: more than 3 L in a pipe run (between the tank and the furthest tap) is a large system too
|
||||
out["grossanlage"], src["grossanlage"] = True, "pipe volume"
|
||||
elif vol and _num(bp.get(GROSS_VOLUME_KEY)) is not None:
|
||||
out["grossanlage"], src["grossanlage"] = vol > float(bp[GROSS_VOLUME_KEY]), "parameter"
|
||||
elif vol:
|
||||
|
||||
@@ -59,11 +59,15 @@ ASSETS = {"grid.import_energy": ("electricity", "counter"), "grid.import_power":
|
||||
# heating oil (methods.md E15): kWh (Hi) where the device reports energy, else its oil meter's
|
||||
# litres × the Parameters row de.heizoel_kwh_per_l (the tariff bundle's params)
|
||||
"oil.energy": ("oil", "counter"), "oil.volume": ("oil", "litres"),
|
||||
"boiler.oil_energy": ("oil", "counter"), "boiler.oil_volume": ("oil", "litres")}
|
||||
"boiler.oil_energy": ("oil", "counter"), "boiler.oil_volume": ("oil", "litres"),
|
||||
# a gas meter counting volume (climate-prices, 2026-11-12; methods.md E5): litres of gas (1000 per m³) ×
|
||||
# the bundle's Brennwert × Zustandszahl of the day (gas_kwh_per_m3, the gas grid operator's or the site's);
|
||||
# none for the day: no value (never m³ as kWh, never a default)
|
||||
"gas.volume": ("gas", "m3"), "boiler.gas_volume": ("gas", "m3")}
|
||||
OIL_KWH_PER_L = "de.heizoel_kwh_per_l"
|
||||
PREFER = ("grid.import_energy", "grid.import_power", "grid.power") # electricity: the counter first
|
||||
# gas and oil: the house's meter before the boiler's own (one of them, never both: the same fuel)
|
||||
PREFER_FUEL = ("gas.energy", "boiler.gas_energy", "oil.energy", "oil.volume", "boiler.oil_energy", "boiler.oil_volume")
|
||||
PREFER_FUEL = ("gas.energy", "boiler.gas_energy", "gas.volume", "boiler.gas_volume", "oil.energy", "oil.volume", "boiler.oil_energy", "boiler.oil_volume")
|
||||
PARAM_FORECAST = "costs.forecast_days" # the Parameters page (fleet), in the tariff bundle's params
|
||||
FORECAST_DAYS = (1, 62) # the parameter's valid range
|
||||
REPORT_EVERY_S = 60 # HA's figures made again at most this often (announce.py)
|
||||
@@ -95,7 +99,8 @@ def _finite(v) -> bool:
|
||||
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
|
||||
|
||||
|
||||
def amounts(records: list[dict], span_s: float, oil_kwh_per_l: float | None = None) -> dict[str, float | None]:
|
||||
def amounts(records: list[dict], span_s: float, oil_kwh_per_l: float | None = None,
|
||||
gas_kwh_per_m3: float | None = None, notes: set | None = None) -> dict[str, float | None]:
|
||||
"""A closed window's kWh per carrier from the cost aggregator's records
|
||||
(telemetry.Aggregator): the counters' deltas (Wh) where the carrier has
|
||||
a counter that has a reading, else its power's mean (W) over the
|
||||
@@ -114,6 +119,15 @@ def amounts(records: list[dict], span_s: float, oil_kwh_per_l: float | None = No
|
||||
# litres of oil: kWh only with the conversion row (none: no value, never litres as kWh)
|
||||
v = r.get("delta") if r.get("last") is not None else None
|
||||
v = v * oil_kwh_per_l if _finite(v) and _finite(oil_kwh_per_l) and oil_kwh_per_l > 0 else None
|
||||
elif kind == "m3":
|
||||
# litres of gas: kWh = m³ × Hs × Z of the day (the bundle's gas_kwh_per_m3); none: no value, said in notes
|
||||
v = r.get("delta") if r.get("last") is not None else None
|
||||
if _finite(v) and _finite(gas_kwh_per_m3) and gas_kwh_per_m3 > 0:
|
||||
v = v / 1000.0 * gas_kwh_per_m3
|
||||
else:
|
||||
if _finite(v) and notes is not None:
|
||||
notes.add("gas_m3")
|
||||
v = None
|
||||
else:
|
||||
m = r.get("mean")
|
||||
v = (max(m, 0.0) if q == "grid.power" else m) * span_s / 3600.0 / 1000.0 if _finite(m) else None
|
||||
@@ -210,7 +224,9 @@ class Ledger:
|
||||
kwh_l = float(self.bundles.box_params(self.clock()).get(OIL_KWH_PER_L))
|
||||
except (TypeError, ValueError, AttributeError):
|
||||
kwh_l = None
|
||||
got = amounts(records, span, kwh_l)
|
||||
notes: set = set()
|
||||
got = amounts(records, span, kwh_l, self.bundles.gas_conversion(start, self.clock()), notes)
|
||||
self.gas_m3_missing = "gas_m3" in notes # a gas meter in m³ without its conversion: the costs page says so
|
||||
sp = self.bundles.slot_prices(start, self.clock())
|
||||
fixed = self.bundles.fixed_charges(start)
|
||||
with self.lock:
|
||||
@@ -472,6 +488,8 @@ def costs_section(ledger: Ledger, now: float, lang: str, meters: dict[str, bool]
|
||||
fixed_now = ledger.bundles.fixed_charges(now)
|
||||
if fixed_now is None:
|
||||
gap("costs", names.name("cg_no_fixed", lang))
|
||||
if getattr(ledger, "gas_m3_missing", False):
|
||||
gap("costs", names.name("cg_no_gas_conv", lang))
|
||||
out = {"month": month, "last_month": last, "carriers": {}}
|
||||
rows = []
|
||||
for c in ledger.carriers(now):
|
||||
|
||||
@@ -38,6 +38,9 @@ QUANTITIES = {
|
||||
"heat.power": ("W", "gauge"), "heat.energy": ("Wh", "counter"),
|
||||
"heatpump.flow_temp": ("°C", "gauge"), "heatpump.dhw_temp": ("°C", "gauge"),
|
||||
"outside.temp": ("°C", "gauge"), "outside.humidity": ("%", "gauge"), "heating.state": ("", "gauge"), "cooling.state": ("", "gauge"), "gas.energy": ("Wh", "counter"),
|
||||
# a gas meter counting volume (m³ → litres of gas): kWh = m³ × Brennwert × Zustandszahl of the billing period,
|
||||
# the tariff bundle's gas_kwh_per_m3 (costs.py); without it its gas is not counted (never a default)
|
||||
"gas.volume": ("L", "counter"),
|
||||
"ev.power": ("W", "gauge"), "ev.energy": ("Wh", "counter"),
|
||||
"room.temp": ("°C", "gauge"), "room.humidity": ("%", "gauge"), "room.setpoint": ("°C", "gauge"),
|
||||
"room.setpoint_low": ("°C", "gauge"), "room.setpoint_high": ("°C", "gauge"),
|
||||
|
||||
@@ -108,6 +108,15 @@ def actions_for(c, want, col, level="plan", why="") -> list[Action]:
|
||||
opt = (c.p("source_options") or {}).get(src)
|
||||
if opt and col.state(e["source"]) != str(opt):
|
||||
act("source", "select_option", {"option": str(opt)}, str(opt))
|
||||
# a combi boiler's hot-water comfort mode (optimizer: on while someone is home and awake; G7)
|
||||
cm = want.get("dhw_comfort") if isinstance(want, dict) else None
|
||||
if c.kind == "heating" and cm in ("on", "off") and "dhw_comfort" in e:
|
||||
if e["dhw_comfort"].split(".")[0] in ("switch", "input_boolean"):
|
||||
switch("dhw_comfort", cm == "on")
|
||||
else:
|
||||
opt = (c.p("dhw_comfort_options") or {}).get(cm)
|
||||
if opt and col.state(e["dhw_comfort"]) != str(opt):
|
||||
act("dhw_comfort", "select_option", {"option": str(opt)}, str(opt))
|
||||
elif c.kind == "ev":
|
||||
v = want.get("set") if isinstance(want, dict) else want
|
||||
if v == "off":
|
||||
@@ -179,6 +188,7 @@ class Executor:
|
||||
self._refused: dict[tuple, float] = {}
|
||||
self.log: list[dict] = [] # the last actions (tests, status)
|
||||
self.shade_moves = None # shades.Moves: what each shade was last moved for
|
||||
self.on_override = None # a callable(ev): each change by hand (comfort.Tolerance)
|
||||
|
||||
# -- what is wanted ------------------------------------------------------
|
||||
def wanted(self, c, now):
|
||||
@@ -335,6 +345,12 @@ class Executor:
|
||||
if cmd and cmd.get("id"):
|
||||
msg["id"] = cmd["id"]
|
||||
await self.publish("action", msg)
|
||||
if self.on_override is not None:
|
||||
try:
|
||||
# a change by hand against the plan: the household's tolerance (comfort.py, G5)
|
||||
self.on_override(dict(ev, level=level if not (bcmd is not None or bplan is not None) else "building"))
|
||||
except Exception as e: # never stops the reports
|
||||
log.warning("override learning: %s", e)
|
||||
log.info("override: %s %s=%s (%s)", ev["control"], ev["entity"], ev["value"], why)
|
||||
self.log.append({"result": "overridden", **ev})
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Hot water as a reserve (docs/methods.md G7 in the plan; backlog 473, 476):
|
||||
the tank's temperature planned per step instead of one floor, and a combi
|
||||
boiler's comfort mode.
|
||||
|
||||
- the floor per step: the draw temperature (the tank's min_temp_c: the
|
||||
mapping's, else dhw.min_temp_c) where the hot-water forecast expects a
|
||||
draw (at least dhw.draw_expected_w in the step), else the lower idle
|
||||
floor dhw.idle_min_temp_c (the owner, 2026-11-12: "during late night
|
||||
reduce hot water to 40"); the plan raises it before the draws and in PV
|
||||
or cheap hours up to the tank's maximum, as a store, where it pays;
|
||||
- a large central system (Großanlage, DVGW W 551: more than
|
||||
de.dvgw_w551_volume_l litres, or more than de.dvgw_w551_pipe_volume_l
|
||||
litres in a pipe run) is never lowered: the law's floor at every step
|
||||
(controls.tank_facts), hard in the plan (PENALTY_LIMIT per K and step)
|
||||
and in the guard;
|
||||
- a heat pump's COP falls with the tank's temperature: by the device's
|
||||
own curve over the tank's temperature (the mapping's cop_tank_curve
|
||||
[[°C, factor]]), else by dhw.hp_cop_drop_pct_per_k above
|
||||
dhw.hp_cop_ref_c (the COP's rating water temperature); the plan heats
|
||||
below the draw temperature at the COP there and above it at the
|
||||
maximum's (two layers, one binary per hour: optimizer.dhw_tank);
|
||||
- the owner's hot-water preferences (preferences "tank:<id>", backlog
|
||||
107): the tank at least c °C in a block (prefer: the short cost; must:
|
||||
MUST_EUR_K per K and step);
|
||||
- a combi boiler without a store (instant hot water): its comfort mode
|
||||
(keeping its heat exchanger warm) off at night (comfort.sleep) and while
|
||||
nobody is home, where the device has a writable comfort entity
|
||||
(dhw_comfort: a switch, or a select with dhw_comfort_options).
|
||||
|
||||
Every number is a Parameters row (SUGGESTED_ROWS); missing: the suggested
|
||||
value and refused names it (the owner's rule, as the battery's)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
STEP_S = 900
|
||||
|
||||
SUGGESTED_ROWS = {
|
||||
"dhw.idle_min_temp_c": 40.0, # the owner (2026-11-12): late night 40 °C
|
||||
"dhw.draw_expected_w": 100.0, # W of hot water's heat in a step: a draw expected (about 1.5 L at 40 K)
|
||||
"dhw.hp_cop_drop_pct_per_k": 2.0, # Carnot at 7 °C outside: COP 35 -> 55 °C water falls about 2 %/K
|
||||
"dhw.hp_cop_ref_c": 35.0, # EN 14511's water rating point W35
|
||||
"de.dvgw_w551_pipe_volume_l": 3.0, # DVGW W 551: more than 3 L in a pipe run is a large system
|
||||
"de.dvgw_w551_min_circulation_c": 55.0, # DVGW W 551: the circulation's return at least 55 °C
|
||||
}
|
||||
|
||||
|
||||
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 rows(box_params: dict | None) -> tuple[dict, list[str]]:
|
||||
"""The rows from the tariff bundle's params; missing: the suggested value. (rows, missing)."""
|
||||
bp = box_params or {}
|
||||
out, missing = {}, []
|
||||
for k, sug in SUGGESTED_ROWS.items():
|
||||
x = _num(bp.get(k))
|
||||
if x is None or x < 0:
|
||||
out[k], missing = sug, missing + [k]
|
||||
else:
|
||||
out[k] = x
|
||||
return out, missing
|
||||
|
||||
|
||||
def gap(missing: list[str]) -> dict:
|
||||
return {"why": "Parameters " + ("rows" if len(missing) > 1 else "row") + " missing: hot water planned with the "
|
||||
"suggested " + ("values" if len(missing) > 1 else "value") + " (" + ", ".join(missing) + ")",
|
||||
"missing": list(missing), "where": "the admin Parameters page (Hot water)", "fallback": "suggested",
|
||||
"kind": "hot_water", "name": "Hot water"}
|
||||
|
||||
|
||||
def floors(draw: list[float], draw_c: float, idle_c: float, law_c: float | None, r: dict) -> list[float]:
|
||||
"""The tank's least temperature per step: the draw temperature where a
|
||||
draw is expected, else the idle floor (never above the draw's); a
|
||||
Großanlage: the law's at every step."""
|
||||
if law_c is not None:
|
||||
return [max(law_c, draw_c)] * len(draw)
|
||||
w_min = float(r["dhw.draw_expected_w"])
|
||||
idle = min(idle_c, draw_c)
|
||||
return [draw_c if w >= w_min else idle for w in draw]
|
||||
|
||||
|
||||
def cop_factor(p: dict, temp_c: float, r: dict) -> float:
|
||||
"""A heat pump's COP at a tank temperature as a share of its rated COP:
|
||||
the device's curve over the tank's temperature (cop_tank_curve
|
||||
[[°C, factor]], linear, flat beyond its ends), else 1 - drop x (T -
|
||||
ref) above ref; never under 0.2 (a heat pump still pumps)."""
|
||||
curve = p.get("cop_tank_curve")
|
||||
if curve:
|
||||
try:
|
||||
pts = sorted((float(a), float(b)) for a, b in curve)
|
||||
except (TypeError, ValueError):
|
||||
pts = []
|
||||
if pts:
|
||||
if temp_c <= pts[0][0]:
|
||||
return max(0.2, pts[0][1])
|
||||
for (x0, y0), (x1, y1) in zip(pts, pts[1:]):
|
||||
if temp_c <= x1:
|
||||
return max(0.2, y0 + (y1 - y0) * (temp_c - x0) / (x1 - x0))
|
||||
return max(0.2, pts[-1][1])
|
||||
drop = float(r["dhw.hp_cop_drop_pct_per_k"]) / 100.0
|
||||
return max(0.2, 1.0 - drop * max(0.0, temp_c - float(r["dhw.hp_cop_ref_c"])))
|
||||
|
||||
|
||||
def combi_comfort(start: int, tz: str, steps: int, presence_w: list[float], sleep: dict) -> list[bool]:
|
||||
"""A combi boiler's comfort mode per step: on while someone is likely
|
||||
home (presence weight at least 0.5) and awake (outside comfort.sleep's
|
||||
hours), else off."""
|
||||
zone = ZoneInfo(tz or "UTC")
|
||||
|
||||
def hm(v):
|
||||
h, m = str(v).split(":")
|
||||
return int(h) * 60 + int(m)
|
||||
s_from, s_to = hm(sleep["from"]), hm(sleep["to"])
|
||||
out = []
|
||||
for t in range(steps):
|
||||
lt = datetime.fromtimestamp(start + t * STEP_S, timezone.utc).astimezone(zone)
|
||||
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)
|
||||
w = presence_w[t] if t < len(presence_w) else 1.0
|
||||
out.append(bool(w >= 0.5 and not asleep))
|
||||
return out
|
||||
@@ -95,7 +95,10 @@ class Collector:
|
||||
class History:
|
||||
"""Quarter-hour means of load and PV (W) for the last 8 days, kept on
|
||||
disk, for "the same quarter hour yesterday" and the box's models' "the
|
||||
same slot a week before" (localml.py)."""
|
||||
same slot a week before" (localml.py); since 2026-11-12 (methods.md G2,
|
||||
G5 in the plan) also the outdoor temperature ("t_out", °C: the comfort
|
||||
band's running mean) and each planned room's temperature ("room:<id>",
|
||||
°C: the flat's mass now, inputs.mass_start)."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self.path = path
|
||||
@@ -103,7 +106,8 @@ class History:
|
||||
try:
|
||||
with open(path) as f:
|
||||
raw = json.load(f)
|
||||
self.slots = {k: {int(t): v for t, v in raw.get(k, {}).items()} for k in self.slots}
|
||||
keys = set(self.slots) | {k for k in raw if k in ("t_out",) or k.startswith("room:")}
|
||||
self.slots = {k: {int(t): v for t, v in raw.get(k, {}).items()} for k in keys}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
@@ -111,13 +115,17 @@ class History:
|
||||
if value is None:
|
||||
return
|
||||
slot = int(now // STEP_S * STEP_S)
|
||||
s, n = self.slots[name].get(slot, [0.0, 0])
|
||||
s, n = self.slots.setdefault(name, {}).get(slot, [0.0, 0])
|
||||
self.slots[name][slot] = [s + value, n + 1]
|
||||
|
||||
def mean(self, name: str, slot: int) -> float | None:
|
||||
s = self.slots[name].get(slot)
|
||||
s = self.slots.get(name, {}).get(slot)
|
||||
return s[0] / s[1] if s and s[1] else None
|
||||
|
||||
def series(self, name: str, start: int, n: int) -> list[float | None]:
|
||||
"""The quarter-hour means of n slots from start (None where none)."""
|
||||
return [self.mean(name, start + k * STEP_S) for k in range(n)]
|
||||
|
||||
def save(self, now: float):
|
||||
cut = now - HISTORY_S
|
||||
for k in self.slots:
|
||||
@@ -179,6 +187,16 @@ def outdoor_temperature(start: int, col: Collector, inputs, ha_forecast: list[di
|
||||
return None, "none"
|
||||
|
||||
|
||||
def outdoor_now(col: Collector, inputs) -> float | None:
|
||||
"""The outdoor temperature now for the history (the comfort band's
|
||||
running mean, G5): the outdoor sensor, else the weather entity's
|
||||
temperature, else None."""
|
||||
v = col.value(inputs.outside_temp) if getattr(inputs, "outside_temp", None) else None
|
||||
if v is None and getattr(inputs, "weather", None):
|
||||
v = number(col.attr(inputs.weather, "temperature"))
|
||||
return v if v is not None and -60.0 < v < 60.0 else None
|
||||
|
||||
|
||||
def watts(col: Collector, eid: str) -> float | None:
|
||||
"""A power sensor's value in W (HA's kW converted)."""
|
||||
v = col.value(eid)
|
||||
@@ -408,6 +426,12 @@ def occupancy(start: int, tz: str, col: Collector, presence, bundles, history, b
|
||||
src["fixed_hours"] += 1
|
||||
src["source"] = ("learnt" if learnt is not None else "fixed_hours")
|
||||
src["presence_sources"] = len(presence or [])
|
||||
if learnt is not None:
|
||||
# the forecast's share per step (the presence now for the first hour): the comfort band's
|
||||
# weight (comfort.presence_weight, G5); taken out by model_state
|
||||
vals = got[0]
|
||||
src["_share"] = [None if (k < 4 and present is not None) or k >= len(vals)
|
||||
else min(1.0, max(0.0, float(vals[k]))) for k in range(STEPS)]
|
||||
return out, src, notes
|
||||
|
||||
|
||||
@@ -622,6 +646,56 @@ def battery_refusal(c, st: dict) -> dict | None:
|
||||
return {"why": "; ".join(why), "where": where, "missing": missing + (["soc"] if st.get("soc_pct") is None else [])}
|
||||
|
||||
|
||||
# The owner's battery algorithm on the box (2026-11-12; docs/methods.md A2.3a, D17): the Parameters page's rows for a
|
||||
# home's (a house's, a flat's) own battery, resolved for the site and sent in its tariff bundle's params (fleet
|
||||
# heatprice.go boxParamKeys). battery.pv_share_pct is not one: it caps a building battery's storing of PV its flats
|
||||
# could use; a household's own PV kept for its own later use is the plan's own business.
|
||||
BATTERY_WEAR_KEY = "battery.wear_ct"
|
||||
BATTERY_RESERVE_KEY = "battery.plan_reserve_pct"
|
||||
BATTERY_TOP_KEY = "battery.plan_max_soc_pct"
|
||||
BATTERY_RATIO_KEY = "battery.discharge_ratio_pct"
|
||||
|
||||
|
||||
def battery_rows(params: dict, fsrc: dict, box_params: dict | None, priced: bool) -> dict:
|
||||
"""The rows a battery is planned with (the owner's rule: no number stands in for a missing one): its wear (unless
|
||||
the device has its own wear_ct), the plan's reserve and top, and the discharge power as battery.discharge_ratio_pct
|
||||
of the one rated power where its facts give only one (the device's rated power or the owner's battery kW: the
|
||||
mapping's max_discharge_w is its own). With a tariff, a row missing from the bundle takes its suggested value
|
||||
(battery_core.SUGGESTED_ROWS) and {"gap": {why, where, missing, fallback}} names it (the owner, 2026-11-12);
|
||||
without one (nothing priced) the battery's own window and power, noted.
|
||||
Else {"params": what the plan uses, "src": per fact where it came from, "notes": [...]}. The shared rules
|
||||
(battery_core.discharge_kw, window: the building's own copy) make the numbers."""
|
||||
from . import battery_core
|
||||
bp = box_params or {}
|
||||
one_power = fsrc.get("max_discharge_w") != "mapping"
|
||||
need = [BATTERY_RESERVE_KEY, BATTERY_TOP_KEY] + ([BATTERY_WEAR_KEY] if number(params.get("wear_ct")) is None else []) \
|
||||
+ ([BATTERY_RATIO_KEY] if one_power else [])
|
||||
vals = {k: number(bp.get(k)) for k in need}
|
||||
missing = [k for k in need if vals[k] is None]
|
||||
out, src, notes, gap = {}, {}, [], None
|
||||
if missing and priced:
|
||||
# the owner (2026-11-12): fall back to the suggested values, with an alarm naming the rows
|
||||
gap = battery_core.suggested_gap(missing)
|
||||
for k in missing:
|
||||
vals[k] = battery_core.SUGGESTED_ROWS[k]
|
||||
if BATTERY_WEAR_KEY in missing:
|
||||
out["wear_ct"], src["wear_ct"] = vals[BATTERY_WEAR_KEY], "suggested"
|
||||
missing = []
|
||||
if missing:
|
||||
notes.append("battery: " + ", ".join(missing) + " not on the box (no tariff): its own window and power")
|
||||
ratio = vals.get(BATTERY_RATIO_KEY)
|
||||
if one_power and ratio is not None and number(params.get("max_charge_w")):
|
||||
ch_kw = float(params["max_charge_w"]) / 1000.0
|
||||
out["max_discharge_w"] = round(battery_core.discharge_kw(ch_kw, None, ratio) * 1000.0, 1)
|
||||
src["max_discharge_w"] = "ratio"
|
||||
for key, name in ((BATTERY_RESERVE_KEY, "plan_reserve_pct"), (BATTERY_TOP_KEY, "plan_max_soc_pct")):
|
||||
if vals.get(key) is not None:
|
||||
out[name], src[name] = vals[key], ("suggested" if gap and key in gap["missing"] else "parameter")
|
||||
if gap and BATTERY_RATIO_KEY in gap["missing"] and "max_discharge_w" in src:
|
||||
src["max_discharge_w"] = "suggested"
|
||||
return {"params": out, "src": src, "notes": notes, **({"gap": gap} if gap else {})}
|
||||
|
||||
|
||||
HYBRID_SWITCH_KEY = "heat.hybrid_switch_eur" # the Parameters page's (via the tariff bundle)
|
||||
|
||||
|
||||
@@ -798,11 +872,22 @@ def _tank_state(c, st: dict, params: dict, start: int, now: float, tz: str, bund
|
||||
for k in ("boiler_type", "part_load_curve"):
|
||||
if (c.params or {}).get(k):
|
||||
params[k] = c.params[k]
|
||||
src = dict(fsrc, draw=dsrc)
|
||||
# hot water as a reserve (hotwater.py, G7): the floor per step (the draw temperature where a draw is
|
||||
# expected, else the idle floor; a Großanlage the law's at every step), the heat pump's COP by the tank's
|
||||
# temperature
|
||||
from . import hotwater
|
||||
hw, hw_missing = hotwater.rows(box_params)
|
||||
params["hp_cop_drop_pct_per_k"] = hw["dhw.hp_cop_drop_pct_per_k"]
|
||||
params["hp_cop_ref_c"] = hw["dhw.hp_cop_ref_c"]
|
||||
if (c.params or {}).get("cop_tank_curve"):
|
||||
params["cop_tank_curve"] = c.params["cop_tank_curve"]
|
||||
floor_c = hotwater.floors(draw, float(facts["min_temp_c"]), hw["dhw.idle_min_temp_c"], facts.get("law_floor_c"), hw)
|
||||
src = dict(fsrc, draw=dsrc, floor="the law's (DVGW W 551)" if facts.get("law_floor_c") is not None else
|
||||
f"{float(facts['min_temp_c']):g} °C at draws, {min(hw['dhw.idle_min_temp_c'], float(facts['min_temp_c'])):g} °C between")
|
||||
if lt.get("ua") and not lt["ua"].get("kept"):
|
||||
src["ua_fit"] = (f"learnt UA {lt['ua']['ua_w_k']:g} W/K is {lt['ua']['ua_w_k'] / max(lt['ua'].get('label_ua_w_k') or 1e-9, 1e-9):.1f}x "
|
||||
"the label's: kept off (check the circulation pump and the insulation)")
|
||||
return {"draw_w": draw, "src": src}
|
||||
return {"draw_w": draw, "src": src, "floor_c": floor_c, **({"hw_missing": hw_missing} if hw_missing else {})}
|
||||
|
||||
|
||||
def heat_site(controls, devices: list, inputs, price_gas: list, price_heat: list, price_oil: list | None = None) -> dict:
|
||||
@@ -888,7 +973,7 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
occupied_hours=OCCUPIED_HOURS, building: dict | None = None, location: dict | None = None,
|
||||
shade_ctx: dict | None = None, grid_order: dict | None = None,
|
||||
grid_max_w: float | None = None, ev_phases: dict | None = None, presence: list | None = None,
|
||||
storefit=None) -> dict:
|
||||
storefit=None, comfort_ctx: dict | None = None) -> dict:
|
||||
"""The 48 h, 15-minute input for the optimiser (JSON: it runs in a
|
||||
subprocess). location: the site's latitude and longitude (HA's
|
||||
configuration); shade_ctx: per cover control its room (temp_c,
|
||||
@@ -929,6 +1014,7 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
# occupied per step: the presence now, then the learnt weekly presence, else 06-22 (occupancy)
|
||||
occupied, occ_src, occ_notes = occupancy(start, tz, col, inputs.presence if presence is None else presence,
|
||||
bundles, history, box, box_params, occupied_hours, fc_src)
|
||||
occ_share = occ_src.pop("_share", None)
|
||||
notes += occ_notes
|
||||
# the forecasts per source for the live error (boxtrain.py), not for the plan
|
||||
cands = {k: v.pop("_cands") for k, v in fc_src.items() if "_cands" in v}
|
||||
@@ -986,7 +1072,7 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
# a room's COP and comfort temperatures: the mapping's (the device's facts, the owner's), or the
|
||||
# defaults (optimizer.shift_envelope publishes no shift from defaults); rooms not planned
|
||||
# (room_refusal) with what their fallback schedule needs
|
||||
cop_src, band_src, fallback = {}, {}, []
|
||||
cop_src, band_src, fallback, zone_src = {}, {}, [], {}
|
||||
one_room = sum(c.kind in ("heating", "cooling") for c in controls) == 1
|
||||
for c in controls:
|
||||
if hasattr(c, "learn_range"):
|
||||
@@ -1004,6 +1090,10 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
params["phases"] = info["phases"]
|
||||
phases_src[c.id] = {"phases": info["phases"], "source": info["source"]}
|
||||
st = device_state(c, col, now)
|
||||
if c.kind == "cover":
|
||||
# its window's facts (G3 in the plan: the installer's, the device's, the owner's; never assumed)
|
||||
from .controls import FACTS
|
||||
params.update({k: float(c.params[k]) for k in FACTS["cover"] if number(c.params.get(k)) is not None})
|
||||
if c.kind == "ev":
|
||||
# the car's departure and energy from the session forecast where it says none (B15)
|
||||
ev_src[c.id], note = ev_session(c, st, sessions, start, now)
|
||||
@@ -1018,15 +1108,36 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
params["cop"] = 1.0 # a resistive heater: all its electricity becomes heat (physics)
|
||||
src, power = _room_rc(c, params, bundles, one_room, now)
|
||||
rooms_src[c.id] = src
|
||||
if params.get("_zone_note"):
|
||||
notes.append(f"{c.id}: {params.pop('_zone_note')}: its own R and C instead")
|
||||
if params.get("zone"):
|
||||
# the flat's mass now: observed on the room's history (B17.5), else the steady state
|
||||
past = start - 96 * STEP_S
|
||||
hist = history if hasattr(history, "series") else None
|
||||
m0, msrc = mass_start(params, hist.series(f"room:{c.id}", past, 96) if hist else [],
|
||||
hist.series("t_out", past, 96) if hist else [],
|
||||
st.get("temp_c") if st.get("temp_c") is not None else None)
|
||||
if m0 is None and t_out is not None and st.get("temp_c") is not None:
|
||||
m0, msrc = mass_start(params, [], [t_out[0]], st["temp_c"])
|
||||
if m0 is not None:
|
||||
params["zone"]["theta_m0"], params["zone"]["theta_m0_src"] = round(m0, 3), msrc
|
||||
zone_src[c.id] = {"share": params["zone"]["share"], "share_from": params["zone"]["share_src"],
|
||||
"mass_now_c": params["zone"].get("theta_m0"), "mass_from": msrc or "none"}
|
||||
zone_eer = None
|
||||
if c.kind == "cooling" and params.get("zone") and params["zone"].get("cool_eer") and power != "electric" \
|
||||
and "cop" not in c.params and not c.params.get("cop_curve"):
|
||||
# an A/C without its datasheet: the flat model's fitted EER (B17, G4; the device's curve wins)
|
||||
params["cop"] = zone_eer = float(params["zone"]["cool_eer"])
|
||||
# an electric fit runs in electric equivalents: the COP cancels (_room_rc)
|
||||
cop_src[c.id] = ("mapping" if "cop" in c.params or c.params.get("cop_curve") else
|
||||
"zone fit" if zone_eer else
|
||||
"electric heater" if c.kind == "heating" and source == "electric" else
|
||||
"electric fit" if power == "electric" and "cop" in params else "none")
|
||||
# comfort/setback/setup: the mapping's, else the box's copy of the Parameters rows
|
||||
# comfort.heating_setpoints / comfort.cooling_setpoints (docs/parameters.md C7)
|
||||
band_src[c.id] = "mapping" if any(k in c.params for k in ("comfort_c", "setback_c", "setup_c")) else "defaults"
|
||||
# what is missing for the room and for its heat source (methods E6)
|
||||
nos = [room_refusal(c, st, src, power, source)]
|
||||
nos = [room_refusal(c, st, src, power, source, cop_known=zone_eer is not None)]
|
||||
if c.kind == "heating":
|
||||
nos.append(heating_refusal(c, params, price_gas, price_heat, getattr(prices, "status", "tariff"),
|
||||
box_params, price_oil))
|
||||
@@ -1059,7 +1170,17 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
continue
|
||||
facts, _, fsrc = c.battery_facts()
|
||||
params.update(facts)
|
||||
battery_src[c.id] = dict(fsrc)
|
||||
# the owner's battery algorithm (A2.3a): the reserve, the top, the discharge power, the wear's row (the
|
||||
# mapping's own wear_ct first: the device's ageing per kWh where its owner knows it)
|
||||
own_wear = number((getattr(c, "params", None) or {}).get("wear_ct"))
|
||||
if own_wear is not None and own_wear >= 0:
|
||||
params["wear_ct"] = own_wear
|
||||
rows = battery_rows(params, fsrc, box_params, prices.status != "none")
|
||||
if "gap" in rows: # planned with the suggested values: reported like a refusal, marked fallback
|
||||
refused[c.id] = dict(rows["gap"], kind="battery", name=c.label() if hasattr(c, "label") else c.id)
|
||||
params.update(rows["params"])
|
||||
notes += rows["notes"]
|
||||
battery_src[c.id] = dict(fsrc, **rows["src"])
|
||||
# its idle loss (A2.3, S.2): never refuses it; without any value 0, a quiet note
|
||||
if hasattr(c, "battery_idle_facts"):
|
||||
fit = storefit.battery_in_force(c.id) if storefit is not None else None
|
||||
@@ -1093,12 +1214,24 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
params["cop_curve"] = []
|
||||
got["src"] = dict(got["src"], cop="its one COP (no outdoor temperature for the curve)")
|
||||
tank_src[c.id] = got["src"]
|
||||
extra = {"draw_w": got["draw_w"]}
|
||||
extra = {"draw_w": got["draw_w"], "floor_c": got["floor_c"]}
|
||||
if got.get("hw_missing") and box_params:
|
||||
from . import hotwater
|
||||
refused["hot_water"] = hotwater.gap(got["hw_missing"])
|
||||
b = c.bounds("temp_c", (extra_limits or {}).get(c.id)) # with a Großanlage's floor (tank_facts)
|
||||
bounds["temp_c"] = [b.lo, b.hi, b.lo_by, b.hi_by]
|
||||
devices.append({"id": c.id, "kind": c.kind, "params": params,
|
||||
"state": st, "bounds": bounds,
|
||||
"channels": sorted(c.writable()), **extra})
|
||||
comfort_info, presence_w = comfort_bands(devices, controls, start, now, tz, t_out, history, box_params, occupied, occ_share,
|
||||
band_src, refused, notes, comfort_ctx or {})
|
||||
# a combi boiler's comfort mode (hotwater.combi_comfort, G7): off at night and while nobody is home
|
||||
for d in devices:
|
||||
if d["kind"] == "heating" and "dhw_comfort" in d["channels"] and \
|
||||
str(d["params"].get("combi") or "").lower() in ("true", "yes", "1"):
|
||||
from . import comfort, hotwater
|
||||
sleep = comfort.rows(box_params)[0]["comfort.sleep"]
|
||||
d["dhw_comfort"] = hotwater.combi_comfort(start, tz, STEPS, presence_w, sleep)
|
||||
clouds = _hourly(weather_forecast or [], "cloud_coverage", start, STEPS)
|
||||
sky_src = "weather forecast"
|
||||
if clouds is None and fwx:
|
||||
@@ -1117,10 +1250,14 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
"tariff": getattr(prices, "tariff_id", ""), "expired_at": getattr(prices, "expired_at", 0),
|
||||
"priced_steps": getattr(prices, "priced_steps", STEPS)},
|
||||
"load_w": load, "pv_w": pv, "t_out": t_out, "sun": sun, "occupied": occupied, "sky": sky,
|
||||
# the probability someone is home per step (comfort.presence_weight: the band's weight, the zone's gain)
|
||||
"presence_w": presence_w,
|
||||
"ghi_w_m2": ghi, "location": location or {},
|
||||
"sources": {"load": load_src, "pv": pv_src, "outdoor": t_src, "model": bundles.model_id(),
|
||||
"sky": sky_src if clouds else "clear", "rooms": rooms_src, "ghi": ghi_src,
|
||||
"rooms_cop": cop_src, "rooms_band": band_src,
|
||||
**({"rooms_zone": zone_src} if zone_src else {}),
|
||||
**({"comfort": comfort_info} if comfort_info else {}),
|
||||
"ev_phases": phases_src,
|
||||
# occupied steps per source (presence now, learnt, fixed hours) and why (B16)
|
||||
"occupancy": occ_src,
|
||||
@@ -1155,7 +1292,12 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
from . import shades
|
||||
for d in devices:
|
||||
if d["kind"] == "cover":
|
||||
d["schedule"] = shades.schedule(d, out, (shade_ctx or {}).get(d["id"]))
|
||||
# with its window's facts the plan places it (G3); else A7's rules on the sun
|
||||
wp = shades.window_plan(d, out, (shade_ctx or {}).get(d["id"]))
|
||||
if wp is not None:
|
||||
d["window"] = wp
|
||||
else:
|
||||
d["schedule"] = shades.schedule(d, out, (shade_ctx or {}).get(d["id"]))
|
||||
return out
|
||||
|
||||
|
||||
@@ -1198,6 +1340,14 @@ def _room_rc(c, params: dict, bundles, only_one: bool, now: float) -> str:
|
||||
return "mapping", "thermal"
|
||||
if has:
|
||||
return "partial", ""
|
||||
# the flat's 2R2C (air and mass, B17) where the cloud's daily check passed, scaled to the room
|
||||
# (G2 in the plan, backlog 473): pre-heating and pre-cooling are stored in the mass
|
||||
zget = getattr(bundles, "zone_rc", None)
|
||||
z, zwhy = zget(c.id, str(c.params.get("area") or ""), only_one, now) if zget else (None, "")
|
||||
if z is not None:
|
||||
return _zone_params(c, params, z), ("electric" if z["power"] == "electric" else "thermal")
|
||||
if zwhy:
|
||||
params["_zone_note"] = zwhy
|
||||
# the box's own fit where it is in force (boxtrain.py), else the cloud's
|
||||
own = getattr(bundles, "own", None)
|
||||
rc = own.room_rc(c.id, str(c.params.get("area") or ""), only_one) if own is not None else None
|
||||
@@ -1230,7 +1380,124 @@ def _room_rc(c, params: dict, bundles, only_one: bool, now: float) -> str:
|
||||
return src, ("electric" if rc.get("power") == "electric" else "thermal")
|
||||
|
||||
|
||||
def room_refusal(c, st: dict, rc: str, power: str, source: str = "electric") -> dict | None:
|
||||
def _zone_params(c, params: dict, z: dict) -> str:
|
||||
"""The room as its share of the flat's 2R2C (bundles.zone_rc): the
|
||||
resistances divided by the share, the capacities and gains times it (a
|
||||
room that is that share of the flat, with the flat's time constants:
|
||||
methods.md G2 in the plan). Fitted against the electric power: R / cop,
|
||||
C x cop as a room's (_room_rc). Into params["zone"] {r_i, r_e, c_a, c_m,
|
||||
gain_w, solar_m2, el_gain_share, occ_gain_w, share, ...}; params' R and
|
||||
C the one-node equivalent (R_i + R_e, C_eff: the shift envelope and the
|
||||
heating levers, which run one node). The mapping's own gains win."""
|
||||
sh = z["share"]
|
||||
k = 1.0
|
||||
electric = str(params.get("heat_source") or "electric") in ("electric", "heat_pump")
|
||||
if z["power"] == "electric" and electric:
|
||||
cop = number(params.get("cop")) or 1.0
|
||||
if c.kind == "cooling" or "cop" in params:
|
||||
params["cop"] = cop
|
||||
k = cop
|
||||
ri, re_ = z["r_i"] / sh / k, z["r_e"] / sh / k
|
||||
ca, cm = z["c_a"] * sh * k, z["c_m"] * sh * k
|
||||
zone = {"r_i": ri, "r_e": re_, "c_a": ca, "c_m": cm, "share": sh, "share_src": z.get("share_src", ""),
|
||||
"power": z["power"], "gain_w": z["gain_w"] * sh * k, "solar_m2": z["solar_m2"] * sh * k,
|
||||
"solar_kind": z.get("solar_kind", "ghi"),
|
||||
"el_gain_share": z["el_gain_share"] * sh * k, "occ_gain_w": z["occ_gain_w"] * sh * k,
|
||||
"cool_eer": z.get("cool_eer")}
|
||||
params["zone"] = zone
|
||||
params["r_k_per_kw"] = ri + re_
|
||||
params["c_kwh_per_k"] = ca + cm * re_ / (ri + re_)
|
||||
if "internal_gain_w" not in c.params:
|
||||
params["internal_gain_w"] = zone["gain_w"]
|
||||
if "solar_m2" not in c.params:
|
||||
params["solar_m2"] = zone["solar_m2"]
|
||||
return "zone 2r2c"
|
||||
|
||||
|
||||
def comfort_bands(devices: list, controls, start: int, now: float, tz: str, t_out: list | None, history,
|
||||
box_params: dict, occupied: list, occ_share: list | None, band_src: dict, refused: dict,
|
||||
notes: list, ctx: dict) -> tuple[dict | None, list[float]]:
|
||||
"""Each planned room's comfort band per step (comfort.py, methods.md G5
|
||||
in the plan) into d["band"]: EN 16798-1's band for the household's
|
||||
choice (ctx "mode": comfort | balanced | saving, the preferences'
|
||||
"comfort"; else the Parameters page's default), on the running mean
|
||||
outdoor temperature (the box's history "t_out" and the forecast), the
|
||||
household's tolerance from its overrides (ctx "tolerance"), weighted by
|
||||
the probability someone is home. The owner's schedule still wins
|
||||
(preferences.apply; the optimizer takes the band only without one).
|
||||
Rows missing: their suggested values and refused["comfort_band"] names
|
||||
them. (the plan's sources.comfort, the presence weight per step)."""
|
||||
from . import comfort
|
||||
raw = (box_params or {}).get(OCC_SHARE_KEY)
|
||||
weights = comfort.presence_weight(occupied, occ_share, number(raw) if not isinstance(raw, bool) else None)
|
||||
rooms = [d for d in devices if d["kind"] in ("heating", "cooling")]
|
||||
if not rooms:
|
||||
return None, weights
|
||||
r, missing = comfort.rows(box_params)
|
||||
if missing and box_params:
|
||||
# the bundle carries the Parameters but not these: the alarm (the owner's rule, as the battery's rows)
|
||||
refused["comfort_band"] = comfort.gap(missing)
|
||||
elif missing:
|
||||
notes.append("comfort band: no Parameters on the box yet (no tariff bundle): EN 16798-1's suggested values")
|
||||
mode = ctx.get("mode") if ctx.get("mode") in comfort.MODES else r["comfort.default_mode"]
|
||||
past_n = 7 * 96
|
||||
past = history.series("t_out", start - past_n * STEP_S, past_n) if hasattr(history, "series") else []
|
||||
days = comfort.daily_means(start, tz, past, start - past_n * STEP_S, t_out)
|
||||
zone = ZoneInfo(tz or "UTC")
|
||||
horizon_days = sorted({datetime.fromtimestamp(start + k * STEP_S, timezone.utc).astimezone(zone).date().isoformat()
|
||||
for k in range(STEPS + 1)})
|
||||
alpha = float(r["comfort.running_mean_alpha"])
|
||||
rm = {d: comfort.running_mean(days, d, alpha) for d in horizon_days}
|
||||
if any(v is None for v in rm.values()):
|
||||
notes.append("comfort band: no running mean outdoor temperature for " +
|
||||
", ".join(d for d, v in rm.items() if v is None) +
|
||||
" (under a day of the box's outdoor history): EN 16798-1's fixed values there")
|
||||
cooled = any(getattr(c, "kind", "") == "cooling" for c in controls)
|
||||
tol = ctx.get("tolerance")
|
||||
info = {"mode": mode, "category": r["comfort.mode_categories"].get(mode), "rows": "suggested" if missing else "parameters",
|
||||
"running_mean_c": {d: (round(v, 2) if v is not None else None) for d, v in rm.items()},
|
||||
"history_days": sum(1 for d in days if d < horizon_days[0]), "tolerance": {}}
|
||||
for d in rooms:
|
||||
kind = d["kind"]
|
||||
p = d["params"]
|
||||
back = p.get("setup_c" if kind == "cooling" else "setback_c")
|
||||
if back is None:
|
||||
continue
|
||||
shift, n = tol.shift(d["id"], kind, now, r) if tol is not None else (0.0, 0)
|
||||
d["band"] = comfort.room_band(r, kind, mode, start, tz, STEPS, weights, rm, float(back), cooled, shift)
|
||||
band_src[d["id"]] = f"en16798 {d['band']['category']}"
|
||||
if n:
|
||||
info["tolerance"][d["id"]] = {"shift_k": round(shift, 2), "overrides": n}
|
||||
return info, weights
|
||||
|
||||
|
||||
def mass_start(params: dict, temps: list, t_out: list, now_c: float | None) -> tuple[float | None, str]:
|
||||
"""The zone's mass temperature now (methods.md B17.5, the fit's
|
||||
observer): the mass equation driven by the room's measured air over the
|
||||
last 24 h (temps, t_out: oldest first, None where missing: the last
|
||||
value held), from the steady state at the first value; without a day of
|
||||
history the steady state now (R_e theta_a + R_i T_out) / (R_i + R_e)."""
|
||||
z = params.get("zone")
|
||||
if not z or now_c is None:
|
||||
return None, ""
|
||||
ri, re_, cm = z["r_i"], z["r_e"], z["c_m"]
|
||||
pairs = [(a, o) for a, o in zip(temps, t_out)]
|
||||
have = [p for p in pairs if p[0] is not None and p[1] is not None]
|
||||
if len(have) < 48:
|
||||
if not t_out or t_out[-1] is None:
|
||||
return None, ""
|
||||
return (re_ * now_c + ri * t_out[-1]) / (ri + re_), "steady state now (under 12 h of the room's history)"
|
||||
a = math.exp(-STEP_S / 3600.0 * (1.0 / ri + 1.0 / re_) / cm)
|
||||
ta, to = have[0]
|
||||
m = (re_ * ta + ri * to) / (ri + re_)
|
||||
for x, y in pairs:
|
||||
ta = x if x is not None else ta
|
||||
to = y if y is not None else to
|
||||
m = a * m + (1 - a) * (re_ * ta + ri * to) / (ri + re_)
|
||||
return m, f"observed over {len(have) // 4} h of the room's history"
|
||||
|
||||
|
||||
def room_refusal(c, st: dict, rc: str, power: str, source: str = "electric", cop_known: bool = False) -> dict | None:
|
||||
"""Why a heating or cooling room is not planned (docs/parameters.md E3: R/C measured, power and COP the device's), or
|
||||
None: no R/C (no fit, the mapping sets neither, or only one of the
|
||||
two), the heater's or cooler's electric power unknown (max_power_w),
|
||||
@@ -1260,7 +1527,8 @@ def room_refusal(c, st: dict, rc: str, power: str, source: str = "electric") ->
|
||||
where.append("the mapping's params (max_power_w, W)")
|
||||
missing.append("max_power_w")
|
||||
# a cooler's COP (a heater's: electric 1, a heat pump's or hybrid's: heating_refusal)
|
||||
if c.kind == "cooling" and rc in ("mapping", "model", "box model") and power != "electric" and "cop" not in c.params:
|
||||
if c.kind == "cooling" and rc in ("mapping", "model", "box model", "zone 2r2c") and power != "electric" \
|
||||
and "cop" not in c.params and not cop_known:
|
||||
why.append("COP unknown (heat per kWh of electricity)")
|
||||
where.append("the mapping's params (cop)")
|
||||
missing.append("cop")
|
||||
|
||||
@@ -266,6 +266,8 @@ NAMES = {
|
||||
"de": "keine Prognose: der Parameter {0} fehlt im Tarif (Parameter-Seite)"},
|
||||
"cg_no_fixed": {"en": "fixed charges unknown: the tariff does not carry them yet",
|
||||
"de": "Grundpreise unbekannt: der Tarif enthält sie noch nicht"},
|
||||
"cg_no_gas_conv": {"en": "the gas meter counts m³ but the tariff has no Brennwert and Zustandszahl for today: its gas is not counted",
|
||||
"de": "der Gaszähler zählt m³, aber der Tarif hat für heute keinen Brennwert und keine Zustandszahl: sein Gas wird nicht gezählt"},
|
||||
"cg_no_meter_electricity": {"en": "no grid meter mapped (energy from the grid or grid power)",
|
||||
"de": "kein Netzzähler zugeordnet (Energie aus dem Netz oder Netzleistung)"},
|
||||
"cg_no_meter_gas": {"en": "gas is priced but no gas meter is mapped", "de": "Gas hat einen Preis, aber kein Gaszähler ist zugeordnet"},
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -78,8 +78,21 @@ HOW = ("must", "prefer")
|
||||
HOW_WORDS = {"must": "must", "muss": "must", "prefer": "prefer", "bevorzugt": "prefer", "gern": "prefer"}
|
||||
LEVELS = ("operator", "installer", "owner") # low to high: the highest set is in force
|
||||
RANK = {lvl: i + 1 for i, lvl in enumerate(LEVELS)}
|
||||
KINDS = {"heating": "room", "cooling": "room", "ev": "ev", "battery": "battery"}
|
||||
RANGE_C = {"heating": (5.0, 30.0), "cooling": (16.0, 32.0)} # controls.RANGE
|
||||
KINDS = {"heating": "room", "cooling": "room", "ev": "ev", "battery": "battery", "dhw_tank": "tank"}
|
||||
COMFORT_KEY = "comfort" # the flat's choice comfort | balanced | saving (methods.md G5): {"mode": ...}
|
||||
COMFORT_MODES = ("comfort", "balanced", "saving")
|
||||
COMFORT_WORDS = {"comfort": "comfort", "komfort": "comfort", "balanced": "balanced", "ausgewogen": "balanced",
|
||||
"saving": "saving", "sparen": "saving", "sparsam": "saving"}
|
||||
|
||||
|
||||
class _Site:
|
||||
"""The site itself for a site-wide preference (the comfort choice)."""
|
||||
id, kind, limits = "", "site", {}
|
||||
|
||||
|
||||
_SITE = _Site()
|
||||
RANGE_C = {"heating": (5.0, 30.0), "cooling": (16.0, 32.0), # controls.RANGE
|
||||
"dhw_tank": (20.0, 80.0)} # a hot-water tank's least temperature in a block (107; dhw.* rows' range)
|
||||
MAX_BLOCKS = 16
|
||||
MAX_OVERRIDES = 20
|
||||
MAX_LOG = 200
|
||||
@@ -177,7 +190,7 @@ def _fmt(x: float) -> str:
|
||||
|
||||
# -- checked values (every source comes through these) --------------------------
|
||||
def check_room(v: dict, kind: str) -> dict:
|
||||
lo, hi = RANGE_C["cooling" if kind == "cooling" else "heating"]
|
||||
lo, hi = RANGE_C.get(kind, RANGE_C["heating"])
|
||||
blocks = (v or {}).get("blocks")
|
||||
if not isinstance(blocks, list) or len(blocks) > MAX_BLOCKS:
|
||||
raise ValueError(f"blocks: a list of at most {MAX_BLOCKS}")
|
||||
@@ -228,8 +241,19 @@ def check_battery(v: dict) -> dict:
|
||||
return out
|
||||
|
||||
|
||||
def check_comfort(v: dict) -> dict:
|
||||
mode = COMFORT_WORDS.get(str((v or {}).get("mode", "")).strip().lower())
|
||||
if mode is None:
|
||||
raise ValueError("comfort: mode comfort, balanced or saving")
|
||||
return {"mode": mode}
|
||||
|
||||
|
||||
def check(key: str, value: dict, kind: str) -> dict:
|
||||
what = key.split(":", 1)[0]
|
||||
if key == COMFORT_KEY:
|
||||
return check_comfort(value)
|
||||
if what == "tank":
|
||||
return check_room(value, "dhw_tank")
|
||||
if what == "room":
|
||||
return check_room(value, kind)
|
||||
if what == "ev":
|
||||
@@ -455,6 +479,12 @@ class Preferences:
|
||||
return dict(per[lvl], level=lvl)
|
||||
return None
|
||||
|
||||
def comfort_mode(self) -> str | None:
|
||||
"""The flat's comfort choice (comfort | balanced | saving), or None:
|
||||
the Parameters page's default (comfort.py, methods.md G5)."""
|
||||
v = self.value(COMFORT_KEY)
|
||||
return v.get("mode") if v and v.get("mode") in COMFORT_MODES else None
|
||||
|
||||
def value(self, key: str) -> dict | None:
|
||||
e = self.effective(key)
|
||||
return e["value"] if e else None
|
||||
@@ -494,7 +524,9 @@ class Preferences:
|
||||
if level not in RANK:
|
||||
return self._refused(now, by, key, f"level: one of {', '.join(LEVELS)}")
|
||||
what, _, cid = key.partition(":")
|
||||
if control is None or control.id != cid or KINDS.get(control.kind) != what:
|
||||
if key == COMFORT_KEY:
|
||||
control = _SITE # the flat's (the site's) own choice: no control
|
||||
elif control is None or control.id != cid or KINDS.get(control.kind) != what:
|
||||
return self._refused(now, by, key, f"no {what} control {cid!r}")
|
||||
if value is None:
|
||||
if level in (self.items.get(key) or {}):
|
||||
@@ -697,6 +729,8 @@ class Preferences:
|
||||
p = ev_need(d, self.value(f"ev:{d['id']}"), ovs, state, zone, now, col, c)
|
||||
elif d["kind"] == "battery":
|
||||
p = battery_series(d, self.value(f"battery:{d['id']}"), ends)
|
||||
elif d["kind"] == "dhw_tank":
|
||||
p = tank_series(d, self.value(f"tank:{d['id']}"), ends)
|
||||
else:
|
||||
p = None
|
||||
if p is not None:
|
||||
@@ -868,7 +902,7 @@ def within_owner(key: str, value: dict, c):
|
||||
mapping's owner level), never above them."""
|
||||
what = key.split(":", 1)[0]
|
||||
owner = lambda q: (c.limits.get(q) or {}).get("owner") or (None, None) # noqa: E731
|
||||
if what == "room":
|
||||
if what in ("room", "tank"):
|
||||
lo, hi = owner("temp_c")
|
||||
for b in value["blocks"]:
|
||||
if (lo is not None and b["c"] < lo) or (hi is not None and b["c"] > hi):
|
||||
@@ -940,6 +974,33 @@ def room_series(d: dict, value: dict | None, ovs: list[dict], state: dict, ends)
|
||||
return {"target": target, "must": must, "group": group, "base": base, "groups": groups}
|
||||
|
||||
|
||||
def tank_series(d: dict, value: dict | None, ends) -> dict | None:
|
||||
"""A hot-water tank's least temperature per step from the owner's blocks
|
||||
(backlog 107; "Mo-Fr 06:00-08:00 55 must"): floor (°C or None), must
|
||||
(°C or None), group (the block, -1: none)."""
|
||||
blocks = (value or {}).get("blocks") or []
|
||||
if not blocks:
|
||||
return None
|
||||
groups = [{"group": f"{d['id']}:{i}", "kind": "block", "how": b["how"], "c": b["c"],
|
||||
"text": f"hot water {days_text(b['days'])} {b['from']}-{b['to']} ≥ {_fmt(b['c'])} °C"}
|
||||
for i, b in enumerate(blocks)]
|
||||
floor, must, group = [], [], []
|
||||
for t in range(len(ends)):
|
||||
wd, m = ends[t]
|
||||
hit = [(i, b) for i, b in enumerate(blocks) if in_block(b, wd, m)]
|
||||
if not hit:
|
||||
floor.append(None)
|
||||
must.append(None)
|
||||
group.append(-1)
|
||||
continue
|
||||
c = max(b["c"] for _, b in hit)
|
||||
ms = [b["c"] for _, b in hit if b["how"] == "must"]
|
||||
floor.append(c)
|
||||
must.append(max(ms) if ms else None)
|
||||
group.append(next(i for i, b in hit if b["c"] == (must[-1] if ms else c)))
|
||||
return {"floor": floor, "must": must, "group": group, "groups": groups}
|
||||
|
||||
|
||||
def next_ready(value: dict | None, zone: ZoneInfo, now: float) -> tuple[float, dict] | None:
|
||||
"""The next ready-by time after now and its entry."""
|
||||
best = None
|
||||
@@ -1024,6 +1085,10 @@ def battery_series(d: dict, value: dict | None, ends) -> dict | None:
|
||||
# -- words ----------------------------------------------------------------------------
|
||||
def describe(key: str, value: dict, kind: str = "") -> str:
|
||||
what = key.split(":", 1)[0]
|
||||
if key == COMFORT_KEY:
|
||||
return f"comfort: {value.get('mode')}"
|
||||
if what == "tank":
|
||||
return ("hot water " + room_text(value)) if value.get("blocks") else "no hot-water times"
|
||||
if what == "room":
|
||||
return room_text(value) or "no schedule"
|
||||
if what == "ev":
|
||||
@@ -1036,15 +1101,21 @@ def describe(key: str, value: dict, kind: str = "") -> str:
|
||||
|
||||
def text_of(key: str, value: dict) -> str:
|
||||
what = key.split(":", 1)[0]
|
||||
return {"room": room_text, "ev": ev_text, "battery": battery_text}.get(what, lambda v: "")(value)
|
||||
if key == COMFORT_KEY:
|
||||
return str((value or {}).get("mode") or "")
|
||||
return {"room": room_text, "tank": room_text, "ev": ev_text, "battery": battery_text}.get(what, lambda v: "")(value)
|
||||
|
||||
|
||||
def from_text(key: str, text: str, control, current: dict) -> dict:
|
||||
what = key.split(":", 1)[0]
|
||||
if key == COMFORT_KEY:
|
||||
return check_comfort({"mode": text})
|
||||
if control is None:
|
||||
raise ValueError(f"no control for {key!r}")
|
||||
if what == "room":
|
||||
return parse_room_text(text, control.kind)
|
||||
if what == "tank":
|
||||
return parse_room_text(text, "dhw_tank")
|
||||
if what == "ev":
|
||||
return parse_ev_text(text, current.get("capacity_kwh"))
|
||||
if what == "battery":
|
||||
|
||||
@@ -28,7 +28,8 @@ owner's choice):
|
||||
consented) and one occupancy or presence binary_sensor per area as
|
||||
room.<area>.occupied (1 while "on"), for the occupancy the box and
|
||||
the cloud learn; device trackers are left to the persons they make
|
||||
up (or mapped by hand);
|
||||
up (or mapped by hand); one window contact per area as
|
||||
room.<area>.window (1 while "on": the thermal fit, B17 G6);
|
||||
4. the rest by name (mapping.suggest): only Cantabile's own quantities
|
||||
(pv, grid, battery, load, heat pump, EV) and one temperature and
|
||||
humidity per area, from sensors that have a value now; marked
|
||||
@@ -275,6 +276,7 @@ def from_profiles(r: Registry, profiles: list[dict]) -> list[tuple[str, dict, fl
|
||||
|
||||
|
||||
PRESENCE_CLASSES = ("occupancy", "presence") # a binary_sensor's device classes that say someone is there
|
||||
WINDOW_CLASSES = ("window",) # a window's contact (the thermal fit's open windows, B17 G6)
|
||||
|
||||
|
||||
def person_id(entity_id: str) -> str:
|
||||
@@ -285,7 +287,9 @@ def person_id(entity_id: str) -> str:
|
||||
def presence_sources(r: Registry) -> list[tuple[str, str, dict, bool]]:
|
||||
"""(asset, entity, read, unique) of the presence sources: HA's persons
|
||||
(person.<id>.home, equals home) and per area one occupancy or presence
|
||||
binary_sensor (room.<area>.occupied, equals on)."""
|
||||
binary_sensor (room.<area>.occupied, equals on); and per area one
|
||||
window contact (room.<area>.window, equals on: the thermal fit leaves
|
||||
the slots a window is open out, methods.md B17 G6)."""
|
||||
out = []
|
||||
for eid in sorted(r.states):
|
||||
if eid.startswith("person."):
|
||||
@@ -298,6 +302,8 @@ def presence_sources(r: Registry) -> list[tuple[str, str, dict, bool]]:
|
||||
area = r.area_name(e)
|
||||
if dc in PRESENCE_CLASSES and area:
|
||||
out.append((f"room.{slug(area)}.occupied", eid, {"equals": "on"}, True))
|
||||
elif dc in WINDOW_CLASSES and area:
|
||||
out.append((f"room.{slug(area)}.window", eid, {"equals": "on"}, True))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -117,6 +117,69 @@ def on_facade(elev: float, az: float, face: float | None) -> float:
|
||||
return max(0.0, x)
|
||||
|
||||
|
||||
def facade_irradiance(ts: float, ghi: float, lat: float, lon: float, face: float, albedo: float = 0.2) -> float:
|
||||
"""W/m² on a vertical window facing `face` (° from north) from the
|
||||
global horizontal irradiance (Erbs' diffuse share, an isotropic sky,
|
||||
the ground's albedo 0.2; as building/thermal2r2c.facade_irradiance,
|
||||
which the flat's model was fitted with: methods.md B17.3). 0 at night."""
|
||||
elev, az = sun_position(ts, lat, lon)
|
||||
se = math.sin(math.radians(elev))
|
||||
if se <= 0 or ghi <= 0:
|
||||
return 0.0
|
||||
doy = (ts / 86400.0) % 365.25 + 1
|
||||
g0 = 1367 * (1 + 0.033 * math.cos(2 * math.pi * doy / 365)) * se
|
||||
kt = min(max(ghi / g0, 0.0), 1.0) if g0 > 0 else 0.0
|
||||
fd = 1 - 0.09 * kt if kt <= 0.22 else \
|
||||
(0.9511 - 0.1604 * kt + 4.388 * kt ** 2 - 16.638 * kt ** 3 + 12.336 * kt ** 4 if kt <= 0.8 else 0.165)
|
||||
dhi = fd * ghi if elev > 2 else ghi
|
||||
cos_inc = math.cos(math.radians(elev)) * math.cos(math.radians(az - face))
|
||||
beam = (ghi - dhi) / se * max(cos_inc, 0.0) if elev > 2 else 0.0
|
||||
return max(0.0, beam + dhi * 0.5 + ghi * albedo * 0.5)
|
||||
|
||||
|
||||
WINDOW_FACTS = ("window_m2", "g_value", "shade_factor")
|
||||
|
||||
|
||||
def window_plan(d: dict, s: dict, ctx: dict | None = None) -> dict | None:
|
||||
"""A cover with its window's facts (methods.md G3 in the plan): its
|
||||
position a plan variable, the sun through the window after it, per step
|
||||
(W) the part a closed cover keeps out (coef: x the closed share) and
|
||||
the rest (fixed); a shutter with the window's U and its closed factor
|
||||
lowers the loss (h_sh W/K x (the room now - outside) x the closed
|
||||
share). The inhabitant's own position holds while the guard keeps off
|
||||
the cover (ctx held_until: fixed there). None without the facts, the
|
||||
facade or the site's location: A7's rules stay (schedule)."""
|
||||
p = d.get("params") or {}
|
||||
face = facing(p.get("facing"))
|
||||
loc = s.get("location") or {}
|
||||
lat, lon = loc.get("latitude"), loc.get("longitude")
|
||||
if face is None or lat is None or lon is None or any(not _pos(p.get(k)) for k in WINDOW_FACTS):
|
||||
return None
|
||||
ctx = ctx or {}
|
||||
area, g, f = float(p["window_m2"]), min(float(p["g_value"]), 1.0), min(float(p["shade_factor"]), 1.0)
|
||||
T, start, step = int(s["steps"]), int(s["start"]), int(s["step_s"])
|
||||
ghi = s.get("ghi_w_m2") or [0.0] * T
|
||||
irr = [facade_irradiance(start + (t + 0.5) * step, float(ghi[t]) if t < len(ghi) else 0.0, float(lat), float(lon), face)
|
||||
for t in range(T)]
|
||||
sun_w = [g * area * i for i in irr]
|
||||
h_sh = 0.0
|
||||
if _pos(p.get("window_u")) and _pos(p.get("closed_u_factor")):
|
||||
h_sh = area * float(p["window_u"]) * (1.0 - min(float(p["closed_u_factor"]), 1.0))
|
||||
held = float(ctx.get("held_until") or 0.0)
|
||||
pos0 = (d.get("state") or {}).get("position_pct")
|
||||
hold_steps = max(0, min(T, int(math.ceil((held - start) / step)))) if held > start and pos0 is not None else 0
|
||||
return {"sun_w": [round(x, 1) for x in sun_w], "shade_factor": f, "h_sh": round(h_sh, 3),
|
||||
"hold_steps": hold_steps, "hold_pos": float(pos0) / 100.0 if pos0 is not None else None,
|
||||
"irr": [round(x, 1) for x in irr]}
|
||||
|
||||
|
||||
def _pos(v) -> bool:
|
||||
try:
|
||||
return float(v) > 0
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def _minutes(hhmm: str) -> int | None:
|
||||
try:
|
||||
h, m = (int(x) for x in str(hhmm).split(":"))
|
||||
|
||||
@@ -209,7 +209,8 @@ def stabilise(plan: dict, state: dict, controls, col, last_set=None, now: float
|
||||
for e in out:
|
||||
if merged and _same(_val(c, merged[-1]), _val(c, e)) and \
|
||||
(merged[-1].get("grid") == e.get("grid") or _val(c, e) == AUTO) and \
|
||||
merged[-1].get("source") == e.get("source"):
|
||||
merged[-1].get("source") == e.get("source") and \
|
||||
merged[-1].get("dhw_comfort") == e.get("dhw_comfort"):
|
||||
continue
|
||||
merged.append(e)
|
||||
plan["devices"][c.id] = merged
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The owner's battery algorithm on the box (docs/methods.md A2.3a, D17): a house's or a flat's own battery planned
|
||||
for the household's money over 48 h from its forecasts, no windows or rules: grid kWh only where the spread pays
|
||||
after the round trip and the wear, several cycles a day where the prices say so, the charge and the discharge each
|
||||
at its own power, the plan's reserve and top as Parameters rows, grid orders and the building's limits as
|
||||
constraints; the same formulation as the building's (the shared battery_core: its copy here, and its plan on the
|
||||
same inputs)."""
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
highspy = pytest.importorskip("highspy")
|
||||
|
||||
from cantabile_edge import battery_core, inputs, optimizer # noqa: E402
|
||||
from test_optimizer import START # noqa: E402
|
||||
|
||||
N = 192
|
||||
ETA = math.sqrt(0.9) # one way: a 90 % round trip
|
||||
|
||||
|
||||
def hour(k):
|
||||
return (k // 4 + 1) % 24 # Berlin in winter
|
||||
|
||||
|
||||
def bat(soc=10.0, floor=10.0, kwh=10.0, ch=3000.0, dis=3000.0, **params):
|
||||
return {"id": "battery", "kind": "battery", "channels": ["setpoint"],
|
||||
"params": {"capacity_wh": kwh * 1000, "max_charge_w": ch, "max_discharge_w": dis, "efficiency": ETA, **params},
|
||||
"state": {"soc_pct": soc}, "bounds": {"soc_pct": [floor, 100, "owner", "device"],
|
||||
"power_w": [-dis, ch, "device", "device"]}}
|
||||
|
||||
|
||||
def home(devices, night=18.0, evening=18.0, load=2000.0, wear=None, export=8.0):
|
||||
"""A home without PV, `load` W all day; the import at `night` ct except 17-21 h at `evening` ct (a dynamic tariff
|
||||
where they differ), a flat feed-in; no end value (the battery's use is the spread alone)."""
|
||||
price = [evening if 17 <= hour(k) < 21 else night for k in range(N)]
|
||||
s = {"v": 1, "start": START, "step_s": 900, "steps": N, "tz": "Europe/Berlin", "price_import": price,
|
||||
"price_export": [export] * N, "price_note": "test", "load_w": [load] * N, "pv_w": [0.0] * N,
|
||||
"t_out": [5.0] * N, "sun": [0.0] * N, "occupied": [1] * N, "devices": devices,
|
||||
"params": {"battery.end_value_pct": 0}}
|
||||
if wear is not None:
|
||||
s["params"]["battery.wear_ct"] = wear
|
||||
return s
|
||||
|
||||
|
||||
def solve(s):
|
||||
m = optimizer.Model(optimizer._prepare(s))
|
||||
assert m.solve(30) in ("Optimal", "Time limit reached")
|
||||
v = m.h.getSolution().col_value
|
||||
d = m.devices["battery"][1]
|
||||
return m, {k: [v[x.index] for x in d[k]] for k in ("ch", "dis", "soc")}
|
||||
|
||||
|
||||
def grid_kwh(r):
|
||||
return sum(r["ch"]) * 0.25 / 1000
|
||||
|
||||
|
||||
# -- grid kWh only where the spread pays ----------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("evening,wear,pays", [(23.6, 3.0, True), (22.5, 3.0, False), (22.5, 0.0, True), (20.3, 0.0, True),
|
||||
(19.7, 0.0, False)])
|
||||
def test_a_house_grid_charges_only_where_the_spread_pays(evening, wear, pays):
|
||||
# 18 ct at night, a 90 % round trip: a grid kWh pays where the evening is above 18 / 0.9 + wear = 20 + wear ct
|
||||
# (each case 0.3-0.6 ct from it; the plan's smoothing costs about 0.25 ct per kWh cycled)
|
||||
_, r = solve(home([bat()], evening=evening, wear=wear))
|
||||
assert (grid_kwh(r) > 1.0) == pays, (evening, wear, grid_kwh(r))
|
||||
|
||||
|
||||
def test_a_flat_tariff_never_grid_charges():
|
||||
_, r = solve(home([bat()], night=30.0, evening=30.0, wear=3.0))
|
||||
assert grid_kwh(r) < 0.05 and sum(r["dis"]) * 0.25 / 1000 < 0.05
|
||||
|
||||
|
||||
def test_several_cycles_a_day():
|
||||
# cheap 02-05 and 11-15, dear 07-10 and 18-21: charged at both cheap runs, delivered at both dear ones
|
||||
s = home([bat(kwh=4.0, ch=2000.0, dis=2000.0)], load=1500.0, wear=3.0)
|
||||
s["price_import"] = [10.0 if 2 <= hour(k) < 5 or 11 <= hour(k) < 15 else 50.0 if 7 <= hour(k) < 10 or 18 <= hour(k) < 21
|
||||
else 30.0 for k in range(N)]
|
||||
_, r = solve(s)
|
||||
day1 = sum(r["dis"][:96]) * 0.25 / 1000
|
||||
assert day1 / (4.0 * 0.9) > 1.5 # more than one and a half cycles of its window
|
||||
steps = [k for k in range(96) if r["ch"][k] > 100]
|
||||
assert any(2 <= hour(k) < 5 for k in steps) and any(11 <= hour(k) < 15 for k in steps)
|
||||
|
||||
|
||||
# -- the charge and the discharge at their own powers; the reserve and the top (the Parameters rows) -----------------
|
||||
|
||||
def test_the_discharge_power_from_the_ratio_where_one_power_is_known():
|
||||
rows = {"battery.plan_reserve_pct": 10, "battery.plan_max_soc_pct": 95, "battery.wear_ct": 3,
|
||||
"battery.discharge_ratio_pct": 65}
|
||||
p = {"max_charge_w": 4000.0, "max_discharge_w": 4000.0}
|
||||
got = inputs.battery_rows(p, {"max_charge_w": "owner", "max_discharge_w": "owner"}, rows, True)
|
||||
assert got["params"]["max_discharge_w"] == 2600.0 and got["src"]["max_discharge_w"] == "ratio"
|
||||
# the mapping's own discharge power is a fact of its own: kept, and the ratio row not needed
|
||||
got = inputs.battery_rows(p, {"max_discharge_w": "mapping"}, {k: v for k, v in rows.items() if "ratio" not in k}, True)
|
||||
assert "max_discharge_w" not in got["params"] and "refused" not in got
|
||||
# in the plan: a full battery and a dear day drain at most at the discharge power
|
||||
s = home([bat(soc=100.0, dis=2600.0)], night=10.0, evening=10.0, load=5000.0)
|
||||
s["price_import"] = [60.0] * 8 + [10.0] * (N - 8)
|
||||
_, r = solve(s)
|
||||
assert max(r["dis"]) <= 2600.0 + 1e-6 and max(r["dis"]) > 2500.0
|
||||
|
||||
|
||||
def test_the_reserve_and_the_top():
|
||||
s = home([bat(soc=50.0, floor=5.0, plan_reserve_pct=30.0, plan_max_soc_pct=80.0)], evening=40.0, wear=0.0)
|
||||
m, r = solve(s)
|
||||
assert m.window_used["battery"]["floor_pct"] == 30.0 and m.window_used["battery"]["top_pct"] == 80.0
|
||||
assert min(r["soc"]) >= 3000.0 - 1 and max(r["soc"]) <= 8000.0 + 1
|
||||
p = optimizer.plan(s, 30)
|
||||
assert p["battery_window"]["battery"]["top_pct"] == 80.0
|
||||
|
||||
|
||||
def test_a_start_under_the_reserve_is_refilled_where_cheapest_not_at_once():
|
||||
# 10 % against a 30 % reserve; 30 ct, but 10 ct 05-08 h on day 1: refilled there, not in the first quarter-hour
|
||||
s = home([bat(soc=10.0, floor=5.0, plan_reserve_pct=30.0, plan_max_soc_pct=100.0)], night=30.0, evening=30.0, wear=0.0)
|
||||
s["price_import"] = [10.0 if k < 96 and 5 <= hour(k) < 8 else 30.0 for k in range(N)]
|
||||
m, r = solve(s)
|
||||
k = m.window_used["battery"]["refill_steps"]
|
||||
assert k == optimizer.REFILL_STEPS
|
||||
cheap = [t for t in range(96) if 5 <= hour(t) < 8]
|
||||
assert sum(r["ch"][t] for t in range(cheap[0])) < 1.0 # nothing forced before the cheap hours
|
||||
assert sum(r["ch"][t] for t in cheap) > 0
|
||||
assert all(e >= 3000.0 - 1 for e in r["soc"][k:])
|
||||
|
||||
|
||||
# -- grid orders and the building's limits are constraints ----------------------------------------------------------
|
||||
|
||||
def test_a_dimming_order_holds_the_grid_charging():
|
||||
# a §14a order (the controllable draw at most 1 kW above the household's use) over the cheap night: the battery's
|
||||
# grid charging stays within it, even where the spread pays
|
||||
s = home([bat()], evening=40.0, wear=0.0)
|
||||
night = [k for k in range(N) if hour(k) < 6]
|
||||
s["grid_order"] = {"limit_w": 1000.0, "from_step": 0, "to_step": N, "penalty": 500.0}
|
||||
_, r = solve(s)
|
||||
assert max(r["ch"][k] for k in night) <= 1000.0 + 1
|
||||
assert grid_kwh(r) > 1.0 # it still charges, slower and longer
|
||||
|
||||
|
||||
def test_a_load_limit_forces_a_discharge_at_a_flat_price():
|
||||
# a flat tariff (no reason to cycle) and the building's binding load limit 18-20 h under the household's 2 kW:
|
||||
# the battery covers the difference there
|
||||
s = home([bat(soc=80.0)], night=30.0, evening=30.0, wear=3.0)
|
||||
lim = [k for k in range(N) if 18 <= hour(k) < 20][:8]
|
||||
s["building"] = {"load_limit": {"value": 500.0, "from_step": lim[0], "to_step": lim[-1] + 1, "penalty": 500.0}}
|
||||
_, r = solve(s)
|
||||
assert all(r["dis"][k] >= 1500.0 - 1 for k in lim)
|
||||
|
||||
|
||||
# -- a flat inside a building: its own bill ------------------------------------------------------------------------
|
||||
|
||||
def test_a_flat_in_a_building_optimises_its_own_bill():
|
||||
"""A flat's own battery under its building (a Mieterstrom or GGV tenant tariff in its bundle): the box plans it
|
||||
against the flat's own prices; the building sees the flat's import after it (C6.1) and never charges it. A tenant
|
||||
band cheaper by more than the round trip and the wear: it charges there for the flat's dear band; the building's
|
||||
limit is kept where it binds."""
|
||||
s = home([bat()], night=18.0, evening=26.0, wear=3.0) # the flat's bands: 18 / 26 ct
|
||||
lim = [k for k in range(N) if 18 <= hour(k) < 19][:4]
|
||||
s["building"] = {"load_limit": {"value": 0.0, "from_step": lim[0], "to_step": lim[-1] + 1, "penalty": 500.0}}
|
||||
_, r = solve(s)
|
||||
assert grid_kwh(r) > 1.0
|
||||
assert all(r["dis"][k] >= 2000.0 - 1 for k in lim)
|
||||
# the same flat on a flat tenant price: nothing cycled for the building
|
||||
s2 = home([bat()], night=26.0, evening=26.0, wear=3.0)
|
||||
_, r2 = solve(s2)
|
||||
assert grid_kwh(r2) < 0.05
|
||||
|
||||
|
||||
# -- a missing row: the suggested value, with an alarm (the owner, 2026-11-12) ---------------------------------------
|
||||
|
||||
def test_a_missing_row_falls_back_to_the_suggested_value_with_an_alarm():
|
||||
p = {"max_charge_w": 3000.0, "max_discharge_w": 3000.0}
|
||||
got = inputs.battery_rows(p, {"max_discharge_w": "device"}, {"battery.wear_ct": 3, "battery.plan_reserve_pct": 10}, True)
|
||||
assert "refused" not in got
|
||||
assert got["gap"]["missing"] == ["battery.plan_max_soc_pct", "battery.discharge_ratio_pct"]
|
||||
assert got["gap"]["fallback"] == "suggested" and "suggested values" in got["gap"]["why"]
|
||||
assert got["params"]["plan_max_soc_pct"] == 95.0 and got["src"]["plan_max_soc_pct"] == "suggested"
|
||||
assert got["params"]["plan_reserve_pct"] == 10 and got["src"]["plan_reserve_pct"] == "parameter"
|
||||
assert got["params"]["max_discharge_w"] == 1950.0 and got["src"]["max_discharge_w"] == "suggested"
|
||||
# the wear's row missing: the suggested wear
|
||||
got = inputs.battery_rows(p, {"max_discharge_w": "device"}, {"battery.plan_reserve_pct": 10,
|
||||
"battery.plan_max_soc_pct": 95, "battery.discharge_ratio_pct": 65}, True)
|
||||
assert got["gap"]["missing"] == ["battery.wear_ct"] and got["params"]["wear_ct"] == 3.0
|
||||
# a device's own wear: the wear's row not needed, no alarm
|
||||
got = inputs.battery_rows(dict(p, wear_ct=2.0), {"max_discharge_w": "mapping"},
|
||||
{"battery.plan_reserve_pct": 10, "battery.plan_max_soc_pct": 95}, True)
|
||||
assert "gap" not in got and "refused" not in got
|
||||
# without a tariff nothing is priced: its own window and power, noted
|
||||
got = inputs.battery_rows(p, {"max_discharge_w": "device"}, {}, False)
|
||||
assert got["params"] == {} and got["notes"] and "gap" not in got
|
||||
|
||||
|
||||
# -- one formulation: the box's MILP against the shared battery_core on the same inputs -------------------------------
|
||||
|
||||
class Cells:
|
||||
"""A battery as battery_core.Block reads one (kWh, kW, round trip)."""
|
||||
|
||||
def __init__(self, kwh, kw, dis_kw, rt, lo, start, wear_ct):
|
||||
self.kw, self.dis_kw, self.efficiency, self.lo, self.hi = kw, dis_kw, rt, lo, kwh
|
||||
self.start, self.wear_ct, self.slot_h, self.standby_w, self.loss_pct_h = start, wear_ct, 0.25, 0.0, 0.0
|
||||
|
||||
def phi(self):
|
||||
return 1.0
|
||||
|
||||
def standby_kwh(self):
|
||||
return 0.0
|
||||
|
||||
def below_floor(self):
|
||||
return max(0.0, self.lo - self.start)
|
||||
|
||||
|
||||
def test_the_box_and_the_shared_core_agree():
|
||||
"""A house with PV, a dynamic tariff and a flat feed-in; the battery's gain over 48 h from the box's MILP and from
|
||||
battery_core.plan (the building's formulation, the copy on the box) within 2 % (the box's smoothing and its one
|
||||
binary per step are the difference)."""
|
||||
pv = [max(0.0, 5000.0 * math.sin(math.pi * (hour(k) + (k % 4) / 4 - 7) / 10)) if 7 <= hour(k) < 17 else 0.0
|
||||
for k in range(N)]
|
||||
price = [24.0 + 10.0 * math.cos(2 * math.pi * (hour(k) - 19) / 24) for k in range(N)]
|
||||
load = [1200.0 + (1800.0 if 17 <= hour(k) < 22 else 0.0) for k in range(N)]
|
||||
|
||||
def edge(devs):
|
||||
s = home(devs, wear=3.0)
|
||||
s.update(price_import=price, pv_w=pv, load_w=load)
|
||||
m = optimizer.Model(optimizer._prepare(s))
|
||||
m.solve(30)
|
||||
val = m.h.getSolution().col_value
|
||||
x = lambda v: val[v.index] # noqa: E731
|
||||
eur = optimizer.energy_of(s, m, x)
|
||||
out = sum(x(v) for v in m.devices["battery"][1]["dis"]) * 0.25 / 1000 if devs else 0.0
|
||||
return eur + out * 0.03 # the wear is the owner's cost too
|
||||
|
||||
gain_edge = edge([]) - edge([bat(soc=20.0, floor=10.0, kwh=10.0, ch=4000.0, dis=3000.0)])
|
||||
kwh = lambda ws: [w * 0.25 / 1000 for w in ws] # noqa: E731
|
||||
hz = battery_core.Horizon(pv=kwh(pv), load=kwh(load), value_ct=price, feed_ct=[8.0] * N, grid_ct=price)
|
||||
c = Cells(10.0, 4.0, 3.0, 0.9, 1.0, 2.0, 3.0)
|
||||
gain_core = battery_core.plan(hz, c)["eur"] - battery_core.plan(hz, None)["eur"]
|
||||
assert gain_edge > 0.5
|
||||
assert gain_edge == pytest.approx(gain_core, rel=0.02)
|
||||
|
||||
|
||||
# -- the saving on one basis -------------------------------------------------------------------------------------------
|
||||
|
||||
def test_the_saving_and_the_wear_on_one_basis():
|
||||
"""cost_eur and baseline_eur are both the energy bought and sold (the baseline has no battery); the wear weighs in
|
||||
the plan's decisions only and is reported apart (battery_wear[...]["eur"]): the saving baseline - cost is not
|
||||
shrunk by a wear term on one side only, and a wear row changes the baseline not at all."""
|
||||
p0 = optimizer.plan(home([bat(soc=50.0)], evening=40.0, wear=0.0), 30)
|
||||
p3 = optimizer.plan(home([bat(soc=50.0)], evening=40.0, wear=3.0), 30)
|
||||
assert p0["baseline_eur"] == p3["baseline_eur"]
|
||||
for p in (p0, p3):
|
||||
assert p["cost_eur"] <= p["baseline_eur"]
|
||||
w = p["battery_wear"]["battery"]
|
||||
assert w["eur"] == pytest.approx(w["kwh"] * w["ct"] / 100.0, abs=1e-3)
|
||||
assert p3["battery_wear"]["battery"]["eur"] > 0 and p0["battery_wear"]["battery"]["eur"] == 0
|
||||
# with the wear the plan cycles no more than without: its energy saving at most the wear-free one's
|
||||
assert p3["baseline_eur"] - p3["cost_eur"] <= p0["baseline_eur"] - p0["cost_eur"] + 1e-6
|
||||
# and after the wear still a gain where the spread pays (40 against 18 ct)
|
||||
assert p3["baseline_eur"] - p3["cost_eur"] - p3["battery_wear"]["battery"]["eur"] > 0
|
||||
@@ -0,0 +1,319 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Hot water and climate in the plan (docs/methods.md G2, G5 in the plan;
|
||||
backlog 473): the flat's 2R2C (air and mass) and the comfort band."""
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
highspy = pytest.importorskip("highspy")
|
||||
|
||||
from cantabile_edge import comfort, optimizer # noqa: E402
|
||||
from cantabile_edge.inputs import mass_start # noqa: E402
|
||||
|
||||
START = 1793232000 # 2026-10-29 00:00 UTC (01:00 in Berlin)
|
||||
ROWS = dict(comfort.SUGGESTED_ROWS)
|
||||
|
||||
|
||||
def house(devices, steps=192, price=None):
|
||||
hour = lambda k: (k // 4 + 1) % 24 # noqa: E731 (Berlin, winter)
|
||||
price = price or [12.0 if hour(k) < 6 else 40.0 if 6 <= hour(k) < 9 or 17 <= hour(k) < 21 else 28.0
|
||||
for k in range(steps)]
|
||||
return {"v": 1, "start": START, "step_s": 900, "steps": steps, "tz": "Europe/Berlin",
|
||||
"price_import": price, "price_export": [8.0] * steps, "price_note": "test",
|
||||
"load_w": [400.0] * steps, "pv_w": [0.0] * steps, "t_out": [0.0] * steps,
|
||||
"sun": [0.0] * steps, "occupied": [1 if 6 <= hour(k) < 22 else 0 for k in range(steps)],
|
||||
"devices": devices}
|
||||
|
||||
|
||||
ZONE = {"r_i": 1.0, "r_e": 6.0, "c_a": 1.5, "c_m": 12.0, "share": 1.0, "gain_w": 0.0, "solar_m2": 0.0,
|
||||
"el_gain_share": 0.0, "occ_gain_w": 0.0, "power": "thermal"}
|
||||
|
||||
|
||||
def room(zone=None, temp=20.0, band=None):
|
||||
p = {"r_k_per_kw": 7.0, "c_kwh_per_k": 1.5 + 12.0 * 6 / 7, "max_power_w": 6000, "comfort_c": 21,
|
||||
"setback_c": 17, "cop": 1.0}
|
||||
if zone:
|
||||
p["zone"] = dict(zone, theta_m0=temp)
|
||||
d = {"id": "heating", "kind": "heating", "channels": ["climate"], "params": p,
|
||||
"state": {"temp_c": temp}, "bounds": {"temp_c": [10, 28, "owner", "owner"]}}
|
||||
if band:
|
||||
d["band"] = band
|
||||
return d
|
||||
|
||||
|
||||
def values(m, key):
|
||||
val = m.h.getSolution().col_value
|
||||
return [val[v.index] for v in m.devices["heating"][1][key]]
|
||||
|
||||
|
||||
# ---- the 2R2C's discrete form -------------------------------------------------------------------
|
||||
|
||||
def test_the_exact_step_matches_a_fine_integration():
|
||||
z = dict(ZONE)
|
||||
ad, bd = optimizer.rc2_discrete(z, 0.25)
|
||||
x = [20.0, 18.0]
|
||||
tout, q = 0.0, 3.0
|
||||
# 10 000 Euler sub-steps over a quarter hour
|
||||
a, m = x
|
||||
h = 0.25 / 10000
|
||||
for _ in range(10000):
|
||||
da = ((m - a) / z["r_i"] + q) / z["c_a"]
|
||||
dm = ((a - m) / z["r_i"] + (tout - m) / z["r_e"]) / z["c_m"]
|
||||
a, m = a + h * da, m + h * dm
|
||||
exact = [ad[0][0] * x[0] + ad[0][1] * x[1] + bd[0][0] * tout + bd[0][1] * q,
|
||||
ad[1][0] * x[0] + ad[1][1] * x[1] + bd[1][0] * tout + bd[1][1] * q]
|
||||
assert exact[0] == pytest.approx(a, abs=1e-3) and exact[1] == pytest.approx(m, abs=1e-3)
|
||||
|
||||
|
||||
def test_the_steady_state_is_kept():
|
||||
z = dict(ZONE)
|
||||
ad, bd = optimizer.rc2_discrete(z, 0.25)
|
||||
# UA = 1/(R_i+R_e) kW/K: 20 K inside-outside needs 20/7 kW
|
||||
q = 20.0 / 7.0
|
||||
a = 20.0
|
||||
m = (z["r_e"] * a + z["r_i"] * 0.0) / 7.0
|
||||
a2 = ad[0][0] * a + ad[0][1] * m + bd[0][1] * q
|
||||
m2 = ad[1][0] * a + ad[1][1] * m + bd[1][0] * 0.0 + bd[1][1] * q
|
||||
assert a2 == pytest.approx(a, abs=1e-6) and m2 == pytest.approx(m, abs=1e-6)
|
||||
|
||||
|
||||
def test_the_mass_now_from_the_rooms_history():
|
||||
p = {"zone": dict(ZONE)}
|
||||
# a day at 21 °C, 0 °C outside: the mass near its steady state (6/7 x 21 = 18 °C)
|
||||
m, src = mass_start(p, [21.0] * 96, [0.0] * 96, 21.0)
|
||||
assert m == pytest.approx(18.0, abs=0.05) and "observed" in src
|
||||
# a setback night: the air fell to 17 the last 8 h, the mass lags above its new steady state (14.6)
|
||||
m2, _ = mass_start(p, [21.0] * 64 + [17.0] * 32, [0.0] * 96, 17.0)
|
||||
assert 14.6 < m2 < 18.0
|
||||
# no history: the steady state now
|
||||
m3, src3 = mass_start(p, [], [0.0], 20.0)
|
||||
assert m3 == pytest.approx(20.0 * 6 / 7) and "steady" in src3
|
||||
|
||||
|
||||
# ---- the plan stores heat in the mass -------------------------------------------------------------
|
||||
|
||||
def test_the_mass_is_preheated_in_cheap_hours():
|
||||
m = optimizer.Model(house([room(ZONE, temp=20.0)]))
|
||||
m.solve(30)
|
||||
mass = values(m, "mass")
|
||||
heat = values(m, "power")
|
||||
# cheap 00-06 local (steps 0-19), dear 06-09: the mass warmed before 06:00, less heat bought at 06-09
|
||||
assert mass[19] > mass[0] + 0.3
|
||||
cheap = sum(heat[0:20]) / 20
|
||||
dear = sum(heat[20:32]) / 12
|
||||
assert cheap > dear
|
||||
|
||||
|
||||
def test_a_one_node_room_stays_as_before():
|
||||
m = optimizer.Model(house([room(None, temp=19.0)]))
|
||||
m.solve(20)
|
||||
assert values(m, "mass") == [] and m.devices["heating"][1]["zone"] is False
|
||||
|
||||
|
||||
# ---- the comfort band (EN 16798-1) ----------------------------------------------------------------
|
||||
|
||||
def test_the_band_edges_by_category_and_running_mean():
|
||||
r = ROWS
|
||||
assert comfort.edges(r, "II", 5.0, False) == (20.0, 26.0) # cold: the design values
|
||||
lo, hi = comfort.edges(r, "II", 20.0, False) # warm: the adaptive line
|
||||
assert lo == pytest.approx(0.33 * 20 + 18.8 - 4) and hi == pytest.approx(0.33 * 20 + 18.8 + 3)
|
||||
assert comfort.edges(r, "II", 20.0, True)[1] == 26.0 # cooled: the fixed upper edge
|
||||
assert comfort.edges(r, "I", 5.0, False)[0] == 21.0 and comfort.edges(r, "III", 5.0, False)[0] == 18.0
|
||||
assert comfort.edges(r, "II", None, False) == (20.0, 26.0)
|
||||
|
||||
|
||||
def test_the_running_mean_weights_the_last_days_most():
|
||||
days = {"2026-10-20": 10.0, "2026-10-21": 0.0}
|
||||
rm = comfort.running_mean(days, "2026-10-22", 0.8)
|
||||
assert rm == pytest.approx((0.0 + 0.8 * 10.0) / 1.8)
|
||||
assert comfort.running_mean(days, "2026-10-20", 0.8) is None
|
||||
|
||||
|
||||
def test_presence_weight_from_the_share():
|
||||
w = comfort.presence_weight([1, 1, 0, 0], [None, 0.4, 0.1, 0.0], 0.2)
|
||||
assert w == [1.0, 1.0, 0.5, 0.0]
|
||||
assert comfort.presence_weight([1, 0], None, 0.2) == [1.0, 0.0]
|
||||
|
||||
|
||||
def band(mode="balanced", weights=None, shift=0.0, steps=192):
|
||||
hour = lambda k: (k // 4 + 1) % 24 # noqa: E731
|
||||
w = weights or [1.0 if 6 <= hour(k) < 22 else 0.0 for k in range(steps)]
|
||||
return comfort.room_band(ROWS, "heating", mode, START, "Europe/Berlin", steps, w, {}, 17.0, False, shift)
|
||||
|
||||
|
||||
def test_the_room_band_per_step():
|
||||
b = band()
|
||||
hour = lambda k: (k // 4 + 1) % 24 # noqa: E731
|
||||
k = next(k for k in range(192) if hour(k + 1) == 12) # a step ending at noon: someone home, awake
|
||||
assert b["lo"][k] == 20.0 and b["w_lo"][k] == 2.0 and b["category"] == "II"
|
||||
night = next(k for k in range(192) if hour(k + 1) == 3)
|
||||
assert b["w_lo"][night] == 0.0 and b["floor"][night] == 17.0
|
||||
assert b["lo"][night] == 19.0 # asleep: 1 K lower
|
||||
arr = [k for k in range(192) if b["arrive"][k] > 0]
|
||||
assert arr and all(hour(k + 1) == 6 for k in arr) # warm by arrival at 06:00
|
||||
s = band("saving")
|
||||
assert s["lo"][k] == 18.0 and s["w_lo"][k] == 1.0
|
||||
c = band("comfort")
|
||||
assert c["lo"][k] == 21.0 and c["w_lo"][k] == 4.0
|
||||
|
||||
|
||||
def test_the_band_lets_an_empty_home_cool_and_warms_it_by_arrival():
|
||||
m = optimizer.Model(house([room(None, temp=20.0, band=band())]))
|
||||
m.solve(30)
|
||||
temps = values(m, "temp")
|
||||
s = m.s
|
||||
occupied = [k for k in range(100, 191) if band()["w_lo"][k] > 0]
|
||||
# inside the band while someone is home (a large room may coast 0.4 K at the last dear evening hours: 2 EUR
|
||||
# per K·h against the heat it would have to hold for the night's setback)
|
||||
assert min(temps[k] for k in occupied) >= 19.5
|
||||
assert sum(max(0.0, 20.0 - temps[k]) for k in occupied) / len(occupied) < 0.05
|
||||
empty = [k for k in range(100, 191) if band()["w_lo"][k] == 0]
|
||||
assert min(temps[k] for k in empty) < 19.5 # it may cool while nobody is home
|
||||
assert min(temps[k] for k in empty) >= 16.95 # never below the setback
|
||||
assert s["occupied"]
|
||||
|
||||
|
||||
def test_the_band_takes_less_heat_than_the_fixed_target():
|
||||
fixed = optimizer.Model(house([room(None, temp=20.0)]))
|
||||
fixed.solve(30)
|
||||
banded = optimizer.Model(house([room(None, temp=20.0, band=band())]))
|
||||
banded.solve(30)
|
||||
assert sum(values(banded, "power")) < sum(values(fixed, "power"))
|
||||
|
||||
|
||||
def test_the_owner_schedule_wins_over_the_band():
|
||||
d = room(None, temp=20.0, band=band())
|
||||
d["pref"] = {"target": [22.0] * 192, "must": [None] * 192, "group": [0] * 192, "base": [17.0] * 192,
|
||||
"groups": [{"group": "heating:0", "kind": "block", "how": "prefer", "c": 22.0, "text": ""}]}
|
||||
m = optimizer.Model(house([d]))
|
||||
m.solve(30)
|
||||
assert m.devices["heating"][1]["banded"] is False
|
||||
|
||||
|
||||
# ---- the household's tolerance from its overrides ---------------------------------------------------
|
||||
|
||||
def test_tolerance_is_learnt_and_shrunk(tmp_path):
|
||||
t = comfort.Tolerance(str(tmp_path))
|
||||
now = START
|
||||
for i in range(5):
|
||||
assert t.record("heating", "heating", 20.0, 22.0, now - i * 3600)
|
||||
shift, n = t.shift("heating", "heating", now, ROWS)
|
||||
assert n == 5 and shift == pytest.approx(2.0 * 5 / (5 + 5))
|
||||
assert comfort.Tolerance(str(tmp_path)).shift("heating", "heating", now, ROWS)[1] == 5 # kept on disk
|
||||
assert not t.record("heating", "heating", 20.0, "heat", now) # not a temperature
|
||||
b = band(shift=shift)
|
||||
hour = lambda k: (k // 4 + 1) % 24 # noqa: E731
|
||||
k = next(k for k in range(192) if hour(k + 1) == 12)
|
||||
assert b["lo"][k] == pytest.approx(21.0)
|
||||
# old overrides are forgotten
|
||||
assert t.shift("heating", "heating", now + 40 * 86400, ROWS) == (0.0, 0)
|
||||
|
||||
|
||||
def test_rows_missing_take_the_suggested_values():
|
||||
r, missing = comfort.rows({"comfort.default_mode": "saving"})
|
||||
assert r["comfort.default_mode"] == "saving" and "comfort.band_categories" in missing
|
||||
g = comfort.gap(missing)
|
||||
assert g["fallback"] == "suggested" and "comfort.band_categories" in g["why"]
|
||||
r2, missing2 = comfort.rows({k: v for k, v in comfort.SUGGESTED_ROWS.items()})
|
||||
assert not missing2
|
||||
_, bad = comfort.rows({**comfort.SUGGESTED_ROWS, "comfort.running_mean_alpha": 2})
|
||||
assert bad == ["comfort.running_mean_alpha"]
|
||||
assert math.isfinite(r2["comfort.value_eur_per_kh"])
|
||||
|
||||
|
||||
# ---- the bundle's zone into the model state ------------------------------------------------------
|
||||
|
||||
def _zone_bundle(tmp_path, **zone):
|
||||
from test_model_series import model, put
|
||||
z = {"model": "2r2c", "power": "thermal", "r_i_k_per_kw": 1.0, "r_e_k_per_kw": 6.0, "c_air_kwh_per_k": 1.5,
|
||||
"c_mass_kwh_per_k": 12.0, "c_eff_kwh_per_k": 11.8, "ua_w_per_k": 142.9, "solar_kind": "ghi",
|
||||
"solar_m2": 2.0, "gain_w": 200.0, "el_gain_share": 0.6, "occ_gain_w": 150.0}
|
||||
z.update(zone)
|
||||
rooms = {"living": {"r_k_per_kw": 8, "c_kwh_per_k": 4, "subzone": {"basis": "valves", "share": 0.6}},
|
||||
"bed": {"r_k_per_kw": 9, "c_kwh_per_k": 3, "subzone": {"basis": "valves", "share": 0.4}}}
|
||||
return put(tmp_path, model(zones={"home": z}, rooms=rooms))
|
||||
|
||||
|
||||
def test_the_bundle_zone_scaled_to_the_room(tmp_path):
|
||||
b = _zone_bundle(tmp_path)
|
||||
z, why = b.zone_rc("living_heating", "", False)
|
||||
assert why == "" and z["share"] == 0.6 and z["r_i"] == 1.0 and "sub-zone" in z["share_src"]
|
||||
one, _ = b.zone_rc("kitchen", "", True)
|
||||
assert one["share"] == 1.0
|
||||
none, why = b.zone_rc("kitchen", "", False)
|
||||
assert none is None and "share" in why
|
||||
bad = _zone_bundle(tmp_path, r_i_k_per_kw=-1)
|
||||
z, why = bad.zone_rc("living", "", True)
|
||||
assert z is None and "r_i_k_per_kw" in why
|
||||
|
||||
|
||||
def test_the_model_state_plans_a_room_on_the_flats_2r2c(tmp_path):
|
||||
from test_room_refusal import INPUTS, TZ, col, room as ctl_room
|
||||
from cantabile_edge.inputs import History, model_state
|
||||
b = _zone_bundle(tmp_path)
|
||||
h = History(str(tmp_path / "history.json"))
|
||||
for k in range(96):
|
||||
h.add("room:living", 20.0, START - (96 - k) * 900)
|
||||
h.add("t_out", 5.0, START - (96 - k) * 900)
|
||||
# two rooms with their valves: each its share of the flat (one control alone would be all of it)
|
||||
s = model_state(START, [ctl_room(cid="living", max_power_w=3000, cop=1), ctl_room(cid="bed", max_power_w=2000, cop=1)],
|
||||
INPUTS, col({"living": 20.0, "bed": 19.0}), b, h, TZ, None)
|
||||
d = s["devices"][0]
|
||||
z = d["params"]["zone"]
|
||||
assert s["sources"]["rooms"] == {"living": "zone 2r2c", "bed": "zone 2r2c"}
|
||||
assert s["devices"][1]["params"]["zone"]["share"] == 0.4
|
||||
# the room is 0.6 of the flat: R / 0.6, C x 0.6, the gains x 0.6
|
||||
assert z["r_i"] == pytest.approx(1 / 0.6) and z["c_m"] == pytest.approx(7.2) and z["gain_w"] == pytest.approx(120)
|
||||
assert z["theta_m0"] == pytest.approx((6 * 20 + 1 * 5) / 7, abs=0.05)
|
||||
assert s["sources"]["rooms_zone"]["living"]["mass_from"].startswith("observed")
|
||||
# the comfort band, EN 16798-1 (no params on the box: the suggested values, a quiet note)
|
||||
assert d["band"]["category"] == "II" and s["sources"]["rooms_band"]["living"] == "en16798 II"
|
||||
assert "comfort_band" not in s["refused"] and any("comfort band" in n for n in s["notes"])
|
||||
p = optimizer.plan(s, 30)
|
||||
assert p["devices"].get("living") is not None
|
||||
|
||||
|
||||
def test_a_cooler_takes_the_zones_fitted_eer(tmp_path):
|
||||
from test_room_refusal import INPUTS, TZ, col, room as ctl_room
|
||||
from cantabile_edge.inputs import model_state
|
||||
b = _zone_bundle(tmp_path, cool_eer=3.2)
|
||||
s = model_state(START, [ctl_room(cid="living", kind="cooling", max_power_w=1500)], INPUTS, col({"living": 26.0}),
|
||||
b, None, TZ, None)
|
||||
assert "living" not in s["refused"] and s["sources"]["rooms_cop"] == {"living": "zone fit"}
|
||||
assert s["devices"][0]["params"]["cop"] == 3.2
|
||||
|
||||
|
||||
def test_the_comfort_choice_is_a_site_preference(tmp_path):
|
||||
from cantabile_edge.preferences import Preferences
|
||||
p = Preferences(str(tmp_path), lambda: START)
|
||||
ok, msg = p.set("comfort", {"mode": "sparen"}, "owner", "owner", None, START)
|
||||
assert ok and p.comfort_mode() == "saving", msg
|
||||
ok, _ = p.set("comfort", {"mode": "warm"}, "owner", "owner", None, START)
|
||||
assert not ok and p.comfort_mode() == "saving"
|
||||
assert Preferences(str(tmp_path), lambda: START).comfort_mode() == "saving"
|
||||
|
||||
|
||||
def test_the_box_params_with_the_rows_raise_no_alarm(tmp_path):
|
||||
from test_room_refusal import INPUTS, TZ, col, room as ctl_room
|
||||
from cantabile_edge.inputs import model_state
|
||||
|
||||
class B:
|
||||
def __init__(self, inner, params):
|
||||
self.inner, self.params = inner, params
|
||||
|
||||
def __getattr__(self, k):
|
||||
return getattr(self.inner, k)
|
||||
|
||||
def box_params(self, now):
|
||||
return self.params
|
||||
inner = _zone_bundle(tmp_path)
|
||||
c = [ctl_room(cid="living", max_power_w=3000, cop=1)]
|
||||
s = model_state(START, c, INPUTS, col({"living": 20.0}), B(inner, {"x": 1}), None, TZ, None)
|
||||
assert s["refused"]["comfort_band"]["fallback"] == "suggested"
|
||||
rows = dict(comfort.SUGGESTED_ROWS, **{"comfort.default_mode": "comfort"})
|
||||
s = model_state(START, c, INPUTS, col({"living": 20.0}), B(inner, rows), None, TZ, None,
|
||||
comfort_ctx={"mode": None})
|
||||
assert "comfort_band" not in s["refused"] and s["devices"][0]["band"]["category"] == "I"
|
||||
s = model_state(START, c, INPUTS, col({"living": 20.0}), B(inner, rows), None, TZ, None,
|
||||
comfort_ctx={"mode": "saving"})
|
||||
assert s["devices"][0]["band"]["category"] == "III"
|
||||
@@ -0,0 +1,38 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""A gas meter counting m3 (climate-prices, 2026-11-12; methods.md E5): kWh = m3 x Brennwert x Zustandszahl of the
|
||||
bundle's period; none for the day: no value and a note (never m3 as kWh, never a default)."""
|
||||
import pytest
|
||||
|
||||
from cantabile_edge import costs
|
||||
from cantabile_edge.bundles import Bundles
|
||||
|
||||
|
||||
def rec(delta_l):
|
||||
return {"asset": "gas.volume", "kind": "counter", "delta": delta_l, "last": 1.0, "n": 2}
|
||||
|
||||
|
||||
def test_litres_of_gas_become_kwh_with_the_conversion():
|
||||
notes = set()
|
||||
# 500 litres = 0.5 m3 x 11.136 kWh/m3
|
||||
assert costs.amounts([rec(500.0)], 900, None, 11.136, notes)["gas"] == pytest.approx(5.568)
|
||||
assert not notes
|
||||
|
||||
|
||||
def test_no_conversion_no_value_and_a_note():
|
||||
notes = set()
|
||||
assert costs.amounts([rec(500.0)], 900, None, None, notes) == {"gas": None}
|
||||
assert notes == {"gas_m3"}
|
||||
|
||||
|
||||
def test_the_energy_counter_wins_over_the_volume():
|
||||
both = [rec(500.0), {"asset": "gas.energy", "kind": "counter", "delta": 2000.0, "last": 1.0, "n": 2}]
|
||||
assert costs.amounts(both, 900, None, 11.0)["gas"] == pytest.approx(2.0)
|
||||
|
||||
|
||||
def test_the_bundle_period_that_covers_the_time():
|
||||
b = Bundles.__new__(Bundles)
|
||||
t = {"site": "s", "expires": 10_000, "gas_kwh_per_m3": [{"from": 100, "to": 200, "kwh_per_m3": 11.1}]}
|
||||
b._valid = lambda now: t
|
||||
assert b.gas_conversion(150, 150) == 11.1
|
||||
assert b.gas_conversion(250, 150) is None
|
||||
assert b.gas_conversion(99, 150) is None
|
||||
@@ -0,0 +1,169 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Hot water as a reserve (docs/methods.md G7 in the plan; backlog 473, 476,
|
||||
107): the tank's temperature per step, a heat pump's COP by the tank's
|
||||
temperature, DVGW W 551's large systems never lowered, the owner's hot-water
|
||||
times, a combi boiler's comfort mode."""
|
||||
import pytest
|
||||
|
||||
highspy = pytest.importorskip("highspy")
|
||||
|
||||
from cantabile_edge import hotwater, optimizer # noqa: E402
|
||||
from cantabile_edge.controls import Control # noqa: E402
|
||||
from cantabile_edge.executor import actions_for # noqa: E402
|
||||
from cantabile_edge.inputs import Collector # noqa: E402
|
||||
|
||||
from test_storage import tank # noqa: E402
|
||||
from test_tank_inputs import PARAMS # noqa: E402
|
||||
|
||||
START = 1793232000 # 2026-10-29 00:00 UTC (01:00 in Berlin)
|
||||
ROWS = dict(hotwater.SUGGESTED_ROWS)
|
||||
|
||||
|
||||
def hour(k):
|
||||
return (k // 4 + 1) % 24 # Berlin, winter
|
||||
|
||||
|
||||
def house(devices, price=None, steps=192):
|
||||
price = price or [30.0] * steps
|
||||
return {"v": 1, "start": START, "step_s": 900, "steps": steps, "tz": "Europe/Berlin",
|
||||
"price_import": price, "price_export": [8.0] * steps, "price_note": "test",
|
||||
"load_w": [400.0] * steps, "pv_w": [0.0] * steps, "t_out": [5.0] * steps,
|
||||
"sun": [0.0] * steps, "occupied": [1 if 6 <= hour(k) < 22 else 0 for k in range(steps)],
|
||||
"devices": devices}
|
||||
|
||||
|
||||
def draws(steps=192):
|
||||
"""Showers 07-08 and 19-20 local: 2 kW of heat."""
|
||||
return [2000.0 if hour(k) in (7, 19) else 0.0 for k in range(steps)]
|
||||
|
||||
|
||||
def solved(s):
|
||||
m = optimizer.Model(s)
|
||||
m.solve(30)
|
||||
val = m.h.getSolution().col_value
|
||||
x = lambda v: val[v.index] # noqa: E731
|
||||
v = m.devices["tank"][1]
|
||||
return m, v, [optimizer.tank_temp(v, t, x) for t in range(m.T)], x
|
||||
|
||||
|
||||
def test_the_floor_per_step():
|
||||
d = draws()
|
||||
f = hotwater.floors(d, 45.0, 40.0, None, ROWS)
|
||||
assert {f[k] for k in range(192) if d[k] > 0} == {45.0} and {f[k] for k in range(192) if d[k] == 0} == {40.0}
|
||||
# the idle floor never above the draw temperature; a Großanlage the law's at every step
|
||||
assert set(hotwater.floors(d, 38.0, 40.0, None, ROWS)) == {38.0}
|
||||
assert set(hotwater.floors(d, 45.0, 40.0, 60.0, ROWS)) == {60.0}
|
||||
|
||||
|
||||
def test_the_tank_coasts_low_at_night_and_is_hot_for_the_draws():
|
||||
t = tank("element", temp=45.0, channels=("power",))
|
||||
t["draw_w"] = draws()
|
||||
t["floor_c"] = hotwater.floors(t["draw_w"], 45.0, 40.0, None, ROWS)
|
||||
m, v, temps, _ = solved(house([t]))
|
||||
# every draw step at least the draw temperature (45 °C; the horizon's last evening aside: nothing after it
|
||||
# values the heat), the night not reheated (it coasts under 45 °C on its standing loss)
|
||||
assert min(temps[k] for k in range(160) if t["draw_w"][k] > 0) >= 44.95
|
||||
night = [k for k in range(80, 120) if 1 <= hour(k + 1) <= 5]
|
||||
# (at one flat price the solver may reheat a little anywhere before the morning: only that it coasts)
|
||||
assert min(temps[k] for k in night) < 44.9
|
||||
|
||||
|
||||
def test_the_reserve_saves_against_one_fixed_floor():
|
||||
t = tank("element", temp=45.0, channels=("power",))
|
||||
t["draw_w"] = draws()
|
||||
fixed = solved(house([dict(t)]))
|
||||
t2 = dict(t, floor_c=hotwater.floors(t["draw_w"], 45.0, 40.0, None, ROWS))
|
||||
reserve = solved(house([t2]))
|
||||
heat = lambda r: sum(optimizer.tank_heat(r[1], k, r[3]) for k in range(192)) # noqa: E731
|
||||
assert heat(reserve) < heat(fixed)
|
||||
|
||||
|
||||
def test_cheap_hours_fill_the_tank_as_a_store():
|
||||
t = tank("element", temp=45.0, channels=("power",))
|
||||
t["draw_w"] = draws()
|
||||
t["floor_c"] = hotwater.floors(t["draw_w"], 45.0, 40.0, None, ROWS)
|
||||
price = [8.0 if 12 <= hour(k) < 15 else 40.0 for k in range(192)]
|
||||
_, _, temps, _ = solved(house([t], price))
|
||||
# the tank stored the cheap midday heat for the evening's draw: well above 45 °C after the cheap hours
|
||||
k = next(k for k in range(96, 192) if hour(k + 1) == 15)
|
||||
assert temps[k] > 50.0
|
||||
|
||||
|
||||
def test_a_heat_pumps_cop_falls_with_the_tank_temperature():
|
||||
assert hotwater.cop_factor({}, 35.0, ROWS) == 1.0
|
||||
assert hotwater.cop_factor({}, 55.0, ROWS) == pytest.approx(0.6)
|
||||
assert hotwater.cop_factor({"cop_tank_curve": [[40, 1.0], [60, 0.7]]}, 50.0, ROWS) == pytest.approx(0.85)
|
||||
t = tank("heat_pump", temp=45.0, channels=("power",), power=1500.0, hp_cop_drop_pct_per_k=2.0, hp_cop_ref_c=35.0)
|
||||
t["draw_w"] = draws()
|
||||
t["floor_c"] = hotwater.floors(t["draw_w"], 45.0, 40.0, None, ROWS)
|
||||
# a spread too small for the COP lost above 45 °C: no storing above it
|
||||
price = [27.0 if 12 <= hour(k) < 15 else 30.0 for k in range(192)]
|
||||
m, v, temps, x = solved(house([t], price))
|
||||
assert v["layers"] is not None and max(temps[96:]) < 46.5
|
||||
# electricity per heat: the upper layer's COP is lower (3 x 0.6 against 3 x 0.8)
|
||||
assert v["layers"][1] == pytest.approx(0.8) and v["layers"][2] == pytest.approx(0.5)
|
||||
# a wide spread pays for it
|
||||
price2 = [5.0 if 12 <= hour(k) < 15 else 40.0 for k in range(192)]
|
||||
_, _, temps2, _ = solved(house([t], price2))
|
||||
assert max(temps2[96:]) > 50.0
|
||||
|
||||
|
||||
def test_a_grossanlage_is_never_lowered():
|
||||
t = tank("element", temp=60.0, channels=("power",), volume=800.0, law_floor_c=60.0)
|
||||
t["draw_w"] = draws()
|
||||
t["floor_c"] = hotwater.floors(t["draw_w"], 45.0, 40.0, 60.0, ROWS)
|
||||
_, v, temps, _ = solved(house([t]))
|
||||
assert v["law"] and min(temps) >= 59.95
|
||||
|
||||
|
||||
def test_the_pipe_volume_makes_a_large_system():
|
||||
c = Control("tank", "dhw_tank", {"switch": "switch.heizstab", "temp_top": "sensor.t_top"}, True,
|
||||
{"heater": "element", "volume_l": 200, "max_power_w": 3000, "pipe_volume_l": 5.0})
|
||||
f, missing, src = c.tank_facts(dict(PARAMS, **{"de.dvgw_w551_pipe_volume_l": 3.0}))
|
||||
assert f["grossanlage"] is True and src["grossanlage"] == "pipe volume" and f["law_floor_c"] == 60
|
||||
c2 = Control("tank", "dhw_tank", {"switch": "switch.heizstab", "temp_top": "sensor.t_top"}, True,
|
||||
{"heater": "element", "volume_l": 200, "max_power_w": 3000, "pipe_volume_l": 2.0})
|
||||
f2, _, _ = c2.tank_facts(dict(PARAMS, **{"de.dvgw_w551_pipe_volume_l": 3.0}))
|
||||
assert f2["grossanlage"] is False
|
||||
|
||||
|
||||
def test_the_owners_hot_water_times(tmp_path):
|
||||
from cantabile_edge.preferences import Preferences
|
||||
t = tank("element", temp=45.0, channels=("power",))
|
||||
t["draw_w"] = draws()
|
||||
t["floor_c"] = hotwater.floors(t["draw_w"], 45.0, 40.0, None, ROWS)
|
||||
s = house([t])
|
||||
p = Preferences(str(tmp_path), lambda: START)
|
||||
c = Control("tank", "dhw_tank", {"power": "number.heizstab"}, True, {})
|
||||
ok, msg = p.apply_msg({"set": {"item": "tank:tank", "value": "daily 06:00-08:00 55 must"}}, {"tank": c},
|
||||
"Europe/Berlin", "owner", "owner")
|
||||
assert ok, msg
|
||||
s = p.apply(s, {"tank": c}, None, START)
|
||||
assert s["devices"][0]["pref"]["must"].count(55.0) > 0
|
||||
plan = optimizer.plan(s, 30)
|
||||
fb = [f for f in plan["prefs"] if f["control"] == "tank"]
|
||||
assert fb and all(f["met"] for f in fb if f["met"] is not None), fb
|
||||
|
||||
|
||||
def test_a_combi_boilers_comfort_mode():
|
||||
w = [1.0 if 6 <= hour(k) < 22 else 0.0 for k in range(192)]
|
||||
sleep = {"from": "22:00", "to": "06:00", "offset_k": -1.0}
|
||||
cc = hotwater.combi_comfort(START, "Europe/Berlin", 192, w, sleep)
|
||||
assert all(cc[k] for k in range(192) if 7 <= hour(k) < 21)
|
||||
assert not any(cc[k] for k in range(192) if hour(k) in (0, 3, 23))
|
||||
d = {"id": "heating", "kind": "heating", "channels": ["climate", "dhw_comfort"],
|
||||
"params": {"r_k_per_kw": 7.0, "c_kwh_per_k": 5.0, "max_power_w": 0, "comfort_c": 21, "setback_c": 17,
|
||||
"heat_source": "boiler", "boiler_efficiency": 0.9, "max_heat_w": 24000, "combi": True},
|
||||
"state": {"temp_c": 20.0}, "bounds": {"temp_c": [10, 28, "owner", "owner"]}, "dhw_comfort": cc}
|
||||
s = house([d])
|
||||
s["price_gas"] = [10.0] * 192
|
||||
p = optimizer.plan(s, 30)
|
||||
vals = {e.get("dhw_comfort") for e in p["devices"]["heating"]}
|
||||
assert vals == {"on", "off"}
|
||||
c = Control("heating", "heating", {"climate": "climate.boiler", "dhw_comfort": "switch.comfort"}, True,
|
||||
{"heat_source": "boiler"})
|
||||
col = Collector()
|
||||
col.on_entities({"a": {"switch.comfort": {"s": "on", "a": {}},
|
||||
"climate.boiler": {"s": "heat", "a": {"temperature": 20.0}}}})
|
||||
acts = actions_for(c, {"set": 20.0, "dhw_comfort": "off"}, col)
|
||||
assert [(a.entity, a.service) for a in acts] == [("switch.comfort", "turn_off")]
|
||||
@@ -95,7 +95,8 @@ def test_model_state_past_the_tariffs_end(tmp_path, src):
|
||||
s = ctl.model_state()
|
||||
assert s["price_import"][0] == 32.0 and s["price_import"][-1] is None # the horizon's tail unpriced
|
||||
assert s["price_heat"] == [None] * 192 and s["price_gas"][0] == 12.7
|
||||
assert s["refused"] == {} # the heating is planned
|
||||
# the heating is planned; the bundle's params lack the comfort band's rows: named (suggested values, G5)
|
||||
assert set(s["refused"]) == {"comfort_band"} and s["refused"]["comfort_band"]["fallback"] == "suggested"
|
||||
assert s["sources"]["outdoor"] == "fleet_forecast" and s["t_out"][0] == 3.0 # the bundle's weather
|
||||
shade = next(d for d in s["devices"] if d["id"] == "shades_living")
|
||||
assert len(shade["schedule"]["set"]) == s["steps"]
|
||||
|
||||
@@ -100,6 +100,21 @@ def test_presence_sources_proposed(tmp_path):
|
||||
assert set(persons) <= again
|
||||
|
||||
|
||||
def test_window_contact_proposed():
|
||||
"""An area's window contact becomes room.<area>.window
|
||||
(1 while "on"), consent off; a door's contact is not proposed."""
|
||||
states, reg = home()
|
||||
states = states + [st("binary_sensor.living_window", "off", "window", None, "Living window", None),
|
||||
st("binary_sensor.front_door", "on", "door", None, "Front door", None)]
|
||||
reg = dict(reg, entities=reg["entities"] + [
|
||||
{"entity_id": "binary_sensor.living_window", "unique_id": "w1", "platform": "zha", "area_id": "living_room"},
|
||||
{"entity_id": "binary_sensor.front_door", "unique_id": "d1", "platform": "zha", "area_id": "living_room"}])
|
||||
got = {a["asset"]: a for a in propose.propose(states, reg, PROFILES)}
|
||||
w = got["room.living_room.window"]
|
||||
assert (w["entity"], w["equals"], w["kind"], w["consent"]) == ("binary_sensor.living_window", "on", "gauge", False)
|
||||
assert not [a for a in got.values() if a["entity"] == "binary_sensor.front_door"]
|
||||
|
||||
|
||||
def test_proposal_from_the_bridge_profiles_and_names():
|
||||
states, reg = home()
|
||||
got = {a["asset"]: a for a in propose.propose(states, reg, PROFILES)}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Shades and A/C as plan variables (docs/methods.md G3, G4 in the plan):
|
||||
a cover with its window's facts is placed by the plan on the sun through
|
||||
the window and a shutter's lower loss; the inhabitant's own position holds;
|
||||
without the facts A7's rules stay."""
|
||||
import pytest
|
||||
|
||||
highspy = pytest.importorskip("highspy")
|
||||
|
||||
from cantabile_edge import optimizer, shades # noqa: E402
|
||||
|
||||
JULY = 1784160000 # 2026-07-16 00:00 UTC (02:00 in Berlin)
|
||||
JAN = 1799107200 # 2027-01-05 00:00 UTC
|
||||
BERLIN = {"latitude": 52.52, "longitude": 13.40}
|
||||
|
||||
|
||||
def hour(start, k):
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
return datetime.fromtimestamp(start + k * 900, timezone.utc).astimezone(ZoneInfo("Europe/Berlin")).hour
|
||||
|
||||
|
||||
def clear_ghi(start, steps):
|
||||
out = []
|
||||
for k in range(steps):
|
||||
el, _ = shades.sun_position(start + (k + 0.5) * 900, BERLIN["latitude"], BERLIN["longitude"])
|
||||
out.append(max(0.0, 1000.0 * __import__("math").sin(__import__("math").radians(el))) if el > 0 else 0.0)
|
||||
return out
|
||||
|
||||
|
||||
def state(start, devices, t_out, steps=96):
|
||||
return {"v": 1, "start": start, "step_s": 900, "steps": steps, "tz": "Europe/Berlin",
|
||||
"price_import": [30.0] * steps, "price_export": [8.0] * steps, "price_note": "test",
|
||||
"load_w": [300.0] * steps, "pv_w": [0.0] * steps, "t_out": [t_out] * steps,
|
||||
"sun": [0.0] * steps, "occupied": [1] * steps, "ghi_w_m2": clear_ghi(start, steps),
|
||||
"location": BERLIN, "devices": devices}
|
||||
|
||||
|
||||
def cover(**facts):
|
||||
p = {"room": "living", "gain_w": 800.0, "facing": "S", "quiet_from": "00:00", "quiet_to": "00:00"}
|
||||
p.update(facts)
|
||||
return {"id": "blind", "kind": "cover", "channels": ["cover"], "params": p, "state": {"position_pct": 100.0},
|
||||
"bounds": {"position_pct": [0, 100, "device", "device"]}}
|
||||
|
||||
|
||||
def room(kind, temp):
|
||||
p = {"r_k_per_kw": 8.0, "c_kwh_per_k": 3.0, "max_power_w": 2000, "comfort_c": 21 if kind == "heating" else 24,
|
||||
"setback_c": 17, "setup_c": 28, "cop": 3.0}
|
||||
return {"id": "living", "kind": kind, "channels": ["climate"], "params": p, "state": {"temp_c": temp},
|
||||
"bounds": {"temp_c": [10, 30, "owner", "owner"]}}
|
||||
|
||||
|
||||
FACTS = {"window_m2": 4.0, "g_value": 0.6, "shade_factor": 0.8}
|
||||
|
||||
|
||||
def test_the_sun_on_a_facade():
|
||||
noon = JULY + 10 * 3600 + 900 # 12:15 local
|
||||
south = shades.facade_irradiance(noon, 800.0, 52.52, 13.40, 180.0)
|
||||
north = shades.facade_irradiance(noon, 800.0, 52.52, 13.40, 0.0)
|
||||
assert south > 2 * north > 0
|
||||
assert shades.facade_irradiance(JULY, 0.0, 52.52, 13.40, 180.0) == 0.0
|
||||
|
||||
|
||||
def test_without_facts_the_rules_stay():
|
||||
s = state(JULY, [], 25.0)
|
||||
assert shades.window_plan(cover(), s) is None
|
||||
assert shades.window_plan(cover(window_m2=4.0, g_value=0.6), s) is None
|
||||
w = shades.window_plan(cover(**FACTS), s)
|
||||
assert w and max(w["sun_w"]) > 500 and w["h_sh"] == 0.0
|
||||
|
||||
|
||||
def plan(start, kind, temp, t_out, fixed_open=False, **facts):
|
||||
c = cover(**facts)
|
||||
s = state(start, [room(kind, temp), c], t_out)
|
||||
c["window"] = shades.window_plan(c, s)
|
||||
if fixed_open:
|
||||
c["bounds"]["position_pct"] = [100, 100, "owner", "owner"]
|
||||
m = optimizer.Model(s)
|
||||
m.solve(30)
|
||||
val = m.h.getSolution().col_value
|
||||
pos = [val[v.index] for v in m.devices["blind"][1]["pos"]]
|
||||
power = [val[v.index] for v in m.devices["living"][1]["power"]]
|
||||
return pos, power, m
|
||||
|
||||
|
||||
def test_summer_shades_first_then_the_ac():
|
||||
pos, power, _ = plan(JULY, "cooling", 25.0, 30.0, **FACTS)
|
||||
sunny = [k for k in range(96) if 11 <= hour(JULY, k) < 16]
|
||||
assert max(pos[k] for k in sunny) < 0.1 # closed against the sun
|
||||
_, power_open, _ = plan(JULY, "cooling", 25.0, 30.0, fixed_open=True, **FACTS)
|
||||
assert sum(power) < sum(power_open) # less cooling with the shade
|
||||
|
||||
|
||||
def test_winter_sun_in_and_the_shutter_closed_at_night():
|
||||
pos, power, _ = plan(JAN, "heating", 21.0, -2.0, window_u=1.3, closed_u_factor=0.6, **FACTS)
|
||||
sunny = [k for k in range(96) if 11 <= hour(JAN, k) < 14]
|
||||
night = [k for k in range(96) if hour(JAN, k) in (1, 2, 3)]
|
||||
assert min(pos[k] for k in sunny) > 0.9 # open: its warmth in
|
||||
assert max(pos[k] for k in night) < 0.1 # closed: the night's heat kept in
|
||||
|
||||
|
||||
def test_the_inhabitants_position_holds():
|
||||
c = cover(**FACTS)
|
||||
c["state"]["position_pct"] = 40.0
|
||||
s = state(JULY, [room("cooling", 25.0), c], 30.0)
|
||||
c["window"] = shades.window_plan(c, s, {"held_until": JULY + 2 * 3600})
|
||||
assert c["window"]["hold_steps"] == 8
|
||||
m = optimizer.Model(s)
|
||||
m.solve(30)
|
||||
val = m.h.getSolution().col_value
|
||||
pos = [val[v.index] for v in m.devices["blind"][1]["pos"]]
|
||||
assert all(abs(p - 0.4) < 1e-6 for p in pos[:8])
|
||||
p = optimizer.plan(s, 30)
|
||||
assert p["devices"]["blind"][0]["set"] is None and "by hand" in p["devices"]["blind"][0]["why"]
|
||||
Reference in new issue
Block a user