Recalibrate only the model parts whose configuration changed

Confirmed: learned models were matched only by zone key, so replacing a
zone's sensors, changing sensor weights, moving or replacing a heat
source or turning a window kept coefficients learned for a different
configuration, silently.

compatibility.py fingerprints exactly what each learned component
depends on: the zone measurement (sensors and relative weights; equal
scaling changes nothing), each zone's heat sources, the neighbour's
measurement, the zone's windows, window orientation (direction term
only), the recovery time (recovery only) and other zones' openings
(cross term only). Comfort weight, target offset and names are not
included. Heat-source baselines have their own fingerprint (sensor and
included sources).

On restore, a changed measurement recalibrates the zone: base and
extended loss/heat/bias keep their values as a warm start, but their
uncertainty, counts and readiness start over, other terms return to the
prior, and the zone's forecast statistics are dropped. Otherwise only
the changed terms are reset; everything else, including other zones,
is kept. Each recalibration is logged (Status model_changes, info log)
and saved at once. Data from before fingerprints (0.4.0) is assumed to
match its current configuration and is fingerprinted at the first
start, so the next edit is detected even before a learned sample.

Tests cover comfort changes, sensor replacement and weights, window
orientation and size, moved and replaced heat sources, re-added zones,
0.4.0 data and a second restart, plus an HA Core test through real
subentry updates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
buzeraandClaude Opus 5.5 committed 2026-10-27 03:35:11 +02:00
1 parent 9bb64e79ca
commit 099c63cd02
10 files changed
+475 -25

No files matched your search

+106
View File
@@ -1087,3 +1087,109 @@ class BoundaryTests(unittest.IsolatedAsyncioTestCase):
self.assertLess(model.ventilation_delta(20.0, {'outside': 5.0, 'ventilation': {**inputs, 'opening': 1.0}}), -0.1)
window = data['windows']['Bedroom window']
self.assertEqual((window['state'], window['last_known_state'], window['unknown_minutes']), ('open', 'open', None))
ZONES = [{'key': 'living', 'name': 'Living', 'sensors': ['sensor.room'], 'neighbors': ['bed']},
{'key': 'bed', 'name': 'Bedroom', 'sensors': ['sensor.bedroom']}]
SOURCES = [{'key': 'ups', 'name': 'UPS', 'sensor': 'sensor.ups_power', 'zone': 'living'}]
WINDOWS = [{'key': 'w', 'name': 'Bed window', 'sensor': 'binary_sensor.bed_window', 'zone': 'bed',
'azimuth': 345}]
def configured(self, zones=None, sources=None, windows=None):
self.entry.data.update(outside_wind_sources=['sensor.wind'], outside_wind_direction_sources=['sensor.wind_dir'])
self.entry.subentries = {}
for kind, items in (('zone', zones or self.ZONES), ('heat_source', self.SOURCES if sources is None else sources),
('window', self.WINDOWS if windows is None else windows)):
for i, data in enumerate(items):
self.entry.subentries[f'{kind}{i}'] = types.SimpleNamespace(
subentry_id=f'{kind}{i}', subentry_type=kind, data=data)
return coordinator.HeatingMPCCoordinator(self.hass, self.entry)
def trained_payload(self):
c = self.configured()
for key in ('living', 'bed'):
base = c.learners[key]
base.count, base.on_count, base.off_count, base.theta = 300, 100, 100, [0.004, 0.12, 0.001]
living = c.extended['living']
living.count, living.on_count, living.off_count = 300, 100, 100
living.theta = [0.004, 0.12, 0.001, 0.15, 0.008]
vent = c.ventilation['bed']
vent.count = 80
vent.theta[vent.features.index('vent_natural')] = 0.01
vent.theta[vent.features.index('vent_wind_dir')] = 0.0005
c._evaluator._days = {'2026-10-27': {'60': {'living': [10, 0.1, 0.2, 0.3, 0.4],
'bed': [10, 0.1, 0.2, 0.3, 0.4]}}}
c._heat_sources._baselines['ups'].samples.extend([200.0] * 24)
return c._payload('sensor.outside')
async def restored(self, payload, **config):
c = self.configured(**config)
c._store.async_load.return_value = payload
await c.async_restore_model()
return c
async def test_comfort_settings_keep_every_learned_coefficient(self):
payload = self.trained_payload()
zones = [{**self.ZONES[0], 'name': 'Lounge', 'comfort_weight': 4, 'target_offset': 1},
{**self.ZONES[1], 'comfort_weight': 0.5}]
c = await self.restored(payload, zones=zones)
self.assertEqual((c.learners['living'].count, c.extended['living'].theta, c.ventilation['bed'].count),
(300, [0.004, 0.12, 0.001, 0.15, 0.008], 80))
self.assertEqual(list(c._model_changes), [])
c._store.async_save.assert_not_called()
async def test_changed_zone_sensors_recalibrate_only_that_zone(self):
payload = self.trained_payload()
zones = [{**self.ZONES[0], 'sensors': ['sensor.room', 'sensor.second']}, self.ZONES[1]]
c = await self.restored(payload, zones=zones)
base = c.learners['living']
self.assertEqual((base.theta, base.count, base.p), ([0.004, 0.12, 0.001], 0, coordinator.Learner().p)) # prior uncertainty
living = c.extended['living']
self.assertEqual((living.count, living.theta[:3], living.coefficient('internal')), (0, [0.004, 0.12, 0.001], 0.0))
# The bedroom keeps its model; only its exchange term with the living room restarts.
self.assertEqual((c.learners['bed'].count, c.ventilation['bed'].count), (300, 80))
self.assertEqual(c.extended['bed'].coefficient('couple:living'), 0.0)
self.assertEqual(set(c._evaluator._days['2026-10-27']['60']), {'bed'}) # living measured differently now
change = next(ch for ch in c._model_changes if ch.get('zone') == 'Living')
self.assertEqual(change['reasons'], ['zone sensors or sensor weights changed'])
# Saved at once with the new fingerprints: another restart changes nothing.
saved = c._store.async_save.call_args.args[0]
again = await self.restored(saved, zones=zones)
self.assertEqual(len(again._model_changes), len(c._model_changes))
again._store.async_save.assert_not_called()
async def test_turned_window_resets_only_the_direction_term(self):
payload = self.trained_payload()
c = await self.restored(payload, windows=[{**self.WINDOWS[0], 'azimuth': 300}])
vent = c.ventilation['bed']
self.assertEqual((vent.coefficient('vent_natural'), vent.coefficient('vent_wind_dir'), vent.count),
(0.01, 0.0, 80))
self.assertEqual((c.learners['bed'].count, c.extended['living'].coefficient('internal')), (300, 0.15))
self.assertEqual(c._model_changes[-1]['reasons'], ['window orientation changed'])
async def test_moved_or_replaced_heat_source(self):
payload = self.trained_payload()
c = await self.restored(payload, sources=[{**self.SOURCES[0], 'zone': 'bed'}])
self.assertEqual(c.extended['living'].coefficient('internal'), 0.0)
self.assertEqual(c.extended['living'].coefficient('couple:bed'), 0.008) # unrelated term kept
self.assertEqual(c.extended['bed'].coefficient('internal'), 0.0) # new there, from the prior
self.assertEqual(len(c._heat_sources._baselines['ups'].samples), 24) # same sensor: same load
replaced = await self.restored(payload, sources=[{**self.SOURCES[0], 'sensor': 'sensor.ups2'}])
self.assertEqual(len(replaced._heat_sources._baselines['ups'].samples), 0)
self.assertEqual(replaced.extended['living'].coefficient('internal'), 0.0)
self.assertIn('baseline', replaced._model_changes[-1]['recalibrated'])
async def test_v040_data_without_fingerprints_is_kept_and_then_fingerprinted(self):
payload = self.trained_payload()
del payload['fingerprints']
c = await self.restored(payload)
self.assertEqual((c.learners['living'].count, c.extended['living'].coefficient('internal')), (300, 0.15))
# Fingerprinted at once, so an edit right after the upgrade is detected.
self.assertEqual(c._store.async_save.call_args.args[0]['fingerprints'], c._fingerprints)
async def test_re_added_zone_with_other_sensors_is_recalibrated(self):
payload = self.trained_payload()
without = await self.restored(payload, zones=[self.ZONES[1]], sources=[])
self.assertIn('living', without._retired)
saved = without._payload('sensor.outside')
back = await self.restored(saved, zones=[{**self.ZONES[0], 'sensors': ['sensor.other']}, self.ZONES[1]])
self.assertEqual((back.learners['living'].theta, back.learners['living'].count), ([0.004, 0.12, 0.001], 0))