From 103df178339d5105b1706150763687432b3cf53f Mon Sep 17 00:00:00 2001 From: Jumpmaster2 Date: Sun, 29 Nov 2026 06:20:17 +0000 Subject: [PATCH] Learn floor residual heat from what really arrives (1.0.0b24) A cold room no longer waits up to four hours for a phantom peak: the carried peak is forgotten once the maximum stalls for a learned dead time (earlier below the switch-on threshold). Expected overshoot saturates at one dead time and is corrected by bounded feedback from expected versus observed peaks, with a conservative migration of the old linear rate. Peaks disturbed by windows, draft, showers (humidity jump), sun or pipe heat are not learned. The AI sees the last expected and real peak. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + .../house_assistant/heating/coordinator.py | 48 ++- .../heating/logic/ai_policy.py | 9 + .../heating/logic/controller.py | 59 +++- .../house_assistant/heating/logic/learning.py | 163 ++++++++-- .../house_assistant/heating/logic/peaks.py | 19 ++ .../house_assistant/heating/logic/prompts.py | 11 +- .../house_assistant/manifest.json | 2 +- docs/heating.en.md | 2 +- docs/heating.md | 2 +- tests/heating/logic/test_overshoot.py | 297 ++++++++++++++++++ tests/heating/logic/test_pipe_coordinator.py | 33 ++ tests/heating/logic/test_pipe_heat.py | 7 +- 13 files changed, 596 insertions(+), 64 deletions(-) create mode 100644 custom_components/house_assistant/heating/logic/peaks.py create mode 100644 tests/heating/logic/test_overshoot.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bea4b98..4a8cde7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.0.0b24 (2026-11-29) + +### Fixed + +- Forget residual heat peaks that fail to arrive once the observed maximum stalls for a learned dead time, allowing cold rooms to heat again; keep the early end after a temperature fall and the four-hour absolute limit. +- Saturate predicted overshoot at one learned dead time, with bounded feedback from clean observed peaks and a conservative migration of legacy learning. Long heating runs no longer multiply an inflated short-run rate. +- Discard overshoot events disturbed by windows, drafts, recovery, rapid room humidity rises, significant solar gain or pipe heat. The AI check now sees the last expected and observed peak and its error. + ## 1.0.0b23 (2026-11-24) ### Added diff --git a/custom_components/house_assistant/heating/coordinator.py b/custom_components/house_assistant/heating/coordinator.py index 1c75e15..bf70fb8 100644 --- a/custom_components/house_assistant/heating/coordinator.py +++ b/custom_components/house_assistant/heating/coordinator.py @@ -165,6 +165,7 @@ humid_issue, next_interval_hours, overheat_issue, + overshoot_feedback, update_stable_count, ) from .logic.ai_schema import ( @@ -1120,7 +1121,13 @@ def _on_switch_change(self, event: Event[EventStateChangedData]) -> None: run_hours = (ts - area.on_since) / 3600 if (not turned_on and area.on_since) else 0.0 if area.learner is not None: area.learner.on_switch( - ts, area.temp, turned_on, run_hours, pipe_active=self.pipe_active(area) + ts, + area.temp, + turned_on, + run_hours, + pipe_active=self.pipe_active(area), + overshoot_factor=area.params.overshoot_factor, + sample=self._learning_sample(area, ts), ) area.on_since = ts if turned_on else None area.off_at = None if turned_on else ts @@ -1988,6 +1995,9 @@ async def _control_area( area.status = AreaStatus.ACTUATOR_UNAVAILABLE self._handle_events(area, ts, window_open_since, temp_before) + # Observe disturbances before a switch callback can finish an event. + area.learner.add_sample(self._learning_sample(area, ts)) + if area.switch_available and decision.want_on == area.switch_on: self._command_done(area) elif ( @@ -1997,27 +2007,30 @@ async def _control_area( ): await self._switch(area, decision.want_on, ts) - area.learner.add_sample( - Sample( - ts, - area.temp, - area.switch_on, - self.outdoor_temp, - self.pv_assumed, - area.airing or area.temp is None, - pv_unknown=self.pv_kw is None, - window_open=area.window_open, - opening=area.opening, - draft=area.draft, - pipe_active=self.pipe_active(area), - pipe_rate_kph=self._pipe_rate(area), - ) - ) # The virtual room first: on the first tick of a day it starts at the real # temperature even if the circuit is running at that moment. self._track_virtual(area, minutes, target) self._count(area, minutes, target, ts) + def _learning_sample(self, area: Area, ts: float) -> Sample: + """The same room/environment snapshot for periodic and switch-event learning.""" + return Sample( + ts, + area.temp, + area.switch_on, + self.outdoor_temp, + self.pv_assumed, + area.airing or area.temp is None, + pv_unknown=self.pv_kw is None, + window_open=area.window_open, + opening=area.opening, + draft=area.draft, + pipe_active=self.pipe_active(area), + pipe_rate_kph=self._pipe_rate(area), + humidity=area.humidity, + sun_factor=area.params.sun_factor, + ) + def _handle_events( self, area: Area, ts: float, open_since: float | None, temp_before: float | None ) -> None: @@ -2910,6 +2923,7 @@ async def _run_check(self) -> None: "sun": r(model.s, 3), "overshoot_k": r(area.learner.overshoot.value), "overshoot_per_h": r(area.learner.overshoot_rate.value, 3), + "last_overshoot": overshoot_feedback(area.learner.last_overshoot), "dead_time_min": r(area.learner.dead_time.value / 60, 0), "recovery_min": r(area.learner.recovery.value / 60, 0), "recovery_model": _recovery_model_payload(area.learner), diff --git a/custom_components/house_assistant/heating/logic/ai_policy.py b/custom_components/house_assistant/heating/logic/ai_policy.py index f3c189a..3b3877b 100644 --- a/custom_components/house_assistant/heating/logic/ai_policy.py +++ b/custom_components/house_assistant/heating/logic/ai_policy.py @@ -143,3 +143,12 @@ def humid_issue(humid_min: float, mould_min: float, minutes: float) -> bool: if minutes <= 0: return False return mould_min >= 30 or humid_min >= HUMID_SHARE * minutes + + +def overshoot_feedback(last: dict[str, float] | None) -> dict[str, float] | None: + """Expose the last clean peak prediction error without adding a policy parameter.""" + if last is None: + return None + return { + key: round(last[key], 3) for key in ("expected_peak", "real_peak", "error_k") if key in last + } diff --git a/custom_components/house_assistant/heating/logic/controller.py b/custom_components/house_assistant/heating/logic/controller.py index b3813b8..65495c5 100644 --- a/custom_components/house_assistant/heating/logic/controller.py +++ b/custom_components/house_assistant/heating/logic/controller.py @@ -7,15 +7,17 @@ from typing import Any from ...core.store_validation import checked, checked_fields, dataclass_schema +from .peaks import ( + PEAK_CARRY_MAX_S, + PEAK_PASSED_K, + PEAK_STALL_RISE_K, + peak_quiet, + peak_stalled, +) FROST_HYSTERESIS = 0.5 # K above the frost limit before frost protection ends RECOVERED_MARGIN = 0.1 # K below the temperature before airing counts as recovered FORCE_ON_BELOW = 1.0 # K below target: heat regardless of predictions -PEAK_PASSED_K = 0.15 # K below the highest temperature since switch-off: overshoot has arrived -# The overshoot expected at switch-off is forgotten after this at the latest. It ends -# earlier once the temperature falls again; the peak comes several dead times after -# the switch-off, so the limit is not tied to the dead time. -PEAK_CARRY_MAX_S = 4 * 3600.0 FLOOR_PULSE_PERIOD_S = 3600.0 # the floor pulses of a visit: run time per hour EPS = 1e-6 # tolerance for comparing sensor values in 0.1 K steps (21.0 - 0.1 > 20.9) @@ -127,6 +129,8 @@ class AreaRuntime: carry_peak: float | None = None # expected peak after switch-off, until it has arrived carry_max: float | None = None # highest temperature seen since switch-off carry_since: float | None = None + carry_last_rise: float | None = None # time of the last meaningful new maximum + carry_rise_max: float | None = None # reference for cumulative small sensor steps events: list[str] = field(default_factory=list) # Not stored and not restored: after a restart a stale peak must not start a carry @@ -268,12 +272,13 @@ def _update_window( return True -def _update_carry(data: ControlInput, rt: AreaRuntime) -> None: - """Keep the overshoot expected at switch-off until the temperature falls again. +def _update_carry( + data: ControlInput, params: ControlParams, learned: LearnedValues, rt: AreaRuntime +) -> None: + """Keep residual heat until its peak passes or evidently fails to arrive. - Without it the switch-on prediction starts from the current temperature, which is - below target by the very overshoot the switch-off counted on, and the circuit would - come back after the minimum off time while the floor is still delivering heat. + Initially the floor may still deliver heat. Once its maximum stalls, a phantom + peak must not keep a cold room waiting through the four-hour absolute limit. """ if data.switch_on: rt.was_on = True @@ -283,13 +288,37 @@ def _update_carry(data: ControlInput, rt: AreaRuntime) -> None: rt.was_on = False rt.carry_peak = rt.last_peak rt.carry_max = data.temp - rt.carry_since = data.now + rt.carry_since = ( + data.last_switch_change + if data.last_switch_change is not None and data.last_switch_change <= data.now + else data.now + ) + rt.carry_last_rise = rt.carry_since + rt.carry_rise_max = data.temp rt.last_peak = None - if rt.carry_peak is None or data.temp is None: + if rt.carry_peak is None: return - rt.carry_max = data.temp if rt.carry_max is None else max(rt.carry_max, data.temp) expired = rt.carry_since is None or data.now - rt.carry_since >= PEAK_CARRY_MAX_S - if expired or data.temp - rt.carry_max <= -PEAK_PASSED_K + EPS: + if expired: + rt.carry_peak = None + return + if data.temp is None: + return + # Older stores lack the progress fields; retain their original switch-off time. + if rt.carry_last_rise is None: + rt.carry_last_rise = rt.carry_since + if rt.carry_rise_max is None: + rt.carry_rise_max = rt.carry_max if rt.carry_max is not None else data.temp + if data.temp - rt.carry_rise_max >= PEAK_STALL_RISE_K - EPS: + rt.carry_last_rise = data.now + rt.carry_rise_max = data.temp + rt.carry_max = data.temp if rt.carry_max is None else max(rt.carry_max, data.temp) + stalled = peak_stalled(data.now, rt.carry_since, rt.carry_last_rise, learned.dead_time_s) + # A cold room must not wait another dead time for an already stalled phantom peak. + cold_stall = data.temp < data.target - params.hysteresis_on and peak_quiet( + data.now, rt.carry_last_rise, learned.dead_time_s + ) + if stalled or cold_stall or data.temp - rt.carry_max <= -PEAK_PASSED_K + EPS: rt.carry_peak = None @@ -419,7 +448,7 @@ def step( """Decide whether the circuit of one area should be on.""" rt.events.clear() may_switch = _may_switch(data, settings) - _update_carry(data, rt) + _update_carry(data, params, learned, rt) recovering = _update_window(data, params, learned, rt) if data.temp is None: diff --git a/custom_components/house_assistant/heating/logic/learning.py b/custom_components/house_assistant/heating/logic/learning.py index 56e5ebe..b42f6db 100644 --- a/custom_components/house_assistant/heating/logic/learning.py +++ b/custom_components/house_assistant/heating/logic/learning.py @@ -10,9 +10,8 @@ pipe_gain * pipe_factor * sum(weight * source_on); this term is not fitted by RLS. Learning subtracts its sample mean from the observed rate unless it dominates the observation or the window includes unmodelled residual heat after source-off. -* Event learners (exponentially weighted means) for the dead time after - switching on, the overshoot after switching off and the recovery time after - airing. +* Event learners: exponentially weighted means for dead time and recovery after + airing, and bounded prediction-error feedback for residual heat after switch-off. * ``RecoveryModel``: least squares estimate of how the recovery after airing depends on the airing itself (how far the room fell, how long cold air touched walls and floor). Draft and cross ventilation cool faster and deeper; both @@ -29,6 +28,7 @@ from typing import Any from ...core.store_validation import checked, dataclass_schema, number, optional, required_mapping +from .peaks import PEAK_PASSED_K, PEAK_STALL_RISE_K, peak_quiet, peak_stalled from .physics import clamp # Bounds keep a learner from drifting into nonsense if a sensor misbehaves. @@ -44,8 +44,16 @@ RISE_K = 0.1 # K above the minimum: a rise may have started (one sensor step) RISE_CONFIRM_K = 0.2 # K above the minimum: the rise is real, not sensor noise RISE_CONFIRM_S = 5 * 60 # s a single step has to last to count as a real rise -PEAK_PASSED_K = 0.15 # K below the highest temperature after switch-off: overshoot is over -MIN_RUN_H = 0.25 # h; shorter runs are rated as if they had lasted this long +MIN_RUN_H = 0.25 # h; diagnostic legacy rate only (not used for prediction) +OVERSHOOT_MODEL_VERSION = 2 +OVERSHOOT_MIGRATION_MAX_K = 0.3 # conservative ceiling for unfiltered legacy learning +OVERSHOOT_ALPHA = 0.5 # correct systematic prediction errors within a few clean cycles +OVERSHOOT_MAX_ERROR_K = 0.3 # Huber limit: one event changes the ceiling by at most 0.15 K +OVERSHOOT_MIN_EXPOSURE = 0.5 # avoid amplifying short-run disturbances by division +SHOWER_RH_RISE = 5.0 # relative humidity percentage points +SHOWER_WINDOW_S = 15 * 60.0 +OVERSHOOT_SUN_PV_KW = 0.3 # ignore tiny PV readings +OVERSHOOT_SUN_GAIN_KPH = 0.05 # learned, scaled solar gain must also be significant # A recovery cut short by heating while the room was still warming up only says the # true value is larger than the time waited. Counting it a little longer lets the # estimate grow in that direction at all; a room that was not warming up says nothing. @@ -56,7 +64,7 @@ SAMPLE_INTERVAL = 15 * 60 # s between model updates RATE_WINDOW = 60 * 60 # s window used to compute dT/dt EDGE = 5 * 60 # s averaged at both ends of the window (sensor quantisation) -MAX_RUN_HOURS_FOR_OVERSHOOT = 3.0 +MAX_RUN_HOURS_FOR_OVERSHOOT = 3.0 # legacy rate diagnostic only TRACK_TIMEOUT = 4 * 3600.0 # Pipe transport delay/residual heat is not measured. Reject the first 20 min # after a source was last seen on, rather than blocking learning for four hours. @@ -353,6 +361,8 @@ class Sample: draft: bool = False # draft through windows open in other rooms pipe_active: bool = False # actual source state, also when gain/factor is zero pipe_rate_kph: float = 0.0 # configured gain * factor * weighted active sources + humidity: float | None = None # room relative humidity in percent + sun_factor: float = 1.0 # controller scale of the learned solar coefficient @dataclass @@ -360,7 +370,9 @@ class AreaLearner: """All learned values of one area plus the trackers that produce them.""" model: ThermalModel = field(default_factory=ThermalModel) - overshoot: Ewma = field(default_factory=lambda: Ewma(0.3)) + overshoot: Ewma = field(default_factory=lambda: Ewma(0.3)) # saturated residual heat in K + overshoot_model_version: int = OVERSHOOT_MODEL_VERSION + last_overshoot: dict[str, float] | None = None # last clean expected/observed peak, for AI overshoot_rate: Ewma = field(default_factory=lambda: Ewma(0.3)) dead_time: Ewma = field(default_factory=lambda: Ewma(1800.0)) recovery: Ewma = field(default_factory=lambda: Ewma(1800.0)) @@ -389,6 +401,8 @@ def as_dict(self) -> dict[str, Any]: "model": self.model.as_dict(), "overshoot": self.overshoot.as_dict(), "overshoot_rate": self.overshoot_rate.as_dict(), + "overshoot_model_version": self.overshoot_model_version, + "last_overshoot": self.last_overshoot, "dead_time": self.dead_time.as_dict(), "recovery": self.recovery.as_dict(), "recovery_model": self.recovery_model.as_dict(), @@ -422,14 +436,31 @@ def from_dict( learner.track_recovery = data.get("track_recovery") learner.track_airing = data.get("track_airing") learner.pipe_last_on = data.get("pipe_last_on") + learner.last_overshoot = data.get("last_overshoot") + learner.overshoot.value = clamp(learner.overshoot.value, *OVERSHOOT_BOUNDS) + if data.get("overshoot_model_version", 1) < OVERSHOOT_MODEL_VERSION: + # Unfiltered legacy estimates: use the smaller mean/rate estimate at one + # dead time, capped at the start value. Retain the rate/count for diagnosis. + ceiling = learner.overshoot.value + if learner.overshoot_rate.count: + rate = clamp(learner.overshoot_rate.value, *OVERSHOOT_RATE_BOUNDS) + ceiling = min(ceiling, rate * learner._saturation_hours()) + learner.overshoot.value = min(ceiling, OVERSHOOT_MIGRATION_MAX_K) return learner # ---------- derived values ---------- def expected_overshoot(self, run_hours: float, factor: float = 1.0) -> float: """Overshoot expected if the circuit is switched off now.""" - hours = clamp(run_hours, 0.0, MAX_RUN_HOURS_FOR_OVERSHOOT) - return max(0.0, self.overshoot_rate.value * hours * factor) + # The sensor's learned value is the robust residual-heat ceiling. Heating + # beyond one dead time cannot store more heat in this saturating model. + return max(0.0, self.overshoot.value * self._exposure(run_hours) * factor) + + def _saturation_hours(self) -> float: + return clamp(self.dead_time.value, *DEAD_TIME_BOUNDS) / 3600.0 + + def _exposure(self, run_hours: float) -> float: + return clamp(run_hours / self._saturation_hours(), 0.0, 1.0) def recovery_s(self, temp: float | None = None) -> float: """Recovery expected if the windows were closed now. @@ -467,6 +498,8 @@ def on_switch( run_hours: float, *, pipe_active: bool = False, + overshoot_factor: float = 1.0, + sample: Sample | None = None, ) -> None: """Call when the circuit was switched on or off.""" if pipe_active: @@ -474,21 +507,44 @@ def on_switch( if temp is None or self._pipe_disturbed(ts): self.track_on = self.track_off = None return + disturbed = sample is not None and self._overshoot_disturbed(sample) + if disturbed: + self.track_off = None if turned_on: - # The controller switches on once the peak has passed: that is a valid sample. + # A restart can end a clean, stalled peak without a measurable fall. t = self.track_off + if t is not None: + self._follow_off_peak(t, temp, ts) if ( t is not None and ts - t["start"] <= TRACK_TIMEOUT - and temp <= t["max"] - PEAK_PASSED_K + EPS + and ( + temp <= t["max"] - PEAK_PASSED_K + EPS + or peak_quiet(ts, t.get("last_rise", t["start"]), self.dead_time.value) + ) ): - self._add_overshoot(t) + self._add_overshoot(t, ts) self.track_on = {"start": ts, "min": temp} self.track_off = None else: if self.track_on is not None: self._confirm_dead_time(self.track_on, ts, temp) - self.track_off = {"start": ts, "t_off": temp, "max": temp, "run_h": run_hours} + expected = self.expected_overshoot(run_hours) + self.track_off = ( + None + if disturbed + else { + "start": ts, + "t_off": temp, + "max": temp, + "run_h": run_hours, + "last_rise": ts, + "rise_max": temp, + "exposure": self._exposure(run_hours), + "expected_base": expected, + "expected": expected * overshoot_factor, + } + ) self.track_on = None def on_window_closed( @@ -564,6 +620,8 @@ def on_window_opened(self, ts: float | None = None, temp_before: float | None = def add_sample(self, sample: Sample) -> list[str]: """Feed one tick. Returns names of values that changed.""" changed: list[str] = [] + if self._overshoot_disturbed(sample): + self.track_off = None self.samples.append(sample) if sample.pipe_active: self.pipe_last_on = sample.ts @@ -656,17 +714,20 @@ def _track(self, s: Sample) -> list[str]: changed.append("dead_time") if self.track_off is not None: t = self.track_off + self._follow_off_peak(t, temp, s.ts) peak_passed = temp <= t["max"] - PEAK_PASSED_K + EPS - if s.valve and not peak_passed: - self.track_off = None - elif peak_passed: - self._add_overshoot(t) + quiet = peak_quiet(s.ts, t.get("last_rise", t["start"]), self.dead_time.value) + stalled = peak_stalled( + s.ts, t["start"], t.get("last_rise", t["start"]), self.dead_time.value + ) + if s.ts - t["start"] > TRACK_TIMEOUT: + self.track_off = None # never settled (sun, people): not a heating peak + elif peak_passed or stalled or (s.valve and quiet): + self._add_overshoot(t, s.ts) self.track_off = None changed.append("overshoot") - elif s.ts - t["start"] > TRACK_TIMEOUT: - self.track_off = None # never fell again (sun, people): not a heating peak - else: - t["max"] = max(t["max"], temp) + elif s.valve: + self.track_off = None # still rising: the next run censors this peak return changed def _confirm_dead_time(self, t: dict[str, float], ts: float, temp: float | None = None) -> bool: @@ -678,13 +739,63 @@ def _confirm_dead_time(self, t: dict[str, float], ts: float, temp: float | None self.dead_time.add(clamp((ts if rise is None else rise) - t["start"], *DEAD_TIME_BOUNDS)) return True - def _add_overshoot(self, t: dict[str, float]) -> None: + @staticmethod + def _follow_off_peak(t: dict[str, float], temp: float, ts: float) -> None: + """Accumulate small rises without treating each 0.01 K jitter as progress.""" + if temp - t.get("rise_max", t["max"]) >= PEAK_STALL_RISE_K - EPS: + t["last_rise"] = ts + t["rise_max"] = temp + t["max"] = max(t["max"], temp) + + def _overshoot_disturbed(self, s: Sample) -> bool: + """Reject the whole peak, including excluded ticks and missing temperatures.""" + if s.excluded or s.window_open or s.draft or s.pipe_active: + return True + if ( + s.pv_kw >= OVERSHOOT_SUN_PV_KW + and self.model.s * s.sun_factor * s.pv_kw >= OVERSHOOT_SUN_GAIN_KPH + ): + return True + if s.humidity is not None: + return any( + p.humidity is not None and s.humidity - p.humidity >= SHOWER_RH_RISE + for p in self.samples + if 0 <= s.ts - p.ts <= SHOWER_WINDOW_S + ) + return False + + def _add_overshoot(self, t: dict[str, float], ts: float) -> None: over = clamp(t["max"] - t["t_off"], *OVERSHOOT_BOUNDS) - self.overshoot.add(over) - # Short runs are rated as if they had lasted MIN_RUN_H: a rate learned too large - # shortens every run, and the rate must still be able to come down. + exposure = t.get("exposure", self._exposure(t.get("run_h", 0.0))) + expected_base = t.get("expected_base", self.overshoot.value * exposure) + # Learn the physical ceiling independently of the AI's overshoot_factor. + # Huber feedback bounds a single event, including short runs, to 0.15 K. + error = (over - expected_base) / max(exposure, OVERSHOOT_MIN_EXPOSURE) + self.overshoot.value = clamp( + self.overshoot.value + + OVERSHOOT_ALPHA * clamp(error, -OVERSHOOT_MAX_ERROR_K, OVERSHOOT_MAX_ERROR_K), + *OVERSHOOT_BOUNDS, + ) + self.overshoot.count += 1 + # Retain the legacy rate as a bounded diagnostic, never as prediction input. run_h = clamp(t.get("run_h", 0.0), MIN_RUN_H, MAX_RUN_HOURS_FOR_OVERSHOOT) - self.overshoot_rate.add(clamp(over / run_h, *OVERSHOOT_RATE_BOUNDS)) + rate = clamp(over / run_h, *OVERSHOOT_RATE_BOUNDS) + self.overshoot_rate.value = clamp( + self.overshoot_rate.value + + OVERSHOOT_ALPHA + * clamp( + rate - self.overshoot_rate.value, -OVERSHOOT_MAX_ERROR_K, OVERSHOOT_MAX_ERROR_K + ), + *OVERSHOOT_RATE_BOUNDS, + ) + self.overshoot_rate.count += 1 + expected = t.get("expected", expected_base) + self.last_overshoot = { + "ts": ts, + "expected_peak": t["t_off"] + expected, + "real_peak": t["max"], + "error_k": over - expected, + } def _track_recovery(self, s: Sample) -> list[str]: if self.track_recovery is None or s.temp is None: diff --git a/custom_components/house_assistant/heating/logic/peaks.py b/custom_components/house_assistant/heating/logic/peaks.py new file mode 100644 index 0000000..eafdc27 --- /dev/null +++ b/custom_components/house_assistant/heating/logic/peaks.py @@ -0,0 +1,19 @@ +"""Shared limits for residual heat peaks in the controller and event learner.""" + +PEAK_PASSED_K = 0.15 # K below the observed maximum: the peak has passed +PEAK_CARRY_MAX_S = 4 * 3600.0 # absolute limit, even while still warming +PEAK_STALL_DEAD_TIMES = 2.0 # allow two dead times for residual heat to arrive +PEAK_STALL_QUIET_DEAD_TIMES = 1.0 # no meaningful new maximum for one dead time +PEAK_STALL_RISE_K = 0.02 # cumulative rise in K; ignore individual 0.01 K sensor jitter + + +def peak_stalled(now: float, start: float, last_rise: float, dead_time_s: float) -> bool: + """A peak has had time to arrive and has stopped making meaningful progress.""" + return now - start >= PEAK_STALL_DEAD_TIMES * dead_time_s and peak_quiet( + now, last_rise, dead_time_s + ) + + +def peak_quiet(now: float, last_rise: float, dead_time_s: float) -> bool: + """The maximum has not advanced for a full thermal response time.""" + return now - last_rise >= PEAK_STALL_QUIET_DEAD_TIMES * dead_time_s diff --git a/custom_components/house_assistant/heating/logic/prompts.py b/custom_components/house_assistant/heating/logic/prompts.py index 015b2fe..ddf2d53 100644 --- a/custom_components/house_assistant/heating/logic/prompts.py +++ b/custom_components/house_assistant/heating/logic/prompts.py @@ -115,7 +115,16 @@ class PromptSpec: "Per area the controller switches on when the predicted temperature (after " "dead_time_min * lead_factor, using the learned cooling rate) falls below target " "- hysteresis_on, and switches off when temperature + expected overshoot * " - "overshoot_factor reaches target + hysteresis_off. Heating pauses after a window " + "overshoot_factor reaches target + hysteresis_off. Expected overshoot grows only " + "up to one learned dead time, then stays at the robust learned overshoot_k " + "ceiling. A carried peak is forgotten when it stalls, earlier if already " + "below the switch-on threshold, and always within 4 h. " + "learned.last_overshoot gives expected_peak and real_peak in C at the last " + "clean switch-off and error_k = real minus expected (negative means the " + "controller overestimated residual heat). The local learner corrects this " + "itself; if negative errors and cold_min persist, consider lowering " + "overshoot_factor instead of repeatedly toggling hysteresis_on. " + "Heating pauses after a window " "(or a draft through windows open in other rooms) was open window_delay_min and " "waits the learned recovery time + recovery_bias_min after closing; the wait " "can end early once the room is back at its temperature before airing, but only " diff --git a/custom_components/house_assistant/manifest.json b/custom_components/house_assistant/manifest.json index 2e84787..1965149 100644 --- a/custom_components/house_assistant/manifest.json +++ b/custom_components/house_assistant/manifest.json @@ -21,5 +21,5 @@ "loggers": ["anthropic"], "requirements": ["anthropic>=0.125.0"], "single_config_entry": true, - "version": "1.0.0b23" + "version": "1.0.0b24" } diff --git a/docs/heating.en.md b/docs/heating.en.md index 22b448e..990f8b4 100644 --- a/docs/heating.en.md +++ b/docs/heating.en.md @@ -13,7 +13,7 @@ Rooms and windows come from the **house** (panel *House Assistant > House*): a r * **Target** with the regular thermostat card. It is stored until you change it. No schedules, no night setback (usually counterproductive with underfloor heating). * **Predictive switch-on:** the circuit turns on when the temperature would fall below target minus the switch-on hysteresis after the learned dead time (taking cooling rate, outdoor temperature and sun into account). * **Predictive sun:** for the cooling over the lead time not only the current PV power counts but the power expected during that time. If the sun is going to warm the room anyway, the circuit does not switch on in the morning; in the evening the control no longer counts on sun that is about to go. The source is an optional PV forecast sensor (e.g. Forecast.Solar) or, without it, the hourly weather forecast (cloud cover) together with the position of the sun. For that the module learns on almost cloudless days how much PV power to expect under a clear sky. The forecast counts only 70 % (option "Trust in the sun forecast"), and 1 K below target it heats regardless of any forecast (option "Always heat below target by", 0.3 to 3 K). Without a PV power sensor everything stays as before. If the sensor gives no value in daytime, the PV power counts as unknown: nothing is calibrated or fed into the model, the expected power is used (PV forecast sensor, or sun position and cloud cover once the scale is learned, otherwise 0); with the sun low or hardly any power to expect, 0 applies. If the value is missing for more than an hour in daytime, a warning is logged. -* **Predictive switch-off:** the circuit turns off when the current temperature plus the expected overshoot reaches target plus the switch-off hysteresis. The overshoot of the slow underfloor heating is learned (depending on the run time). After switching off, the heat still in the floor is taken into account when switching on again until the temperature falls; otherwise the circuit would start again right after the minimum pause. +* **Predictive switch-off:** the circuit turns off when the current temperature plus the expected overshoot reaches target plus the switch-off hysteresis. Expected overshoot grows with run time up to one learned dead time, then stays at the robust learned ceiling shown by the overshoot sensor. Clean observed peaks correct prediction errors, with a maximum change of 0.15 K per event. Peaks disturbed by windows, drafts, recovery, pipe heat, a room humidity rise of at least 5 percentage points within 15 minutes or significant learned solar gain are discarded. After switching off, residual heat is carried until the temperature falls 0.15 K from its observed maximum, or until at least two dead times have passed without a meaningful new maximum for one dead time. Below target minus switch-on hysteresis, one quiet dead time already releases the carry. A cumulative rise of 0.02 K counts as progress; four hours remains the absolute limit. The AI check receives the last clean expected and observed peak and their difference. * **Windows:** if a window of the room is open for longer than the window delay, the heat request pauses. After closing, the learned recovery time is awaited because screed and walls often warm the room by themselves. After a minimum wait of the mean learned recovery time times *Wait after airing*, recovery ends when the temperature is within 0.1 K of its previous value. The full recovery time including bias is the upper bound; 0 % disables the minimum wait. The recovery time follows the airing itself (see *Learning per room*): after short airing the heating waits less than after long airing in frost or cross ventilation. **Tilted** counts like open but with only 25 % of the opening area: from a window handle (open, tilted, closed) or a tilt contact of the window. An unavailable contact counts as closed, as before. * **Cross ventilation and draft, automatic:** from the arrangement of the windows on the house (wall and position, floor from the Home Assistant area of the room) the module tells two cases: * *Cross ventilation:* an own window is open together with a window of another room on the same floor on an opposite or adjacent wall. diff --git a/docs/heating.md b/docs/heating.md index 783ff5b..62208aa 100644 --- a/docs/heating.md +++ b/docs/heating.md @@ -13,7 +13,7 @@ Räume und Fenster kommen aus dem **Haus** (Panel *House Assistant > Haus*): Ein * **Sollwert** über die normale Thermostatkarte. Er bleibt dauerhaft gespeichert, bis du ihn änderst. Keine Zeitpläne, keine Nachtabsenkung (bei Fußbodenheizung meist kontraproduktiv). * **Vorausschauend einschalten:** Der Kreis geht an, wenn die Temperatur nach der gelernten Totzeit (unter Berücksichtigung von Abkühlrate, Außentemperatur und Sonne) unter Sollwert minus Einschalthysterese fallen würde. * **Sonne vorausschauend:** Für die Abkühlung über die Vorlaufzeit zählt nicht nur die aktuelle PV-Leistung, sondern die in dieser Zeit erwartete. Ist absehbar, dass die Sonne den Raum ohnehin aufheizt, schaltet der Kreis morgens nicht erst ein; abends rechnet die Regelung nicht mehr mit Sonne, die gleich verschwindet. Quelle ist ein optionaler PV-Prognosesensor (z. B. Forecast.Solar) oder, ohne ihn, die stündliche Wettervorhersage (Bewölkung) zusammen mit dem Sonnenstand. Dafür lernt das Modul an fast wolkenlosen Tagen, wie viel PV-Leistung bei klarem Himmel zu erwarten ist. Die Prognose fließt nur zu 70 % ein (Option „Vertrauen in die Sonnenprognose“), und 1 K unter Sollwert wird unabhängig von jeder Vorhersage geheizt (Option „Immer heizen unter Sollwert um“, 0,3 bis 3 K). Ohne PV-Leistungssensor bleibt alles wie bisher. Liefert der Sensor tagsüber keinen Wert, gilt die PV-Leistung als unbekannt: Es wird dann nichts kalibriert und nichts ins Modell übernommen, gerechnet wird mit der erwarteten Leistung (PV-Prognosesensor oder Sonnenstand und Bewölkung, sobald die Skala gelernt ist, sonst 0); bei tief stehender Sonne oder wenn ohnehin kaum Leistung zu erwarten ist, gilt 0. Fehlt der Wert länger als eine Stunde bei Tag, steht eine Warnung im Protokoll. -* **Vorausschauend abschalten:** Der Kreis geht aus, wenn die aktuelle Temperatur plus das erwartete Überschwingen den Sollwert plus Ausschalthysterese erreicht. Das Überschwingen der trägen Fußbodenheizung wird gelernt (abhängig von der Laufzeit). Nach dem Abschalten wird die noch im Boden steckende Wärme beim Wiedereinschalten berücksichtigt, bis die Temperatur wieder fällt; sonst liefe der Kreis nach der Mindestpause sofort wieder an. +* **Vorausschauend abschalten:** Der Kreis geht aus, wenn die aktuelle Temperatur plus das erwartete Überschwingen den Sollwert plus Ausschalthysterese erreicht. Das erwartete Überschwingen steigt mit der Laufzeit bis zu einer gelernten Totzeit und bleibt danach beim robust gelernten Höchstwert, den der Überschwing-Sensor zeigt. Ungestörte Spitzen korrigieren Vorhersagefehler um höchstens 0,15 K je Ereignis. Ereignisse mit Fenster, Zugluft, Erholung, Rohrwärme, einem Raumfeuchteanstieg von mindestens 5 Prozentpunkten in 15 Minuten oder deutlichem gelerntem Sonnengewinn werden verworfen. Nach dem Abschalten wird Restwärme berücksichtigt, bis die Temperatur 0,15 K unter das beobachtete Maximum fällt oder nach mindestens zwei Totzeiten eine Totzeit lang kein nennenswert höheres Maximum auftrat. Unter Sollwert minus Einschalthysterese genügt bereits eine Totzeit ohne Fortschritt. Ein aufsummierter Anstieg von 0,02 K zählt als Fortschritt; vier Stunden bleiben die absolute Grenze. Der KI-Check erhält die letzte ungestörte erwartete und beobachtete Spitze samt Abweichung. * **Fenster:** Ist ein Fenster des Raums länger als die Fensterverzögerung offen, pausiert die Heizanforderung. Nach dem Schließen wird die gelernte Erholungszeit abgewartet, weil Estrich und Wände den Raum oft selbst wieder aufheizen. Die Mindestwartezeit entspricht dem eingestellten Anteil *Wartezeit nach dem Lüften* an der mittleren gelernten Erholungszeit. Danach endet die Erholung, sobald die Temperatur bis auf 0,1 K wieder erreicht ist. Die volle Erholungszeit einschließlich Korrektur ist die Obergrenze; 0 % hebt die Mindestwartezeit auf. Die Erholungszeit richtet sich nach der Lüftung selbst (siehe *Lernen je Raum*): Nach kurzem Stoßlüften wartet die Heizung kürzer als nach langem Lüften bei Frost oder Querlüften. **Gekippt** zählt wie offen, aber nur mit 25 % der Öffnungsfläche: über einen Fenstergriff (offen, gekippt, zu) oder einen Kipp-Kontakt des Fensters. Ein nicht verfügbarer Kontakt zählt wie bisher als zu. * **Querlüften und Luftzug, automatisch:** Aus der Lage der Fenster am Haus (Wand und Position, Etage aus dem Home-Assistant-Bereich des Raums) erkennt das Modul zwei Fälle: * *Querlüften:* ein eigenes Fenster ist offen, zusammen mit einem Fenster eines anderen Raums derselben Etage an einer gegenüberliegenden oder angrenzenden Wand. diff --git a/tests/heating/logic/test_overshoot.py b/tests/heating/logic/test_overshoot.py new file mode 100644 index 0000000..2d93f0a --- /dev/null +++ b/tests/heating/logic/test_overshoot.py @@ -0,0 +1,297 @@ +"""Residual heat regression tests: stalled peaks, robust saturation and disturbances.""" + +from dataclasses import replace + +import pytest + +from custom_components.house_assistant.core.store_validation import dataclass_schema, validate +from custom_components.house_assistant.heating.logic.ai_policy import overshoot_feedback +from custom_components.house_assistant.heating.logic.controller import ( + AreaRuntime, + AreaSettings, + ControlInput, + ControlParams, + LearnedValues, + step, +) +from custom_components.house_assistant.heating.logic.learning import ( + AreaLearner, + Ewma, + Sample, + learner_schema, +) + +DEAD = 35 * 60.0 + + +def _input(now=0.0, temp=20.79, **kwargs): + data = ControlInput(now, temp, 21.5, True, True, True, 7, False, False, 0.0) + return replace(data, **kwargs) + + +def _sample(ts, temp=20.79, **kwargs): + return Sample(ts, temp, False, 0, 0, False, **kwargs) + + +def _step(rt, now, temp=20.79, target=21.5, dead=DEAD): + return step( + _input(now, temp, target=target), + ControlParams(lead_factor=2), + AreaSettings(), + LearnedValues(dead_time_s=dead, cool_rate_kph=0.05), + rt, + ) + + +def _carry(): + return AreaRuntime( + carry_peak=21.5, carry_max=20.79, carry_since=0.0, carry_last_rise=0.0, carry_rise_max=20.79 + ) + + +def test_live_cold_room_restarts_within_two_dead_times(): + rt = _carry() + # The predicted 21.5 C never arrives: real peak is only 20.98 C. + for minute in range(71): + temp = round(20.79 + min(minute, 25) * 0.19 / 25, 2) + decision = _step(rt, minute * 60, temp) + if decision.want_on: + break + assert 35 <= minute <= 70 + assert decision.may_switch and rt.carry_peak is None + assert decision.predicted_temp < 21.3 + + +def test_flat_cold_carry_ends_after_one_quiet_dead_time(): + rt = _carry() + assert not _step(rt, DEAD - 1).want_on + assert _step(rt, DEAD).want_on + assert rt.carry_peak is None + + +def test_stall_ends_carry_even_when_not_currently_below_on_threshold(): + rt = _carry() + assert not _step(rt, DEAD, target=20.9).want_on + assert rt.carry_peak is not None + _step(rt, 2 * DEAD, target=20.9) + assert rt.carry_peak is None + + +def test_sensor_jitter_does_not_extend_a_stalled_carry(): + rt = _carry() + for minute in range(36): + decision = _step(rt, minute * 60, 20.80 if minute % 2 else 20.79) + assert rt.carry_peak is None and decision.want_on + + +def test_cumulative_small_rises_keep_carry_while_peak_is_approaching(): + rt = _carry() + for minute in range(100): + _step(rt, minute * 60, 20.79 + minute * 0.01, target=22) + assert rt.carry_peak is not None + + +def test_peak_drop_keeps_existing_early_end(): + rt = _carry() + _step(rt, 60, 20.98) + assert rt.carry_peak is not None + assert _step(rt, 120, 20.83).want_on + assert rt.carry_peak is None # 0.15 K fall, well before a dead time + + +@pytest.mark.parametrize("missing_temp", [False, True]) +def test_four_hour_limit_even_without_a_stall(missing_temp): + rt = _carry() + # Continuous rises, so the stall condition cannot terminate the carry. + for minute in range(240): + _step(rt, minute * 60, 20.79 + minute * 0.01, target=25) + assert rt.carry_peak is not None + _step(rt, 4 * 3600, None if missing_temp else 23.19, target=25) + assert rt.carry_peak is None + + +def test_carry_progress_persists_and_old_runtime_loads(): + rt = _carry() + _step(rt, 600, 20.90) + stored = rt.as_dict() + validate(stored, dataclass_schema(AreaRuntime)) + assert not any(k in stored for k in AreaRuntime.TRANSIENT) + rt = AreaRuntime.from_dict(stored) + assert rt.carry_last_rise == 600 + assert _step(rt, 600 + DEAD, 20.90).want_on + old = AreaRuntime.from_dict({"carry_peak": 21.5, "carry_max": 20.98, "carry_since": 0}) + assert _step(old, 2 * DEAD, 20.98).want_on + assert old.carry_peak is None + + +def test_expected_overshoot_saturates_at_dead_time(): + learner = AreaLearner.create(DEAD, 1800) + learner.overshoot = Ewma(0.2, 10) + learner.overshoot_rate = Ewma(2.0, 10) # legacy outliers must not affect prediction + saturation_h = DEAD / 3600 + assert learner.expected_overshoot(-1) == 0 + assert learner.expected_overshoot(0) == 0 + assert learner.expected_overshoot(saturation_h / 2) == pytest.approx(0.1) + assert learner.expected_overshoot(saturation_h) == pytest.approx(0.2) + assert learner.expected_overshoot(1.81) == pytest.approx(0.2) + assert learner.expected_overshoot(20) == pytest.approx(0.2) + assert learner.expected_overshoot(20, 1.5) == pytest.approx(0.3) + + +def _cycle(learner, ts, actual=0.19, run_h=1.81, factor=1.0): + learner.on_switch(ts, 20.79, False, run_h, overshoot_factor=factor) + learner.add_sample(_sample(ts + 600, 20.79 + actual)) + learner.add_sample(_sample(ts + 2 * DEAD, 20.79 + actual)) + assert learner.track_off is None + + +def test_error_feedback_corrects_large_overestimate_in_five_clean_cycles(): + learner = AreaLearner.create(DEAD, 1800) + learner.overshoot = Ewma(0.71, 100) + values = [] + for i in range(5): + _cycle(learner, i * 20000) + values.append(learner.expected_overshoot(1.81)) + assert values == sorted(values, reverse=True) + assert values[-1] == pytest.approx(0.19, abs=0.03) + assert learner.overshoot.count == 105 + feedback = overshoot_feedback(learner.last_overshoot) + assert feedback["real_peak"] == 20.98 + assert feedback["error_k"] < 0 + assert feedback["expected_peak"] > feedback["real_peak"] + + +@pytest.mark.parametrize("run_h", [0.17, 0.18, 0.24, 1.0]) +def test_single_hot_peak_has_bounded_influence(run_h): + learner = AreaLearner.create(DEAD, 1800) + learner.overshoot = Ewma(0.2, 10) + _cycle(learner, 0, actual=0.89, run_h=run_h) + assert learner.overshoot.value <= 0.35 + 1e-6 + assert learner.expected_overshoot(2) <= 0.35 + 1e-6 + for i in range(1, 5): + _cycle(learner, i * 20000, actual=0.2) + assert learner.expected_overshoot(2) == pytest.approx(0.2, abs=0.02) + + +def test_feedback_remembers_applied_factor_but_learns_physical_heat(): + learner = AreaLearner.create(DEAD, 1800) + learner.overshoot = Ewma(0.2, 10) + learner.on_switch(0, 20.79, False, 2, overshoot_factor=2) + assert learner.track_off["expected"] == pytest.approx(0.4) + assert learner.track_off["expected_base"] == pytest.approx(0.2) + stored = learner.as_dict() + validate(stored, learner_schema()) + learner = AreaLearner.from_dict(stored, DEAD, 1800) + learner.add_sample(_sample(600, 20.99)) + learner.add_sample(_sample(2 * DEAD, 20.99)) + assert learner.overshoot.value == pytest.approx(0.2) + assert learner.last_overshoot["expected_peak"] == pytest.approx(21.19) + assert learner.last_overshoot["error_k"] == pytest.approx(-0.2) + copy = AreaLearner.from_dict(learner.as_dict(), DEAD, 1800) + assert copy.as_dict() == learner.as_dict() + + +@pytest.mark.parametrize( + "mean,rate,expected", [(0.16, 0.39, 0.16), (0.71, 2, 0.3), (0.5, 0.1, DEAD / 36000)] +) +def test_legacy_migration_uses_conservative_bounded_estimate(mean, rate, expected): + old = { + "overshoot": {"value": mean, "count": 10}, + "overshoot_rate": {"value": rate, "count": 20}, + "dead_time": {"value": DEAD, "count": 5}, + } + validate(old, learner_schema()) + learner = AreaLearner.from_dict(old, 1800, 1800) + assert learner.expected_overshoot(2) == pytest.approx(expected) + assert learner.overshoot.count == 10 + assert learner.overshoot_rate == Ewma(rate, 20) + # New-format learning above the migration cap survives every later restart. + learner.overshoot.value = 0.6 + copy = AreaLearner.from_dict(learner.as_dict(), 1800, 1800) + assert copy.expected_overshoot(2) == 0.6 + + +@pytest.mark.parametrize( + "disturbance", + [ + {"window_open": True}, + {"draft": True}, + {"excluded": True}, + {"pipe_active": True}, + {"pv_kw": 1.0}, + ], +) +@pytest.mark.parametrize("temp", [20.98, None]) +def test_disturbed_event_is_discarded_even_on_missing_temperature(disturbance, temp): + learner = AreaLearner.create(DEAD, 1800) + learner.on_switch(0, 20.79, False, 2) + sample = replace(_sample(600, temp), **disturbance) + learner.add_sample(sample) + assert learner.track_off is None + learner.add_sample(_sample(2 * DEAD, 20.5)) + assert learner.overshoot.count == learner.overshoot_rate.count == 0 + assert learner.last_overshoot is None + + +@pytest.mark.parametrize( + "elapsed,rise,discard", [(900, 5, True), (600, 6, True), (901, 5, False), (900, 4.9, False)] +) +def test_shower_rh_jump_boundaries(elapsed, rise, discard): + learner = AreaLearner.create(DEAD, 1800) + learner.add_sample(_sample(0, humidity=50)) + learner.on_switch(60, 20.79, False, 2) + learner.add_sample(_sample(elapsed, None, humidity=50 + rise)) + assert (learner.track_off is None) == discard + assert learner.overshoot.count == 0 + + +@pytest.mark.parametrize( + "pv,coefficient,factor,discard", + [ + (1, 0.1, 1, True), + (0.29, 1, 1, False), + (1, 0.01, 1, False), + (1, 0.1, 0, False), + (0.5, 0.1, 1, True), + ], +) +def test_sun_requires_both_pv_and_learned_effect(pv, coefficient, factor, discard): + learner = AreaLearner.create(DEAD, 1800) + learner.model.theta[2] = coefficient + learner.on_switch(0, 20.79, False, 2) + learner.add_sample(replace(_sample(600, sun_factor=factor), pv_kw=pv)) + assert (learner.track_off is None) == discard + + +def test_disturbance_on_switch_event_cannot_finish_or_start_a_peak(): + learner = AreaLearner.create(DEAD, 1800) + learner.on_switch(0, 20.79, False, 2) + learner.add_sample(_sample(600, 20.98)) + sample = _sample(1200, 20.79, window_open=True) + learner.on_switch(1200, 20.79, True, 0, sample=sample) + assert learner.overshoot.count == 0 + learner.on_switch(1300, 20.79, False, 2, sample=sample) + assert learner.track_off is None + + +def test_clean_zero_peak_is_learned_on_restart_without_waiting_for_a_drop(): + learner = AreaLearner.create(DEAD, 1800) + learner.on_switch(0, 20.79, False, 2) + learner.add_sample(_sample(600)) + learner.on_switch(DEAD, 20.79, True, 0) + assert learner.overshoot.count == 1 + assert learner.overshoot.value == pytest.approx(0.15) + + +def test_new_rise_at_switch_on_censors_unfinished_peak(): + learner = AreaLearner.create(DEAD, 1800) + learner.on_switch(0, 20.79, False, 2) + learner.add_sample(_sample(600, 20.80)) + learner.on_switch(DEAD, 20.98, True, 0) + assert learner.overshoot.count == 0 + assert learner.track_off is None + + +def test_negative_legacy_rate_cannot_create_a_negative_ceiling(): + learner = AreaLearner.from_dict({"overshoot_rate": {"value": -1.0, "count": 5}}, DEAD, 1800) + assert learner.overshoot.value == learner.expected_overshoot(2) == 0 diff --git a/tests/heating/logic/test_pipe_coordinator.py b/tests/heating/logic/test_pipe_coordinator.py index 1f699f7..497f94c 100644 --- a/tests/heating/logic/test_pipe_coordinator.py +++ b/tests/heating/logic/test_pipe_coordinator.py @@ -329,3 +329,36 @@ async def test_live_topology_with_distinct_weights(): assert all("pipe" not in a for a in payload["areas"][1:]) assert all(a["pipes_through"] == ["Wohnbereich"] for a in payload["areas"][1:4]) assert "Abstellkammer" not in str(target["pipe"]) + + +def test_learning_snapshot_passes_room_humidity_and_scaled_sun(): + c = _coordinator() + area = c.areas["plain"] + area.humidity = 57.0 + area.params.sun_factor = 1.4 + c.pv_kw = 1.0 + sample = c._learning_sample(area, 1000) + assert sample.humidity == 57.0 + assert sample.sun_factor == 1.4 and sample.pv_kw == 1.0 + area.learner.on_switch(1000, 21.5, False, 2, sample=sample) + assert area.learner.track_off is None # significant room solar gain + + +async def test_check_includes_clean_expected_and_real_peak(): + c = _coordinator() + area = c.areas["plain"] + area.learner.last_overshoot = { + "ts": 1234, + "expected_peak": 21.5, + "real_peak": 20.98, + "error_k": -0.52, + } + await c._run_check() + payload = json.loads(c._ai_call.call_args.args[2]) + assert payload["areas"][2]["learned"]["last_overshoot"] == { + "expected_peak": 21.5, + "real_peak": 20.98, + "error_k": -0.52, + } + assert "overshoot_factor" in payload["areas"][2]["params"] + assert "last_overshoot" not in payload["areas"][2]["params"] diff --git a/tests/heating/logic/test_pipe_heat.py b/tests/heating/logic/test_pipe_heat.py index 8b46747..ca66c9a 100644 --- a/tests/heating/logic/test_pipe_heat.py +++ b/tests/heating/logic/test_pipe_heat.py @@ -221,8 +221,11 @@ def test_explicitly_disabled_pipe_samples_are_identical(): new.add_sample(replace(sample, pipe_active=False, pipe_rate_kph=0.0)) assert old.as_dict() == new.as_dict() assert old.model.n_cool > 0 - # Snapshot produced with the committed learner before the correction: - snapshot = json.dumps(old.as_dict(), sort_keys=True).encode() + # Keep the pre-correction thermal snapshot, omitting only new overshoot metadata. + legacy = old.as_dict() + legacy.pop("overshoot_model_version") + legacy.pop("last_overshoot") + snapshot = json.dumps(legacy, sort_keys=True).encode() assert ( hashlib.sha256(snapshot).hexdigest() == "26fc17dcadc35482380f032ea0ffb1bb3926cdf0f06b104e8aa2c01441347386"