Repository navigation
feat(loadmodel): adaptive heating coefficient — learn from measurements - #377
Conversation
HeatingW_per_degC was operator-set and never moved. If the value drifted
from reality (or the house didn't actually track outdoor temperature),
forecasts silently inflated cold-day load. The MPC then made decisions
on phantom heating draw — which is what bit site .40 on a sunny May
afternoon (planner expected ~2.8 kW load on a hot bright slot; actual
~0.5 kW; the dispatcher then absorbed the surplus into the battery).
One-parameter SGD on the prediction residual:
coef ← coef + HeatingAlpha · err / deltaT
Gated on `bucket.Samples ≥ MinTrustSamples` (the residual derives the
slope from the bucket baseline, so an untrusted bucket would feed prior
error into the heating estimate) and on `deltaT ≥ 3 °C` (warm and
near-reference samples don't carry a usable heating signal — and
dividing by a tiny deltaT amplifies noise). Clamped to [0, 1500] W/°C.
Critically, the fit runs BEFORE the outlier filter. Without that
ordering a wildly stale coefficient can never recover: every cold-day
sample under a wrong coef looks like a 5-10 kW outlier vs warm-day
MAE, gets rejected, and nothing pulls the value down.
Operator config (`Planner.HeatingWPerDegC` / `SetHeatingCoef`) still
seeds the initial estimate and is re-applied on
POST /api/loadmodel/reset. Households whose load is temperature-
independent (district heating, solar-gain-dominated shoulder seasons,
well-insulated homes) converge toward 0 W/°C — answering the user's
"vi har ju mätvärden" intuition: the model uses what it sees.
Tests:
- TestHeatingCoefLearnsFromMeasurements: heated home converges to true slope
- TestHeatingCoefLearnsDownForUnheatedHome: stale operator value drifts to 0
- TestHeatingFitWaitsForBucketTrust: under-trusted bucket doesn't drive fit
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd2defa2cf
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // floor. | ||
| if tempC < HeatingReferenceC-HeatingMinDeltaT && b.Samples >= MinTrustSamples { | ||
| deltaT := HeatingReferenceC - tempC | ||
| m.HeatingW_per_degC += HeatingAlpha * err / deltaT |
There was a problem hiding this comment.
Preserve learned heating coefficient across restarts
When this line learns a coefficient different from the operator seed, the value is saved in the model state, but the actual startup path restores the model with NewService and then immediately calls loadSvc.SetHeatingCoef(cfg.Weather.HeatingWPerDegC) in go/cmd/forty-two-watts/main.go lines 671-676, overwriting every restored profile. After any process restart the MPC goes back to the static config value, so the adaptive fix for phantom heating load is lost until enough new samples relearn it.
Useful? React with 👍 / 👎.
Four findings from Codex on the dispatch / loadmodel changes shipped in v0.107.0. Two are P1 (regressions that defeat their own PR's purpose); two are P2 (defensive predicate + observability gap). P1 (PR #377): SeedHeatingCoef preserves learned value across restarts. main.go called SetHeatingCoef unconditionally at startup, clobbering the persisted online-fit value with the config seed. Every binary update wiped the adaptive learning. New SeedHeatingCoef is a no-op when the model already has samples; operator config is the cold-start prior, observation drives the value once learning has begun. SetHeatingCoef remains for explicit operator override (eg. API endpoint, manual reset). P1 (PR #378): Cover-load carve-out forces grid_target=0. The carve-out only set useEnergyPath=false; production wires PlanTarget alongside SlotDirective, so the !useEnergyPath branch called PlanTarget and then SetGridTarget(plannedImportW). A cover-load slot with 1.7 kW planned import then made PI try to import 1.7 kW — the opposite of the carve-out's purpose. Fix routes both carve-out predicates to SetGridTarget(0) and skips the legacy PlanTarget block. P2 (PR #375): passiveArbitrageIdleSlot predicate tightened. Was `dir.BatteryEnergyWh <= idleWhGate` which matched any negative-energy slot (planned discharge). Tightened to |BatteryEnergyWh| ≤ idleWhGate. The planned-discharge case folds into coverLoadDischargeSlot, which is now extended to planner_passive_arbitrage too (was arbitrage-only). The live-export gate fires on either predicate. P2 (PR #379): SlotDeliveryStats.SignMismatchCount. Planned -425 Wh vs actual +425 Wh would have scored |ratio|=1.0=on-target — the largest possible miss, invisible. New counter fires when planned and actual have opposite signs for non-idle slots; the magnitude over/under counters then only fire on same-sign cases, keeping their semantics clean. Tests: - TestSeedHeatingCoefDoesNotOverwriteLearnedValue - TestSeedHeatingCoefAppliesOnColdStart - TestPlannerArbitrageCoverLoadChasesGridZeroNotPlannedImport - TestCoverLoadDischargeDoesNotAbsorbLiveSurplus (both modes) - TestSlotMetricsDetectsSignMismatch Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
HeatingW_per_degCis no longer a frozen operator value — it's fit online from observed residualscoef ← coef + α · err / deltaT, gated on bucket trust anddeltaT ≥ 3 °C, clamped to[0, 1500] W/°C/api/loadmodel/resetBackground
Found 2026-05-28 on site .40: planner predicted 2782 W load on a sunny May afternoon (actual 504 W). Root cause: stale operator heating coef × ambient
(18 − 11.4 °C) × 300 W/°C = 1980 Wof phantom load applied without seasonal or solar-gain awareness. Dispatcher fix (#375) prevents the symptom; this PR addresses the cause.User direction was explicit: "Vår load modell bör ju vara lärande av vad som faktiskt händer. … Kanske har man ett hushåll som inte alls påverkas av utomhustemp? då ska den faktorn ner till noll." The implementation honours that — uses measurements as truth, converges toward zero for temperature-independent homes.
Test plan
TestHeatingCoefLearnsFromMeasurements— heated home converges to true 250 W/°CTestHeatingCoefLearnsDownForUnheatedHome— stale operator value 500 drifts to ~0 after enough samplesTestHeatingFitWaitsForBucketTrust— under-trusted bucket doesn't drive fitmake verify-allcleanPOST /api/loadmodel/resetto clear the contaminated state, watch coef converge from telemetry over the coming days🤖 Generated with Claude Code