Files
cantabile-ha-addons/src/edge/cantabile_edge/optimizer.py
T

2841 lines
154 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The plan: a MILP over the next 48 h in 15-minute steps (HiGHS), re-made
every 15 minutes in a subprocess with a time limit (controller.py):
python -m cantabile_edge.optimizer < state.json > plan.json
Objective: the grid's cost (the tariff's import and export prices) plus
penalties for comfort the plan gives up and for the floors and limits it
would cross.
Prices (docs/parameters.md U1; no price is ever made up):
- no tariff (none received, expired, none for now: state["prices"]
status "none"): the plan is made without prices, for comfort, the
limits and the owner's musts only. The meter's energy and the devices'
energy carry a tiny engineering weight (NO_PRICE_EUR_KWH: of plans
otherwise equal, the one that moves the least energy), so nothing is
shifted, pre-heated, stored or exported for a price; the battery stays
in its own mode unless a reserve the owner set needs charging; the
market's contracts are not planned (nothing to compare them with).
The plan's cost and baseline are None and its price_note says why.
- a tariff that prices only the first n steps (beyond its end, or a gap):
the plan covers those n steps only (_cut), never a step without a
price as if it were free.
- a step without an export price: export is unpriced there, it carries
no value (neither earned nor charged, coefficient 0) - not "0 ct" as a
fact: the plan exports what it cannot use, but never discharges a
battery or plans anything to export, and the meter's import/export
switch treats it as worth nothing. Curtailing (spill) has its own small
engineering cost (SPILL_EUR_KWH), so PV is never curtailed while the
meter can take it, whatever export is worth; a negative export price
(a real one) still curtails. Floors and limits are soft here, with a penalty far above any
price, so there is always a plan (a room already below its floor must be
able to come back); the executor's guard enforces them hard on every action.
Device models (one function each, small and replaceable):
battery state of charge (estimated from params.soc_pct when no sensor),
charge/discharge power, efficiency, never both at once (binary);
the last charge free within its bounds, each kWh left worth V
(end_value: the Parameters page's battery.end_value_pct of the
mean feed-in price, under the cheapest import price; missing:
0, noted in the plan's "notes"); its idle loss (S.2): the
standby W taken from the cells while they hold charge (the grid
only as a valve), the cells' self-discharge as a factor per step
dhw_tank a hot-water tank's stored heat above the cold water (one node,
S.5): its standing loss UA (T - T_room), its heater's heat by
carrier, the hot water drawn (the dhw forecast), comfort between
min and max temperature, a legionella run where planned; the
plan's "storage" reports what each store loses
heating a room's first-order thermal model (R in K/kW, C in kWh/K, the
cooling outside temperature, heat from the device, from the sun
through the room's covers, and the fit's internal gain and sun
(internal_gain_w, solar_m2 x the irradiance; the sun's only
where the room has no cover in the plan, which carries it));
comfort target when occupied, setback/setup otherwise; a
switched boiler is on/off (binary). Only with its R and C (the
mapping's both, or a fit: never built-in defaults), its electric
power (max_power_w), its COP where the model needs it and its
temperature now; else the room is not planned (inputs.
room_refusal): its thermostat follows the owner's
or installer's schedule within the room's limits
(fallback_entries), else keeps its own setpoint
ev the energy needed by the departure time, between min and max
current (binary), only while connected
cover the share of the sun's heat into its room (0 closed .. 1 open);
a small penalty for closing it while someone is home in daylight.
With a schedule (shades.py: rules on the sun on its facade, the
season, quiet hours) its positions are fixed to it and its plan
entries are the schedule's moves
Heat by its source (docs/methods.md E6; params.heat_source, the prices
state["price_gas"] and state["price_heat"] per step, fleet heatprice.go):
electric / heat_pump electric W through the meter at the import price; heat
= COP x W (params cop, or cop_curve at the step's
outside temperature)
boiler gas W (billed, Hs) at the gas price; heat = the
boiler's efficiency x W; up to max_heat_w of heat
district heat W at the heat price; up to max_heat_w
hybrid both, one at a time (a binary per step: the heat pump
or the boiler), each change of source costing the
Parameters page's heat.hybrid_switch_eur (state
"params", from the tariff bundle: no flapping)
The plan's cost then counts gas and heat too (gas_eur, heat_eur). A control
whose price or facts are missing never reaches the plan (inputs.py
heating_refusal: refused with the reason). A boiler's gas follows its
part-load curve (E6.4: the mapping's boiler_type or part_load_curve; LP
segments where convex, binaries where not); a source's heat and its cost
are HeatSupply's, the heat no model decides (the space heat where no room
is planned, the hot water drawn) heat_demand's: the heat outlook (A2.16), a
fixed labelled term of the cost (cost_parts.heat_outlook_eur). CO2 (A2.15):
the Parameters page's co2.planner_eur_per_t on the grid import, gas and
district heat at the tariff bundle's factors; the plan reports co2_kg.
The grid operator's limit (gridorder.py, state["grid_order"]: §14a through
the EEBUS bridge): the controllable consumers may draw at most
limit_w from the grid beyond the household's own net load, i.e. the import
at most max(0, load - pv) + limit_w per step, with a penalty far above any
building request (nobody overrides it).
The market's contracts in force (state["market"], from the market bundle;
the market's step 2, minimal, shadow: the plan only, no commands): a contract
the home buys on is an import source at its price, one it sells on an
export sink, through the same meter as the grid (which keeps the tariff's
import and feed-in prices), so the plan exchanges where the contract beats
the grid. Each step uses its own slot's terms (window, amounts, price) when
the bundle carries the coming slots (a contract's "terms", term_at). The
plan's "market" lists per contract the planned kWh and the saving against
the grid (vs_grid_eur).
The building's requests (building.py, state["building"]): a load limit on
the grid import and a thermostat cap are constraints with a penalty (binding
far above any price, flexible with a price), a shift request a soft target
(the window's import lowered by its kWh against the house's own net load).
A battery plan (the building's one plan for its battery, its own box
following it) is a tracking target per step: the batteries' grid-side power
(their sum) at the building's W, each kWh off it at the request's penalty
(above any price, below the owner's floors and the SoC bounds, which win:
battery_plan). The battery's plan entries then say "building <id>: ..." and
stay setpoints (not the inverter's own self-consumption mode). A battery
bound to a building (building.py battery_bound) charges beyond the
building's W only from the PV surplus, and where no plan covers a step
(lapsed, or beyond its 24 h) it is in self-consumption only: no grid
charging, no discharge into the grid, the inverter's own mode.
The owner's preferences (preferences.py, a device's "pref"): a room's
target per step from its schedule (in place of the occupied hours) at the
comfort cost, and a "must" as a floor (heating) or limit (cooling) with the
penalty MUST_EUR_K, inside the bounds and under a building's thermostat cap; a
car's ready-by time and energy (a must at EV_MUST_EUR_KWH, a prefer valued
at its max_ct per kWh with min_kwh at EV_SHORT_EUR_KWH); a battery's
reserve as its floor per step. The plan's "prefs" says per preference
whether it is met; with state["prefs_cost"] its "prefs_cost" the cost of
each must (pref_costs: the plan made again without it).
"""
import copy
import json
import math
import sys
import time
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
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
PENALTY_LIMIT = 5.0 # EUR per unit and step across a floor or limit (K, % of a battery, kWh)
COMFORT_EUR_KH = 2.0 # EUR per K and hour below (heating) or above (cooling) the comfort target
# while someone is home: above any price (0.30 let a room cool by 1.3 K
# at a 40 ct peak); pre-heating in cheap hours still pays
EV_SHORT_EUR_KWH = 1.0 # EUR per kWh the car lacks at departure
EV_MUST_EUR_KWH = 5.0 # EUR per kWh a car lacks at a "must" ready-by (preferences.py): above any price,
# below a building's binding load limit (50) and the grid operator's (500)
MUST_EUR_K = 20.0 # EUR per K and slot across a room's "must" (preferences.py): 80 EUR per K·h, so the
# heat a room holds (C kWh/K) is not worth letting it fall even at 3 EUR/kWh; it stays
# inside the bounds and under a building's cap, so those still win
COST_SOLVE_S = 8.0 # s at most per extra plan for a must's cost (pref_costs)
COST_MAX = 6 # musts costed per plan at most
LIGHT_EUR = 0.002 # EUR per step for a closed cover while someone is home in daylight
CHANGE_EUR_KW = 0.002 # EUR per kW a device's power changes from one step to the next: smooth
# 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)
SPILL_EUR_KWH = 1e-3 # EUR per kWh of PV curtailed (ENG: never curtail while the meter takes it;
# above NO_PRICE_EUR_KWH so export wins over spill without a tariff)
END_VALUE_KEY = "battery.end_value_pct" # the Parameters page's (via the tariff bundle's params): % of the
# mean feed-in price a kWh left in the battery at the end is worth
WEAR_KEY = "battery.wear_ct" # the Parameters page's (via the tariff bundle's params): net ct per kWh a battery
# discharges, its ageing per kWh cycled (the owner's battery algorithm, 2026-11-12:
# in every decision, as the building's battery_core); a device's own wear_ct wins
END_VALUE_GAP_CT = 0.5 # ct/kWh: the end value at least this far below the cheapest import price (ENG: never
# buy grid energy into the battery only to keep it; building/mieterstrom.py's twin)
GRID_MAX_W = 43470.0 # W: the site's connection when the state does not say (state["grid_max_w"],
# config grid_max_w): a German house connection's usual 63 A main fuse,
# 3 x 230 V x 63 A
CO2_KEY = "co2.planner_eur_per_t" # the Parameters page's (via the tariff bundle's params): EUR per t of CO2 the
# plan weighs on its grid import, gas and district heat (0: cost only)
CO2_BASIS_KEY = "co2.basis" # the Parameters page's: direct | lifecycle (the plan reports which)
LEGIONELLA_EVERY = 4 # steps: a tank's legionella run is checked on the hour (ENG: a binary per hour, not
# per step: solve time)
RELAY_STEPS = 4 # steps: a tank element's relay is on or off for a whole hour in the plan (ENG: solve
# time; the guard's min_switch_s keeps it from cycling faster anyway)
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)
class Model:
def __init__(self, s: dict):
self.s = s
self.T, self.dt = s["steps"], s["step_s"] / 3600.0
self.h = highspy.Highs()
self.h.setOptionValue("output_flag", False)
self.flows = [[] for _ in range(self.T)] # (+1 into the house's balance | -1 out of it, var)
self.cost = [] # (coef, var)
self.devices = {} # id -> (kind, vars for the plan)
# False: no tariff, no prices (_prepare); a state not prepared: priced
# where it has a tariff and an import price for every step
self.priced = s["priced"] if "priced" in s else (
(s.get("prices") or {}).get("status", "tariff") != "none" and
all(v is not None for v in (s.get("price_import") or [None])[:self.T]))
self.notes: list[str] = [] # what the plan assumed or left out, quietly (no alarm)
self.co2w = self.co2_weight()
def note(self, text: str):
if text and text not in self.notes:
self.notes.append(text)
# -- CO2 (docs/methods.md A2.15) -------------------------------------------
def co2_weight(self) -> float:
"""w, EUR per t of CO2 in the objective: the Parameters page's
co2.planner_eur_per_t (the tariff bundle's params); 0 (cost only)
without a tariff, without the parameter (noted) or without any CO2
factor in the bundle (noted while w > 0; the parameter's absence is
noted where the bundle has factors to weigh)."""
if not self.priced:
return 0.0
raw = (self.s.get("params") or {}).get(CO2_KEY)
try:
w = float(raw)
except (TypeError, ValueError):
w = None
if w is None or not math.isfinite(w) or w < 0:
if self.s.get("co2"):
self.note(f"{CO2_KEY} missing: CO2 not weighed (cost only)")
return 0.0
if w > 0 and not self.s.get("co2"):
self.note("no CO2 factors in the tariff: CO2 not weighed")
return 0.0
return w
def co2_factor(self, carrier: str, t: int) -> float | None:
"""g CO2 per kWh of a carrier in step t (the bundle's), or None."""
c = self.s.get("co2") or {}
if carrier == "electricity":
xs = c.get("electricity") or []
v = xs[t] if t < len(xs) else None
else:
v = c.get(carrier)
return float(v) if isinstance(v, (int, float)) and math.isfinite(v) and v >= 0 else None
def co2_wh(self, carrier: str, t: int) -> float:
"""The CO2 term per W held for one step of a carrier's input: w x
f x dt / 1000 kWh / 1e6 g per t (A2.15); 0 with no weight, and 0
where the carrier has no factor (that carrier unweighed, noted)."""
if not self.co2w:
return 0.0
f = self.co2_factor(carrier, t)
if f is None:
self.note(f"no CO2 factor for {carrier}" + (" in some steps" if carrier == "electricity" else "")
+ f": {carrier} unweighed there")
return 0.0
return self.co2w * f * self.dt / 1000.0 / 1e6
# -- a boiler's part load (docs/methods.md E6.4) ----------------------------------
def boiler_curve(self, cid: str, p: dict, qmax: float, eff: float) -> dict:
"""A boiler's gas against its heat: its part-load curve (the
mapping's part_load_curve, else the Parameters page's
boiler.part_load_<boiler_type>) as segments, the full-load point
for an on/off one; none: one constant efficiency (noted). {segs,
convex, gmax (gas W at full heat), full (the full-load efficiency)}."""
pts, why = part_load(p, self.s.get("params"))
if pts is None or qmax <= 0:
why = why if pts is None else "no max_heat_w: one constant efficiency"
self.note(f"{cid}: {why}")
return {"segs": None, "convex": True, "gmax": qmax / eff if eff else 0.0, "full": eff, "from": why}
segs, convex, capped = gas_segments(qmax, eff, pts)
if capped:
self.note(f"{cid}: the part-load efficiency held at 1 (no more heat than the gas's Hs)")
full = min(1.0, eff * relative_efficiency(pts, 1.0))
return {"segs": segs, "convex": convex, "gmax": sum(dq * sl for dq, sl in segs), "full": full, "from": why}
def boiler_step(self, bc: dict, cost: float, switched: bool, qmax: float) -> tuple:
"""One step's gas input of a boiler and its heat terms ((W of heat
per W of the variable, variable), ...): on its curve (convex: an LP's
segments; efficiency rising with load: one binary per segment beyond
the first, so a segment is used only once the one before is full),
at its full-load point when switched on/off, else at the one
efficiency. (gas var, terms)."""
if switched:
gmax = qmax / bc["full"] if bc["full"] else 0.0
u = self.var(0.0, 1.0, integer=True)
pg = self.var(0.0, gmax, cost=cost)
self.h.addConstr(pg - gmax * u == 0)
return pg, [(bc["full"], pg)]
if not bc["segs"]:
pg = self.var(0.0, bc["gmax"], cost=cost)
return pg, [(bc["full"], pg)]
segs = bc["segs"]
ds = [self.var(0.0, dq) for dq, _ in segs]
pg = self.var(0.0, bc["gmax"], cost=cost)
self.h.addConstr(pg - sum((sl * d for (_, sl), d in zip(segs, ds)), start=Lin()) == 0)
if not bc["convex"]:
for k in range(1, len(segs)):
y = self.var(0.0, 1.0, integer=True)
self.h.addConstr(ds[k] - segs[k][0] * y <= 0)
self.h.addConstr(ds[k - 1] - segs[k - 1][0] * y >= 0)
return pg, [(1.0, d) for d in ds]
def var(self, lo=0.0, hi=highspy.kHighsInf, cost=0.0, integer=False):
v = self.h.addVariable(lb=lo, ub=hi, type=highspy.HighsVarType.kInteger if integer else
highspy.HighsVarType.kContinuous)
if cost:
self.cost.append((cost, v))
return v
def smooth(self, series):
"""The cost of every change in a power series (W variables or
expressions), |p[t] - p[t-1]|."""
for a, b in zip(series, series[1:]):
d = self.var(cost=CHANGE_EUR_KW / 1000.0)
self.h.addConstr(d - b + a >= 0)
self.h.addConstr(d + b - a >= 0)
def eur_wh(self, t: int, price_ct: float | None) -> float:
"""EUR for one W held for one step at this price (None: no price, 0)."""
return 0.0 if price_ct is None else self.dt / 1000.0 * price_ct / 100.0
def use_cost(self, t: int = 0) -> float:
"""Without a tariff: a device's energy's tie-break weight per W and
step (NO_PRICE_EUR_KWH; rising a little over the horizon, so of
equal plans the earlier wins); with one 0 (its prices count)."""
if self.priced:
return 0.0
return self.dt / 1000.0 * NO_PRICE_EUR_KWH * (1.0 + t / max(1, self.T))
# -- the house -------------------------------------------------------
def grid(self):
"""Import and export through the meter, each at most the site's
connection (grid_max_w; never below the house's own net load or
surplus, so there is always a plan). The meter either imports or
exports in a step: a binary where the feed-in pays at least the
import price (else importing to export at once would earn money and
the plan would run to the bound). Elsewhere none is needed: doing
both costs more than doing less of each, which keeps the balance and
only loosens every other constraint on the import (all are upper
bounds: the building's, the grid order's); steps with a market
contract have their own switch (market)."""
s = self.s
cap = float(s.get("grid_max_w") or GRID_MAX_W)
self.gin, self.gout, self.gcap = [], [], []
for t in range(self.T):
net = s["load_w"][t] - s["pv_w"][t]
hi_in, hi_out = max(cap, net), max(cap, -net)
if self.priced:
# the import's price, and its CO2 at the weight (A2.15; no credit for export)
gi = self.var(0.0, hi_in, cost=self.eur_wh(t, s["price_import"][t]) + self.co2_wh("electricity", t))
# an unpriced export (None) carries no value: coefficient 0
go = self.var(0.0, hi_out, cost=-self.eur_wh(t, s["price_export"][t]))
else:
gi = self.var(0.0, hi_in, cost=self.dt / 1000.0 * NO_PRICE_EUR_KWH)
go = self.var(0.0, hi_out, cost=self.dt / 1000.0 * NO_PRICE_EUR_KWH)
spill = self.var(0.0, max(0.0, s["pv_w"][t]), cost=self.dt / 1000.0 * SPILL_EUR_KWH)
self.gin.append(gi)
self.gout.append(go)
self.gcap.append((hi_in, hi_out))
self.flows[t] += [(1, gi), (-1, go), (-1, spill)]
def grid_switch(self, skip):
"""The meter's import/export switch where the feed-in pays at least
the import price (grid), outside the steps in skip (market's own)."""
s = self.s
if not self.priced:
return # both carry the same tiny weight: doing both never pays
for t in range(self.T):
pe = s["price_export"][t] if s["price_export"][t] is not None else 0.0 # unpriced: worth nothing
if t in skip or pe < s["price_import"][t]:
continue
hi_in, hi_out = self.gcap[t]
imp = self.var(0.0, 1.0, integer=True)
self.h.addConstr(self.gin[t] - hi_in * imp <= 0)
self.h.addConstr(self.gout[t] + hi_out * imp <= hi_out)
def market(self):
"""The market's contracts in force (state["market"], bundles.py
market_for_model; shadow, the market's step 2): a contract the home
buys on is an import source at its price, one it sells on an export
sink, both through the same meter as the grid. Bounds per step: the
best-effort maximum; a firm amount (bought: at least that much; sold:
a shortfall costs the contract's price again, a stand-in for its
penalty); take-or-pay (the minimum is paid whether used or not). The
meter either imports or exports in a step (a binary where a contract
applies), so nothing bought is resold."""
self.buy = [[] for _ in range(self.T)] # contract import vars per step
self.sell = [[] for _ in range(self.T)]
self.contracts = [] # (contract, {step: var}, {step: paid var})
steps = set()
for c in self.s.get("market") or []:
vars_, paid_ = {}, {}
for t in range(max(0, c["from_step"]), min(self.T, c["to_step"])):
k = term_at(c, t) # this step's terms (the coming slots), else the contract's
if k is None:
continue
hi = k["max_w"] if k.get("max_w") else MARKET_MAX_W
eur = self.eur_wh(t, k["price_ct"])
if c["direction"] == "buys":
lo = min(k.get("guaranteed_w") or 0.0, hi)
mwh = k.get("minimum_wh") or 0.0
if mwh > 0: # take-or-pay: what is paid covers at least the minimum
v = self.var(lo, hi)
paid = self.var(mwh / self.dt, cost=eur)
self.h.addConstr(paid - v >= 0)
paid_[t] = paid
else:
v = self.var(lo, hi, cost=eur)
self.buy[t].append(v)
self.flows[t].append((1, v))
else:
v = self.var(0.0, hi, cost=-eur)
g = min(k.get("guaranteed_w") or 0.0, hi)
if g > 0:
short = self.var(cost=eur)
self.h.addConstr(v + short >= g)
self.sell[t].append(v)
self.flows[t].append((-1, v))
vars_[t] = v
steps.add(t)
self.contracts.append((c, vars_, paid_))
for t in steps:
imp = self.var(0.0, 1.0, integer=True)
self.h.addConstr(sum(self.buy[t], start=Lin()) + self.gin[t] - MARKET_MAX_W * imp <= 0)
self.h.addConstr(sum(self.sell[t], start=Lin()) + self.gout[t] + MARKET_MAX_W * imp <= MARKET_MAX_W)
self.grid_switch(steps)
def meter_in(self, t):
"""The meter's import in step t: the grid's and the contracts' bought."""
return self.gin[t] + sum(self.buy[t], start=Lin()) if self.buy[t] else self.gin[t]
def building(self):
"""The building's load limit and shift request (on the meter's import)."""
req = self.s.get("building") or {}
lim = req.get("load_limit")
if lim:
for t in range(lim["from_step"], lim["to_step"]):
over = self.var(cost=lim["penalty"] * self.dt / 1000.0)
self.h.addConstr(self.meter_in(t) - over <= lim["value"])
sh = req.get("shift_request")
if sh:
a, b = sh["from_step"], sh["to_step"]
base = sum(max(0.0, self.s["load_w"][t] - self.s["pv_w"][t]) * self.dt for t in range(a, b))
target = max(0.0, base - sh["value"] * 1000.0)
miss = self.var(cost=sh["penalty"] / 1000.0)
imp = sum((self.dt * self.meter_in(t) for t in range(a, b)), start=Lin())
self.h.addConstr(imp - miss <= target)
def battery_plan(self):
"""The building's plan for its battery (state["building"]
["battery_plan"], building.py; docs/methods.md A9.3): per step it
covers, the battery's grid-side power (charge - discharge) tracks
the target, each W off it costing penalty x dt / 1000 (EUR per kWh
of deviation). A site with several batteries: their sum tracks it.
The SoC bounds and the owner's reserve (PENALTY_LIMIT, per % and
step) cost far more, so they win; no battery planned: nothing.
A battery bound to a building (state["building"]["battery_bound"],
A9.4): it charges more than the building's plan only from the
house's PV surplus (a reserve below its floor is refilled from PV,
from the grid only as far as the plan itself charges); a step no
plan covers (lapsed, or beyond its window) is self-consumption only:
charged from the PV surplus, discharged for the house's own use,
never from or into the grid for the box's own tariff."""
bld = self.s.get("building") or {}
bp, bound = bld.get("battery_plan"), bld.get("battery_bound")
bats = [v for kind, v in self.devices.values() if kind == "battery" and v]
if not bats or not (bp or bound):
return
ws = bp["schedule_w"] if bp else []
a, b = (max(0, bp["from_step"]), min(self.T, bp["to_step"], len(ws))) if bp else (0, 0)
load, pv = self.s["load_w"], self.s["pv_w"]
for t in range(self.T):
w = ws[t] if a <= t < b else None
if w is None and not bound:
continue
net = sum((v["ch"][t] - v["dis"][t] for v in bats), start=Lin())
surplus, deficit = max(0.0, pv[t] - load[t]), max(0.0, load[t] - pv[t])
if w is not None:
pos = self.var(cost=bp["penalty"] * self.dt / 1000.0)
neg = self.var(cost=bp["penalty"] * self.dt / 1000.0)
self.h.addConstr(net - pos + neg == float(w))
if bound:
# above the building's W only from the PV surplus: never the box's own grid charging
self.h.addConstr(net <= max(float(w), 0.0) + surplus)
else:
# self-consumption only (no building plan covers the step)
self.h.addConstr(net <= surplus)
self.h.addConstr(net >= -deficit)
if bound and bound.get("lapsed"):
self.notes.append(f"the battery plan of building {bound['building']} ended "
f"{time.strftime('%d %b %H:%M UTC', time.gmtime(bound.get('until') or 0))} and was not renewed: "
"the battery runs in self-consumption only (no grid charging) until the next one")
def grid_order(self):
"""The grid operator's limit on the controllable consumers' draw."""
o = self.s.get("grid_order") or {}
if not o:
return
for t in range(o["from_step"], min(o["to_step"], self.T)):
base = max(0.0, self.s["load_w"][t] - self.s["pv_w"][t])
over = self.var(cost=o["penalty"] * self.dt / 1000.0)
self.h.addConstr(self.meter_in(t) - over <= base + o["limit_w"])
def balance(self):
s = self.s
for t in range(self.T):
expr = sum((sign * v for sign, v in self.flows[t]), start=Lin())
self.h.addConstr(expr == s["load_w"][t] - s["pv_w"][t])
# -- devices ---------------------------------------------------------
def end_value(self) -> float:
"""V, ct per kWh left in a battery at the plan's end (docs/methods.md
A2.5, as the building's D5.17): the Parameters page's
battery.end_value_pct (state["params"], the tariff bundle's) of the
horizon's mean export price, at most END_VALUE_GAP_CT below its
cheapest import price (never grid energy bought only to keep it),
never below 0. 0 without a tariff, without an export price or
without the parameter (noted: self.end_note)."""
if hasattr(self, "_end_v"):
return self._end_v
self._end_v, self.end_note = 0.0, ""
if not self.priced:
return 0.0
raw = (self.s.get("params") or {}).get(END_VALUE_KEY)
try:
pct = float(raw)
except (TypeError, ValueError):
pct = None
if pct is None or not math.isfinite(pct):
self.end_note = f"{END_VALUE_KEY} missing: the battery's charge at the end valued at 0"
return 0.0
pe = [p for p in (self.s.get("price_export") or [])[:self.T] if p is not None]
if not pe:
self.end_note = "no export price: the battery's charge at the end valued at 0"
return 0.0
v = pct / 100.0 * sum(pe) / len(pe)
cheapest = min(self.s["price_import"][:self.T])
if v > cheapest - END_VALUE_GAP_CT:
v = cheapest - END_VALUE_GAP_CT
self.end_note = (f"the battery's end value capped at {max(0.0, v):.1f} ct/kWh, "
f"{END_VALUE_GAP_CT:g} ct below the cheapest import price")
self._end_v = max(0.0, v)
return self._end_v
def wear(self, p: dict) -> tuple[float, str]:
"""The battery's wear (ct per kWh discharged) and where it came from: the device's own wear_ct, else the
Parameters page's battery.wear_ct (state["params"]); 0 without a tariff (nothing is priced) or without
either (as before 2026-11-12: "none")."""
if not self.priced:
return 0.0, "none"
for raw, src in ((p.get("wear_ct"), "device"), ((self.s.get("params") or {}).get(WEAR_KEY), "parameter")):
try:
v = float(raw)
except (TypeError, ValueError):
continue
if math.isfinite(v) and v >= 0:
return v, src
return 0.0, "none"
def battery(self, d):
p, st, b = d["params"], d["state"], d["bounds"]
cap = max(1.0, float(p["capacity_wh"]))
eff = float(p["efficiency"])
lo_pct, hi_pct = b["soc_pct"][0], b["soc_pct"][1]
plo, phi = b["power_w"][0], b["power_w"][1]
max_ch = max(0.0, min(float(p["max_charge_w"]), phi))
max_dis = max(0.0, min(float(p["max_discharge_w"]), -plo))
soc0 = cap * min(max(float(st["soc_pct"]), 0.0), 100.0) / 100.0
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
# phi per step. Facts with their source (inputs.model_state); none: 0 (noted there)
p0 = max(0.0, float(p.get("standby_w") or 0.0))
lam_h = max(0.0, float(p.get("self_discharge_pct_month") or 0.0)) / 100.0 / HOURS_PER_MONTH
phi = (1.0 - lam_h) ** self.dt
grid_side = p.get("standby_in_load") is False
wear_ct, wear_src = self.wear(p)
wear_eur = wear_ct / 100.0 * self.dt / 1000.0 # EUR per W discharged over a step
self.wear_used = getattr(self, "wear_used", {})
self.wear_used[d["id"]] = {"ct": wear_ct, "src": wear_src}
lbs, lgs = [], []
for t in range(self.T):
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(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)
z = self.var(0.0, 1.0, integer=True)
self.h.addConstr(c - max_ch * z <= 0)
self.h.addConstr(x + max_dis * z <= max_dis)
e = self.var(0.0, cap, cost=STORE_TIE_EUR_WH if p0 > 0 else 0.0)
under = self.var(cost=PENALTY_LIMIT / cap * 100) # Wh below the floor, per % of the battery
over = self.var(cost=PENALTY_LIMIT / cap * 100)
if p0 > 0:
lb = self.var(0.0, p0)
lg = self.var(0.0, p0, cost=STANDBY_GRID_EUR_KWH * self.dt / 1000.0)
self.h.addConstr(lb + lg == p0)
if grid_side:
self.flows[t].append((-1, lg))
self.h.addConstr(e - phi * prev - self.dt * eff * c + self.dt / eff * x + self.dt * lb == 0)
lbs.append(lb)
lgs.append(lg)
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_t / 100.0 * cap)
self.flows[t] += [(-1, c), (1, x)]
soc.append(e)
ch.append(c)
dis.append(x)
prev = e
# the end value (docs/methods.md A2.5, as the building's D5.17): the
# last charge is free within its bounds, each kWh left in it worth V
# (without a tariff nothing is drained for a price anyway: V 0)
v_ct = self.end_value()
if v_ct:
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": 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")})
def room(self, d, cooling: bool, gains):
p, st, b = d["params"], d["state"], d["bounds"]
r, c = float(p["r_k_per_kw"]), float(p["c_kwh_per_k"])
# the device's electric power and COP: facts (inputs.room_refusal / heating_refusal left out
# a room without them); a boiler or a heat station draws no electricity in the plan
elec = cooling or str(p.get("heat_source") or "electric") in ("electric", "heat_pump", "hybrid")
pmax = float(p["max_power_w"]) if elec else 0.0
cop = float(p["cop"]) if p.get("cop") is not None else 0.0 # 0: none (a curve alone, or no electricity)
lo, hi = b["temp_c"][0], b["temp_c"][1]
comfort = float(p["comfort_c"])
other = float(p["setup_c"] if cooling else p["setback_c"])
t0 = st.get("temp_c")
t0 = float(t0) if t0 is not None else comfort
switched = not cooling and "switch" in d["channels"] and "climate" not in d["channels"]
temps, powers, prev = [], [], t0
band = [] # per step the owner's band (the shift envelope's: shift_envelope)
# what makes the heat (module docstring; inputs.py refused it where a price or fact is missing)
src = "electric" if cooling else str(p.get("heat_source") or "electric")
# facts and parameters, never defaults: inputs.heating_refusal left out a control without them
eff = float(p["boiler_efficiency"]) if src in ("boiler", "hybrid") else None
qmax = float(p["max_heat_w"]) if src in ("boiler", "hybrid", "district") else 0.0
# a boiler's gas or a heat station's heat against the room's heat, at its carrier's price and CO2 (E6)
sup = HeatSupply(self, d["id"], p, "district" if src == "district" else "boiler",
switched and src == "boiler") if src in ("boiler", "hybrid", "district") else None
gmax = sup.gmax if sup and src != "district" else 0.0
switch_eur = float((self.s.get("params") or {})["heat.hybrid_switch_eur"]) if src == "hybrid" else 0.0
t_out = self.s["t_out"]
cops = [cop_at(p, t_out[t]) if p.get("cop_curve") else cop for t in range(self.T)]
els, gss, dhs, hxs, bxs, prev_u = [], [], [], [], [], None
hts, occs = [], [] # per step the heat's terms; the occupancy the target used
if src == "hybrid" and st.get("source") in ("heat_pump", "boiler"):
prev_u = 1.0 if st["source"] == "heat_pump" else 0.0 # the source now: a change from it counts
a = self.dt / (r * c)
internal = self.hourly(p.get("internal_gain_w") or 0.0)
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
# get what is left of its most heat in each step (the hot-water forecast; without one the rooms keep
# all of it, noted). With a store (a dhw_tank whose heater is this boiler: shares_with) the store is
# its own device: its draws come from the store, and the burner's heat is shared (dhw_tank)
combi = combi_dhw(self, d["id"], p, src) if not cooling else None
for t in range(self.T):
terms = [] # (W of heat per W of input, the input)
pw = pg = ph = None
if src in ("electric", "heat_pump", "hybrid"):
if switched and src != "hybrid":
u = self.var(0.0, 1.0, integer=True)
pw = self.var(0.0, pmax, cost=self.use_cost(t))
self.h.addConstr(pw - pmax * u == 0)
else:
pw = self.var(0.0, pmax, cost=self.use_cost(t))
self.flows[t].append((-1, pw))
terms.append((cops[t], pw))
if src in ("boiler", "hybrid"):
pg, bterms = sup.variables(t)
terms += bterms
# the burner's heat alone (a hybrid's heat pump apart): what a store it heats shares (dhw_tank)
bxs.append(sum((k * v for k, v in bterms), start=Lin()))
if src == "district":
ph, hterms = sup.variables(t)
terms += hterms
if src == "hybrid":
hu = self.var(0.0, 1.0, integer=True) # 1: the heat pump, 0: the boiler
self.h.addConstr(pw - pmax * hu <= 0)
self.h.addConstr(pg + gmax * hu <= gmax)
if prev_u is not None:
sw = self.var(cost=switch_eur)
self.h.addConstr(sw - hu + prev_u >= 0)
self.h.addConstr(sw + hu - prev_u >= 0)
prev_u = hu
els.append(pw)
gss.append(pg)
dhs.append(ph)
heat = sum((k * v for k, v in terms), start=Lin())
hxs.append(heat)
hts.append(list(terms))
if combi is not None:
self.h.addConstr(heat <= max(qmax - combi[t], 0.0))
main = pw if pw is not None else pg if pg is not None else ph
tt = self.var(-50.0, 80.0)
sign = -1.0 if cooling else 1.0
covers = gains(t)
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:
b_hi = min(target, must) if must is not None else target
band.append((max(lo, cap["value"]) if capped else lo, max(min(b_hi, hi), lo)))
else:
b_lo = max(target, must) if must is not None else target
band.append((min(max(b_lo, lo), hi), min(hi, cap["value"]) if capped else hi))
if must is not None:
# a bound inside the bounds in force, and under a building's cap
mv = min(max(must, lo), hi)
if capped:
mv = max(mv, cap["value"]) if cooling else min(mv, cap["value"])
cross = self.var(cost=MUST_EUR_K)
if cooling:
self.h.addConstr(tt - cross <= mv)
else:
self.h.addConstr(tt + cross >= mv)
under = self.var(cost=PENALTY_LIMIT)
over = self.var(cost=PENALTY_LIMIT)
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:
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:
miss_cap = self.var(cost=cap["penalty"] * self.dt)
if cooling:
self.h.addConstr(tt + miss_cap >= cap["value"]) # cooling: not below the cap
else:
self.h.addConstr(tt - miss_cap <= cap["value"]) # heating: not above it
temps.append(tt)
powers.append(main)
prev = tt
self.smooth(powers if src != "hybrid" else [a_ + b_ for a_, b_ in zip(els, gss)])
# power: the electric input (None for gas and district heat: no electricity to shed or price);
# gas, district: their inputs; heat: per step the heat terms
self.devices[d["id"]] = ("cooling" if cooling else "heating",
{"temp": temps, "power": els, "gas": gss, "district": dhs, "src": src,
"fuel": boiler_fuel(p) if src in ("boiler", "hybrid") else None,
"cops": cops, "eff": eff, "heat": hxs, "qmax": qmax, "burner": bxs,
"pmax": {"electric": pmax, "heat_pump": pmax, "hybrid": pmax, "boiler": gmax,
"district": qmax}[src], "switched": switched,
# the shift envelope (electric sources only): Wh of electricity per K at the mean COP
"keep": 1 - a, "wh_per_k": 1000.0 * c / (sum(cops) / len(cops)) if cops and min(cops) > 0 else 0.0,
"band": band,
# for the heating levers the baseline does not count (heatlevers.py, E14): the
# room's model, the heat's terms per step, its source's conversion and facts
"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"),
# 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."""
if not isinstance(v, list):
return [float(v)] * self.T
zone = ZoneInfo(self.s.get("tz") or "UTC")
start, step = self.s["start"], self.s["step_s"]
return [float(v[datetime.fromtimestamp(start + t * step, timezone.utc).astimezone(zone).hour % len(v)])
for t in range(self.T)]
def ev(self, d):
p, st, b = d["params"], d["state"], d["bounds"]
pref = d.get("pref") # the owner's ready-by (preferences.py)
# not plugged in: nothing, or the session forecast's next session as an
# expected load (inputs.ev_session; no owner's ready-by): the plan sees
# it (prices, the battery), nothing acts on it (_entry: no commands)
exp = st.get("expected") if not st.get("connected") and not pref else None
if not st.get("connected") and not (exp and exp.get("need_wh") is not None and
int(exp.get("to_step", 0)) > int(exp.get("from_step", 0))):
self.devices[d["id"]] = ("ev", None)
return
volts = ev_volts(p, "plan")
imax = min(float(p["max_current_a"]), b["current_a"][1])
imin = max(float(p["min_current_a"]), b["current_a"][0])
sess = st.get("session") or {} # the session forecast's, where the car says none
first = 0
if exp:
first, dep, need = int(exp["from_step"]), int(exp["to_step"]), float(exp["need_wh"])
else:
if st.get("departure"):
dep = departure_step(self.s, str(st["departure"]))
elif sess.get("dep_step") is not None:
dep = min(self.T, int(sess["dep_step"]))
else:
dep = departure_step(self.s, str(p["departure"]))
need = float(st["need_wh"]) if st.get("need_wh") is not None else \
float(sess["need_wh"]) if sess.get("need_wh") is not None else float(p["need_wh"])
if pref:
dep, need = int(pref["dep_step"]), float(pref["need_wh"])
if pref.get("off"):
need = 0.0
powers, total = [], Lin()
for t in range(self.T):
if t < first or t >= dep or imax < imin:
powers.append(None)
continue
y = self.var(0.0, 1.0, integer=True)
pw = self.var(0.0, imax * volts, cost=self.use_cost(t))
self.h.addConstr(pw - imax * volts * y <= 0)
self.h.addConstr(pw - imin * volts * y >= 0)
self.flows[t].append((-1, pw))
powers.append(pw)
total += self.dt * pw
if pref and pref["how"] == "prefer":
# a kWh is worth max_ct to the owner (without one: today's), min_kwh at any price
worth = EV_SHORT_EUR_KWH if pref.get("max_ct") is None else max(0.0, pref["max_ct"]) / 100.0
short = self.var(cost=worth / 1000.0)
self.h.addConstr(total + short >= need)
mwh = min(float(pref.get("min_wh") or 0.0), need)
if mwh > 0:
short_min = self.var(cost=EV_SHORT_EUR_KWH / 1000.0)
self.h.addConstr(total + short_min >= mwh)
else:
short = self.var(cost=(EV_MUST_EUR_KWH if pref else EV_SHORT_EUR_KWH) / 1000.0)
self.h.addConstr(total + short >= need)
self.smooth([p for p in powers if p is not None])
self.devices[d["id"]] = ("ev", {"power": powers, "volts": volts, "dep": dep,
"pmax": imax * volts if imax >= imin else 0.0, "need": need,
# the ready-by and the energy known (shift_envelope): not the
# defaults, not a forecast session (expected: not plugged in yet)
"known": ev_known(st, pref) and not exp, "expected": bool(exp)})
def dhw_tank(self, d):
"""A hot-water tank (docs/methods.md A13; design S.4-S.6): its stored
heat above the cold water E_t = phi E_(t-1) + dt (Q_t - D_t + u_t - P0)
with phi = 1 - UA dt / (c_w V), P0 = UA (T_cw - T_room) (the standing
loss UA (T - T_room) in E); Q its heater's heat (an element's W, a
heat pump's COP x W, a boiler's gas by its efficiency, district heat);
D the hot water drawn (the dhw forecast); u the draw it could not
give (at dhw.short_eur_kwh: never infeasible). Between the comfort's
E_min (min_temp_c; a Großanlage at least the law's 60 °C, soft here,
hard in the guard) and E_max (max_temp_c, the device's own maximum).
A legionella run where the mapping says "plan" and it falls due in
the horizon: one step at legionella_temp_c, the cheapest (binaries
over the steps before its due time)."""
p, st, b = d["params"], d["state"], d["bounds"]
cw = WATER_WH_PER_L_K * float(p["volume_l"]) # Wh per K
t_cw = float(p["cold_water_c"])
room = st.get("room_c") if st.get("room_c") is not None else float(p["room_temp_c"])
ua = float(p["ua_w_k"])
phi = 1.0 - ua * self.dt / cw
p0 = ua * (t_cw - room)
lo_c = float(p["min_temp_c"])
if p.get("law_floor_c") is not None:
lo_c = max(lo_c, float(p["law_floor_c"]))
hi_c = min(float(p["max_temp_c"]), b["temp_c"][1])
lo_c = min(lo_c, hi_c)
emin, emax = cw * (lo_c - t_cw), cw * (hi_c - t_cw)
e0 = cw * (float(st["temp_c"]) - t_cw)
short = float(p["short_eur_kwh"]) / 1000.0 * self.dt # EUR per W short for a step
draw = [max(0.0, float(v)) for v in (d.get("draw_w") or [0.0] * self.T)[:self.T]]
draw += [0.0] * (self.T - len(draw))
heater = str(p["heater"])
switched = heater == "element" and not ({"water_heater", "power"} & set(d.get("channels") or []))
pmax = float(p.get("max_power_w") or 0.0) if heater in ("element", "heat_pump") else 0.0
cops = [1.0] * self.T
if heater == "heat_pump":
cops = [cop_at(p, self.s["t_out"][t]) if p.get("cop_curve") else float(p["cop"]) for t in range(self.T)]
sup = HeatSupply(self, d["id"], p, heater) if heater in ("boiler", "district") else None
shared = burner = None
if heater == "boiler" and p.get("shares_with"):
# its boiler is the rooms' boiler (a combi, a system boiler or a hybrid's gas boiler with a
# store): one burner, the store's heat and the rooms' heat from that burner together
# at most its heat output (a hybrid's heat pump is not the burner: its heat is not counted)
kind, rv = self.devices.get(p["shares_with"], (None, None))
if kind == "heating" and rv and rv.get("src") in ("boiler", "hybrid") and rv.get("qmax") and rv.get("burner"):
burner = (rv["burner"], rv["qmax"])
else:
self.note(f"{d['id']}: its boiler's room control {p['shares_with']} is not planned or has no boiler: "
"the tank's boiler planned alone")
if heater == "heat_pump" and p.get("shares_with"):
kind, rv = self.devices.get(p["shares_with"], (None, None))
if kind == "heating" and rv and rv.get("power"):
shared = (rv["power"], rv["pmax"])
else:
self.note(f"{d['id']}: its heat pump's room control {p['shares_with']} is not planned: "
"the tank's heat pump planned alone")
# legionella (the mapping's "plan"): the due step from its last run (inputs: storefit's)
leg = st.get("legionella") or {}
e_leg, window = None, []
if str(p.get("legionella") or "device") == "plan" and leg.get("due_step") is not None:
t_leg = float(p["legionella_temp_c"])
if t_leg > hi_c + 1e-9:
self.note(f"{d['id']}: legionella run at {t_leg:g} °C above the tank's maximum {hi_c:g} °C: not planned")
else:
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"):
pw = self.var(0.0, pmax, cost=self.use_cost(t))
if switched:
# a relay: on or off for a whole hour (RELAY_STEPS: 48 binaries, not 192)
if t % RELAY_STEPS == 0:
y = self.var(0.0, 1.0, integer=True)
self.h.addConstr(pw - pmax * y == 0)
self.flows[t].append((-1, 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":
pg, terms = sup.variables(t)
else:
ph, terms = sup.variables(t)
q = sum((k * v for k, v in terms), start=Lin())
if burner is not None and t < len(burner[0]):
self.h.addConstr(q + burner[0][t] <= burner[1])
# never below the cold water's (or a colder room's) temperature
e_lb = min(0.0, e0, cw * (room - t_cw))
e = self.var(e_lb, highspy.kHighsInf)
u = self.var(0.0, max(draw[t], 0.0), cost=short) # the draw not given
# 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 >= 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)
lsum += lt
es.append(e)
pws.append(pw)
gss.append(pg)
dhs.append(ph)
heats.append(terms)
unmet.append(u)
prev = e
if e_leg is not None and window:
miss = self.var(cost=PENALTY_LIMIT)
self.h.addConstr(lsum + miss >= 1)
self.smooth([v for v in (pws if heater in ("element", "heat_pump") else gss if heater == "boiler" else dhs)])
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, "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"),
# 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"]
lo, hi = b["position_pct"][0] / 100.0, b["position_pct"][1] / 100.0
sch = d.get("schedule")
if sch:
# the shade's moves by rules (shades.py): fixed here; the room
# gets the sun on its facade through them
room = p.get("room") if p.get("room") in room_ids else None
xs = [self.var(min(max(x / 100.0, 0.0), 1.0), min(max(x / 100.0, 0.0), 1.0)) for x in sch["pos"]] \
if room else []
sun = sch["sun"] if sch.get("facade") else self.s["sun"]
self.devices[d["id"]] = ("cover", {"pos": xs, "gain_w": float(p["gain_w"]), "room": room,
"schedule": sch, "sun": sun})
return
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)
daylight = self.s["sun"][t] > 0.05 and self.s["occupied"][t]
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"],
**({"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):
s = self.s
self.grid()
self.market()
covers = [d for d in s["devices"] if d["kind"] == "cover"]
rooms = {d["id"] for d in s["devices"] if d["kind"] in ("heating", "cooling")}
for d in covers:
self.cover(d, rooms)
for d in s["devices"]:
k = d["kind"]
if k == "battery":
self.battery(d)
elif k in ("heating", "cooling"):
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:
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":
self.ev(d)
for d in s["devices"]:
if d["kind"] == "dhw_tank":
self.dhw_tank(d) # after the rooms: a heat pump it shares with is planned
self.building()
self.battery_plan()
self.grid_order()
self.balance()
obj = sum((c * v for c, v in self.cost), start=Lin())
self.h.setOptionValue("time_limit", float(time_limit))
# tight: the differences between good plans are cents, the total
# cost euros (a 1 % gap left an EV charging at the evening price)
self.h.setOptionValue("mip_rel_gap", 1e-4)
self.h.setOptionValue("mip_abs_gap", 0.002)
self.h.minimize(obj)
status = self.h.getModelStatus()
info = self.h.getInfo()
if info.primal_solution_status != 2: # no feasible solution
raise RuntimeError(f"no plan: {self.h.modelStatusToString(status)}")
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
# site needs per step that no model in the plan decides; HeatSupply says
# what one W of heat from a source takes as input and costs (price, CO2,
# part load). Today the demand is met when it is demanded:
# HeatSupply.delivered is the one place that says so.
def is_combi(p: dict) -> bool:
"""A combi boiler (Kombitherme, 392): the heating control's
param combi (the mapping's, from the device or its owner): one burner
for the rooms and the hot water. A store is a device of its own (a
dhw_tank whose heater is this boiler, shares_with): combi_dhw."""
return p.get("combi") is True or str(p.get("combi") or "").lower() in ("true", "yes", "1")
def combi_dhw(m: "Model", cid: str, p: dict, src: str) -> list[float] | None:
"""A combi boiler's hot water per step (W of heat, the site's hot-water
forecast dhw_w), which it makes first (methods.md E6.6): the rooms'
heat is capped at its most heat less it. None for any other source, for
a combi that heats a store of its own (a dhw_tank with heater boiler and
shares_with this control: the store takes the draws, the burner is shared
there), or without a forecast (noted: the rooms keep its
whole output)."""
if src != "boiler" or not is_combi(p):
return None
for t in m.s.get("devices") or []:
tp = t.get("params") or {}
if t.get("kind") == "dhw_tank" and str(tp.get("heater") or "") == "boiler" and tp.get("shares_with") == cid:
return None
q = heat_demand(m.s, "dhw", m.T)
if q is None:
m.note(f"{cid}: a combi boiler without a hot-water forecast: its rooms keep its whole output (no hot-water meter)")
return None
return [max(0.0, float(v)) for v in q]
HEAT_DEMANDS = {"space": "heat_w", "dhw": "dhw_w"} # the model bundle's series (B13, B16)
def heat_demand(s: dict, kind: str, steps: int) -> list[float] | None:
"""The heat (W per step) of a demand the plan takes as it comes: "space"
the site's heat forecast (heat_w), "dhw" its hot water drawn (dhw_w);
None without a forecast."""
xs = s.get(HEAT_DEMANDS[kind])
if not xs:
return None
return [max(0.0, float(v)) for v in xs[:steps]]
class HeatSupply:
"""One heat source's heat in the plan (E6): a boiler's gas (its part
load, E6.4; on/off at its full-load point when switched) or district
heat, each W of input at its carrier's price and CO2 (A2.15). facts:
boiler_efficiency, max_heat_w, boiler_type, part_load_curve (a heating
control's params, or the site's: inputs.heat_site). variables(t): its
input and heat as the MILP's (a room's heat); delivered(demand): a fixed
heat as numbers (the heat outlook)."""
def __init__(self, m: "Model", cid: str, facts: dict, source: str, switched: bool = False):
self.m, self.cid, self.source, self.switched = m, cid, source, switched
# a boiler's fuel: gas or heating oil (the control's "fuel", E15); district heat: heat
self.carrier = boiler_fuel(facts) if source == "boiler" else "heat"
self.prices = (m.s.get("price_" + self.carrier) or [None] * m.T)
self.qmax = float(facts.get("max_heat_w") or 0.0)
self.eff = float(facts["boiler_efficiency"]) if source == "boiler" else None
self.curve = m.boiler_curve(cid, facts, self.qmax, self.eff) if source == "boiler" else None
@property
def gmax(self) -> float:
"""The most input (W): a boiler's gas at full heat, a heat station's heat."""
if self.source != "boiler":
return self.qmax
return self.qmax / self.curve["full"] if self.switched else self.curve["gmax"]
def cost_wh(self, t: int) -> float:
"""EUR per W of input held for step t: the carrier's price and its CO2 at the weight."""
p = self.prices[t] if t < len(self.prices) else None
return self.m.eur_wh(t, p) + self.m.co2_wh(self.carrier, t)
def variables(self, t: int) -> tuple:
"""Step t's input variable and its heat terms ((W of heat per W of
the variable, variable), ...) for the MILP."""
if self.source == "boiler":
return self.m.boiler_step(self.curve, self.cost_wh(t), self.switched, self.qmax)
ph = self.m.var(0.0, self.qmax, cost=self.cost_wh(t))
return ph, [(1.0, ph)]
def input_w(self, heat_w: float) -> float:
"""The input (W) for a heat (W): district heat as it is; a boiler's
gas on its curve (beyond its most heat at the full-load efficiency),
else at its one efficiency."""
q = max(0.0, heat_w)
if self.source != "boiler":
return q
segs = self.curve["segs"]
if not segs:
return q / self.eff
g, left = 0.0, q
for dq, sl in segs:
take = min(left, dq)
g, left = g + take * sl, left - take
return g + left / self.curve["full"]
def delivered(self, demand: list[float]) -> dict:
"""A demand met when it is demanded (the one place it is said: the
heat in step t is the demand of step t), as numbers: per step the
heat and the input (W), and in all the kWh, the cost at the
carrier's price (steps without one: unpriced_kwh) and the CO2 at its
factor (None where a step has none)."""
m = self.m
heat = [max(0.0, q) for q in demand[:m.T]]
inputs = [self.input_w(q) for q in heat]
eur = unpriced = kg = 0.0
no_factor = False
for t, w in enumerate(inputs):
kwh = w * m.dt / 1000.0
p = self.prices[t] if t < len(self.prices) else None
if p is None:
unpriced += kwh
else:
eur += kwh * p / 100.0
f = m.co2_factor(self.carrier, t)
if f is None:
no_factor = no_factor or kwh > 0
else:
kg += kwh * f / 1000.0
out = {"heat_w": [round(w) for w in heat], "input_w": [round(w) for w in inputs],
"heat_kwh": round(sum(heat) * m.dt / 1000.0, 2), "input_kwh": round(sum(inputs) * m.dt / 1000.0, 2),
"eur": round(eur, 2), "co2_kg": None if no_factor else round(kg, 2)}
if unpriced:
out["unpriced_kwh"] = round(unpriced, 2)
return out
def ev_known(st: dict, pref: dict | None) -> bool:
"""A car's ready-by and energy are facts: the ready-by the owner's
preference or the car's (its charger's departure entity), the energy
the car's (energy-needed entity) or the owner's (kWh, or % with the
car's state of charge and capacity). The mapping's defaults (need_wh,
departure) are not; a preference in % without the car's charge falls
back to them (preferences.py), so it is not either."""
dep = bool(pref) or st.get("departure") is not None
need = st.get("need_wh") is not None or bool(pref) and (
pref.get("kwh") is not None or (pref.get("soc_pct") is not None and bool(pref.get("capacity_wh"))))
return dep and need
def departure_step(s: dict, hhmm: str) -> int:
"""The step of the next departure (local time), within the horizon."""
zone = ZoneInfo(s.get("tz") or "UTC")
start = datetime.fromtimestamp(s["start"], timezone.utc).astimezone(zone)
h, m = (int(x) for x in hhmm.split(":"))
dep = start.replace(hour=h, minute=m, second=0, microsecond=0)
if dep <= start:
dep += timedelta(days=1)
return min(s["steps"], int((dep.timestamp() - s["start"]) // s["step_s"]))
def _round(v: float, step: float) -> float:
return round(v / step) * step
def _prepare(s: dict) -> dict:
"""The state as the plan takes it (U1): without a tariff (status none,
or no import price for the first step) priced False and no market; a
tariff that prices only the first n steps: the horizon cut to them."""
pi = s.get("price_import") or []
status = (s.get("prices") or {}).get("status", "tariff")
# gas and heat: a boiler's or district heat's steps only while their price lasts
n = s["steps"]
srcs = {str((d.get("params") or {}).get("heat_source") or "electric") for d in s.get("devices") or []
if d["kind"] == "heating"}
fuels = {boiler_fuel(d.get("params") or {}) for d in s.get("devices") or []
if d["kind"] == "heating" and str((d.get("params") or {}).get("heat_source") or "") in ("boiler", "hybrid")}
# a hot-water tank's heater: a tank's boiler is on gas (inputs.tank_refusal asks for the gas price)
tanks = {str((d.get("params") or {}).get("heater") or "") for d in s.get("devices") or [] if d["kind"] == "dhw_tank"}
srcs |= tanks
if "boiler" in tanks:
fuels.add("gas")
for key, need in (("price_gas", {"boiler", "hybrid"} if "gas" in fuels else set()),
("price_oil", {"boiler", "hybrid"} if "oil" in fuels else set()), ("price_heat", {"district"})):
xs = s.get(key) or []
if srcs & need and xs:
n = min(n, next((k for k, v in enumerate(xs) if v is None), len(xs)))
if n == 0:
n = s["steps"] # refused upstream (inputs.heating_refusal): nothing to cut for
if status == "none" or not pi or pi[0] is None:
s = dict(s, priced=False, market=[])
return _cut(s, n) if n < s["steps"] else s
n = min(n, next((k for k, v in enumerate(pi) if v is None), len(pi)))
s = dict(s, priced=True)
return _cut(s, n) if n < s["steps"] else s
def _cut(s: dict, n: int) -> dict:
"""The state for its first n steps: every per-step list (any list of
the horizon's length, at any depth) cut to n, the step ranges (from_step,
to_step, dep_step) kept inside it (a car's ready-by beyond it: "beyond")."""
T = s["steps"]
def cut(x):
if isinstance(x, list):
return [cut(v) for v in (x[:n] if len(x) == T else x)]
if isinstance(x, dict):
y = {k: cut(v) for k, v in x.items()}
for k in ("from_step", "to_step"):
if isinstance(y.get(k), int):
y[k] = min(y[k], n)
if isinstance(y.get("dep_step"), int) and y["dep_step"] > n:
y["dep_step"], y["beyond"] = n, True
return y
return x
out = cut(s)
out["steps"] = n
return out
def plan(s: dict, time_limit: float = 30.0) -> dict:
t0 = time.time()
s = _prepare(s)
m = Model(s)
status = m.solve(time_limit)
val = m.h.getSolution().col_value
x = lambda v: val[v.index] # noqa: E731
start, step, T = s["start"], s["step_s"], m.T
pi = s["price_import"]
devices = {}
for d in s["devices"]:
kind, v = m.devices.get(d["id"], (d["kind"], None))
entries = []
for t in range(T):
e = _entry(d, kind, v, t, x, s, pi, (x(m.gin[t]), x(m.gout[t])))
if e is not None and (not entries or _key(entries[-1]) != _key(e)):
entries.append({"t": start + t * step, **e})
devices[d["id"]] = entries
market = market_plan(s, m, x)
energy = energy_of(s, m, x, market)
heat_cost = carrier_costs(s, m, x)
# the heat no room model plans (a district-heated or gas home): its expected cost, a fixed term (A2.16)
outlook = heat_outlook(s, m)
parts = None
if energy is not None:
parts = {"electricity_eur": round(energy, 2), "gas_eur": round(heat_cost["gas_eur"], 2),
"heat_eur": round(heat_cost["heat_eur"], 2)}
if heat_cost["oil_eur"]:
parts["oil_eur"] = round(heat_cost["oil_eur"], 2)
energy += heat_cost["gas_eur"] + heat_cost["heat_eur"] + heat_cost["oil_eur"]
if outlook is not None:
parts["heat_outlook_eur"] = round(outlook["eur"], 2)
energy += outlook["eur"]
base = baseline(s, m, x)
if base is not None and outlook is not None:
base += outlook["eur"] # the same heat with or without the plan
out = {"v": 1, "made": int(time.time()), "start": start, "step_s": step, "status": status,
"solve_s": round(time.time() - t0, 2), "devices": devices, "flex": flexibility(m, x),
# without a tariff no cost: None, never a cost at a made-up price
"cost_eur": round(energy, 2) if energy is not None else None,
"baseline_eur": round(base, 2) if base is not None else None,
"priced": m.priced, "steps": T, "price_state": s.get("prices") or {},
"price_note": s.get("price_note", ""), "sources": s.get("sources", {})}
bats = [v for kind, v in m.devices.values() if kind == "battery" and v]
if bats and m.priced:
# the batteries' end value (A2.5): V and the change of their charge at it, not in cost_eur
v_ct = m.end_value()
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
# 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:
out["heat_outlook"] = outlook
# what the stores lose while they hold energy, their facts' sources (design note 10.5)
storage = storage_report(s, m, x)
if storage:
out["storage"] = storage
co2 = co2_report(s, m, x, outlook)
if co2 is not None:
out["co2_kg"] = co2
out["co2_basis"] = (s.get("co2") or {}).get("basis") or str((s.get("params") or {}).get(CO2_BASIS_KEY) or "")
# what the plan assumed for want of a fact, or left out (also published; quiet: no alarm): the inputs'
# notes (inputs.model_state: occupancy, the car's forecast session), the battery's end value, the model's
notes = [str(n) for n in s.get("notes") or []]
if getattr(m, "end_note", ""):
notes.append(m.end_note)
notes += m.notes
if notes:
out["notes"] = notes
# the site's energy per carrier and use, per step for 24 h (the console's plan chart; methods A2.17)
series = plan_series(s, m, x, outlook)
if series:
out["series"] = series
steps_eur = step_costs(s, m, x)
if steps_eur is not None:
out["steps_eur"] = steps_eur # per step and carrier: with and without the plan (costs.py)
out["saving_parts"] = saving_parts(s, m, x, steps_eur) # by carrier and lever (plansplit.py, E14)
if heat_cost["gas_eur"] or heat_cost["heat_eur"] or heat_cost["oil_eur"]:
out["gas_eur"], out["heat_eur"] = round(heat_cost["gas_eur"], 2), round(heat_cost["heat_eur"], 2)
if heat_cost["oil_eur"]:
out["oil_eur"] = round(heat_cost["oil_eur"], 2)
# rooms not planned (inputs.room_refusal): the thermostat's
# fallback schedule, and which one in their refusal
refused = copy.deepcopy(s.get("refused") or {})
for d in s.get("fallback") or []:
entries = fallback_entries(s, d)
if entries:
devices[d["id"]] = entries
if d["id"] in refused:
refused[d["id"]]["fallback"] = ("schedule" if entries else
"own" if "climate" in d.get("channels", []) else "none")
if refused:
out["refused"] = refused # controls not planned, and why (U2, E6)
if market:
out["market"] = market
if any(d.get("pref") for d in s["devices"]) or any(d.get("pref") for d in s.get("fallback") or []):
out["prefs"] = pref_feedback(s, m, x) + fallback_feedback(s)
if s.get("prefs_cost") and energy is not None:
out["prefs_cost"] = pref_costs(s, energy, t0 + time_limit)
return out
def energy_of(s, m, x, market=None) -> float:
"""The plan's cost for power (EUR): the grid's import less its feed-in
(an unpriced export counts nothing), and the market's contracts; None
without a tariff."""
if not m.priced:
return None
pi, pe = s["price_import"], s["price_export"]
e = sum(m.eur_wh(t, pi[t]) * x(m.gin[t]) - m.eur_wh(t, pe[t]) * x(m.gout[t]) for t in range(m.T))
return e + sum(c["cost_eur"] for c in (market if market is not None else market_plan(s, m, x)))
def _when(s, ts: float) -> str:
return datetime.fromtimestamp(ts, timezone.utc).astimezone(ZoneInfo(s.get("tz") or "UTC")).strftime("%a %H:%M")
TOL_K = 0.3 # a room's target counts as met within this
TOL_PCT = 0.5 # a battery's reserve
TOL_WH = 50.0 # a car's energy
def pref_feedback(s, m, x) -> list[dict]:
"""Per preference (a room's block, boost or away; a car's next ready-by;
a battery's reserve): met or not in the plan, and in a few words why.
Fields: control, group, kind, how, label, met (None: not in the
plan's 48 h, or not plugged in), detail, and per kind the numbers."""
out = []
start, step, T = s["start"], s["step_s"], m.T
for d in s["devices"]:
pref = d.get("pref")
if not pref:
continue
kind, v = m.devices.get(d["id"], (d["kind"], None))
if kind in ("heating", "cooling") and v:
out += _room_feedback(s, d, pref, v, x, kind == "cooling")
elif kind == "battery" and v:
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": "battery", "how": "must", "label": g["text"]}
if not ts:
out.append(dict(f, met=None, detail="not in the next 48 h"))
continue
soc = [100.0 * x(v["soc"][t]) / v["cap"] for t in ts]
worst = min(range(len(ts)), key=lambda k: soc[k] - v["floors"][ts[k]])
miss = v["floors"][ts[worst]] - soc[worst]
met = miss <= TOL_PCT
f.update(met=met, min_pct=round(min(soc), 1), floor_pct=round(v["floors"][ts[worst]], 1))
if not met:
f["detail"] = f"{soc[worst]:.0f} % at {_when(s, start + (ts[worst] + 1) * step)}"
if d["state"].get("soc_pct") is not None and float(d["state"]["soc_pct"]) < v["floors"][ts[0]]:
f["detail"] += f" (starts at {float(d['state']['soc_pct']):.0f} %)"
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
def _room_feedback(s, d, pref, v, x, cooling) -> list[dict]:
out = []
start, step, T = s["start"], s["step_s"], len(pref["target"])
lo, hi, lo_by, hi_by = (d["bounds"]["temp_c"] + ["device", "device"])[:4]
cap = (s.get("building") or {}).get("thermostat_cap")
sign = -1.0 if cooling else 1.0
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": g["kind"], "how": g["how"], "label": g["text"]}
if not ts:
out.append(dict(f, met=None, detail="not in the next 48 h"))
continue
notes = []
want = []
for t in ts:
w0 = pref["must"][t] if g["how"] == "must" and pref["must"][t] is not None else pref["target"][t]
w = min(max(w0, lo), hi)
by = (hi_by if not cooling else lo_by) if sign * (w0 - w) > 1e-9 else None
if cap and cap["from_step"] <= t < cap["to_step"]:
wc = max(w, cap["value"]) if cooling else min(w, cap["value"])
if wc != w:
by, w = "building", wc
if by and by not in notes:
notes.append(by)
want.append(w)
temps = [x(v["temp"][t]) for t in ts]
gap = [sign * (w - tt) for w, tt in zip(want, temps)]
k = max(range(len(ts)), key=lambda i: gap[i])
met = gap[k] <= TOL_K
f.update(met=met, first=start + ts[0] * step, worst_c=round(temps[k], 1), want_c=round(want[k], 1))
bits = []
if notes:
held = min(want) if not cooling else max(want)
bits.append(f"held at {held:g} °C by the {notes[0]}'s limit")
f["held_by"] = notes[0]
if not met:
bits.append(f"{temps[k]:.1f} °C at {_when(s, start + (ts[k] + 1) * step)}")
if bits:
f["detail"] = "; ".join(bits)
out.append(f)
return out
def _ev_feedback(s, d, pref, v, x, m) -> dict:
start, step = s["start"], s["step_s"]
f = {"control": d["id"], "group": pref["group"], "kind": "ev", "how": pref["how"],
"label": f"car {pref['text']}", "at": pref["at"], "need_kwh": round(pref["need_wh"] / 1000.0, 2)}
plug = f"; plugged in at {_when(s, pref['plugged_at'])}" if pref.get("plugged_at") else ""
if pref.get("note"):
f["note"] = pref["note"]
if v is None:
return dict(f, met=None if pref["how"] == "prefer" else False, detail="not plugged in")
pw = [x(p) if p is not None else 0.0 for p in v["power"]]
dep = min(v["dep"], len(pw))
wh = sum(m.dt * p for p in pw[:dep])
short = max(0.0, pref["need_wh"] - wh)
pi = s["price_import"]
f["planned_kwh"] = round(wh / 1000.0, 2)
f["charge_eur"] = round(sum(m.eur_wh(t, pi[t]) * pw[t] for t in range(dep)), 2) if m.priced else None
reached = ""
if pref.get("soc_pct") is not None and pref.get("capacity_wh"):
pct = min(100.0, float(pref["soc_pct"]) + 100.0 * wh / pref["capacity_wh"])
f["reached_pct"] = round(pct, 0)
reached = f"{pct:.0f} %"
else:
reached = f"{wh / 1000.0:.1f} kWh"
when = _when(s, pref["at"])
if pref.get("beyond"):
f.update(met=None, detail=f"{reached} by the end of the plan (the ready-by is later){plug}")
return f
if pref["how"] == "prefer":
f["met"] = short <= max(TOL_WH, 0.01 * pref["need_wh"])
f["detail"] = f"{reached} by {when}" + ("" if f["met"] else
f" ({short / 1000.0:.1f} kWh less: dearer than the price wanted)") + plug
return f
f["met"] = short <= max(TOL_WH, 0.01 * pref["need_wh"])
if f["met"]:
f["detail"] = f"{reached} by {when}{plug}"
return f
# a must it cannot meet: by how much, and when it could be ready at full power from now
f["short_kwh"] = round(short / 1000.0, 2)
rate = v.get("pmax") or 0.0
if rate > 0:
n = math.ceil(pref["need_wh"] / (rate * m.dt) - 1e-9)
f["ready_at"] = int(start + n * step)
can = f"; ready at full power by {_when(s, f['ready_at'])}"
else:
can = "; it may not charge now (a limit holds it at 0 A)"
f["detail"] = f"{reached} by {when}, short by {short / 1000.0:.1f} kWh{can}{plug}"
return f
def pref_costs(s, energy: float, deadline: float) -> dict:
"""Each must's cost (EUR a day): the plan's cost for power less that of
the plan made again without it (a room's block at its setback, a
battery's reserve at its floor before); a car's must: what its charging
costs (no second plan). At most COST_MAX, each within COST_SOLVE_S and
the time left."""
out = {}
days = s["steps"] * s["step_s"] / 86400.0
n = 0
for i, d in enumerate(s["devices"]):
pref = d.get("pref")
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"]:
continue
left = deadline - time.time() - 1.0
if n >= COST_MAX or left < 1.0:
return out
n += 1
s2 = copy.deepcopy(s)
s2["prefs_cost"] = False
s2["devices"][i]["pref"]["off"] = gi
try:
m2 = Model(s2)
m2.solve(min(COST_SOLVE_S, left))
val = m2.h.getSolution().col_value
e2 = energy_of(s2, m2, lambda v: val[v.index])
except Exception: # noqa: BLE001 - a cost is not worth failing the plan
continue
c = (energy - e2) / days
out[g["group"]] = round(c if abs(c) >= 0.005 else 0.0, 2)
return out
def term_at(c: dict, t: int) -> dict | None:
"""A market contract's terms in plan step t: its per-step terms when the
bundle told the coming slots (None: it does not apply then), else the
contract's own (held over from_step .. to_step)."""
per = c.get("terms")
if per is None:
return c
return per[t] if 0 <= t < len(per) else None
def contract_energy(m, x, c, vars_, paid_):
"""A market contract's steps in the plan with energy used or paid:
(step, kWh used, kWh paid, the step's price ct). A take-or-pay
contract's paid energy is at least its minimum, used or not."""
for t, v in sorted(vars_.items()):
e = max(x(v), 0.0) * m.dt / 1000.0
pay = max(x(paid_[t]) * m.dt / 1000.0, e) if t in paid_ else e
if pay < 1e-6:
continue
yield t, e, pay, (term_at(c, t) or c)["price_ct"]
def contract_eur(c, e, pay, price) -> float:
"""What a contract's step costs (EUR; < 0 received): bought, the kWh
paid at its price; sold, the kWh delivered at its price."""
return pay * price / 100.0 if c["direction"] == "buys" else -e * price / 100.0
def market_plan(s, m, x) -> list[dict]:
"""Per contract in the plan (shadow): the planned energy per step and in
all (kWh), what is paid, and what it saves against the grid: bought,
import price x kWh used - contract price x kWh paid; sold, (contract
price - feed-in) x kWh (EUR; < 0: dearer than the grid). A take-or-pay
contract's paid energy is at least its minimum, used or not (what the
optimisation pays). Fields: id, name, direction, price_ct, steps [{t,
kwh, paid_kwh}] (steps with energy used or paid only), planned_kwh,
paid_kwh, cost_eur (> 0 paid, < 0 received), vs_grid_eur."""
out = []
pi, pe = s["price_import"], s["price_export"]
for c, vars_, paid_ in getattr(m, "contracts", []):
steps, kwh, paid_kwh, cost, vs = [], 0.0, 0.0, 0.0, 0.0
for t, e, pay, price in contract_energy(m, x, c, vars_, paid_):
steps.append({"t": s["start"] + t * s["step_s"], "kwh": round(e, 4), "paid_kwh": round(pay, 4)})
kwh += e
paid_kwh += pay
cost += contract_eur(c, e, pay, price)
if c["direction"] == "buys":
vs += (e * pi[t] - pay * price) / 100.0
else:
vs += e * (price - (pe[t] or 0.0)) / 100.0 # an unpriced export: worth nothing
out.append({"id": c["id"], "name": c.get("name", ""), "direction": c["direction"], "price_ct": c["price_ct"],
"steps": steps, "planned_kwh": round(kwh, 4), "paid_kwh": round(paid_kwh, 4),
"cost_eur": round(cost, 4), "vs_grid_eur": round(vs, 4)})
return out
FLEX_STEPS = 96 # 24 h at 15 min: what a building plans with (shed_w, grid_w)
SHIFT_STEPS = 192 # 48 h: the shift envelope (the band prices' horizon)
SHIFT_DEVICES = 16 # devices in a shift envelope at most (the fleet's storage bound)
def flexibility(m, x) -> dict:
"""What the flat could do for its building (the building
asks for flexibility, it doesn't cap averages; building/README.md hole
3), per step for the next 24 h: grid_w, the planned import through the
meter (the grid's and a market contract's: a flat supplied by its
building's pool imports through a contract, and its gin alone was 0, so
shed_w was 0 too: docs/methods.md A11); shed_w, how much of it the
controllable devices (heating, cooling, EV, the battery's charging)
could drop in that step, plus what the battery could still discharge
(its spare power, bounded by the energy above its floor): what a
load_limit can take away without touching the household's own use.
shift (48 h, shift_envelope): the energy the devices can move, for a
building's price bands; absent where no device's facts are known."""
n = min(m.T, FLEX_STEPS)
bought = [x(m.gin[t]) + sum((x(v) for v in m.buy[t]), 0.0) for t in range(m.T)]
grid = [round(bought[t]) for t in range(n)]
shed = [0.0] * n
for kind, v in m.devices.values():
if v is None:
continue
if kind == "battery":
for t in range(min(n, len(v["dis"]))):
# what it holds above its floor after this step's idle loss (S.2)
stored = (max(v.get("phi", 1.0) * x(v["soc"][t - 1]) - m.dt * v.get("p0", 0.0), 0.0) if t else
max(x(v["soc"][0]), 0.0)) - v["floor_wh"]
spare = max(v["max_dis"] - x(v["dis"][t]), 0.0)
shed[t] += max(min(spare, stored / m.dt if m.dt else 0.0), 0.0)
cols = v.get("ch") if kind == "battery" else v.get("power")
for t in range(min(n, len(cols or []))):
if cols[t] is not None and hasattr(cols[t], "index"): # an EV's steps after departure are empty
shed[t] += max(x(cols[t]), 0.0)
out = {"grid_w": grid, "shed_w": [round(min(sh, g)) for sh, g in zip(shed, grid)],
"net_w": [round(bought[t] - x(m.gout[t]) - sum((x(v) for v in m.sell[t]), 0.0)) for t in range(n)]}
sh = shift_envelope(m, x)
if sh:
out["shift"] = sh
return out
def plan_series(s, m, x, outlook) -> dict:
"""The plan's energy picture per step for the next 24 h (FLEX_STEPS; W,
the mean power in the step: docs/methods.md A2.17), for the console's
plan chart: electricity's sources (import_w, pv_w: the forecast, the
battery's discharge) and uses (load_w: the house's own forecast,
heating_w / cooling_w: electric heat and cooling, ev_w, dhw_element_w:
a tank's electric heater, the battery's charge, export_w), and the other
carriers' inputs: gas_w and oil_w (a boiler's fuel, Hi), heat_w (heat
bought from a district or the building), dhw_w (hot water's heat drawn,
where forecast); per hot-water tank its planned temperature
("tank_c:<id>", °C). Only what the site has (a key absent: not in the plan,
never 0 for it); the heat outlook (A2.16) adds its fixed heat as drawn."""
n = min(m.T, FLEX_STEPS)
out: dict[str, list] = {}
def add(key, t, w):
out.setdefault(key, [0.0] * n)[t] += w
for t in range(n):
add("import_w", t, x(m.gin[t]) + sum((x(v) for v in m.buy[t]), 0.0))
add("export_w", t, x(m.gout[t]) + sum((x(v) for v in m.sell[t]), 0.0))
add("load_w", t, max(0.0, float(s["load_w"][t])))
if any(float(v) > 0 for v in s["pv_w"][:n]):
out["pv_w"] = [max(0.0, float(v)) for v in s["pv_w"][:n]]
temps = {}
for did, (kind, v) in m.devices.items():
if not v:
continue
if kind == "battery":
for t in range(min(n, len(v["ch"]))):
add("battery_charge_w", t, _x(x, v["ch"][t]))
add("battery_discharge_w", t, _x(x, v["dis"][t]))
continue
if kind == "ev":
for t in range(min(n, len(v["power"]))):
add("ev_w", t, _x(x, v["power"][t]))
continue
if kind not in ("heating", "cooling", "dhw_tank"):
continue
el = "dhw_element_w" if kind == "dhw_tank" else kind + "_w"
fuel = (v.get("fuel") or "gas") + "_w"
for col, key in (("power", el), ("gas", fuel), ("district", "heat_w")):
xs = v.get(col) or []
if not any(c is not None and hasattr(c, "index") for c in xs[:n]):
continue
for t in range(min(n, len(xs))):
add(key, t, _x(x, xs[t]))
if kind == "dhw_tank":
# its planned mean temperature at each step's end (°C, not W: "tank_c:<id>")
temps["tank_c:" + did] = [round(tank_temp(v, t, x), 1) for t in range(min(n, len(v["e"])))]
for t in range(min(n, len(v.get("draw") or []))):
d = v["draw"][t]
add("dhw_w", t, float(d) if isinstance(d, (int, float)) else _x(x, d))
if outlook:
key = {"gas": "gas_w", "oil": "oil_w", "heat": "heat_w"}.get(outlook.get("carrier"))
for kind, ln in (outlook.get("lines") or {}).items():
for t in range(min(n, len(ln["input_w"]))):
if key:
add(key, t, float(ln["input_w"][t]))
if kind == "dhw":
add("dhw_w", t, float(ln["heat_w"][t]))
return {**{k: [round(w) for w in v] for k, v in out.items()}, **temps}
def _x(x, v) -> float:
"""A step's value: a variable's, or 0 where there is none (an EV's steps after departure)."""
return x(v) if v is not None and hasattr(v, "index") else 0.0
def shift_envelope(m, x) -> dict | None:
"""The energy each controllable device can move over the next 48 h,
from what the plan already knows (docs/methods.md A11), for the
building's price bands (building/mieterstrom.py: the flats' agents
re-plan against the band prices; the building models that response
with this). Per device, per step (W, Wh; the step is step_s):
battery base_w (the planned grid-side power: charge > 0, discharge
< 0), soc_wh (the state of charge at the start), lo_wh per
step (its floor: the bounds and the owner's reserve), max_wh
(its ceiling), cap_wh (its capacity: a metered % in Wh for
the building's coordinator), ch_w, dis_w (its power), eta (one way), end_wh (the planned
last state of charge: the building keeps at least it)
ev, heating, cooling
base_w (planned), up_w / down_w (the most it can draw above /
below base_w), lo_wh / hi_wh (the bounds of the moved energy
store S_t = keep * S_(t-1) + (p_t - base_t) * dt, S_(-1) = 0),
keep (1 a lossless store: a car; a room's heat decays toward
its plan: 1 - dt / (R C))
Published only from facts: a battery with its ratings (a battery
without them is not planned at all: U2); a car plugged in whose
ready-by and energy are the owner's preference or the car's own (never
the defaults); a room whose R and C are fitted (or the mapping's) with
the device's COP (the mapping's, or none needed: a fit against the
electric power) and the owner's band (preferences, or the mapping's
comfort temperatures); a room without them is not planned at all. None of them: None."""
s = m.s
n = min(m.T, SHIFT_STEPS)
if n <= 0:
return None
dt = m.dt
src = s.get("sources") or {}
rooms, cops, bands = src.get("rooms") or {}, src.get("rooms_cop") or {}, src.get("rooms_band") or {}
out = []
for d in s["devices"]:
kind, v = m.devices.get(d["id"], (d["kind"], None))
if v is None:
continue
if kind == "battery":
base = [_x(x, v["ch"][t]) - _x(x, v["dis"][t]) for t in range(n)]
out.append({"id": d["id"], "kind": "battery", "base_w": [round(b) for b in base],
"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),
"standby_src": ((src.get("battery") or {}).get(d["id"]) or {}).get("standby_w", "none")})
elif kind == "ev":
if not v.get("known") or v["pmax"] <= 0:
continue
p = [_x(x, v["power"][t]) for t in range(n)]
dep = min(v["dep"], n)
if dep <= 0 or sum(p) <= 0 and v["need"] <= 0:
continue
up = [max(0.0, v["pmax"] - p[t]) if t < dep else 0.0 for t in range(n)]
down = [p[t] if t < dep else 0.0 for t in range(n)]
lo, hi, cum = [], [], 0.0
for t in range(n):
cum += p[t] * dt
if t < dep - 1: # before the ready-by: between nothing and the need delivered
lo.append(-cum)
hi.append(max(0.0, v["need"] - cum))
else: # at and after it: what the plan delivers (a ready-by beyond the horizon: no less by its end)
end = v["need"] - cum
lo.append(min(0.0, end) if v["dep"] <= n else 0.0)
hi.append(max(0.0, end))
out.append({"id": d["id"], "kind": "ev", "base_w": [round(a) for a in p], "up_w": [round(a) for a in up],
"down_w": [round(a) for a in down], "lo_wh": [round(a) for a in lo], "hi_wh": [round(a) for a in hi],
"keep": 1.0})
elif kind in ("heating", "cooling"):
if v.get("switched"):
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", "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" 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)
lo, hi = [], []
for t in range(n):
blo, bhi = v["band"][t]
a, b = sorted((sign * (blo - temps[t]) * k, sign * (bhi - temps[t]) * k))
lo.append(min(a, 0.0)) # the plan's own temperature is always inside
hi.append(max(b, 0.0))
out.append({"id": d["id"], "kind": kind, "base_w": [round(a) for a in p],
"up_w": [round(max(0.0, v["pmax"] - a)) for a in p], "down_w": [round(a) for a in p],
"lo_wh": [round(a) for a in lo], "hi_wh": [round(a) for a in hi], "keep": round(v["keep"], 6)})
elif kind == "dhw_tank":
if v["heater"] not in ("element", "heat_pump") or v["switched"] or v["pmax"] <= 0:
continue # gas, district heat or a relay: no band of electric power
p = [_x(x, v["power"][t]) for t in range(n)]
cop = sum(v["cops"][:n]) / n
lo, hi = [], []
for t in range(n):
e = _x(x, v["e"][t])
# the heat it can hold more or less than planned, in Wh of electricity at the mean COP
lo.append(min(0.0, (v["emin"] - e) / cop))
hi.append(max(0.0, (v["emax"] - e) / cop))
out.append({"id": d["id"], "kind": "dhw_tank", "base_w": [round(a) for a in p],
"up_w": [round(max(0.0, v["pmax"] - a)) for a in p], "down_w": [round(a) for a in p],
"lo_wh": [round(a) for a in lo], "hi_wh": [round(a) for a in hi], "keep": round(v["phi"], 6)})
if not out:
return None
return {"v": 1, "start": s["start"], "step_s": s["step_s"], "steps": n, "devices": out[:SHIFT_DEVICES]}
def _charge_why(pi, t) -> str:
"""Why the battery charges from the grid: "cheap grid power" only in the
cheapest quarter of the horizon's prices and 10 % below their mean
(sim-munich-1 called 47.6 ct cheap: an evening day-ahead price under a
50 ct flat); else what it is for, the dearer hours later."""
p25 = sorted(pi)[len(pi) // 4]
mean = sum(pi) / len(pi)
if pi[t] <= p25 + 1e-9 and pi[t] < 0.9 * mean:
return f"cheap grid power ({pi[t]:.1f} ct)"
later = pi[t + 1:]
if later and max(later) > pi[t]:
k = t + 1 + later.index(max(later))
return f"charge for dearer hours later ({pi[t]:.1f} ct now, {pi[k]:.1f} ct in {(k - t) * 15 // 60} h)"
return f"charge from the grid ({pi[t]:.1f} ct)"
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"), e.get("dhw_comfort"))
def boiler_fuel(p: dict) -> str:
"""A boiler's fuel (docs/methods.md E15): "oil" where its control says
fuel: oil (heating oil EL), else "gas": a boiler before branch
heating-oil was a gas boiler by definition (the schema's meaning, not a
guess; inputs.heating_refusal refuses any other fuel)."""
return "oil" if str((p or {}).get("fuel") or "gas") == "oil" else "gas"
def carrier_costs(s, m, x) -> dict:
"""What the plan's gas, heating oil and district heat cost (EUR), at
their prices (the rooms'); a boiler's input (column "gas") at its
fuel's price."""
dh = s.get("price_heat") or []
out = {"gas_eur": 0.0, "heat_eur": 0.0, "oil_eur": 0.0}
for kind, v in m.devices.values():
if kind not in ("heating", "dhw_tank") or not v:
continue
fuel = v.get("fuel") or "gas"
for key, prices, col in ((fuel + "_eur", s.get("price_" + fuel) or [], "gas"), ("heat_eur", dh, "district")):
for t, var in enumerate(v.get(col) or []):
if var is not None and t < len(prices) and prices[t] is not None:
out[key] += m.eur_wh(t, prices[t]) * x(var)
return out
def _inputs_w(v, t, x) -> float:
"""A heating or cooling device's input in step t (W: electric, gas or
district heat; a hybrid's both)."""
return sum(x(c[t]) for c in (v.get("power"), v.get("gas"), v.get("district")) if c and c[t] is not None)
GRID_ZERO_W = 50.0 # the meter's import and export below this: the battery balances the house
KEEP_OWN = "release" # executor.RELEASE: the thermostat keeps its own setpoint (nothing written)
def fallback_entries(s, d) -> list[dict]:
"""A room not planned (inputs.room_refusal): its
thermostat's fallback schedule, no optimisation. Per step the target of
the owner's (or installer's) schedule and overrides in force
(preferences.room_series: a block's temperature, a must at least it;
outside the blocks the setback (heating) / setup (cooling); a boost;
away at the setback), rounded to the half degree and held inside the
room's bounds (the owner's and installer's limits, the device's range).
Without blocks (an override alone) the steps outside the override keep
the thermostat's own setpoint (KEEP_OWN). No schedule, or a switched
heater without a thermostat: none (the executor's safe value: the
device as it is)."""
pref = d.get("pref")
if not pref or "climate" not in (d.get("channels") or []):
return []
cooling = d["kind"] == "cooling"
lo, hi = d["bounds"]["temp_c"][0], d["bounds"]["temp_c"][1]
lo_h = math.ceil(lo * 2) / 2 if lo is not None else None
hi_h = math.floor(hi * 2) / 2 if hi is not None else None
groups = pref["groups"]
blocks = any(g["kind"] == "block" for g in groups)
out = []
for t in range(min(s["steps"], len(pref["target"]))):
g = pref["group"][t]
if g == -1 and not blocks:
e = {"set": KEEP_OWN, "why": "fallback: the thermostat's own setpoint (room not optimised, no schedule)"}
else:
want = float(pref["target"][t])
must = pref["must"][t]
if must is not None:
want = min(want, float(must)) if cooling else max(want, float(must))
v = _round(want, 0.5)
if lo_h is not None:
v = max(v, lo_h)
if hi_h is not None:
v = min(v, hi_h)
what = groups[g]["text"] if g >= 0 else ("setup" if cooling else "setback") + " outside your schedule"
e = {"set": v, "why": f"fallback schedule (room not optimised): {what}"}
if not out or _key(out[-1]) != _key(e):
out.append({"t": s["start"] + t * s["step_s"], **e})
return out
def fallback_feedback(s) -> list[dict]:
"""A not-planned room's preferences (fallback_entries): not optimised,
the thermostat set to them; met unknown (no plan of the room to tell)."""
out = []
for d in s.get("fallback") or []:
pref = d.get("pref")
if not pref or "climate" not in (d.get("channels") or []):
continue
for gi, g in enumerate(pref["groups"]):
out.append({"control": d["id"], "group": g["group"], "kind": g["kind"], "how": g["how"],
"label": g["text"], "met": None,
"detail": "room not optimised: set as the thermostat's schedule"
if gi in pref["group"] else "not in the next 48 h"})
return out
def _entry(d, kind, v, t, x, s, pi, grid_w=(1e9, 1e9)):
"""What a device is to do in step t, and why (a few words). grid_w:
the meter's planned import and export in t."""
occ = s["occupied"][t]
if v is None:
return None
if kind == "battery":
net = x(v["ch"][t]) - x(v["dis"][t])
if 0 < net <= v.get("p0", 0.0) / v["eff"] + 1.0:
# a charge no larger than the idle loss: the plan holds the battery (at its floor, its
# standby taken from the grid, as the inverter does itself): no grid charging for it
net = 0.0
net = _round(net, 50.0)
surplus = s["pv_w"][t] - s["load_w"][t]
grid = net > max(0.0, surplus) + 50
bld = s.get("building") or {}
bp, bound = bld.get("battery_plan"), bld.get("battery_bound")
target = bp["schedule_w"][t] if bp and t < len(bp["schedule_w"]) else None
if target is not None:
# the building's plan for its battery (Model.battery_plan): a setpoint, not the own mode
why = f"building {bp['building']}: its battery plan ({target:+.0f} W)"
if abs(net - target) > GRID_ZERO_W:
why += (", more from the PV surplus to your battery's reserve" if bound and net > target and net > 0
else ", within your battery's limits and reserve")
return {"set": net, "grid": grid, "why": why}
if bound:
# bound to a building without its plan for this step (A9.4): the inverter's own self-consumption
end = time.strftime("%d %b %H:%M UTC", time.gmtime(bound.get("until") or 0))
why = (f"building {bound['building']}: its battery plan ended {end}, not renewed" if bound.get("lapsed")
else f"building {bound['building']}: no battery plan after {end}")
return {"set": net, "grid": False, "auto": True, "why": why + ": self-consumption only, no grid charging"}
if not s.get("priced", True):
# no tariff: the battery in its own mode, unless the owner's
# reserve needs charging from the grid
if grid:
return {"set": net, "grid": True, "why": "charge to the reserve you set (no tariff)"}
return {"set": net, "grid": False, "auto": True, "why": "no tariff: the battery in its own mode"}
if net > 0:
why = _charge_why(pi, t) if grid else "PV surplus"
elif net < 0:
mean = sum(pi) / len(pi)
# "peak" only well above the horizon's average (Sim Munich: a plain
# 28 ct hour was called a peak)
why = (f"price peak ({pi[t]:.1f} ct)" if pi[t] >= 1.2 * mean else
f"above the average price ({pi[t]:.1f} ct, average {mean:.1f})")
else:
why = "hold"
if grid_w[0] < GRID_ZERO_W and grid_w[1] < GRID_ZERO_W and not grid:
# what the battery does is what its own self-consumption mode does:
# the inverter follows the house (no setpoint to chase the PV or
# the load every quarter hour)
return {"set": net, "grid": False, "auto": True,
"why": "self-consumption: the battery covers the house" if net <= 0 else
"self-consumption: PV surplus into the battery"}
return {"set": net, "grid": grid, "why": why}
if kind in ("heating", "cooling"):
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)
p = v["power"][t]
if p is None:
return {"set": "off", "why": "after departure"}
amps = round(x(p) / v["volts"])
ph = ((s.get("sources") or {}).get("ev_phases") or {}).get(d["id"])
ph = f"; {phase_words(ph)}" if ph else ""
if pi[t] is None:
if amps < 1:
return {"set": "off", "why": "not needed now (no tariff)" + ph}
return {"set": amps, "why": "charge for the departure (no tariff)" + ph}
if amps < 1:
return {"set": "off", "why": "wait for cheaper hours" + ph}
return {"set": amps, "why": f"cheapest hours before departure ({pi[t]:.1f} ct){ph}"}
if kind == "cover" and v.get("schedule"):
sch = v["schedule"]
if sch["set"][t] is None:
return {"set": None, "why": ""}
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]
if pos < 100 and sun > 0.05:
why = "shade: keep the sun's heat out"
elif sun > 0.05:
why = "open: daylight and the sun's heat"
elif pos < 100:
why = "closed: no sun"
else:
why = "open"
return {"set": pos, "why": why}
return None
TANK_HEAT_W = 50.0 # W of heat below which a tank's heater counts as off in a step (ENG: rounding)
def tank_heat(v, t, x) -> float:
"""A tank's planned heat in step t (W)."""
return sum(k * x(var) for k, var in v["heat"][t])
def tank_temp(v, t, x) -> float:
"""A tank's planned mean temperature at the end of step t (S.4 backwards)."""
return v["t_cw"] + x(v["e"][t]) / v["cw"]
def _tank_entry(d, v, t, x, s, pi):
"""What a tank's heater is to do in step t (docs/methods.md A13): a
water heater's target °C (heating: the planned temperature, rounded up
to the degree; else the comfort's least, which its thermostat keeps), a
relay's on/off, a stepless element's W, an SG-Ready state (3: store
above the comfort, 2: normal); and why."""
q = tank_heat(v, t, x)
temp = tank_temp(v, t, x)
on = q > TANK_HEAT_W
chans = set(d.get("channels") or [])
lo, hi = v["lo_c"], v["hi_c"]
leg = v["e_leg"] is not None and t in v["window"] and x(v["e"][t]) >= v["e_leg"] - 1.0
price = {"boiler": s.get("price_gas"), "district": s.get("price_heat")}.get(v["heater"]) or pi
pr = price[t] if t < len(price) else None
if not on:
why = "off: warm enough"
elif leg:
why = f"legionella run ({(v['e_leg'] / v['cw'] + v['t_cw']):.0f} °C)"
elif v["heater"] in ("element", "heat_pump") and s["pv_w"][t] - s["load_w"][t] > 0.5 * q / max(v["cops"][t], 1.0):
why = "store PV surplus as hot water"
elif temp > lo + 1.0 and pr is not None:
why = f"store heat while it is cheap ({pr:.1f} ct)"
else:
why = f"keep the tank at {lo:.0f} °C"
if "water_heater" in chans:
target = min(max(math.ceil(temp), math.ceil(lo)), math.floor(hi)) if on else math.ceil(lo)
return {"set": float(target), "why": why}
if "power" in chans and v["heater"] in ("element", "heat_pump"):
return {"set": _round(x(v["power"][t]), 50.0) if on else 0.0, "why": why}
if "switch" in chans:
return {"set": "on" if on else "off", "why": why}
if "sg_ready" in chans:
return {"set": "sg:3" if on and temp > lo + 1.0 else "sg:2", "why": why}
return None
def _carrier_price(s, carrier: str, t: int):
xs = s.get({"electricity": "price_import", "gas": "price_gas", "heat": "price_heat"}[carrier]) or []
return xs[t] if t < len(xs) else None
def _tank_input_w(v, t, heat_w: float) -> tuple[str, float]:
"""The carrier and its input (W) for a tank's heat (W): an element's
electricity, a heat pump's by its COP, a boiler's gas by its full-load
efficiency, district heat as it is."""
if v["heater"] in ("element", "heat_pump"):
return "electricity", heat_w / max(v["cops"][t], 1e-9)
if v["heater"] == "boiler":
return "gas", heat_w / (v["eff"] or 1.0)
return "heat", heat_w
def tank_baseline(m, v) -> float:
"""The tank without the plan (EUR): its own thermostat holding the
comfort's least from the same start, the same draw and the standing
loss, each W of heat at its carrier's mean price over the horizon
(tank_baseline_steps summed)."""
return sum(sum(eur) for eur in tank_baseline_steps(m, v).values())
def tank_thermostat_heat(m, v) -> list[float]:
"""The heat (W per step) the tank's own thermostat gives without the
plan: from the plan's own start E_0 (the heat in it now), the same
balance as Model.dhw_tank, E_t = phi E_(t-1) + dt (q_t - D_t - P0),
heating only when E would fall below the comfort's least E_min, at most
the heater's output (an element's or heat pump's W x COP, a boiler's or
heat station's max_heat_w). A tank above its least coasts down as the
plan's does: the heat already in it is not a saving of the plan (until
2026-11-09 the baseline held E_min from the first step, and a tank
started warm showed its stored heat as saved: 0.75 EUR per plan for
300 L at 55 °C over a 45 °C least, at one price)."""
return tank_thermostat(m, v)[0]
def tank_thermostat(m, v, emin: float | None = None) -> tuple[list[float], float]:
"""tank_thermostat_heat holding emin (Wh above the cold water; None:
the comfort's least E_min): (the heat per step, W; the stored heat at
the horizon's end, Wh). The store's lever (heatlevers.py) holds the
store's own setpoint with it."""
e, dt, out = v["e0"], m.dt, []
emin = v["emin"] if emin is None else emin
for t in range(m.T):
need = (emin - v["phi"] * e) / dt + v["draw"][t] + v["p0"]
if v["heater"] in ("element", "heat_pump"):
cap = v["pmax"] * v["cops"][t] if v["pmax"] else math.inf
else:
cap = v.get("qmax") or math.inf
q = min(max(0.0, need), cap)
e = v["phi"] * e + dt * (q - v["draw"][t] - v["p0"])
out.append(q)
return out, e
def tank_baseline_steps(m, v) -> dict:
"""tank_baseline per carrier and step: {carrier: [EUR per step]}, the
carriers with a price only (step_costs' base side, so the split's base
is baseline()): the thermostat's heat (tank_thermostat_heat) as its
heater's input at the carrier's mean price."""
s = m.s
out = {}
heat = tank_thermostat_heat(m, v)
for carrier in ("electricity", "gas", "heat"):
ps = [p for p in [_carrier_price(s, carrier, t) for t in range(m.T)] if p is not None]
if not ps:
continue
mean = sum(ps) / len(ps)
eur = [0.0] * m.T
for t in range(m.T):
c, w = _tank_input_w(v, t, heat[t])
if c == carrier:
eur[t] += m.eur_wh(t, mean) * w
out[carrier] = eur
return out
def storage_report(s, m, x) -> dict:
"""Per store what it loses while it holds energy (design note 10.5):
the battery's idle loss (its standby and the cells' self-discharge,
S.2) and the tank's standing loss (S.5), over the horizon and its first
24 h, each kWh at the step's price of what replaces it (the import
price; a tank's heat by its carrier); the facts with their source; a
tank's planned temperatures and heat per hour, its draw, the comfort it
missed and its legionella run."""
out = {}
src = s.get("sources") or {}
n24 = min(m.T, FLEX_STEPS)
for d in s["devices"]:
kind, v = m.devices.get(d["id"], (d["kind"], None))
if v is None or kind not in ("battery", "dhw_tank"):
continue
if kind == "battery":
loss = []
for t in range(m.T):
prev = x(v["soc"][t - 1]) if t else v["soc0"]
loss.append((1.0 - v["phi"]) * prev + m.dt * v["p0"]) # Wh in the step
fsrc = (src.get("battery") or {}).get(d["id"]) or {}
eur = sum(loss[t] / 1000.0 * (s["price_import"][t] or 0.0) / 100.0 for t in range(n24)) if m.priced else None
r = {"kind": "battery", "standby_w": round(v["p0"], 1), "standby_src": fsrc.get("standby_w", "none"),
"self_discharge_pct_month": round(v["lam_h"] * HOURS_PER_MONTH * 100.0, 3),
"self_discharge_src": fsrc.get("self_discharge_pct_month", "none"), "standby_in_load": v["in_load"],
"idle_loss_kwh": round(sum(loss) / 1000.0, 3), "idle_loss_kwh_24h": round(sum(loss[:n24]) / 1000.0, 3),
"idle_loss_eur_24h": None if eur is None else round(eur, 3),
"from_grid_kwh": round(sum(m.dt * x(g) for g in v["lg"]) / 1000.0, 3)}
fit = (src.get("battery_fit") or {}).get(d["id"])
if fit:
r["fit"] = fit
if r["from_grid_kwh"] > 0.001 and v["in_load"] is None:
m.note(f"{d['id']}: the battery's standby drawn from the grid at times; whether the house load holds "
"it is not said (mapping standby_in_load): not added to the load")
out[d["id"]] = r
continue
p, st = d["params"], d["state"]
loss, eur = [], 0.0
for t in range(m.T):
prev = x(v["e"][t - 1]) if t else v["e0"]
lw = v["ua"] * (v["t_cw"] + prev / v["cw"] - v["room"]) # W, UA (T - T_room)
loss.append(lw * m.dt)
if t < n24 and m.priced:
c, w = _tank_input_w(v, t, max(0.0, lw))
pr = _carrier_price(s, c, t)
eur += m.eur_wh(t, pr) * w if pr is not None else 0.0
heat = [tank_heat(v, t, x) for t in range(m.T)]
temps = [tank_temp(v, t, x) for t in range(m.T)]
hours = range(0, m.T, 4)
r = {"kind": "dhw_tank", "heater": v["heater"], "volume_l": float(p["volume_l"]), "ua_w_k": round(v["ua"], 3),
"standby_w": round(v["ua"] * ERP_TEST_DT_K, 1), "loss_src": ((src.get("dhw_tank") or {}).get(d["id"]) or {}).get(
"ua_w_k", "none"),
"temp_c": round(float(st["temp_c"]), 1), "stored_kwh": round(v["e0"] / 1000.0, 2),
"usable_kwh": round(max(0.0, v["e0"] - v["emin"]) / 1000.0, 2), "min_temp_c": round(v["lo_c"], 1),
"max_temp_c": round(v["hi_c"], 1), "grossanlage": bool(p.get("grossanlage")),
# its cold water and room (°C): the building plan composes a central boiler's store with them (C2.12)
"room_c": round(float(v["room"]), 1), "cold_water_c": round(float(v["t_cw"]), 1),
"idle_loss_kwh": round(sum(loss) / 1000.0, 3), "idle_loss_kwh_24h": round(sum(loss[:n24]) / 1000.0, 3),
"idle_loss_eur_24h": round(eur, 3) if m.priced else None,
"draw_kwh_24h": round(sum(v["draw"][:n24]) * m.dt / 1000.0, 3),
"heat_kwh_24h": round(sum(heat[:n24]) * m.dt / 1000.0, 3),
"short_kwh": round(sum(x(u) for u in v["unmet"]) * m.dt / 1000.0, 3),
"temp_plan_c": [round(temps[min(k + 3, m.T - 1)], 1) for k in hours],
"heat_w": [round(sum(heat[k:k + 4]) / len(heat[k:k + 4])) for k in hours],
"legionella": {"mode": str(p.get("legionella") or "device"), "last": (st.get("legionella") or {}).get("last"),
"due": (st.get("legionella") or {}).get("due"), "planned": None}}
if p.get("erp_class"):
r["erp_class"] = p["erp_class"]
if v["e_leg"] is not None:
hit = next((t for t in v["window"] if x(v["e"][t]) >= v["e_leg"] - 1.0), None)
r["legionella"]["planned"] = s["start"] + (hit + 1) * s["step_s"] if hit is not None else None
if r["short_kwh"] > 0.05:
m.note(f"{d['id']}: the tank cannot give {r['short_kwh']:.1f} kWh of the hot water forecast "
"(its heater's power or maximum temperature)")
out[d["id"]] = r
return out
def heat_outlook(s, m) -> dict | None:
"""The heat no model in the plan decides (docs/methods.md A2.16;
backlog 45.3, the box's part): the site's space heat where no room
model plans it (every heating control refused, or none) and its hot
water (an unshiftable demand today; a tank between it and its heater:
backlog 329), each a heat_demand delivered when demanded by the site's
source (state["heat_site"], inputs.heat_site: a boiler's gas by its
efficiency at the load, E6.4; district heat as it is), at the carrier's
price and CO2. A fixed term of the plan's cost (nothing in it is
decided). {source, from, carrier, eur, co2_kg, heat_kwh, input_kwh,
efficiency, part_load, lines: {space, dhw: HeatSupply.delivered}}; None
where none can be made (the reason noted, quietly: a control's refusal
says what to enter; no hot-water meter is nobody's fault)."""
site = s.get("heat_site") or {}
if site.get("note"):
m.note(site["note"])
return None
src = site.get("source")
if src not in ("boiler", "district"):
return None
if src == "boiler" and not site.get("boiler_efficiency"):
m.note("heat outlook: the boiler's efficiency unknown")
return None
sup = HeatSupply(m, site.get("from") or "heat", site, src)
if not any(p is not None for p in sup.prices[:m.T]):
m.note(f"heat outlook: no {sup.carrier} price")
return None
lines = {}
# hot water a planned tank stores and heats is the tank's (Model.dhw_tank): not here again
tanked = any(k == "dhw_tank" and v for k, v in m.devices.values())
for kind in (("space",) if site.get("space") else ()) + (() if tanked else ("dhw",)):
q = heat_demand(s, kind, m.T)
if q is None:
m.note("heat outlook: no heat forecast for this site" if kind == "space" else
"heat outlook: no hot-water forecast (no hot-water meter at this site yet): hot water not in it")
continue
lines[kind] = sup.delivered(q)
if not lines:
return None
co2 = [ln["co2_kg"] for ln in lines.values()]
out = {"source": src, "from": site.get("from", ""), "carrier": sup.carrier,
"eur": round(sum(ln["eur"] for ln in lines.values()), 2),
"co2_kg": None if None in co2 else round(sum(co2), 2),
"heat_kwh": round(sum(ln["heat_kwh"] for ln in lines.values()), 2),
"input_kwh": round(sum(ln["input_kwh"] for ln in lines.values()), 2), "lines": lines}
unpriced = sum(ln.get("unpriced_kwh", 0.0) for ln in lines.values())
if unpriced:
out["unpriced_kwh"] = round(unpriced, 2)
if src == "boiler":
out["efficiency"] = sup.eff
out["part_load"] = sup.curve["from"]
if is_combi(site) and "dhw" in lines:
# a combi (392): its hot water, as drawn or into its store (E6.6)
out["combi"] = True
return out
def co2_report(s, m, x, outlook) -> dict | None:
"""The plan's CO2 (kg) by carrier, and the baseline's (A2.15): the
meter's import at each step's factor (feed-in earns no credit), the
rooms' gas and district heat at theirs, the heat outlook's;
the baseline as baseline() (the house's net import without a battery,
the devices' electricity at the horizon's mean factor, the same gas and
heat). Steps or carriers without a factor are left out (incomplete:
true). None where the bundle has no CO2 factor at all."""
c = s.get("co2") or {}
if not c:
return None
T = m.T
kwh = m.dt / 1000.0
out, base, incomplete = {"electricity": 0.0}, {"electricity": 0.0}, False
fe = [m.co2_factor("electricity", t) for t in range(T)]
known = [f for f in fe if f is not None]
mean = sum(known) / len(known) if known else None
for t in range(T):
if fe[t] is None:
incomplete = True
continue
out["electricity"] += x(m.gin[t]) * kwh * fe[t] / 1000.0
net = s["load_w"][t] - s["pv_w"][t]
base["electricity"] += max(net, 0.0) * kwh * fe[t] / 1000.0
for kind, v in m.devices.values():
if not v or kind not in ("heating", "cooling", "ev", "dhw_tank"):
continue
if mean is not None:
base["electricity"] += sum(x(p) * kwh * mean / 1000.0 for p in v.get("power") or [] if p is not None
and hasattr(p, "index"))
for col, carrier in (("gas", v.get("fuel") or "gas"), ("district", "heat")):
e = sum(x(g) * kwh for g in v.get(col) or [] if g is not None)
if e <= 0:
continue
f = m.co2_factor(carrier, 0)
if f is None:
incomplete = True
continue
out[carrier] = out.get(carrier, 0.0) + e * f / 1000.0
base[carrier] = base.get(carrier, 0.0) + e * f / 1000.0
if outlook is not None:
if outlook.get("co2_kg") is None:
incomplete = True
else:
out[outlook["carrier"]] = out.get(outlook["carrier"], 0.0) + outlook["co2_kg"]
base[outlook["carrier"]] = base.get(outlook["carrier"], 0.0) + outlook["co2_kg"]
r = {"plan": round(sum(out.values()), 2), "baseline": round(sum(base.values()), 2),
"carriers": {k: round(v, 2) for k, v in out.items()}}
if incomplete:
r["incomplete"] = True
if m.co2w:
r["weight_eur_per_t"] = m.co2w
if c.get("electricity_source"):
r["electricity_source"] = c["electricity_source"]
return r
def baseline(s, m, x) -> float:
"""An estimate of the cost without the plan: the house's net load at its
prices, no battery, and the devices' energy (as the plan uses it) at the
mean import price, the EV's as soon as it is plugged in; None without
a tariff."""
if not m.priced:
return None
T, pi, pe = m.T, s["price_import"], s["price_export"]
cost = 0.0
for t in range(T):
net = s["load_w"][t] - s["pv_w"][t]
cost += m.eur_wh(t, pi[t]) * max(net, 0) - m.eur_wh(t, pe[t]) * max(-net, 0)
mean = sum(pi) / T
for kind, v in m.devices.values():
if not v:
continue
if kind == "battery":
# its idle loss is there with or without the plan: replaced at the mean import price (S.2)
cost += sum(m.eur_wh(t, mean) for t in range(T)) * v.get("p0", 0.0)
elif kind == "dhw_tank":
cost += tank_baseline(m, v)
if kind in ("heating", "cooling"):
# each input as the plan uses it at its mean price (electricity, gas, district heat)
cost += sum(m.eur_wh(t, mean) * x(v["power"][t]) for t in range(T) if v["power"][t] is not None)
for col, key in (("gas", "price_" + (v.get("fuel") or "gas")), ("district", "price_heat")):
ps = [p for p in (s.get(key) or [])[:T] if p is not None]
if ps and any(c is not None for c in v.get(col) or []):
mp = sum(ps) / len(ps)
cost += sum(m.eur_wh(t, mp) * x(c) for t, c in enumerate(v[col]) if c is not None)
elif kind == "ev":
wh = sum(m.dt * x(p) for p in v["power"] if p is not None)
# as soon as it can charge: from now, an expected session from its arrival
a = next((t for t, p in enumerate(v["power"]) if p is not None), 0)
asap = pi[a:a + max(1, math.ceil(wh / max(1.0, v["volts"] * 16) / m.dt))] or pi[:1]
cost += wh / 1000.0 * (sum(asap) / len(asap)) / 100.0
return cost
def step_costs(s, m, x) -> dict | None:
"""Per step and carrier what the plan costs and what the same step
would cost without it, at the same prices (EUR; costs.py books the step
of each quarter-hour as the household's saving by the plan, methods.md
A12):
electricity plan: the grid's import less its feed-in at the step's
prices, and the market's contracts in the step (a
tenant-power flat's energy bought from its building at the
offer's price of that slot, a sale at its price; as
energy_of, market_plan); without: the house's net load at
the grid's prices (no battery) and the planned devices'
electric energy of the step at the horizon's mean import
price (a car's at the mean of its as-soon-as-possible
steps, a tank's by its own thermostat), as baseline()
gas, heat the heating's gas or district heat of the step at its
price, against the same energy at the horizon's mean price
(a tank's: its own thermostat's, tank_baseline_steps)
Summed over the steps and carriers, plan is cost_eur and base
baseline_eur, each less the heat outlook (a fixed term in both): the
split's saving is the plan's own. A step's saving can be
negative (a battery charging now for later). None without a tariff."""
if not m.priced:
return None
T, pi, pe = m.T, s["price_import"], s["price_export"]
el_plan = [m.eur_wh(t, pi[t]) * x(m.gin[t]) - m.eur_wh(t, pe[t]) * x(m.gout[t]) for t in range(T)]
for c, vars_, paid_ in getattr(m, "contracts", []):
for t, e, pay, price in contract_energy(m, x, c, vars_, paid_):
el_plan[t] += contract_eur(c, e, pay, price)
tanks = {d: tank_baseline_steps(m, v) for d, (kind, v) in m.devices.items() if kind == "dhw_tank" and v}
el_base = []
for t in range(T):
net = s["load_w"][t] - s["pv_w"][t]
el_base.append(m.eur_wh(t, pi[t]) * max(net, 0) - m.eur_wh(t, pe[t]) * max(-net, 0))
mean = sum(pi) / T
out = {"electricity": {"plan": el_plan, "base": el_base}}
for carrier, col, key in (("gas", "gas", "price_gas"), ("oil", "gas", "price_oil"), ("heat", "district", "price_heat")):
prices = (s.get(key) or [])[:T]
ps = [p for p in prices if p is not None]
if not ps:
continue
mp = sum(ps) / len(ps)
plan_c, base_c, used = [0.0] * T, [0.0] * T, False
for d, (kind, v) in m.devices.items():
if kind not in ("heating", "dhw_tank") or not v:
continue
if col == "gas" and (v.get("fuel") or "gas") != carrier:
continue # a boiler's input at its own fuel's price only
for t, var in enumerate(v.get(col) or []):
if var is not None and t < len(prices) and prices[t] is not None:
used = True
plan_c[t] += m.eur_wh(t, prices[t]) * x(var)
if kind == "heating":
base_c[t] += m.eur_wh(t, mp) * x(var)
if kind == "dhw_tank" and carrier in tanks[d]:
# without the plan: the tank's own thermostat (baseline's tank_baseline)
used = used or any(tanks[d][carrier])
for t, eur in enumerate(tanks[d][carrier]):
base_c[t] += eur
if used:
out[carrier] = {"plan": plan_c, "base": base_c}
for d, (kind, v) in m.devices.items():
if not v:
continue
if kind == "battery" and v.get("p0"):
for t in range(T):
el_base[t] += m.eur_wh(t, mean) * v["p0"]
if kind in ("heating", "cooling"):
for t in range(T):
if v["power"][t] is not None:
el_base[t] += m.eur_wh(t, mean) * x(v["power"][t])
elif kind == "dhw_tank":
for t, eur in enumerate(tanks[d].get("electricity") or []):
el_base[t] += eur
elif kind == "ev":
wh = sum(m.dt * x(p) for p in v["power"] if p is not None)
# as soon as it can charge: from now, an expected session from its arrival
a = next((t for t, p in enumerate(v["power"]) if p is not None), 0)
asap = pi[a:a + max(1, math.ceil(wh / max(1.0, v["volts"] * 16) / m.dt))] or pi[:1]
amean = sum(asap) / len(asap)
for t, p in enumerate(v["power"]):
if p is not None:
el_base[t] += m.eur_wh(t, amean) * x(p)
return {c: {k: [round(y, 5) for y in ys] for k, ys in d.items()} for c, d in out.items()}
def main():
s = json.load(sys.stdin)
limit = float(sys.argv[1]) if len(sys.argv) > 1 else 30.0
try:
out = plan(s, limit)
except Exception as e: # the caller keeps its last plan
json.dump({"v": 1, "error": str(e)}, sys.stdout)
sys.exit(1)
json.dump(out, sys.stdout)
if __name__ == "__main__":
main()