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
@@ -2,7 +2,9 @@
|
||||
"""Inputs for the optimiser: the latest states of the controls' and the
|
||||
inputs' entities (presence, temperatures, humidity, outside temperature,
|
||||
sun, weather), a short local history of load and PV (the fallback when no
|
||||
model bundle says), and the 15-minute model state for the horizon.
|
||||
model bundle says), and the 15-minute model state for the horizon. A
|
||||
room's R and C: the mapping's, else the model bundle's (its rooms), else
|
||||
the defaults; sources.rooms says which per control.
|
||||
|
||||
None of this leaves the site; only the plan does (controller.py).
|
||||
|
||||
@@ -138,10 +140,36 @@ def _hourly(forecast: list[dict], key: str, start: int, steps: int) -> list[floa
|
||||
return out
|
||||
|
||||
|
||||
def _series(name, start, bundles, history, tz, now_value, default):
|
||||
s = bundles.forecast(name, start, STEP_S, STEPS, tz) if bundles else None
|
||||
if s is not None:
|
||||
return s, "model"
|
||||
def watts(col: Collector, eid: str) -> float | None:
|
||||
"""A power sensor's value in W (HA's kW converted)."""
|
||||
v = col.value(eid)
|
||||
if v is not None and col.attr(eid, "unit_of_measurement") == "kW":
|
||||
v *= 1000.0
|
||||
return v
|
||||
|
||||
|
||||
def base_load(col: Collector, inputs) -> float | None:
|
||||
"""The house's load without the devices the plan plans itself (Finding
|
||||
A2-a): load_power less the planned devices' own meters
|
||||
(inputs.controlled_power: heat pump, A/C, charger), never below 0. A
|
||||
device meter without a value counts 0 (a charger's sensor goes
|
||||
unavailable while idle). None while the load has none."""
|
||||
eids = [inputs.load_power] if isinstance(inputs.load_power, str) else list(inputs.load_power or [])
|
||||
vals = [watts(col, e) for e in eids if e]
|
||||
if not vals or None in vals:
|
||||
return None
|
||||
ctl = sum(watts(col, e) or 0.0 for e in getattr(inputs, "controlled_power", None) or [])
|
||||
return max(0.0, sum(vals) - ctl)
|
||||
|
||||
|
||||
def _series(name, start, bundles, history, tz, now_value, default, model_names=None):
|
||||
"""A series for the horizon: the model bundle's (the first of
|
||||
model_names it has, default name), else the same quarter hour 1 or 2
|
||||
days back, else the value now, else the default."""
|
||||
for m in (model_names if model_names is not None else (name,)):
|
||||
s = bundles.forecast(m, start, STEP_S, STEPS, tz) if bundles else None
|
||||
if s is not None:
|
||||
return s, "model" if m == name else f"model ({m})"
|
||||
out, have = [], 0
|
||||
for k in range(STEPS):
|
||||
t = start + k * STEP_S
|
||||
@@ -228,15 +256,28 @@ def cover_position(col: Collector, ent: str) -> float | None:
|
||||
def model_state(now: float, controls, inputs, col: Collector, bundles, history, tz: str,
|
||||
weather_forecast: list[dict] | None, extra_limits: dict | None = None,
|
||||
occupied_hours=(6, 22), building: dict | None = None, location: dict | None = None,
|
||||
shade_ctx: dict | None = None, grid_order: dict | None = None) -> dict:
|
||||
shade_ctx: dict | None = None, grid_order: dict | None = None,
|
||||
grid_max_w: float | None = None, ev_phases: dict | None = None) -> dict:
|
||||
"""The 48 h, 15-minute input for the optimiser (JSON: it runs in a
|
||||
subprocess). location: the site's latitude and longitude (HA's
|
||||
configuration); shade_ctx: per cover control its room (temp_c,
|
||||
setpoint_c, season: shades.py)."""
|
||||
setpoint_c, season: shades.py); grid_max_w: the site's connection (W,
|
||||
config; the optimiser's default without it); ev_phases: per EV control
|
||||
its phase count and source (evphases.EvPhases.all), else the mapping's."""
|
||||
start = int(now // STEP_S * STEP_S)
|
||||
zone = ZoneInfo(tz or "UTC")
|
||||
prices = bundles.prices(start, STEP_S, STEPS, now)
|
||||
load, load_src = _series("load_w", start, bundles, history, tz, col.total(inputs.load_power), 500.0)
|
||||
# the base load: the house without the planned devices (Finding A2-a), so
|
||||
# the plan, the building's shift and the grid order's base (optimizer)
|
||||
# do not count them twice. The model's base_load_w is that; its load_w
|
||||
# (load.power as metered) is too only where no planned device has a meter
|
||||
# inside it, else the history of the base load stands in.
|
||||
ctl = getattr(inputs, "controlled_power", None) or []
|
||||
load, load_src = _series("load_w", start, bundles, history, tz, base_load(col, inputs), 500.0,
|
||||
("base_load_w",) if ctl else ("base_load_w", "load_w"))
|
||||
if ctl and not load_src.startswith("model") and bundles and \
|
||||
bundles.forecast("load_w", start, STEP_S, 1, tz) is not None:
|
||||
load_src += " (the model's load_w includes the planned devices: not used)"
|
||||
pv, pv_src = _series("pv_w", start, bundles, history, tz, None, 0.0)
|
||||
t_out = _hourly(weather_forecast or [], "temperature", start, STEPS)
|
||||
t_src = "weather forecast"
|
||||
@@ -270,7 +311,8 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
continue
|
||||
h = datetime.fromtimestamp(start + k * STEP_S, timezone.utc).astimezone(zone).hour
|
||||
occupied.append(1 if occupied_hours[0] <= h < occupied_hours[1] else 0)
|
||||
devices = []
|
||||
devices, rooms_src, phases_src = [], {}, {}
|
||||
one_room = sum(c.kind in ("heating", "cooling") for c in controls) == 1
|
||||
for c in controls:
|
||||
if hasattr(c, "learn_range"):
|
||||
c.learn_range(col) # a climate's own min_temp..max_temp
|
||||
@@ -278,18 +320,34 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
for q in _quantities(c):
|
||||
b = c.bounds(q, (extra_limits or {}).get(c.id))
|
||||
bounds[q] = [b.lo, b.hi, b.lo_by, b.hi_by]
|
||||
devices.append({"id": c.id, "kind": c.kind, "params": {k: c.p(k) for k in _param_names(c)},
|
||||
params = {k: c.p(k) for k in _param_names(c)}
|
||||
if c.kind == "ev":
|
||||
# the count from the best evidence (evphases.py); None: the plan assumes 1
|
||||
info = (ev_phases or {}).get(c.id) or \
|
||||
({"phases": float(c.params["phases"]), "source": "mapping"} if c.params.get("phases") else
|
||||
{"phases": None, "source": "assumed"})
|
||||
params["phases"] = info["phases"]
|
||||
phases_src[c.id] = {"phases": info["phases"], "source": info["source"]}
|
||||
if c.kind in ("heating", "cooling"):
|
||||
rooms_src[c.id] = _room_rc(c, params, bundles, one_room, now)
|
||||
devices.append({"id": c.id, "kind": c.kind, "params": params,
|
||||
"state": device_state(c, col, now), "bounds": bounds,
|
||||
"channels": sorted(c.writable())})
|
||||
clouds = _hourly(weather_forecast or [], "cloud_coverage", start, STEPS)
|
||||
sky = [max(0.0, min(1.0, 1 - c / 100.0)) for c in clouds] if clouds else [1.0] * STEPS
|
||||
ghi, ghi_src = irradiance(start, location, sky, sun if peak > 100 else None)
|
||||
out = {"v": 1, "start": start, "step_s": STEP_S, "steps": STEPS, "tz": tz,
|
||||
"price_import": prices.import_ct, "price_export": prices.export_ct, "price_note": prices.note,
|
||||
"load_w": load, "pv_w": pv, "t_out": t_out, "sun": sun, "occupied": occupied, "sky": sky,
|
||||
"location": location or {},
|
||||
"ghi_w_m2": ghi, "location": location or {},
|
||||
"sources": {"load": load_src, "pv": pv_src, "t_out": t_src, "model": bundles.model_id(),
|
||||
"sky": "weather forecast" if clouds else "clear"},
|
||||
"devices": devices, "building": building or {}, "grid_order": grid_order or {}}
|
||||
"sky": "weather forecast" if clouds else "clear", "rooms": rooms_src, "ghi": ghi_src,
|
||||
"ev_phases": phases_src},
|
||||
"devices": devices, "building": building or {}, "grid_order": grid_order or {},
|
||||
# the market's contracts in force as sources and sinks (shadow, the market's step 2)
|
||||
"market": bundles.market_for_model(start, STEP_S, STEPS, now) if hasattr(bundles, "market_for_model") else []}
|
||||
if grid_max_w:
|
||||
out["grid_max_w"] = float(grid_max_w)
|
||||
# a shade's moves by rules on the sun and its room (shades.py); the
|
||||
# optimiser takes them as they are
|
||||
from . import shades
|
||||
@@ -299,6 +357,58 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
return out
|
||||
|
||||
|
||||
def irradiance(start: int, location: dict | None, sky: list[float],
|
||||
pv_sun: list[float] | None) -> tuple[list[float], str]:
|
||||
"""Global irradiance per step (W/m²) for a room's fitted sun
|
||||
(solar_m2): Haurwitz's clear sky, 1098 cos z exp(-0.057 / cos z), at
|
||||
the step's middle where the site's location is known, times the sky
|
||||
(1 - the forecast's cloud cover); else the PV forecast scaled to its
|
||||
peak (pv_sun, A1.2) times 1000 W/m², a rough stand-in; else none (the
|
||||
sun's elevation now, held, would shine all night)."""
|
||||
from .shades import sun_position
|
||||
lat, lon = (location or {}).get("latitude"), (location or {}).get("longitude")
|
||||
if lat is None or lon is None:
|
||||
if pv_sun is None:
|
||||
return [0.0] * STEPS, "none (no location, no PV forecast)"
|
||||
return [1000.0 * max(0.0, x) for x in pv_sun], "PV forecast"
|
||||
out = []
|
||||
for k in range(STEPS):
|
||||
elev, _ = sun_position(start + k * STEP_S + STEP_S / 2, float(lat), float(lon))
|
||||
cz = math.sin(math.radians(elev))
|
||||
clear = 1098.0 * cz * math.exp(-0.057 / cz) if cz > 0.01 else 0.0
|
||||
out.append(round(clear * max(0.0, min(1.0, sky[k] if k < len(sky) else 1.0)), 1))
|
||||
return out, "clear sky x the sky"
|
||||
|
||||
|
||||
def _room_rc(c, params: dict, bundles, only_one: bool, now: float) -> str:
|
||||
"""A heating or cooling control's R and C: the mapping's own, else the
|
||||
model's room (bundles.room_rc), else the defaults. A room fitted against
|
||||
the electric power: C * cop and R / cop (the same RC; the optimiser's
|
||||
heat is cop * P). Into params; where they came from."""
|
||||
if "r_k_per_kw" in c.params or "c_kwh_per_k" in c.params:
|
||||
return "mapping"
|
||||
get = getattr(bundles, "room_rc", None)
|
||||
rc = get(c.id, str(c.params.get("area") or ""), only_one, now) if get else None
|
||||
if rc is None:
|
||||
return "defaults"
|
||||
r, cap = rc["r_k_per_kw"], rc["c_kwh_per_k"]
|
||||
gain, solar = rc.get("gain_w") or 0.0, rc.get("solar_m2") or 0.0
|
||||
cop = number(params.get("cop")) or 1.0
|
||||
if rc.get("power") == "electric" and cop > 0:
|
||||
# fitted in electric equivalents: the heat is cop times (like C)
|
||||
r, cap = r / cop, cap * cop
|
||||
gain = [g * cop for g in gain] if isinstance(gain, list) else gain * cop
|
||||
solar *= cop
|
||||
params["r_k_per_kw"], params["c_kwh_per_k"] = r, cap
|
||||
# the fit's internal gain and sun (Finding B6-a): R and C were fitted
|
||||
# with them; the mapping's own, where it sets them, win
|
||||
if "internal_gain_w" not in c.params:
|
||||
params["internal_gain_w"] = gain
|
||||
if "solar_m2" not in c.params:
|
||||
params["solar_m2"] = solar
|
||||
return "model"
|
||||
|
||||
|
||||
def _quantities(c) -> list[str]:
|
||||
return {"battery": ["soc_pct", "power_w"], "heating": ["temp_c"], "cooling": ["temp_c"],
|
||||
"ev": ["current_a"], "cover": ["position_pct"]}[c.kind]
|
||||
|
||||
Reference in new issue
Block a user