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

150 lines
8.6 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's saving split by carrier and lever (docs/methods.md A12, E14):
for the console's Savings page, which shows per carrier what the household
paid with Cantabile and would have paid without, and the levers load
shifting / off-peak buying and heating apart.
From the plan's own per-step costs (optimizer.step_costs: per carrier what
each step costs with the plan and without it, at the same prices), summed
over the horizon, and the heating's share of the electricity saving: the
heating and cooling devices' electric draw at the horizon's mean import
price (as the baseline counts it) against the step's own price, i.e. the
saving from moving the heat pump's or heater's electricity in time. The rest
of the electricity saving is load shifting and off-peak buying (battery,
car, appliances). Gas and district heat are the heating's alone.
{"electricity": {"plan_eur", "base_eur", "heating_eur"},
"gas": {"plan_eur", "base_eur"[, "why", "note"]}, "heat": {...}, "oil": {...}}
Gas, heating oil and district heat whose saving rounds to 0.00 EUR carry
why (a code) and note (in words) instead of a bare 0 (2026-11-09, the
owner: "we still have no saving from gas/oil?"; methods E14):
not_used the carrier is priced, the plan makes no heat with it (a
hybrid's heat pump made all of it)
flat_price one price at every step of the horizon: the plan's heat costs
the same whenever it is made, there is nothing to move in time
(the baseline counts the plan's own heat at the mean price,
A12.2; a lower room temperature is not counted as a saving,
E14; a hybrid's choice of source is not counted either)
not_shifted the price varies, but the heat lies where it is needed
not_planned the heating or tank on it was refused (its refusal's why: e.g.
no gas price); 0 in plan and base, nothing of it is planned
Electricity whose saving rounds to 0.00 EUR carries why and note too (audit
2026-11-09: 28 homes showed electricity 0 without a reason):
no_lever the plan moves no electricity: no battery, no car plugged in
or expected, no electric heating (heat pump, heater) and no
electric hot water; the household's own use is a fixed term
(a district-heat or gas flat, a car away)
flat_price it has a lever, but one import price at every step and no
battery: the lever's draw costs the same whenever it runs
not_shifted the price varies (or a battery could store), but the plan
found nothing cheaper than the baseline: the draw already lies
in the cheapest hours, or nothing is due in the horizon
The levers found are in the note.
base_eur − plan_eur summed over the carriers is the plan's own saving,
baseline_eur − cost_eur: the plan's electricity carries the market's
contracts (a tenant-power flat's energy bought from its building at the
offer's price per slot, GGV §42b / Mieterstrom §42a / §42c; before, only the
grid meter was priced and such a flat showed electricity 0.00 against a
baseline of its whole load). None without a tariff (no step
costs)."""
def saving_parts(s: dict, m, x, steps: dict | None) -> dict | None:
if steps is None:
return None
out = {}
for carrier, d in steps.items():
out[carrier] = {"plan_eur": round(sum(d["plan"]), 4), "base_eur": round(sum(d["base"]), 4)}
if "electricity" in out:
pi = s["price_import"]
mean = sum(pi) / m.T
heating = 0.0
for kind, v in m.devices.values():
if not v or kind not in ("heating", "cooling"):
continue
for t, p in enumerate(v["power"]):
if p is not None:
heating += m.eur_wh(t, mean - pi[t]) * x(p)
out["electricity"]["heating_eur"] = round(heating, 4)
if "electricity" in out:
why = electricity_zero_why(s, m, out["electricity"])
if why is not None:
out["electricity"].update(why)
for carrier in HEAT_CARRIERS:
why = zero_why(s, m, carrier, out.get(carrier))
if why is not None:
out.setdefault(carrier, {"plan_eur": 0.0, "base_eur": 0.0}).update(why)
return out
HEAT_CARRIERS = {"gas": ("price_gas", "gas"), "oil": ("price_oil", "heating oil"), "heat": ("price_heat", "district heat")}
ZERO_EUR = 0.005 # a saving that rounds to 0.00 EUR
def zero_why(s: dict, m, carrier: str, part: dict | None) -> dict | None:
"""Why a heat carrier's saving is 0 in this plan ({why, note}; module
docstring), None where it has a saving or is not there at all."""
key, words = HEAT_CARRIERS[carrier]
if part is None:
# not in the plan: a heating control or tank on it refused for want of its price
for r in (s.get("refused") or {}).values():
if f"{carrier}_price" in (r.get("missing") or []):
return {"why": "not_planned", "note": f"its heating is not planned: {r.get('why') or 'refused'}"}
return None
if abs(part["base_eur"] - part["plan_eur"]) >= ZERO_EUR:
return None
hybrid = any(kind == "heating" and v and v.get("src") == "hybrid" and (v.get("fuel") or "gas") == carrier
for kind, v in m.devices.values())
col = "district" if carrier == "heat" else "gas"
rooms = any(kind == "heating" and v and any(c is not None for c in v.get(col) or [])
and (carrier == "heat" or (v.get("fuel") or "gas") == carrier) for kind, v in m.devices.values())
tail = "; a hybrid's choice between heat pump and boiler is not counted as a saving" if hybrid else ""
if abs(part["plan_eur"]) < ZERO_EUR and abs(part["base_eur"]) < ZERO_EUR:
return {"why": "not_used", "note": (f"the heat pump made all the heat in this plan: no {words} used" if hybrid
else f"no {words} used in this plan") + tail}
ps = [p for p in (s.get(key) or [])[:m.T] if p is not None]
if ps and max(ps) - min(ps) < 1e-9:
return {"why": "flat_price", "note": f"one {words} price ({ps[0]:.2f} ct/kWh) at every hour of the plan: its heat "
"costs the same whenever it is made, nothing to move in time"
+ ("; a lower room temperature is not counted as a saving" if rooms else "")
+ tail}
return {"why": "not_shifted", "note": f"the {words} price varies, but the heat was needed when it was made" + tail}
def electric_levers(m) -> list[str]:
"""What in this plan can move electricity in time (its words)."""
out = []
for kind, v in m.devices.values():
if not v:
continue # e.g. a car not plugged in and none expected
if kind == "battery" and float(v.get("cap") or 0) > 0:
out.append("battery")
elif kind == "ev":
out.append("car")
elif kind in ("heating", "cooling") and v.get("src") in ("electric", "heat_pump", "hybrid"):
out.append({"heat_pump": "heat pump", "hybrid": "hybrid's heat pump"}.get(v["src"], "electric heating")
if kind == "heating" else "cooling")
elif kind == "dhw_tank" and v.get("src") == "electric":
out.append("electric hot water")
return sorted(set(out))
def electricity_zero_why(s: dict, m, part: dict) -> dict | None:
"""Why the electricity saving is 0 in this plan ({why, note}; module docstring), None where it has one."""
if abs(part["base_eur"] - part["plan_eur"]) >= ZERO_EUR:
return None
levers = electric_levers(m)
if not levers:
return {"why": "no_lever", "note": "nothing in this plan moves electricity in time (no battery, no car plugged in "
"or expected, no heat pump or electric heating, no electric hot water): "
"the household's own use is the same with and without the plan"}
ps = [p for p in (s.get("price_import") or [])[:m.T] if p is not None]
if ps and max(ps) - min(ps) < 1e-9 and "battery" not in levers:
return {"why": "flat_price", "note": f"one electricity price ({ps[0]:.2f} ct/kWh) at every hour of the plan: "
f"the {', '.join(levers)} costs the same whenever it runs"}
return {"why": "not_shifted", "note": f"the {', '.join(levers)} found nothing cheaper in this plan: its draw "
"already lies in the cheapest hours, or nothing is due in the horizon"}