cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.629: full source
This commit is contained in:
1 parent
d5fbcacaa4
commit
85edd56ec8
46 files changed
+3518
-267
No files matched your search
@@ -14,9 +14,12 @@ 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)
|
||||
heating a room's first-order thermal model (R in K/kW, C in kWh/K, the
|
||||
cooling outside temperature, heat from the device and from the sun
|
||||
through the room's covers); comfort target when occupied,
|
||||
setback/setup otherwise; a switched boiler is on/off (binary)
|
||||
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)
|
||||
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);
|
||||
@@ -31,6 +34,16 @@ 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
|
||||
@@ -46,6 +59,9 @@ from zoneinfo import ZoneInfo
|
||||
import highspy
|
||||
from highspy.highs import highs_linear_expression as Lin
|
||||
|
||||
from .controls import ev_volts
|
||||
from .evphases import words as phase_words
|
||||
|
||||
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
|
||||
@@ -56,6 +72,10 @@ CHANGE_EUR_KW = 0.002 # EUR per kW a device's power changes from one step to
|
||||
# plans (equal prices would otherwise give any order, and a charger or
|
||||
# boiler must not be switched back and forth)
|
||||
CLOSED_EUR = 0.00002 # EUR per step for a closed cover: open when nothing is at stake
|
||||
MARKET_MAX_W = 100000.0 # W: a contract without a maximum, and the meter's import/export switch
|
||||
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
|
||||
|
||||
|
||||
class Model:
|
||||
@@ -89,31 +109,112 @@ class Model:
|
||||
|
||||
# -- 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
|
||||
self.gin, self.gout = [], []
|
||||
cap = float(s.get("grid_max_w") or GRID_MAX_W)
|
||||
self.gin, self.gout, self.gcap = [], [], []
|
||||
for t in range(self.T):
|
||||
gi = self.var(cost=self.eur_wh(t, s["price_import"][t]))
|
||||
go = self.var(cost=-self.eur_wh(t, s["price_export"][t]))
|
||||
net = s["load_w"][t] - s["pv_w"][t]
|
||||
hi_in, hi_out = max(cap, net), max(cap, -net)
|
||||
gi = self.var(0.0, hi_in, cost=self.eur_wh(t, s["price_import"][t]))
|
||||
go = self.var(0.0, hi_out, cost=-self.eur_wh(t, s["price_export"][t]))
|
||||
spill = self.var(0.0, max(0.0, s["pv_w"][t]))
|
||||
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
|
||||
for t in range(self.T):
|
||||
if t in skip or s["price_export"][t] < 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 grid import)."""
|
||||
"""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.gin[t] - over <= lim["value"])
|
||||
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.gin[t] for t in range(a, b)), start=Lin())
|
||||
imp = sum((self.dt * self.meter_in(t) for t in range(a, b)), start=Lin())
|
||||
self.h.addConstr(imp - miss <= target)
|
||||
|
||||
def grid_order(self):
|
||||
@@ -124,7 +225,7 @@ class Model:
|
||||
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.gin[t] - over <= base + o["limit_w"])
|
||||
self.h.addConstr(self.meter_in(t) - over <= base + o["limit_w"])
|
||||
|
||||
def balance(self):
|
||||
s = self.s
|
||||
@@ -180,6 +281,9 @@ class Model:
|
||||
switched = not cooling and "switch" in d["channels"] and "climate" not in d["channels"]
|
||||
temps, powers, prev = [], [], t0
|
||||
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
|
||||
for t in range(self.T):
|
||||
if switched:
|
||||
u = self.var(0.0, 1.0, integer=True)
|
||||
@@ -190,10 +294,13 @@ class Model:
|
||||
self.flows[t].append((-1, pw))
|
||||
tt = self.var(-50.0, 80.0)
|
||||
sign = -1.0 if cooling else 1.0
|
||||
gain = sum((g * gx for g, gx in gains(t)), start=Lin())
|
||||
# T[t+1] = T[t] (1 - a) + a T_out + dt/C (± cop P/1000 + sun gain/1000)
|
||||
covers = gains(t)
|
||||
gain = sum((g * gx for g, gx in covers), start=Lin())
|
||||
# the fit's (B6): its internal gain, and its sun where no cover carries it
|
||||
fixed = internal[t] + (solar * ghi[t] if not covers and t < len(ghi) else 0.0)
|
||||
# T[t+1] = T[t] (1 - a) + a T_out + dt/C (± cop P/1000 + sun gain/1000 + fixed gains/1000)
|
||||
self.h.addConstr(tt - (1 - a) * prev - sign * self.dt / c * cop / 1000.0 * pw
|
||||
- self.dt / c / 1000.0 * gain == a * self.s["t_out"][t])
|
||||
- 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]
|
||||
target = min(max(comfort if occ else other, lo), hi)
|
||||
miss = self.var(cost=COMFORT_EUR_KH * self.dt)
|
||||
@@ -219,12 +326,21 @@ class Model:
|
||||
self.devices[d["id"]] = ("cooling" if cooling else "heating",
|
||||
{"temp": temps, "power": powers, "pmax": pmax, "switched": switched})
|
||||
|
||||
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"]
|
||||
if not st.get("connected"):
|
||||
self.devices[d["id"]] = ("ev", None)
|
||||
return
|
||||
volts = float(p["voltage"]) * float(p["phases"])
|
||||
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])
|
||||
dep = departure_step(self.s, str(st.get("departure") or p["departure"]))
|
||||
@@ -279,6 +395,7 @@ class Model:
|
||||
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:
|
||||
@@ -349,10 +466,59 @@ def plan(s: dict, time_limit: float = 30.0) -> dict:
|
||||
devices[d["id"]] = entries
|
||||
energy = sum(m.eur_wh(t, pi[t]) * x(m.gin[t]) - m.eur_wh(t, s["price_export"][t]) * x(m.gout[t])
|
||||
for t in range(T))
|
||||
return {"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),
|
||||
"cost_eur": round(energy, 2), "baseline_eur": round(baseline(s, m, x), 2),
|
||||
"price_note": s.get("price_note", ""), "sources": s.get("sources", {})}
|
||||
market = market_plan(s, m, x)
|
||||
energy += sum(c["cost_eur"] for c in market)
|
||||
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),
|
||||
"cost_eur": round(energy, 2), "baseline_eur": round(baseline(s, m, x), 2),
|
||||
"price_note": s.get("price_note", ""), "sources": s.get("sources", {})}
|
||||
if market:
|
||||
out["market"] = market
|
||||
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 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, v in sorted(vars_.items()):
|
||||
e = max(x(v), 0.0) * m.dt / 1000.0
|
||||
pay = max(x(paid_[t]) * m.dt / 1000.0, e) if t in paid_ else e
|
||||
if pay < 1e-6:
|
||||
continue
|
||||
price = (term_at(c, t) or c)["price_ct"]
|
||||
steps.append({"t": s["start"] + t * s["step_s"], "kwh": round(e, 4), "paid_kwh": round(pay, 4)})
|
||||
kwh += e
|
||||
paid_kwh += pay
|
||||
if c["direction"] == "buys":
|
||||
cost += pay * price / 100.0
|
||||
vs += (e * pi[t] - pay * price) / 100.0
|
||||
else:
|
||||
cost -= e * price / 100.0
|
||||
vs += e * (price - pe[t]) / 100.0
|
||||
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
|
||||
@@ -432,9 +598,11 @@ def _entry(d, kind, v, t, x, s, pi):
|
||||
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 amps < 1:
|
||||
return {"set": "off", "why": "wait for cheaper hours"}
|
||||
return {"set": amps, "why": f"cheapest hours before departure ({pi[t]:.1f} ct)"}
|
||||
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"]
|
||||
return {"set": sch["set"][t], "why": sch["why"][t] if sch["set"][t] is not None else ""}
|
||||
|
||||
Reference in new issue
Block a user