cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1030: full source
This commit is contained in:
1 parent
e2c7085d2c
commit
cddd34dcbc
30 files changed
+2141
-51
No files matched your search
@@ -34,7 +34,11 @@ 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)
|
||||
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")
|
||||
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
|
||||
@@ -92,6 +96,12 @@ 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).
|
||||
|
||||
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
|
||||
@@ -139,7 +149,11 @@ NO_PRICE_EUR_KWH = 1e-4 # EUR per kWh through the meter and per kWh a device u
|
||||
# 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)
|
||||
GRID_MAX_W = 43470.0 # W: the site's connection when the state does not say (state["grid_max_w"],
|
||||
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
|
||||
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
|
||||
|
||||
@@ -304,6 +318,27 @@ class Model:
|
||||
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."""
|
||||
bp = (self.s.get("building") or {}).get("battery_plan")
|
||||
bats = [v for kind, v in self.devices.values() if kind == "battery" and v]
|
||||
if not bp or not bats:
|
||||
return
|
||||
ws = bp["schedule_w"]
|
||||
for t in range(max(0, bp["from_step"]), min(self.T, bp["to_step"], len(ws))):
|
||||
if ws[t] is None:
|
||||
continue
|
||||
pos = self.var(cost=bp["penalty"] * self.dt / 1000.0)
|
||||
neg = self.var(cost=bp["penalty"] * self.dt / 1000.0)
|
||||
net = sum((v["ch"][t] - v["dis"][t] for v in bats), start=Lin())
|
||||
self.h.addConstr(net - pos + neg == float(ws[t]))
|
||||
|
||||
def grid_order(self):
|
||||
"""The grid operator's limit on the controllable consumers' draw."""
|
||||
o = self.s.get("grid_order") or {}
|
||||
@@ -321,6 +356,40 @@ class Model:
|
||||
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 battery(self, d):
|
||||
p, st, b = d["params"], d["state"], d["bounds"]
|
||||
cap = max(1.0, float(p["capacity_wh"]))
|
||||
@@ -330,7 +399,6 @@ class Model:
|
||||
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
|
||||
mean_price = sum(self.s["price_import"]) / self.T if self.priced else None
|
||||
soc, prev, ch, dis = [], soc0, [], []
|
||||
pref = d.get("pref") # the owner's reserve per step (preferences.py)
|
||||
floors = []
|
||||
@@ -355,11 +423,12 @@ class Model:
|
||||
ch.append(c)
|
||||
dis.append(x)
|
||||
prev = e
|
||||
# energy left at the end is worth the mean price: no draining at the
|
||||
# horizon (without a tariff nothing is drained for a price anyway)
|
||||
if mean_price is not None:
|
||||
short = self.var(cost=mean_price / 100.0 / 1000.0)
|
||||
self.h.addConstr(prev + short >= min(soc0, hi_pct / 100.0 * cap))
|
||||
# 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": lo_pct / 100.0 * cap, "floors": floors,
|
||||
@@ -611,6 +680,7 @@ class Model:
|
||||
elif k == "ev":
|
||||
self.ev(d)
|
||||
self.building()
|
||||
self.battery_plan()
|
||||
self.grid_order()
|
||||
self.balance()
|
||||
obj = sum((c * v for c, v in self.cost), start=Lin())
|
||||
@@ -732,6 +802,17 @@ def plan(s: dict, time_limit: float = 30.0) -> dict:
|
||||
"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)}
|
||||
if getattr(m, "end_note", ""):
|
||||
out["notes"] = [m.end_note] # what the plan assumed for want of a fact (also published)
|
||||
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)
|
||||
if heat_cost["gas_eur"] or heat_cost["heat_eur"]:
|
||||
out["gas_eur"], out["heat_eur"] = round(heat_cost["gas_eur"], 2), round(heat_cost["heat_eur"], 2)
|
||||
# rooms not planned (inputs.room_refusal): the thermostat's
|
||||
@@ -1039,7 +1120,8 @@ def shift_envelope(m, x) -> dict | None:
|
||||
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), ch_w, dis_w (its power), eta (one way), end_wh (the planned
|
||||
(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 /
|
||||
@@ -1071,7 +1153,8 @@ def shift_envelope(m, x) -> dict | None:
|
||||
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"]), "ch_w": round(v["max_ch"]), "dis_w": round(v["max_dis"]),
|
||||
"max_wh": round(v["hi_wh"]), "cap_wh": round(v["cap"]),
|
||||
"ch_w": round(v["max_ch"]), "dis_w": round(v["max_dis"]),
|
||||
"eta": round(v["eff"], 4), "end_wh": round(_x(x, v["soc"][n - 1]))})
|
||||
elif kind == "ev":
|
||||
if not v.get("known") or v["pmax"] <= 0:
|
||||
@@ -1239,6 +1322,14 @@ def _entry(d, kind, v, t, x, s, pi, grid_w=(1e9, 1e9)):
|
||||
net = _round(net, 50.0)
|
||||
surplus = s["pv_w"][t] - s["load_w"][t]
|
||||
grid = net > max(0.0, surplus) + 50
|
||||
bp = (s.get("building") or {}).get("battery_plan")
|
||||
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 += ", within your battery's limits and reserve"
|
||||
return {"set": net, "grid": grid, "why": why}
|
||||
if not s.get("priced", True):
|
||||
# no tariff: the battery in its own mode, unless the owner's
|
||||
# reserve needs charging from the grid
|
||||
@@ -1337,7 +1428,11 @@ def _entry(d, kind, v, t, x, s, pi, grid_w=(1e9, 1e9)):
|
||||
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 ""}
|
||||
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":
|
||||
pos = _round(100 * x(v["pos"][t]), 10.0)
|
||||
sun = s["sun"][t]
|
||||
@@ -1384,6 +1479,64 @@ def baseline(s, m, x) -> float:
|
||||
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 meter's import less its feed-in at the step's
|
||||
prices; without: the house's net load at those 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), 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 step's saving can be negative (a battery charging now for later). The
|
||||
market's contracts are not in it. 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)]
|
||||
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"), ("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 kind, v in m.devices.values():
|
||||
if kind != "heating" or not v:
|
||||
continue
|
||||
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)
|
||||
base_c[t] += m.eur_wh(t, mp) * x(var)
|
||||
if used:
|
||||
out[carrier] = {"plan": plan_c, "base": base_c}
|
||||
for kind, v in m.devices.values():
|
||||
if not v:
|
||||
continue
|
||||
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 == "ev":
|
||||
wh = sum(m.dt * x(p) for p in v["power"] if p is not None)
|
||||
asap = pi[:max(1, math.ceil(wh / max(1.0, v["volts"] * 16) / m.dt))]
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user