cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.2019: full source
This commit is contained in:
1 parent
c0a6f8a579
commit
5168a4a590
27 files changed
+2815
-126
No files matched your search
@@ -95,7 +95,10 @@ class Collector:
|
||||
class History:
|
||||
"""Quarter-hour means of load and PV (W) for the last 8 days, kept on
|
||||
disk, for "the same quarter hour yesterday" and the box's models' "the
|
||||
same slot a week before" (localml.py)."""
|
||||
same slot a week before" (localml.py); since 2026-11-12 (methods.md G2,
|
||||
G5 in the plan) also the outdoor temperature ("t_out", °C: the comfort
|
||||
band's running mean) and each planned room's temperature ("room:<id>",
|
||||
°C: the flat's mass now, inputs.mass_start)."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self.path = path
|
||||
@@ -103,7 +106,8 @@ class History:
|
||||
try:
|
||||
with open(path) as f:
|
||||
raw = json.load(f)
|
||||
self.slots = {k: {int(t): v for t, v in raw.get(k, {}).items()} for k in self.slots}
|
||||
keys = set(self.slots) | {k for k in raw if k in ("t_out",) or k.startswith("room:")}
|
||||
self.slots = {k: {int(t): v for t, v in raw.get(k, {}).items()} for k in keys}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
@@ -111,13 +115,17 @@ class History:
|
||||
if value is None:
|
||||
return
|
||||
slot = int(now // STEP_S * STEP_S)
|
||||
s, n = self.slots[name].get(slot, [0.0, 0])
|
||||
s, n = self.slots.setdefault(name, {}).get(slot, [0.0, 0])
|
||||
self.slots[name][slot] = [s + value, n + 1]
|
||||
|
||||
def mean(self, name: str, slot: int) -> float | None:
|
||||
s = self.slots[name].get(slot)
|
||||
s = self.slots.get(name, {}).get(slot)
|
||||
return s[0] / s[1] if s and s[1] else None
|
||||
|
||||
def series(self, name: str, start: int, n: int) -> list[float | None]:
|
||||
"""The quarter-hour means of n slots from start (None where none)."""
|
||||
return [self.mean(name, start + k * STEP_S) for k in range(n)]
|
||||
|
||||
def save(self, now: float):
|
||||
cut = now - HISTORY_S
|
||||
for k in self.slots:
|
||||
@@ -179,6 +187,16 @@ def outdoor_temperature(start: int, col: Collector, inputs, ha_forecast: list[di
|
||||
return None, "none"
|
||||
|
||||
|
||||
def outdoor_now(col: Collector, inputs) -> float | None:
|
||||
"""The outdoor temperature now for the history (the comfort band's
|
||||
running mean, G5): the outdoor sensor, else the weather entity's
|
||||
temperature, else None."""
|
||||
v = col.value(inputs.outside_temp) if getattr(inputs, "outside_temp", None) else None
|
||||
if v is None and getattr(inputs, "weather", None):
|
||||
v = number(col.attr(inputs.weather, "temperature"))
|
||||
return v if v is not None and -60.0 < v < 60.0 else None
|
||||
|
||||
|
||||
def watts(col: Collector, eid: str) -> float | None:
|
||||
"""A power sensor's value in W (HA's kW converted)."""
|
||||
v = col.value(eid)
|
||||
@@ -408,6 +426,12 @@ def occupancy(start: int, tz: str, col: Collector, presence, bundles, history, b
|
||||
src["fixed_hours"] += 1
|
||||
src["source"] = ("learnt" if learnt is not None else "fixed_hours")
|
||||
src["presence_sources"] = len(presence or [])
|
||||
if learnt is not None:
|
||||
# the forecast's share per step (the presence now for the first hour): the comfort band's
|
||||
# weight (comfort.presence_weight, G5); taken out by model_state
|
||||
vals = got[0]
|
||||
src["_share"] = [None if (k < 4 and present is not None) or k >= len(vals)
|
||||
else min(1.0, max(0.0, float(vals[k]))) for k in range(STEPS)]
|
||||
return out, src, notes
|
||||
|
||||
|
||||
@@ -622,6 +646,56 @@ def battery_refusal(c, st: dict) -> dict | None:
|
||||
return {"why": "; ".join(why), "where": where, "missing": missing + (["soc"] if st.get("soc_pct") is None else [])}
|
||||
|
||||
|
||||
# The owner's battery algorithm on the box (2026-11-12; docs/methods.md A2.3a, D17): the Parameters page's rows for a
|
||||
# home's (a house's, a flat's) own battery, resolved for the site and sent in its tariff bundle's params (fleet
|
||||
# heatprice.go boxParamKeys). battery.pv_share_pct is not one: it caps a building battery's storing of PV its flats
|
||||
# could use; a household's own PV kept for its own later use is the plan's own business.
|
||||
BATTERY_WEAR_KEY = "battery.wear_ct"
|
||||
BATTERY_RESERVE_KEY = "battery.plan_reserve_pct"
|
||||
BATTERY_TOP_KEY = "battery.plan_max_soc_pct"
|
||||
BATTERY_RATIO_KEY = "battery.discharge_ratio_pct"
|
||||
|
||||
|
||||
def battery_rows(params: dict, fsrc: dict, box_params: dict | None, priced: bool) -> dict:
|
||||
"""The rows a battery is planned with (the owner's rule: no number stands in for a missing one): its wear (unless
|
||||
the device has its own wear_ct), the plan's reserve and top, and the discharge power as battery.discharge_ratio_pct
|
||||
of the one rated power where its facts give only one (the device's rated power or the owner's battery kW: the
|
||||
mapping's max_discharge_w is its own). With a tariff, a row missing from the bundle takes its suggested value
|
||||
(battery_core.SUGGESTED_ROWS) and {"gap": {why, where, missing, fallback}} names it (the owner, 2026-11-12);
|
||||
without one (nothing priced) the battery's own window and power, noted.
|
||||
Else {"params": what the plan uses, "src": per fact where it came from, "notes": [...]}. The shared rules
|
||||
(battery_core.discharge_kw, window: the building's own copy) make the numbers."""
|
||||
from . import battery_core
|
||||
bp = box_params or {}
|
||||
one_power = fsrc.get("max_discharge_w") != "mapping"
|
||||
need = [BATTERY_RESERVE_KEY, BATTERY_TOP_KEY] + ([BATTERY_WEAR_KEY] if number(params.get("wear_ct")) is None else []) \
|
||||
+ ([BATTERY_RATIO_KEY] if one_power else [])
|
||||
vals = {k: number(bp.get(k)) for k in need}
|
||||
missing = [k for k in need if vals[k] is None]
|
||||
out, src, notes, gap = {}, {}, [], None
|
||||
if missing and priced:
|
||||
# the owner (2026-11-12): fall back to the suggested values, with an alarm naming the rows
|
||||
gap = battery_core.suggested_gap(missing)
|
||||
for k in missing:
|
||||
vals[k] = battery_core.SUGGESTED_ROWS[k]
|
||||
if BATTERY_WEAR_KEY in missing:
|
||||
out["wear_ct"], src["wear_ct"] = vals[BATTERY_WEAR_KEY], "suggested"
|
||||
missing = []
|
||||
if missing:
|
||||
notes.append("battery: " + ", ".join(missing) + " not on the box (no tariff): its own window and power")
|
||||
ratio = vals.get(BATTERY_RATIO_KEY)
|
||||
if one_power and ratio is not None and number(params.get("max_charge_w")):
|
||||
ch_kw = float(params["max_charge_w"]) / 1000.0
|
||||
out["max_discharge_w"] = round(battery_core.discharge_kw(ch_kw, None, ratio) * 1000.0, 1)
|
||||
src["max_discharge_w"] = "ratio"
|
||||
for key, name in ((BATTERY_RESERVE_KEY, "plan_reserve_pct"), (BATTERY_TOP_KEY, "plan_max_soc_pct")):
|
||||
if vals.get(key) is not None:
|
||||
out[name], src[name] = vals[key], ("suggested" if gap and key in gap["missing"] else "parameter")
|
||||
if gap and BATTERY_RATIO_KEY in gap["missing"] and "max_discharge_w" in src:
|
||||
src["max_discharge_w"] = "suggested"
|
||||
return {"params": out, "src": src, "notes": notes, **({"gap": gap} if gap else {})}
|
||||
|
||||
|
||||
HYBRID_SWITCH_KEY = "heat.hybrid_switch_eur" # the Parameters page's (via the tariff bundle)
|
||||
|
||||
|
||||
@@ -798,11 +872,22 @@ def _tank_state(c, st: dict, params: dict, start: int, now: float, tz: str, bund
|
||||
for k in ("boiler_type", "part_load_curve"):
|
||||
if (c.params or {}).get(k):
|
||||
params[k] = c.params[k]
|
||||
src = dict(fsrc, draw=dsrc)
|
||||
# hot water as a reserve (hotwater.py, G7): the floor per step (the draw temperature where a draw is
|
||||
# expected, else the idle floor; a Großanlage the law's at every step), the heat pump's COP by the tank's
|
||||
# temperature
|
||||
from . import hotwater
|
||||
hw, hw_missing = hotwater.rows(box_params)
|
||||
params["hp_cop_drop_pct_per_k"] = hw["dhw.hp_cop_drop_pct_per_k"]
|
||||
params["hp_cop_ref_c"] = hw["dhw.hp_cop_ref_c"]
|
||||
if (c.params or {}).get("cop_tank_curve"):
|
||||
params["cop_tank_curve"] = c.params["cop_tank_curve"]
|
||||
floor_c = hotwater.floors(draw, float(facts["min_temp_c"]), hw["dhw.idle_min_temp_c"], facts.get("law_floor_c"), hw)
|
||||
src = dict(fsrc, draw=dsrc, floor="the law's (DVGW W 551)" if facts.get("law_floor_c") is not None else
|
||||
f"{float(facts['min_temp_c']):g} °C at draws, {min(hw['dhw.idle_min_temp_c'], float(facts['min_temp_c'])):g} °C between")
|
||||
if lt.get("ua") and not lt["ua"].get("kept"):
|
||||
src["ua_fit"] = (f"learnt UA {lt['ua']['ua_w_k']:g} W/K is {lt['ua']['ua_w_k'] / max(lt['ua'].get('label_ua_w_k') or 1e-9, 1e-9):.1f}x "
|
||||
"the label's: kept off (check the circulation pump and the insulation)")
|
||||
return {"draw_w": draw, "src": src}
|
||||
return {"draw_w": draw, "src": src, "floor_c": floor_c, **({"hw_missing": hw_missing} if hw_missing else {})}
|
||||
|
||||
|
||||
def heat_site(controls, devices: list, inputs, price_gas: list, price_heat: list, price_oil: list | None = None) -> dict:
|
||||
@@ -888,7 +973,7 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
occupied_hours=OCCUPIED_HOURS, building: dict | None = None, location: dict | None = None,
|
||||
shade_ctx: dict | None = None, grid_order: dict | None = None,
|
||||
grid_max_w: float | None = None, ev_phases: dict | None = None, presence: list | None = None,
|
||||
storefit=None) -> dict:
|
||||
storefit=None, comfort_ctx: 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,
|
||||
@@ -929,6 +1014,7 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
# occupied per step: the presence now, then the learnt weekly presence, else 06-22 (occupancy)
|
||||
occupied, occ_src, occ_notes = occupancy(start, tz, col, inputs.presence if presence is None else presence,
|
||||
bundles, history, box, box_params, occupied_hours, fc_src)
|
||||
occ_share = occ_src.pop("_share", None)
|
||||
notes += occ_notes
|
||||
# the forecasts per source for the live error (boxtrain.py), not for the plan
|
||||
cands = {k: v.pop("_cands") for k, v in fc_src.items() if "_cands" in v}
|
||||
@@ -986,7 +1072,7 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
# a room's COP and comfort temperatures: the mapping's (the device's facts, the owner's), or the
|
||||
# defaults (optimizer.shift_envelope publishes no shift from defaults); rooms not planned
|
||||
# (room_refusal) with what their fallback schedule needs
|
||||
cop_src, band_src, fallback = {}, {}, []
|
||||
cop_src, band_src, fallback, zone_src = {}, {}, [], {}
|
||||
one_room = sum(c.kind in ("heating", "cooling") for c in controls) == 1
|
||||
for c in controls:
|
||||
if hasattr(c, "learn_range"):
|
||||
@@ -1004,6 +1090,10 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
params["phases"] = info["phases"]
|
||||
phases_src[c.id] = {"phases": info["phases"], "source": info["source"]}
|
||||
st = device_state(c, col, now)
|
||||
if c.kind == "cover":
|
||||
# its window's facts (G3 in the plan: the installer's, the device's, the owner's; never assumed)
|
||||
from .controls import FACTS
|
||||
params.update({k: float(c.params[k]) for k in FACTS["cover"] if number(c.params.get(k)) is not None})
|
||||
if c.kind == "ev":
|
||||
# the car's departure and energy from the session forecast where it says none (B15)
|
||||
ev_src[c.id], note = ev_session(c, st, sessions, start, now)
|
||||
@@ -1018,15 +1108,36 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
params["cop"] = 1.0 # a resistive heater: all its electricity becomes heat (physics)
|
||||
src, power = _room_rc(c, params, bundles, one_room, now)
|
||||
rooms_src[c.id] = src
|
||||
if params.get("_zone_note"):
|
||||
notes.append(f"{c.id}: {params.pop('_zone_note')}: its own R and C instead")
|
||||
if params.get("zone"):
|
||||
# the flat's mass now: observed on the room's history (B17.5), else the steady state
|
||||
past = start - 96 * STEP_S
|
||||
hist = history if hasattr(history, "series") else None
|
||||
m0, msrc = mass_start(params, hist.series(f"room:{c.id}", past, 96) if hist else [],
|
||||
hist.series("t_out", past, 96) if hist else [],
|
||||
st.get("temp_c") if st.get("temp_c") is not None else None)
|
||||
if m0 is None and t_out is not None and st.get("temp_c") is not None:
|
||||
m0, msrc = mass_start(params, [], [t_out[0]], st["temp_c"])
|
||||
if m0 is not None:
|
||||
params["zone"]["theta_m0"], params["zone"]["theta_m0_src"] = round(m0, 3), msrc
|
||||
zone_src[c.id] = {"share": params["zone"]["share"], "share_from": params["zone"]["share_src"],
|
||||
"mass_now_c": params["zone"].get("theta_m0"), "mass_from": msrc or "none"}
|
||||
zone_eer = None
|
||||
if c.kind == "cooling" and params.get("zone") and params["zone"].get("cool_eer") and power != "electric" \
|
||||
and "cop" not in c.params and not c.params.get("cop_curve"):
|
||||
# an A/C without its datasheet: the flat model's fitted EER (B17, G4; the device's curve wins)
|
||||
params["cop"] = zone_eer = float(params["zone"]["cool_eer"])
|
||||
# an electric fit runs in electric equivalents: the COP cancels (_room_rc)
|
||||
cop_src[c.id] = ("mapping" if "cop" in c.params or c.params.get("cop_curve") else
|
||||
"zone fit" if zone_eer else
|
||||
"electric heater" if c.kind == "heating" and source == "electric" else
|
||||
"electric fit" if power == "electric" and "cop" in params else "none")
|
||||
# comfort/setback/setup: the mapping's, else the box's copy of the Parameters rows
|
||||
# comfort.heating_setpoints / comfort.cooling_setpoints (docs/parameters.md C7)
|
||||
band_src[c.id] = "mapping" if any(k in c.params for k in ("comfort_c", "setback_c", "setup_c")) else "defaults"
|
||||
# what is missing for the room and for its heat source (methods E6)
|
||||
nos = [room_refusal(c, st, src, power, source)]
|
||||
nos = [room_refusal(c, st, src, power, source, cop_known=zone_eer is not None)]
|
||||
if c.kind == "heating":
|
||||
nos.append(heating_refusal(c, params, price_gas, price_heat, getattr(prices, "status", "tariff"),
|
||||
box_params, price_oil))
|
||||
@@ -1059,7 +1170,17 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
continue
|
||||
facts, _, fsrc = c.battery_facts()
|
||||
params.update(facts)
|
||||
battery_src[c.id] = dict(fsrc)
|
||||
# the owner's battery algorithm (A2.3a): the reserve, the top, the discharge power, the wear's row (the
|
||||
# mapping's own wear_ct first: the device's ageing per kWh where its owner knows it)
|
||||
own_wear = number((getattr(c, "params", None) or {}).get("wear_ct"))
|
||||
if own_wear is not None and own_wear >= 0:
|
||||
params["wear_ct"] = own_wear
|
||||
rows = battery_rows(params, fsrc, box_params, prices.status != "none")
|
||||
if "gap" in rows: # planned with the suggested values: reported like a refusal, marked fallback
|
||||
refused[c.id] = dict(rows["gap"], kind="battery", name=c.label() if hasattr(c, "label") else c.id)
|
||||
params.update(rows["params"])
|
||||
notes += rows["notes"]
|
||||
battery_src[c.id] = dict(fsrc, **rows["src"])
|
||||
# its idle loss (A2.3, S.2): never refuses it; without any value 0, a quiet note
|
||||
if hasattr(c, "battery_idle_facts"):
|
||||
fit = storefit.battery_in_force(c.id) if storefit is not None else None
|
||||
@@ -1093,12 +1214,24 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
params["cop_curve"] = []
|
||||
got["src"] = dict(got["src"], cop="its one COP (no outdoor temperature for the curve)")
|
||||
tank_src[c.id] = got["src"]
|
||||
extra = {"draw_w": got["draw_w"]}
|
||||
extra = {"draw_w": got["draw_w"], "floor_c": got["floor_c"]}
|
||||
if got.get("hw_missing") and box_params:
|
||||
from . import hotwater
|
||||
refused["hot_water"] = hotwater.gap(got["hw_missing"])
|
||||
b = c.bounds("temp_c", (extra_limits or {}).get(c.id)) # with a Großanlage's floor (tank_facts)
|
||||
bounds["temp_c"] = [b.lo, b.hi, b.lo_by, b.hi_by]
|
||||
devices.append({"id": c.id, "kind": c.kind, "params": params,
|
||||
"state": st, "bounds": bounds,
|
||||
"channels": sorted(c.writable()), **extra})
|
||||
comfort_info, presence_w = comfort_bands(devices, controls, start, now, tz, t_out, history, box_params, occupied, occ_share,
|
||||
band_src, refused, notes, comfort_ctx or {})
|
||||
# a combi boiler's comfort mode (hotwater.combi_comfort, G7): off at night and while nobody is home
|
||||
for d in devices:
|
||||
if d["kind"] == "heating" and "dhw_comfort" in d["channels"] and \
|
||||
str(d["params"].get("combi") or "").lower() in ("true", "yes", "1"):
|
||||
from . import comfort, hotwater
|
||||
sleep = comfort.rows(box_params)[0]["comfort.sleep"]
|
||||
d["dhw_comfort"] = hotwater.combi_comfort(start, tz, STEPS, presence_w, sleep)
|
||||
clouds = _hourly(weather_forecast or [], "cloud_coverage", start, STEPS)
|
||||
sky_src = "weather forecast"
|
||||
if clouds is None and fwx:
|
||||
@@ -1117,10 +1250,14 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
"tariff": getattr(prices, "tariff_id", ""), "expired_at": getattr(prices, "expired_at", 0),
|
||||
"priced_steps": getattr(prices, "priced_steps", STEPS)},
|
||||
"load_w": load, "pv_w": pv, "t_out": t_out, "sun": sun, "occupied": occupied, "sky": sky,
|
||||
# the probability someone is home per step (comfort.presence_weight: the band's weight, the zone's gain)
|
||||
"presence_w": presence_w,
|
||||
"ghi_w_m2": ghi, "location": location or {},
|
||||
"sources": {"load": load_src, "pv": pv_src, "outdoor": t_src, "model": bundles.model_id(),
|
||||
"sky": sky_src if clouds else "clear", "rooms": rooms_src, "ghi": ghi_src,
|
||||
"rooms_cop": cop_src, "rooms_band": band_src,
|
||||
**({"rooms_zone": zone_src} if zone_src else {}),
|
||||
**({"comfort": comfort_info} if comfort_info else {}),
|
||||
"ev_phases": phases_src,
|
||||
# occupied steps per source (presence now, learnt, fixed hours) and why (B16)
|
||||
"occupancy": occ_src,
|
||||
@@ -1155,7 +1292,12 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
||||
from . import shades
|
||||
for d in devices:
|
||||
if d["kind"] == "cover":
|
||||
d["schedule"] = shades.schedule(d, out, (shade_ctx or {}).get(d["id"]))
|
||||
# with its window's facts the plan places it (G3); else A7's rules on the sun
|
||||
wp = shades.window_plan(d, out, (shade_ctx or {}).get(d["id"]))
|
||||
if wp is not None:
|
||||
d["window"] = wp
|
||||
else:
|
||||
d["schedule"] = shades.schedule(d, out, (shade_ctx or {}).get(d["id"]))
|
||||
return out
|
||||
|
||||
|
||||
@@ -1198,6 +1340,14 @@ def _room_rc(c, params: dict, bundles, only_one: bool, now: float) -> str:
|
||||
return "mapping", "thermal"
|
||||
if has:
|
||||
return "partial", ""
|
||||
# the flat's 2R2C (air and mass, B17) where the cloud's daily check passed, scaled to the room
|
||||
# (G2 in the plan, backlog 473): pre-heating and pre-cooling are stored in the mass
|
||||
zget = getattr(bundles, "zone_rc", None)
|
||||
z, zwhy = zget(c.id, str(c.params.get("area") or ""), only_one, now) if zget else (None, "")
|
||||
if z is not None:
|
||||
return _zone_params(c, params, z), ("electric" if z["power"] == "electric" else "thermal")
|
||||
if zwhy:
|
||||
params["_zone_note"] = zwhy
|
||||
# the box's own fit where it is in force (boxtrain.py), else the cloud's
|
||||
own = getattr(bundles, "own", None)
|
||||
rc = own.room_rc(c.id, str(c.params.get("area") or ""), only_one) if own is not None else None
|
||||
@@ -1230,7 +1380,124 @@ def _room_rc(c, params: dict, bundles, only_one: bool, now: float) -> str:
|
||||
return src, ("electric" if rc.get("power") == "electric" else "thermal")
|
||||
|
||||
|
||||
def room_refusal(c, st: dict, rc: str, power: str, source: str = "electric") -> dict | None:
|
||||
def _zone_params(c, params: dict, z: dict) -> str:
|
||||
"""The room as its share of the flat's 2R2C (bundles.zone_rc): the
|
||||
resistances divided by the share, the capacities and gains times it (a
|
||||
room that is that share of the flat, with the flat's time constants:
|
||||
methods.md G2 in the plan). Fitted against the electric power: R / cop,
|
||||
C x cop as a room's (_room_rc). Into params["zone"] {r_i, r_e, c_a, c_m,
|
||||
gain_w, solar_m2, el_gain_share, occ_gain_w, share, ...}; params' R and
|
||||
C the one-node equivalent (R_i + R_e, C_eff: the shift envelope and the
|
||||
heating levers, which run one node). The mapping's own gains win."""
|
||||
sh = z["share"]
|
||||
k = 1.0
|
||||
electric = str(params.get("heat_source") or "electric") in ("electric", "heat_pump")
|
||||
if z["power"] == "electric" and electric:
|
||||
cop = number(params.get("cop")) or 1.0
|
||||
if c.kind == "cooling" or "cop" in params:
|
||||
params["cop"] = cop
|
||||
k = cop
|
||||
ri, re_ = z["r_i"] / sh / k, z["r_e"] / sh / k
|
||||
ca, cm = z["c_a"] * sh * k, z["c_m"] * sh * k
|
||||
zone = {"r_i": ri, "r_e": re_, "c_a": ca, "c_m": cm, "share": sh, "share_src": z.get("share_src", ""),
|
||||
"power": z["power"], "gain_w": z["gain_w"] * sh * k, "solar_m2": z["solar_m2"] * sh * k,
|
||||
"solar_kind": z.get("solar_kind", "ghi"),
|
||||
"el_gain_share": z["el_gain_share"] * sh * k, "occ_gain_w": z["occ_gain_w"] * sh * k,
|
||||
"cool_eer": z.get("cool_eer")}
|
||||
params["zone"] = zone
|
||||
params["r_k_per_kw"] = ri + re_
|
||||
params["c_kwh_per_k"] = ca + cm * re_ / (ri + re_)
|
||||
if "internal_gain_w" not in c.params:
|
||||
params["internal_gain_w"] = zone["gain_w"]
|
||||
if "solar_m2" not in c.params:
|
||||
params["solar_m2"] = zone["solar_m2"]
|
||||
return "zone 2r2c"
|
||||
|
||||
|
||||
def comfort_bands(devices: list, controls, start: int, now: float, tz: str, t_out: list | None, history,
|
||||
box_params: dict, occupied: list, occ_share: list | None, band_src: dict, refused: dict,
|
||||
notes: list, ctx: dict) -> tuple[dict | None, list[float]]:
|
||||
"""Each planned room's comfort band per step (comfort.py, methods.md G5
|
||||
in the plan) into d["band"]: EN 16798-1's band for the household's
|
||||
choice (ctx "mode": comfort | balanced | saving, the preferences'
|
||||
"comfort"; else the Parameters page's default), on the running mean
|
||||
outdoor temperature (the box's history "t_out" and the forecast), the
|
||||
household's tolerance from its overrides (ctx "tolerance"), weighted by
|
||||
the probability someone is home. The owner's schedule still wins
|
||||
(preferences.apply; the optimizer takes the band only without one).
|
||||
Rows missing: their suggested values and refused["comfort_band"] names
|
||||
them. (the plan's sources.comfort, the presence weight per step)."""
|
||||
from . import comfort
|
||||
raw = (box_params or {}).get(OCC_SHARE_KEY)
|
||||
weights = comfort.presence_weight(occupied, occ_share, number(raw) if not isinstance(raw, bool) else None)
|
||||
rooms = [d for d in devices if d["kind"] in ("heating", "cooling")]
|
||||
if not rooms:
|
||||
return None, weights
|
||||
r, missing = comfort.rows(box_params)
|
||||
if missing and box_params:
|
||||
# the bundle carries the Parameters but not these: the alarm (the owner's rule, as the battery's rows)
|
||||
refused["comfort_band"] = comfort.gap(missing)
|
||||
elif missing:
|
||||
notes.append("comfort band: no Parameters on the box yet (no tariff bundle): EN 16798-1's suggested values")
|
||||
mode = ctx.get("mode") if ctx.get("mode") in comfort.MODES else r["comfort.default_mode"]
|
||||
past_n = 7 * 96
|
||||
past = history.series("t_out", start - past_n * STEP_S, past_n) if hasattr(history, "series") else []
|
||||
days = comfort.daily_means(start, tz, past, start - past_n * STEP_S, t_out)
|
||||
zone = ZoneInfo(tz or "UTC")
|
||||
horizon_days = sorted({datetime.fromtimestamp(start + k * STEP_S, timezone.utc).astimezone(zone).date().isoformat()
|
||||
for k in range(STEPS + 1)})
|
||||
alpha = float(r["comfort.running_mean_alpha"])
|
||||
rm = {d: comfort.running_mean(days, d, alpha) for d in horizon_days}
|
||||
if any(v is None for v in rm.values()):
|
||||
notes.append("comfort band: no running mean outdoor temperature for " +
|
||||
", ".join(d for d, v in rm.items() if v is None) +
|
||||
" (under a day of the box's outdoor history): EN 16798-1's fixed values there")
|
||||
cooled = any(getattr(c, "kind", "") == "cooling" for c in controls)
|
||||
tol = ctx.get("tolerance")
|
||||
info = {"mode": mode, "category": r["comfort.mode_categories"].get(mode), "rows": "suggested" if missing else "parameters",
|
||||
"running_mean_c": {d: (round(v, 2) if v is not None else None) for d, v in rm.items()},
|
||||
"history_days": sum(1 for d in days if d < horizon_days[0]), "tolerance": {}}
|
||||
for d in rooms:
|
||||
kind = d["kind"]
|
||||
p = d["params"]
|
||||
back = p.get("setup_c" if kind == "cooling" else "setback_c")
|
||||
if back is None:
|
||||
continue
|
||||
shift, n = tol.shift(d["id"], kind, now, r) if tol is not None else (0.0, 0)
|
||||
d["band"] = comfort.room_band(r, kind, mode, start, tz, STEPS, weights, rm, float(back), cooled, shift)
|
||||
band_src[d["id"]] = f"en16798 {d['band']['category']}"
|
||||
if n:
|
||||
info["tolerance"][d["id"]] = {"shift_k": round(shift, 2), "overrides": n}
|
||||
return info, weights
|
||||
|
||||
|
||||
def mass_start(params: dict, temps: list, t_out: list, now_c: float | None) -> tuple[float | None, str]:
|
||||
"""The zone's mass temperature now (methods.md B17.5, the fit's
|
||||
observer): the mass equation driven by the room's measured air over the
|
||||
last 24 h (temps, t_out: oldest first, None where missing: the last
|
||||
value held), from the steady state at the first value; without a day of
|
||||
history the steady state now (R_e theta_a + R_i T_out) / (R_i + R_e)."""
|
||||
z = params.get("zone")
|
||||
if not z or now_c is None:
|
||||
return None, ""
|
||||
ri, re_, cm = z["r_i"], z["r_e"], z["c_m"]
|
||||
pairs = [(a, o) for a, o in zip(temps, t_out)]
|
||||
have = [p for p in pairs if p[0] is not None and p[1] is not None]
|
||||
if len(have) < 48:
|
||||
if not t_out or t_out[-1] is None:
|
||||
return None, ""
|
||||
return (re_ * now_c + ri * t_out[-1]) / (ri + re_), "steady state now (under 12 h of the room's history)"
|
||||
a = math.exp(-STEP_S / 3600.0 * (1.0 / ri + 1.0 / re_) / cm)
|
||||
ta, to = have[0]
|
||||
m = (re_ * ta + ri * to) / (ri + re_)
|
||||
for x, y in pairs:
|
||||
ta = x if x is not None else ta
|
||||
to = y if y is not None else to
|
||||
m = a * m + (1 - a) * (re_ * ta + ri * to) / (ri + re_)
|
||||
return m, f"observed over {len(have) // 4} h of the room's history"
|
||||
|
||||
|
||||
def room_refusal(c, st: dict, rc: str, power: str, source: str = "electric", cop_known: bool = False) -> dict | None:
|
||||
"""Why a heating or cooling room is not planned (docs/parameters.md E3: R/C measured, power and COP the device's), or
|
||||
None: no R/C (no fit, the mapping sets neither, or only one of the
|
||||
two), the heater's or cooler's electric power unknown (max_power_w),
|
||||
@@ -1260,7 +1527,8 @@ def room_refusal(c, st: dict, rc: str, power: str, source: str = "electric") ->
|
||||
where.append("the mapping's params (max_power_w, W)")
|
||||
missing.append("max_power_w")
|
||||
# a cooler's COP (a heater's: electric 1, a heat pump's or hybrid's: heating_refusal)
|
||||
if c.kind == "cooling" and rc in ("mapping", "model", "box model") and power != "electric" and "cop" not in c.params:
|
||||
if c.kind == "cooling" and rc in ("mapping", "model", "box model", "zone 2r2c") and power != "electric" \
|
||||
and "cop" not in c.params and not cop_known:
|
||||
why.append("COP unknown (heat per kWh of electricity)")
|
||||
where.append("the mapping's params (cop)")
|
||||
missing.append("cop")
|
||||
|
||||
Reference in new issue
Block a user