moprecont 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- moprecont/__init__.py +7 -0
- moprecont/appliances.py +326 -0
- moprecont/blinds.py +104 -0
- moprecont/control.py +112 -0
- moprecont/cooling.py +200 -0
- moprecont/core/__init__.py +1 -0
- moprecont/core/mpc_core.py +1533 -0
- moprecont/core/mpc_learn.py +448 -0
- moprecont/core/mpc_trust.py +123 -0
- moprecont/criteria.py +115 -0
- moprecont/cycles.py +63 -0
- moprecont/dhw.py +170 -0
- moprecont/ensemble.py +461 -0
- moprecont/ev.py +37 -0
- moprecont/fan.py +155 -0
- moprecont/fitdata.py +280 -0
- moprecont/fitpipe.py +219 -0
- moprecont/forecast.py +162 -0
- moprecont/health.py +649 -0
- moprecont/heatflows.py +166 -0
- moprecont/house.py +256 -0
- moprecont/learn.py +287 -0
- moprecont/live.py +113 -0
- moprecont/network.py +140 -0
- moprecont/outlook.py +338 -0
- moprecont/pareto.py +50 -0
- moprecont/plan.py +171 -0
- moprecont/price.py +221 -0
- moprecont/ring.py +194 -0
- moprecont/trust.py +86 -0
- moprecont-0.1.0.dist-info/METADATA +76 -0
- moprecont-0.1.0.dist-info/RECORD +34 -0
- moprecont-0.1.0.dist-info/WHEEL +4 -0
- moprecont-0.1.0.dist-info/licenses/LICENSE +21 -0
moprecont/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""moprecont: model predictive control for building heating.
|
|
2
|
+
|
|
3
|
+
The thermal RC model, its nightly fit, the 36 h optimiser, the 7-day ensemble outlook and the
|
|
4
|
+
supporting pieces (price model, heat flows, cooling, learning, trust, health checks) behind the
|
|
5
|
+
HeatMind Home Assistant integration, as a plain Python library (numpy only).
|
|
6
|
+
"""
|
|
7
|
+
__version__ = "0.1.0"
|
moprecont/appliances.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""Appliance learning mode and fan bands (port of AppDaemon mpc_appliances) — pure python + numpy.
|
|
2
|
+
|
|
3
|
+
Learns which room each electrical appliance (or window/door/switch) warms or cools.
|
|
4
|
+
Why: the model spreads the measured internal gains over the rooms with fixed shares. A desktop of a
|
|
5
|
+
few hundred watts lands in ONE room; an open window or an extraction hood cools one room. Once a
|
|
6
|
+
link is accepted, the engine moves that appliance's power out of the shared internal gains into the
|
|
7
|
+
room it heats (and a cooling switch becomes a negative heat input for its room).
|
|
8
|
+
|
|
9
|
+
Per appliance and room, on 5-minute samples (here: the recorder's 5-minute statistics, so there is
|
|
10
|
+
history from day one instead of a private log that first has to fill):
|
|
11
|
+
|
|
12
|
+
excess(room) = T_room − mean(T of all rooms) how warm the room runs against the house
|
|
13
|
+
contrast = mean(excess | appliance on) − mean(excess | off), Welch t-statistic,
|
|
14
|
+
night (23-07: no sun, little heating) first, day as fallback
|
|
15
|
+
|
|
16
|
+
A pair becomes a PROPOSAL when the room runs at least DELTA_K warmer or cooler with the appliance on,
|
|
17
|
+
|t| >= T_STAT, with enough on and off samples. The excess is zero-sum over the rooms, so per appliance
|
|
18
|
+
only the direction of its strongest room is proposed. Correlation is not attribution (a desk lamp
|
|
19
|
+
follows the sun too), so links are only used after the user accepts them.
|
|
20
|
+
|
|
21
|
+
Fan bands: the ventilation fan per band (default 20/35/50/75/100 %), per room the excess contrast
|
|
22
|
+
against the lowest band; a higher band can also warm a room, the sign per room is kept.
|
|
23
|
+
|
|
24
|
+
Commands (HA event ``mpc_corr``, same as AppDaemon): scan, accept, reject, reset (appliance, zone).
|
|
25
|
+
"""
|
|
26
|
+
import math
|
|
27
|
+
import re
|
|
28
|
+
import time as _time
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
DELTA_K = 0.25 # K contrast threshold
|
|
33
|
+
T_STAT = 3.0 # Welch t threshold
|
|
34
|
+
MIN_ON = 40 # minimum 5-min samples with the appliance on (and off) before judging
|
|
35
|
+
MIN_W = 15.0 # appliances below this peak power (p95) are too small to warm a room
|
|
36
|
+
NIGHT = (23, 7)
|
|
37
|
+
STEP = 300
|
|
38
|
+
FAN_BANDS = (20, 35, 50, 75, 100)
|
|
39
|
+
|
|
40
|
+
# entity ids that are not an appliance in a room (the heating itself, energy flows, PV, meters, EV,
|
|
41
|
+
# planner/model templates); matched as substrings
|
|
42
|
+
EXCLUDE = ["radiator", "solis", "pv", "solar", "grid", "electricity_meter", "meter_rest", "meter_remainder",
|
|
43
|
+
"heat_pump", "heatpump", "warmtepomp", "hf_", "forecast", "solcast", "_plan", "ev_", "charger",
|
|
44
|
+
"laadpaal", "standby", "base_load", "load_power", "balance", "thermal", "internal_heat",
|
|
45
|
+
"ventilation_loss", "infiltration_loss", "compress", "active_power_l", "_l1", "_l2", "_l3",
|
|
46
|
+
"charging_power", "gain_", "loss_", "co2", "humidity", "battery", "total", "mpc_", "heatmind",
|
|
47
|
+
"inverter", "boiler", "machine_power", "dsmr", "p1_", "power_consumption", "power_production",
|
|
48
|
+
# switches that are part of the heating itself (zone valves, thermostat relays, inverted
|
|
49
|
+
# heating switches): they follow the room temperature, they do not cause it
|
|
50
|
+
"heating", "verwarming", "thermostat", "valve", "klep", "inverted", "tado", "mpc_heating"]
|
|
51
|
+
SWITCH_T = 6.0 # a switch needs stronger evidence: many switches follow the clock (lights, schedules)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def discover(states, exclude=(), known=()):
|
|
55
|
+
"""Candidate appliances from HA states: {name: (entity_id, kind)}.
|
|
56
|
+
|
|
57
|
+
states: iterable of objects with entity_id, state and attributes. Power sensors (device_class
|
|
58
|
+
power, unit W) are kind "power"; opening binary sensors (windows/doors) and switch.* are kind
|
|
59
|
+
"switch" (1 = on/open). Configured entities (``known``) and the exclude patterns are skipped.
|
|
60
|
+
"""
|
|
61
|
+
out = {}
|
|
62
|
+
skip = list(EXCLUDE) + list(exclude or [])
|
|
63
|
+
known = set(known or [])
|
|
64
|
+
for st in states:
|
|
65
|
+
eid = st.entity_id
|
|
66
|
+
if eid in known or any(p in eid for p in skip):
|
|
67
|
+
continue
|
|
68
|
+
a = st.attributes or {}
|
|
69
|
+
dc, unit = a.get("device_class"), a.get("unit_of_measurement")
|
|
70
|
+
if eid.startswith("sensor.") and dc == "power" and unit in ("W", "w"):
|
|
71
|
+
kind = "power"
|
|
72
|
+
elif eid.startswith("binary_sensor.") and dc in ("opening", "window", "door"):
|
|
73
|
+
kind = "switch"
|
|
74
|
+
elif eid.startswith("switch."):
|
|
75
|
+
kind = "switch"
|
|
76
|
+
else:
|
|
77
|
+
continue
|
|
78
|
+
name = re.sub(r"[^a-z0-9]+", "_", (a.get("friendly_name") or eid.split(".", 1)[1]).lower()).strip("_")
|
|
79
|
+
if name in out:
|
|
80
|
+
name = re.sub(r"[^a-z0-9]+", "_", eid.split(".", 1)[1].lower())
|
|
81
|
+
out[name] = (eid, kind)
|
|
82
|
+
return out
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def welch(a, b, min_n=MIN_ON):
|
|
86
|
+
"""(delta, t) of two samples; flat samples with a gap are certain (t = 999)."""
|
|
87
|
+
a, b = np.asarray(a, float), np.asarray(b, float)
|
|
88
|
+
if len(a) < min_n or len(b) < min_n:
|
|
89
|
+
return float("nan"), float("nan")
|
|
90
|
+
va, vb = a.var(ddof=1) / len(a), b.var(ddof=1) / len(b)
|
|
91
|
+
delta = float(a.mean() - b.mean())
|
|
92
|
+
if va + vb <= 0:
|
|
93
|
+
return (delta, 999.0) if abs(delta) > 1e-9 else (float("nan"), float("nan"))
|
|
94
|
+
return delta, float(delta / math.sqrt(va + vb))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def night_mask(grid):
|
|
98
|
+
h = np.array([_time.localtime(float(t)).tm_hour for t in grid])
|
|
99
|
+
return (h >= NIGHT[0]) | (h < NIGHT[1])
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def scan(grid, powers, temps, kinds=None, night=None):
|
|
103
|
+
"""Per appliance and room the on/off contrast of the room-temperature excess.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
grid: sample times (epoch s).
|
|
107
|
+
powers: {name: array} (W, or 1/0 for a switch), NaN = unknown.
|
|
108
|
+
temps: {room: array} (°C).
|
|
109
|
+
kinds: {name: "power" | "switch"}.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
{"name:room": result dict}.
|
|
113
|
+
"""
|
|
114
|
+
kinds = kinds or {}
|
|
115
|
+
grid = np.asarray(grid, float)
|
|
116
|
+
if not temps:
|
|
117
|
+
return {}
|
|
118
|
+
T = {z: np.asarray(v, float) for z, v in temps.items()}
|
|
119
|
+
import warnings
|
|
120
|
+
with warnings.catch_warnings(), np.errstate(all="ignore"):
|
|
121
|
+
warnings.simplefilter("ignore", RuntimeWarning)
|
|
122
|
+
mean_t = np.nanmean(np.vstack(list(T.values())), axis=0)
|
|
123
|
+
night = night_mask(grid) if night is None else night
|
|
124
|
+
results = {}
|
|
125
|
+
for name, arr in powers.items():
|
|
126
|
+
power = np.asarray(arr, float)
|
|
127
|
+
ok = np.isfinite(power)
|
|
128
|
+
if ok.sum() < 4 * MIN_ON:
|
|
129
|
+
continue
|
|
130
|
+
kind = kinds.get(name, "power")
|
|
131
|
+
if kind == "power":
|
|
132
|
+
p95 = float(np.nanpercentile(power, 95))
|
|
133
|
+
if p95 < MIN_W:
|
|
134
|
+
continue
|
|
135
|
+
on_all = ok & (power >= max(0.4 * p95, MIN_W))
|
|
136
|
+
off_all = ok & (power <= max(0.15 * p95, 5.0))
|
|
137
|
+
else:
|
|
138
|
+
p95 = None
|
|
139
|
+
on_all = ok & (power >= 0.5)
|
|
140
|
+
off_all = ok & (power < 0.5)
|
|
141
|
+
if on_all.sum() < MIN_ON or off_all.sum() < MIN_ON:
|
|
142
|
+
continue
|
|
143
|
+
for z, tz in T.items():
|
|
144
|
+
ex = tz - mean_t
|
|
145
|
+
pair_ok = ok & np.isfinite(ex)
|
|
146
|
+
res = {"appliance": name, "zone": z, "kind": kind,
|
|
147
|
+
"p95_w": None if p95 is None else round(p95, 1),
|
|
148
|
+
"mean_w": round(float(np.nanmean(power)), 1),
|
|
149
|
+
"delta_k": None, "dir": None, "t": None, "window": None, "n_on": 0, "n_off": 0}
|
|
150
|
+
for label, mask in (("nacht", night), ("dag", ~night)):
|
|
151
|
+
on_m, off_m = pair_ok & on_all & mask, pair_ok & off_all & mask
|
|
152
|
+
if on_m.sum() < MIN_ON or off_m.sum() < MIN_ON:
|
|
153
|
+
continue
|
|
154
|
+
delta, t_stat = welch(ex[on_m], ex[off_m])
|
|
155
|
+
if math.isfinite(delta):
|
|
156
|
+
res.update(delta_k=round(delta, 2), dir="warm" if delta >= 0 else "koel",
|
|
157
|
+
t=round(t_stat, 1), window=label, n_on=int(on_m.sum()), n_off=int(off_m.sum()))
|
|
158
|
+
break
|
|
159
|
+
results[f"{name}:{z}"] = res
|
|
160
|
+
return results
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def fan_bands(grid, temps, fan, bands=FAN_BANDS, night=None):
|
|
164
|
+
"""Per room and fan band the excess contrast against the lowest band: {room: {band: {...}}}."""
|
|
165
|
+
pct = np.asarray(fan, float)
|
|
166
|
+
ok = np.isfinite(pct)
|
|
167
|
+
if ok.sum() < 4 * MIN_ON or len(bands) < 2 or not temps:
|
|
168
|
+
return {}
|
|
169
|
+
grid = np.asarray(grid, float)
|
|
170
|
+
night = night_mask(grid) if night is None else night
|
|
171
|
+
T = {z: np.asarray(v, float) for z, v in temps.items()}
|
|
172
|
+
import warnings
|
|
173
|
+
with warnings.catch_warnings(), np.errstate(all="ignore"):
|
|
174
|
+
warnings.simplefilter("ignore", RuntimeWarning)
|
|
175
|
+
mean_t = np.nanmean(np.vstack(list(T.values())), axis=0)
|
|
176
|
+
bands = sorted(float(b) for b in bands)
|
|
177
|
+
idx = np.abs(np.where(ok, pct, 0.0)[:, None] - np.asarray(bands)[None, :]).argmin(axis=1)
|
|
178
|
+
idx[~ok] = -1
|
|
179
|
+
out = {}
|
|
180
|
+
for z, tz in T.items():
|
|
181
|
+
ex = tz - mean_t
|
|
182
|
+
zres = {}
|
|
183
|
+
for bi in range(1, len(bands)):
|
|
184
|
+
for label, mask in (("nacht", night), ("dag", ~night)):
|
|
185
|
+
on_m = (idx == bi) & mask & np.isfinite(ex)
|
|
186
|
+
off_m = (idx == 0) & mask & np.isfinite(ex)
|
|
187
|
+
if on_m.sum() < MIN_ON or off_m.sum() < MIN_ON:
|
|
188
|
+
continue
|
|
189
|
+
delta, t_stat = welch(ex[on_m], ex[off_m])
|
|
190
|
+
if math.isfinite(delta):
|
|
191
|
+
b = bands[bi]
|
|
192
|
+
zres[str(int(b) if float(b).is_integer() else b)] = {
|
|
193
|
+
"delta_k": round(delta, 2), "t": round(t_stat, 1), "n": int(on_m.sum()), "window": label}
|
|
194
|
+
break
|
|
195
|
+
if zres:
|
|
196
|
+
out[z] = zres
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def proposals(results, decisions):
|
|
201
|
+
"""Open proposals: qualifying pairs in the direction of each appliance's strongest room, not yet
|
|
202
|
+
decided, strongest first."""
|
|
203
|
+
qual = {}
|
|
204
|
+
for res in results.values():
|
|
205
|
+
if res.get("delta_k") is None:
|
|
206
|
+
continue
|
|
207
|
+
t_min = SWITCH_T if res.get("kind") == "switch" else T_STAT
|
|
208
|
+
if abs(res["delta_k"]) >= DELTA_K and abs(res.get("t") or 0) >= t_min:
|
|
209
|
+
qual.setdefault(res["appliance"], []).append(res)
|
|
210
|
+
out = []
|
|
211
|
+
for rs in qual.values():
|
|
212
|
+
lead = max(rs, key=lambda r: (abs(r["delta_k"]), abs(r["t"] or 0)))
|
|
213
|
+
warm = lead["delta_k"] >= 0
|
|
214
|
+
for res in rs:
|
|
215
|
+
if decisions.get(f"{res['appliance']}:{res['zone']}") in ("accepted", "rejected"):
|
|
216
|
+
continue
|
|
217
|
+
if (res["delta_k"] >= 0) == warm:
|
|
218
|
+
out.append(res)
|
|
219
|
+
out.sort(key=lambda r: -abs((r["delta_k"] or 0) * (r["t"] or 0)))
|
|
220
|
+
return out
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def decide(state, cmd, appliance=None, zone=None):
|
|
224
|
+
"""Apply an mpc_corr command to the learning state (decisions + metadata). Returns a text or None."""
|
|
225
|
+
dec = state.setdefault("decisions", {})
|
|
226
|
+
meta = state.setdefault("meta", {})
|
|
227
|
+
key = f"{appliance}:{zone}"
|
|
228
|
+
res = (state.get("results") or {}).get(key) or {}
|
|
229
|
+
if cmd == "accept" and appliance and zone:
|
|
230
|
+
dec[key] = "accepted"
|
|
231
|
+
meta[key] = {k: res.get(k) for k in ("dir", "delta_k", "kind", "window", "mean_w", "p95_w")}
|
|
232
|
+
meta[key]["entity"] = (state.get("appliances") or {}).get(appliance, [None])[0]
|
|
233
|
+
richt = "koelt" if (res.get("dir") or "warm") == "koel" else "verwarmt"
|
|
234
|
+
return f"Apparaat-koppeling geaccepteerd: {appliance} {richt} '{zone}'"
|
|
235
|
+
if cmd == "reject" and appliance and zone:
|
|
236
|
+
dec[key] = "rejected"
|
|
237
|
+
return f"Apparaat-koppeling verworpen: {appliance} -> '{zone}'"
|
|
238
|
+
if cmd == "reset" and key in dec:
|
|
239
|
+
dec.pop(key, None)
|
|
240
|
+
meta.pop(key, None)
|
|
241
|
+
return f"Apparaat-koppeling hersteld naar voorstel: {appliance} -> '{zone}'"
|
|
242
|
+
return None
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def refresh_meta(state):
|
|
246
|
+
"""Keep the metadata of accepted links in step with the latest scan."""
|
|
247
|
+
for key, verdict in (state.get("decisions") or {}).items():
|
|
248
|
+
res = (state.get("results") or {}).get(key)
|
|
249
|
+
if verdict != "accepted" or not res or res.get("delta_k") is None:
|
|
250
|
+
continue
|
|
251
|
+
m = state.setdefault("meta", {}).setdefault(key, {})
|
|
252
|
+
m.update({k: res.get(k) for k in ("dir", "delta_k", "kind", "window", "mean_w", "p95_w")})
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def links(state, get_state):
|
|
256
|
+
"""Accepted links, live: [{appliance, zone, kind, dir, delta_k, window, w, on, entity}].
|
|
257
|
+
|
|
258
|
+
get_state(entity_id) -> state string or None."""
|
|
259
|
+
out = []
|
|
260
|
+
apps = state.get("appliances") or {}
|
|
261
|
+
for key, verdict in sorted((state.get("decisions") or {}).items()):
|
|
262
|
+
if verdict != "accepted":
|
|
263
|
+
continue
|
|
264
|
+
name, zone = key.split(":", 1)
|
|
265
|
+
meta = (state.get("meta") or {}).get(key) or {}
|
|
266
|
+
eid = (apps.get(name) or [meta.get("entity")])[0] or meta.get("entity")
|
|
267
|
+
kind = meta.get("kind") or (apps.get(name) or [None, "power"])[1]
|
|
268
|
+
w, on = None, False
|
|
269
|
+
st = get_state(eid) if eid else None
|
|
270
|
+
if kind == "power":
|
|
271
|
+
try:
|
|
272
|
+
w = float(st)
|
|
273
|
+
w = w if math.isfinite(w) else None
|
|
274
|
+
except (TypeError, ValueError):
|
|
275
|
+
w = None
|
|
276
|
+
thr = max(0.2 * float(meta.get("p95_w") or MIN_W), 5.0)
|
|
277
|
+
on = bool(w is not None and w >= thr)
|
|
278
|
+
else:
|
|
279
|
+
on = st in ("on", "open")
|
|
280
|
+
out.append({"appliance": name, "zone": zone, "kind": kind, "dir": meta.get("dir"),
|
|
281
|
+
"delta_k": meta.get("delta_k"), "window": meta.get("window"), "entity": eid,
|
|
282
|
+
"w": None if w is None else round(w, 1), "on": on})
|
|
283
|
+
return out
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def zone_heat(links_now, room_ids, G_zone=None):
|
|
287
|
+
"""Per-room heat input (W) from the accepted links now, plus the electric power that moves out of
|
|
288
|
+
the shared internal gains.
|
|
289
|
+
|
|
290
|
+
A power appliance that warms a room puts its live wattage in that room. A link that cools a room
|
|
291
|
+
(fan, hood, open window) is a negative input: its learned contrast times the room's conductance to
|
|
292
|
+
the rest of the house (G_zone, W/K), applied while it is on. Returns (Iz list, moved_w).
|
|
293
|
+
"""
|
|
294
|
+
Iz = [0.0] * len(room_ids)
|
|
295
|
+
moved = 0.0
|
|
296
|
+
pos = {r: i for i, r in enumerate(room_ids)}
|
|
297
|
+
for ln in links_now:
|
|
298
|
+
i = pos.get(ln["zone"])
|
|
299
|
+
if i is None or not ln.get("on"):
|
|
300
|
+
continue
|
|
301
|
+
if ln.get("kind") == "power" and ln.get("dir") != "koel" and ln.get("w") is not None:
|
|
302
|
+
Iz[i] += float(ln["w"])
|
|
303
|
+
moved += float(ln["w"])
|
|
304
|
+
elif ln.get("dir") == "koel" and ln.get("delta_k") is not None and G_zone is not None:
|
|
305
|
+
Iz[i] += float(ln["delta_k"]) * float(G_zone[i]) # delta_k < 0 -> negative watts
|
|
306
|
+
return Iz, moved
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def payload(state, links_now):
|
|
310
|
+
"""Attributes of sensor.mpc_appliance_correlations and sensor.mpc_appliance_links (AppDaemon shape)."""
|
|
311
|
+
decisions = state.get("decisions") or {}
|
|
312
|
+
results = state.get("results") or {}
|
|
313
|
+
accepted = {k.split(":")[0]: k.split(":")[1] for k, v in decisions.items() if v == "accepted"}
|
|
314
|
+
prop = proposals(results, decisions)
|
|
315
|
+
n = int(state.get("n") or 0)
|
|
316
|
+
info = state.get("info")
|
|
317
|
+
corr_state = info or f"{len(prop)} voorstellen · {len(accepted)} geaccepteerd"
|
|
318
|
+
corr = {"proposals": prop[:10], "accepted": accepted, "checked": len(results),
|
|
319
|
+
"n_hist": state.get("n_hist") or [], "n": n, "last_scan": state.get("t"),
|
|
320
|
+
"appliances": len(state.get("appliances") or {}),
|
|
321
|
+
"how_to": "event mpc_corr: {cmd: accept|reject|scan|reset, appliance, zone}"}
|
|
322
|
+
lk_state = (f"{len(links_now)} koppeling" if len(links_now) == 1 else f"{len(links_now)} koppelingen") \
|
|
323
|
+
if links_now else "geen koppelingen"
|
|
324
|
+
lk = {"links": links_now, "fan_bands": state.get("fan_bands") or {},
|
|
325
|
+
"how_to": "accepteer/verwerp via event mpc_corr; dagelijkse scan om 04:00"}
|
|
326
|
+
return corr_state, corr, lk_state, lk
|
moprecont/blinds.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Pure port of the AppDaemon blinds logic (mpc_actuators.py BLIND_DEFAULTS, daylight,
|
|
2
|
+
blind_model's write side). No Home Assistant imports: engine feeds grid/readings in,
|
|
3
|
+
actuators.py writes cover/set_cover_position (only when the marker switch is on).
|
|
4
|
+
"""
|
|
5
|
+
import math
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
BLIND_DEFAULTS = {
|
|
11
|
+
"entity": None,
|
|
12
|
+
"toggle": None,
|
|
13
|
+
"zone": None,
|
|
14
|
+
"levels": [0, 25, 50, 75, 100],
|
|
15
|
+
"min_day": 100, # in daylight open, unless it is a warm day (shade_tout)
|
|
16
|
+
"shade_tout": 15.0, # daytime shading only when the day's max outdoor temp exceeds this
|
|
17
|
+
"min_move_minutes": 60, # at least this long between two MPC moves in daylight
|
|
18
|
+
"night_closed": True, # closed after sunset, open after sunrise
|
|
19
|
+
"override_hours": 4,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def merge_blinds(user):
|
|
24
|
+
if user is None:
|
|
25
|
+
return None
|
|
26
|
+
cfg = dict(BLIND_DEFAULTS, **(user or {}))
|
|
27
|
+
if not cfg.get("entity"):
|
|
28
|
+
return None
|
|
29
|
+
return cfg
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def daylight(grid, lat=52.2, lon=6.9):
|
|
33
|
+
"""Sun above the horizon (simple solar position), per grid step. Port of daylight()."""
|
|
34
|
+
lat = math.radians(float(lat))
|
|
35
|
+
lon = float(lon)
|
|
36
|
+
out = np.zeros(len(grid), bool)
|
|
37
|
+
for k, t in enumerate(np.asarray(grid, float) + 900 / 2):
|
|
38
|
+
d = datetime.fromtimestamp(t, timezone.utc)
|
|
39
|
+
n = d.timetuple().tm_yday
|
|
40
|
+
decl = math.radians(23.44) * math.sin(2 * math.pi * (284 + n) / 365)
|
|
41
|
+
hour = d.hour + d.minute / 60 + lon / 15
|
|
42
|
+
ha = math.radians(15 * (hour - 12))
|
|
43
|
+
el = math.asin(math.sin(lat) * math.sin(decl) + math.cos(lat) * math.cos(decl) * math.cos(ha))
|
|
44
|
+
out[k] = el > math.radians(-2)
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def blind_decision(cfg, *, now, day, tmax_today=None, cur=None, override_until=0.0,
|
|
49
|
+
last_move=0.0, active=True):
|
|
50
|
+
"""Cover position to write now, whether it is a fixed night/day transition, and why.
|
|
51
|
+
|
|
52
|
+
Returns (position|None, fixed, reason). None = leave the blinds alone.
|
|
53
|
+
Night -> closed (privacy), normal day -> open; only on a warm day (day max outdoor >
|
|
54
|
+
shade_tout) may the blinds shade (position 0), at most once per min_move_minutes.
|
|
55
|
+
"""
|
|
56
|
+
if not cfg:
|
|
57
|
+
return None, True, None
|
|
58
|
+
night_pos = 0.0 if cfg.get("night_closed", True) else 100.0
|
|
59
|
+
base = 100.0 if day else night_pos
|
|
60
|
+
warm = tmax_today is not None and float(tmax_today) > float(cfg.get("shade_tout", 15.0))
|
|
61
|
+
fixed = not (day and warm)
|
|
62
|
+
if now < float(override_until) and cur is not None:
|
|
63
|
+
return float(cur), True, "handmatig bediend"
|
|
64
|
+
if not active:
|
|
65
|
+
return (float(cur) if cur is not None else base), True, "zonwering niet onder MPC"
|
|
66
|
+
if fixed:
|
|
67
|
+
return base, True, "nacht/dag stand"
|
|
68
|
+
calm = now - float(last_move) >= float(cfg.get("min_move_minutes", 60)) * 60
|
|
69
|
+
if calm and (cur is None or abs(float(cur) - 0.0) >= 5):
|
|
70
|
+
return 0.0, False, "zonwering (warme dag)"
|
|
71
|
+
return None, False, "beweegt niet (min_move_minutes)"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def blind_model(cfg, grid, T_o, zone_index, *, cur=None, override_until=0.0, writes=True,
|
|
75
|
+
lat=52.2, lon=6.9):
|
|
76
|
+
"""Blinds model for the optimiser (AppDaemon blind_model).
|
|
77
|
+
|
|
78
|
+
Night: closed (privacy, night_closed). A cold day: open all daylight (sun on the windows is a gain).
|
|
79
|
+
Only on a warm day (forecast maximum above shade_tout) may the optimiser choose a daylight position
|
|
80
|
+
from ``levels``; moves cost w_move_blind in the plan. A manual move fixes the current position until
|
|
81
|
+
the override ends; without MPC writing the first half hour stays as it is.
|
|
82
|
+
"""
|
|
83
|
+
import datetime as _dt
|
|
84
|
+
grid = np.asarray(grid, float)
|
|
85
|
+
day = daylight(grid, lat, lon)
|
|
86
|
+
night_pos = 0.0 if cfg.get("night_closed", True) else 100.0
|
|
87
|
+
base = np.where(day, 100.0, night_pos)
|
|
88
|
+
dates = [_dt.date.fromtimestamp(float(t)) for t in grid]
|
|
89
|
+
tmax = {}
|
|
90
|
+
for d, v in zip(dates, T_o):
|
|
91
|
+
tmax[d] = max(tmax.get(d, -99.0), float(v))
|
|
92
|
+
close_ok = np.array([tmax[d] > float(cfg.get("shade_tout", 15.0)) for d in dates])
|
|
93
|
+
fixed = np.where(day & close_ok, np.nan, base)
|
|
94
|
+
reason = None
|
|
95
|
+
now = float(grid[0])
|
|
96
|
+
if now < float(override_until) and cur is not None:
|
|
97
|
+
fixed[grid < float(override_until)] = float(cur)
|
|
98
|
+
reason = "handmatig bediend"
|
|
99
|
+
elif not writes and cur is not None:
|
|
100
|
+
fixed[:2] = float(cur)
|
|
101
|
+
return {"zone": int(zone_index), "levels": [float(x) for x in cfg.get("levels") or [0, 25, 50, 75, 100]],
|
|
102
|
+
"base": base, "fixed": fixed, "fc": float(cfg.get("fc_closed", 0.65)),
|
|
103
|
+
"dH": float(cfg.get("dH_closed", 0.0)), "day": day, "close_ok": close_ok,
|
|
104
|
+
"min_day": float(cfg.get("min_day", 100)), "current": cur, "reason": reason}
|
moprecont/control.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Control decisions for the HACS integration (fase 3) — pure python, no HA imports.
|
|
2
|
+
|
|
3
|
+
Simplified ports of the AppDaemon engine's master-thermostat gate and DHW/boiler logic:
|
|
4
|
+
- gate_decision(): does the plan need enough heat in the next 30 min to run the heat pump?
|
|
5
|
+
Hysteresis via the persisted ``prev`` ("on"/"off"/None).
|
|
6
|
+
- boiler_target(): price-band boiler setpoint with a comfort floor on a cold tank.
|
|
7
|
+
|
|
8
|
+
Both are gated at the caller (actuators.py) by switch.mpc_heating_active — never called
|
|
9
|
+
for writing while the marker is off.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def gate_decision(need_w, prev=None, gate_on_w=400.0, gate_off_w=100.0):
|
|
14
|
+
"""Master thermostat gate: "on" when the plan needs >= gate_on_w in the next 30 min,
|
|
15
|
+
"off" below gate_off_w, otherwise keep the previous state (hysteresis)."""
|
|
16
|
+
if need_w >= gate_on_w:
|
|
17
|
+
return "on"
|
|
18
|
+
if need_w <= gate_off_w:
|
|
19
|
+
return "off"
|
|
20
|
+
return prev
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def master_setpoint(gate, master_temp, house_avg, offset=0.8, lower_k=0.3):
|
|
24
|
+
"""Setpoint for the master thermostat given the gate decision.
|
|
25
|
+
|
|
26
|
+
on: clearly above max(master_temp, house_avg) + offset -> heat pump runs
|
|
27
|
+
off: 1 K under min(master_temp, house_avg) -> heat pump stops
|
|
28
|
+
"""
|
|
29
|
+
if gate == "on":
|
|
30
|
+
return round(max(master_temp, house_avg) + offset, 2)
|
|
31
|
+
if gate == "off":
|
|
32
|
+
return round(min(master_temp, house_avg) - 1.0, 2)
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def boiler_target(bands, price, tank_temp=None, comfort_floor_c=50.0, very_cheap=0.05,
|
|
37
|
+
price_ref=0.45, min_c=45.0, max_c=60.0):
|
|
38
|
+
"""DHW boiler setpoint from price bands + comfort floor.
|
|
39
|
+
|
|
40
|
+
bands: [[share, temp_c], ...] with share = upper quantile of the (normalised) price at
|
|
41
|
+
which that temperature applies, e.g. [[0.15, 60], [0.35, 55], ..., [1.01, 45]].
|
|
42
|
+
price is normalised against [very_cheap, price_ref]; a tank below comfort_floor_c lifts
|
|
43
|
+
the target to the floor. Result is clamped to [min_c, max_c].
|
|
44
|
+
"""
|
|
45
|
+
norm = (price - very_cheap) / max(price_ref - very_cheap, 1e-6)
|
|
46
|
+
norm = min(max(norm, 0.0), 1.0)
|
|
47
|
+
target = None
|
|
48
|
+
for share, temp in sorted(bands, key=lambda b: b[0]):
|
|
49
|
+
if norm <= share:
|
|
50
|
+
target = float(temp)
|
|
51
|
+
break
|
|
52
|
+
if target is None:
|
|
53
|
+
target = float(bands[-1][1]) if bands else min_c
|
|
54
|
+
if tank_temp is not None and tank_temp < comfort_floor_c:
|
|
55
|
+
target = max(target, comfort_floor_c)
|
|
56
|
+
return round(min(max(target, min_c), max_c), 1)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def override_until(now, override_hours=1.0, next_pattern_change=None, max_h=12.0):
|
|
60
|
+
"""End of a manual zone change (AppDaemon MPCEngine.override_until): the next change in the week
|
|
61
|
+
pattern, but at least ``override_hours`` and at most ``max_h`` hours ahead.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
now: epoch seconds of the manual change.
|
|
65
|
+
override_hours: minimum duration of the override.
|
|
66
|
+
next_pattern_change: epoch of the next scheduled setpoint change in the week pattern, or None.
|
|
67
|
+
max_h: upper bound of the override window.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
Epoch until which MPC leaves the zone alone.
|
|
71
|
+
"""
|
|
72
|
+
lo = now + float(override_hours) * 3600.0
|
|
73
|
+
hi = now + float(max_h) * 3600.0
|
|
74
|
+
if next_pattern_change is not None and lo <= next_pattern_change <= hi:
|
|
75
|
+
return float(next_pattern_change)
|
|
76
|
+
return lo
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def master_write_decision(now, writes, day_key=None, quota=30, override_until_ts=0.0,
|
|
80
|
+
min_interval_s=1800.0, last_write_ts=0.0):
|
|
81
|
+
"""May MPC write the master thermostat now? (AppDaemon master-write quota + override, mpc_engine).
|
|
82
|
+
|
|
83
|
+
The master thermostat cloud API has a daily quota and may only be polled hourly at night, so writes
|
|
84
|
+
are limited to ``quota`` per day, at most one per ``min_interval_s``, and never while a manual change
|
|
85
|
+
holds (``override_until_ts``).
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
now: epoch seconds.
|
|
89
|
+
writes: {"day": <iso date>, "n": <count>} persisted counter (mutated when a write is allowed).
|
|
90
|
+
day_key: iso date of ``now``; when it differs from writes["day"] the counter resets.
|
|
91
|
+
quota: master_max_writes per day.
|
|
92
|
+
override_until_ts: manual-change hold on the master, epoch until which no write happens.
|
|
93
|
+
min_interval_s: minimum time since the last write.
|
|
94
|
+
last_write_ts: epoch of the last master write.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
(allowed, reason). When allowed, the caller must record the write (writes["n"] += 1).
|
|
98
|
+
"""
|
|
99
|
+
if day_key is None:
|
|
100
|
+
from datetime import datetime as _dt
|
|
101
|
+
day_key = _dt.fromtimestamp(now).date().isoformat()
|
|
102
|
+
writes = writes if isinstance(writes, dict) else {}
|
|
103
|
+
if writes.get("day") != day_key:
|
|
104
|
+
writes["day"] = day_key
|
|
105
|
+
writes["n"] = 0
|
|
106
|
+
if now < float(override_until_ts or 0.0):
|
|
107
|
+
return False, "handmatige wijziging van de master thermostaat"
|
|
108
|
+
if writes.get("n", 0) >= int(quota):
|
|
109
|
+
return False, f"dagbudget van {quota} schrijfacties bereikt"
|
|
110
|
+
if last_write_ts and now - float(last_write_ts) < float(min_interval_s):
|
|
111
|
+
return False, "minder dan 30 min sinds de laatste master-schrijfactie"
|
|
112
|
+
return True, None
|