moprecont 0.1.0__tar.gz

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.
Files changed (44) hide show
  1. moprecont-0.1.0/.github/workflows/publish.yml +38 -0
  2. moprecont-0.1.0/.github/workflows/tests.yml +15 -0
  3. moprecont-0.1.0/.gitignore +5 -0
  4. moprecont-0.1.0/LICENSE +21 -0
  5. moprecont-0.1.0/PKG-INFO +76 -0
  6. moprecont-0.1.0/README.md +51 -0
  7. moprecont-0.1.0/pyproject.toml +42 -0
  8. moprecont-0.1.0/src/moprecont/__init__.py +7 -0
  9. moprecont-0.1.0/src/moprecont/appliances.py +326 -0
  10. moprecont-0.1.0/src/moprecont/blinds.py +104 -0
  11. moprecont-0.1.0/src/moprecont/control.py +112 -0
  12. moprecont-0.1.0/src/moprecont/cooling.py +200 -0
  13. moprecont-0.1.0/src/moprecont/core/__init__.py +1 -0
  14. moprecont-0.1.0/src/moprecont/core/mpc_core.py +1533 -0
  15. moprecont-0.1.0/src/moprecont/core/mpc_learn.py +448 -0
  16. moprecont-0.1.0/src/moprecont/core/mpc_trust.py +123 -0
  17. moprecont-0.1.0/src/moprecont/criteria.py +115 -0
  18. moprecont-0.1.0/src/moprecont/cycles.py +63 -0
  19. moprecont-0.1.0/src/moprecont/dhw.py +170 -0
  20. moprecont-0.1.0/src/moprecont/ensemble.py +461 -0
  21. moprecont-0.1.0/src/moprecont/ev.py +37 -0
  22. moprecont-0.1.0/src/moprecont/fan.py +155 -0
  23. moprecont-0.1.0/src/moprecont/fitdata.py +280 -0
  24. moprecont-0.1.0/src/moprecont/fitpipe.py +219 -0
  25. moprecont-0.1.0/src/moprecont/forecast.py +162 -0
  26. moprecont-0.1.0/src/moprecont/health.py +649 -0
  27. moprecont-0.1.0/src/moprecont/heatflows.py +166 -0
  28. moprecont-0.1.0/src/moprecont/house.py +256 -0
  29. moprecont-0.1.0/src/moprecont/learn.py +287 -0
  30. moprecont-0.1.0/src/moprecont/live.py +113 -0
  31. moprecont-0.1.0/src/moprecont/network.py +140 -0
  32. moprecont-0.1.0/src/moprecont/outlook.py +338 -0
  33. moprecont-0.1.0/src/moprecont/pareto.py +50 -0
  34. moprecont-0.1.0/src/moprecont/plan.py +171 -0
  35. moprecont-0.1.0/src/moprecont/price.py +221 -0
  36. moprecont-0.1.0/src/moprecont/ring.py +194 -0
  37. moprecont-0.1.0/src/moprecont/trust.py +86 -0
  38. moprecont-0.1.0/tests/test_control.py +62 -0
  39. moprecont-0.1.0/tests/test_mpc_core.py +89 -0
  40. moprecont-0.1.0/tests/test_outlook.py +151 -0
  41. moprecont-0.1.0/tests/test_pareto.py +73 -0
  42. moprecont-0.1.0/tests/test_plan.py +121 -0
  43. moprecont-0.1.0/tests/test_price.py +121 -0
  44. moprecont-0.1.0/tests/test_trust_learn.py +80 -0
@@ -0,0 +1,38 @@
1
+ # Publishes to PyPI on a version tag (v0.1.0, ...) with PyPI trusted publishing: no token in the repo.
2
+ # One-time on pypi.org (account kwabratseur): Publishing → Add a pending publisher →
3
+ # project moprecont, owner Kwabratseur, repository moprecont, workflow publish.yml, environment pypi.
4
+ name: publish
5
+ on:
6
+ push:
7
+ tags: ["v*"]
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-python@v5
14
+ with:
15
+ python-version: "3.13"
16
+ - run: pip install build pytest numpy
17
+ - run: |
18
+ tag="${GITHUB_REF_NAME#v}"
19
+ ver=$(python -c "import re;print(re.search(r'__version__ = \"(.+)\"', open('src/moprecont/__init__.py').read()).group(1))")
20
+ test "$tag" = "$ver" || { echo "::error::tag $tag != __version__ $ver"; exit 1; }
21
+ - run: pip install -e . && pytest -q
22
+ - run: python -m build
23
+ - uses: actions/upload-artifact@v4
24
+ with:
25
+ name: dist
26
+ path: dist/
27
+ pypi:
28
+ needs: build
29
+ runs-on: ubuntu-latest
30
+ environment: pypi
31
+ permissions:
32
+ id-token: write
33
+ steps:
34
+ - uses: actions/download-artifact@v4
35
+ with:
36
+ name: dist
37
+ path: dist/
38
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,15 @@
1
+ name: tests
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ runs-on: ubuntu-latest
6
+ strategy:
7
+ matrix:
8
+ python: ["3.12", "3.13"]
9
+ steps:
10
+ - uses: actions/checkout@v4
11
+ - uses: actions/setup-python@v5
12
+ with:
13
+ python-version: ${{ matrix.python }}
14
+ - run: pip install -e .[test]
15
+ - run: pytest -q
@@ -0,0 +1,5 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ build/
5
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kwabratseur
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.5
2
+ Name: moprecont
3
+ Version: 0.1.0
4
+ Summary: Model predictive control for building heating: thermal RC model, nightly fit, 36 h optimiser and 7-day outlook (the engine behind HeatMind for Home Assistant)
5
+ Project-URL: Homepage, https://github.com/Kwabratseur/moprecont
6
+ Project-URL: Issues, https://github.com/Kwabratseur/moprecont/issues
7
+ Project-URL: Home Assistant integration, https://github.com/Kwabratseur/HeatMind
8
+ Author: Kwabratseur
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: heat pump,heating,home assistant,model predictive control,mpc,thermal model
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Home Automation
19
+ Classifier: Topic :: Scientific/Engineering
20
+ Requires-Python: >=3.12
21
+ Requires-Dist: numpy>=1.26
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest>=8; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # moprecont
27
+
28
+ **Mo**del **pre**dictive **cont**rol for building heating, as a plain Python library (numpy only).
29
+ It is the engine behind [HeatMind](https://github.com/Kwabratseur/HeatMind), the Home Assistant
30
+ integration, split out so it can be tested, reused and simulated outside Home Assistant.
31
+
32
+ ```
33
+ pip install moprecont
34
+ ```
35
+
36
+ ## What is in it
37
+
38
+ | Module | What it does |
39
+ |---|---|
40
+ | `moprecont.core.mpc_core` | Thermal RC network per room (rooms, floor masses, attic, outside), heat pump with COP and supply temperature, simulation, Kalman state estimation, the nightly fit (regularised Levenberg-Marquardt on 24 h free-run error) and the optimiser |
41
+ | `moprecont.core.mpc_trust` | Graded authority: how far the plan may deviate, from tracked prediction error |
42
+ | `moprecont.core.mpc_learn` | Learning mode: deliberate setpoint/supply variations that make the fit identifiable |
43
+ | `moprecont.plan` | One planning cycle (36 h, 15-min steps): context, optimiser, plan summary |
44
+ | `moprecont.outlook`, `moprecont.ensemble` | 7-day ensemble outlook (40 members), cold snap / heatwave / expensive stretch / mild spell, EV windows, battery plan, power-cut hours |
45
+ | `moprecont.fitdata`, `moprecont.fitpipe` | Dataset from a week of history, fit pipeline with acceptance rules |
46
+ | `moprecont.price` | Ridge price model (wind, sun, hour, weekday) beyond the day-ahead prices |
47
+ | `moprecont.heatflows`, `moprecont.network` | Heat balance per room, RC network for display |
48
+ | `moprecont.cooling`, `moprecont.fan`, `moprecont.blinds`, `moprecont.dhw`, `moprecont.ev` | Cooling above the dew point, ventilation, blinds, hot water, EV |
49
+ | `moprecont.trust`, `moprecont.learn`, `moprecont.appliances` | Trust bookkeeping, learning cycles, appliance-to-room learning |
50
+ | `moprecont.health`, `moprecont.cycles`, `moprecont.ring`, `moprecont.forecast`, `moprecont.house` | Health checks, compressor cycles, past ring buffer, forecast parsing, house description |
51
+
52
+ ## Minimal example
53
+
54
+ ```python
55
+ from moprecont import plan
56
+
57
+ house = {"rooms": [
58
+ {"id": "living", "name": "Living", "floor": 0, "controlled": True, "envelope": 14.0,
59
+ "emitter": 60.0, "solar": 0.6, "internal": 0.6, "neighbours": ["bed"]},
60
+ {"id": "bed", "name": "Bedroom", "floor": 1, "controlled": True, "envelope": 10.0,
61
+ "emitter": 40.0, "solar": 0.4, "internal": 0.4, "neighbours": ["living"]},
62
+ ]}
63
+ # floor envelope 2.9 W/K, calibration 1.0; 36 h ahead at a flat 0.25 EUR/kWh
64
+ out = plan.run_shadow_plan(house, 2.9, 1.0, zone_temps=[20.5, 19.8], zone_setpoints=[21.0, 20.5],
65
+ t_out=5.0, t_att=10.0, price=0.25, horizon_h=36)
66
+ terms = out["plan"]["terms"]
67
+ print(f"{terms['kwh']:.1f} kWh, EUR {terms['energie']:.2f} planned")
68
+ ```
69
+
70
+ ## Status
71
+
72
+ 0.x: the API follows what HeatMind needs and may change between minor versions. The modules were
73
+ moved from the HeatMind integration unchanged apart from package-relative imports; HeatMind will
74
+ depend on a pinned version.
75
+
76
+ MIT licensed. AI assistance in development is disclosed in the HeatMind repository.
@@ -0,0 +1,51 @@
1
+ # moprecont
2
+
3
+ **Mo**del **pre**dictive **cont**rol for building heating, as a plain Python library (numpy only).
4
+ It is the engine behind [HeatMind](https://github.com/Kwabratseur/HeatMind), the Home Assistant
5
+ integration, split out so it can be tested, reused and simulated outside Home Assistant.
6
+
7
+ ```
8
+ pip install moprecont
9
+ ```
10
+
11
+ ## What is in it
12
+
13
+ | Module | What it does |
14
+ |---|---|
15
+ | `moprecont.core.mpc_core` | Thermal RC network per room (rooms, floor masses, attic, outside), heat pump with COP and supply temperature, simulation, Kalman state estimation, the nightly fit (regularised Levenberg-Marquardt on 24 h free-run error) and the optimiser |
16
+ | `moprecont.core.mpc_trust` | Graded authority: how far the plan may deviate, from tracked prediction error |
17
+ | `moprecont.core.mpc_learn` | Learning mode: deliberate setpoint/supply variations that make the fit identifiable |
18
+ | `moprecont.plan` | One planning cycle (36 h, 15-min steps): context, optimiser, plan summary |
19
+ | `moprecont.outlook`, `moprecont.ensemble` | 7-day ensemble outlook (40 members), cold snap / heatwave / expensive stretch / mild spell, EV windows, battery plan, power-cut hours |
20
+ | `moprecont.fitdata`, `moprecont.fitpipe` | Dataset from a week of history, fit pipeline with acceptance rules |
21
+ | `moprecont.price` | Ridge price model (wind, sun, hour, weekday) beyond the day-ahead prices |
22
+ | `moprecont.heatflows`, `moprecont.network` | Heat balance per room, RC network for display |
23
+ | `moprecont.cooling`, `moprecont.fan`, `moprecont.blinds`, `moprecont.dhw`, `moprecont.ev` | Cooling above the dew point, ventilation, blinds, hot water, EV |
24
+ | `moprecont.trust`, `moprecont.learn`, `moprecont.appliances` | Trust bookkeeping, learning cycles, appliance-to-room learning |
25
+ | `moprecont.health`, `moprecont.cycles`, `moprecont.ring`, `moprecont.forecast`, `moprecont.house` | Health checks, compressor cycles, past ring buffer, forecast parsing, house description |
26
+
27
+ ## Minimal example
28
+
29
+ ```python
30
+ from moprecont import plan
31
+
32
+ house = {"rooms": [
33
+ {"id": "living", "name": "Living", "floor": 0, "controlled": True, "envelope": 14.0,
34
+ "emitter": 60.0, "solar": 0.6, "internal": 0.6, "neighbours": ["bed"]},
35
+ {"id": "bed", "name": "Bedroom", "floor": 1, "controlled": True, "envelope": 10.0,
36
+ "emitter": 40.0, "solar": 0.4, "internal": 0.4, "neighbours": ["living"]},
37
+ ]}
38
+ # floor envelope 2.9 W/K, calibration 1.0; 36 h ahead at a flat 0.25 EUR/kWh
39
+ out = plan.run_shadow_plan(house, 2.9, 1.0, zone_temps=[20.5, 19.8], zone_setpoints=[21.0, 20.5],
40
+ t_out=5.0, t_att=10.0, price=0.25, horizon_h=36)
41
+ terms = out["plan"]["terms"]
42
+ print(f"{terms['kwh']:.1f} kWh, EUR {terms['energie']:.2f} planned")
43
+ ```
44
+
45
+ ## Status
46
+
47
+ 0.x: the API follows what HeatMind needs and may change between minor versions. The modules were
48
+ moved from the HeatMind integration unchanged apart from package-relative imports; HeatMind will
49
+ depend on a pinned version.
50
+
51
+ MIT licensed. AI assistance in development is disclosed in the HeatMind repository.
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "moprecont"
7
+ dynamic = ["version"]
8
+ description = "Model predictive control for building heating: thermal RC model, nightly fit, 36 h optimiser and 7-day outlook (the engine behind HeatMind for Home Assistant)"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Kwabratseur" }]
13
+ requires-python = ">=3.12"
14
+ dependencies = ["numpy>=1.26"]
15
+ keywords = ["mpc", "model predictive control", "heating", "heat pump", "home assistant", "thermal model"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Home Automation",
24
+ "Topic :: Scientific/Engineering",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/Kwabratseur/moprecont"
29
+ Issues = "https://github.com/Kwabratseur/moprecont/issues"
30
+ "Home Assistant integration" = "https://github.com/Kwabratseur/HeatMind"
31
+
32
+ [project.optional-dependencies]
33
+ test = ["pytest>=8"]
34
+
35
+ [tool.hatch.version]
36
+ path = "src/moprecont/__init__.py"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/moprecont"]
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
@@ -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"
@@ -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