From ca31a441f5977eca1b1725a5294aa6cf6c622039 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:06:14 +0100 Subject: [PATCH 01/20] fix(autolearn): learn the season median of the weather factor from measured minutes Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/pvreserve.go | 89 ++++++++++++++++++- .../internal/autolearn/pvreserve_test.go | 82 +++++++++++++++++ 2 files changed, 170 insertions(+), 1 deletion(-) diff --git a/dashboard/internal/autolearn/pvreserve.go b/dashboard/internal/autolearn/pvreserve.go index dc0f474b..ce785c2b 100644 --- a/dashboard/internal/autolearn/pvreserve.go +++ b/dashboard/internal/autolearn/pvreserve.go @@ -19,6 +19,17 @@ const ( weatherKMax = 1.2 // weatherKDefault ist das Saisonmedian, solange keines gesetzt ist. weatherKDefault = 0.5 + // weatherHistBins ist die Anzahl der Faecher je Tag. Festlegung: 0 bis 1.2 + // in Schritten von weatherHistStep. + weatherHistBins = 24 + // weatherHistStep ist die Breite eines Fachs. Festlegung. + weatherHistStep = 0.05 + // weatherHistDays ist die Anzahl gehaltener Kalendertage, der Tag von at + // eingeschlossen. Festlegung. + weatherHistDays = 28 + // weatherMedianMin ist die Mindestzahl gemessener Minuten fuer ein + // Saisonmedian aus den Messungen. Festlegung. + weatherMedianMin = 60 ) // weatherSample ist eine gemessene oder angehobene k zum Zeitpunkt at. @@ -27,6 +38,12 @@ type weatherSample struct { k float64 } +// WeatherDay ist das Histogramm der gemessenen k eines Kalendertags. +type WeatherDay struct { + Day string `json:"day"` + Bins [weatherHistBins]uint16 `json:"bins"` +} + // Weather misst den Wetterfaktor k = PV-Ist / Bestkurve. Gemessen wird nur in // ungedrosselten Minuten. Ohne neue Messung altert k zum Saisonmedian. type Weather struct { @@ -35,6 +52,7 @@ type Weather struct { ring [weatherRing]weatherSample next int n int + days []WeatherDay } // WeatherSample ist eine gespeicherte Messung fuer Neustarts. @@ -46,6 +64,7 @@ type WeatherSample struct { // WeatherState ist der gespeicherte Zustand von Weather fuer Neustarts. type WeatherState struct { Median *float64 `json:"median,omitempty"` + Days []WeatherDay `json:"days,omitempty"` Samples []WeatherSample `json:"samples,omitempty"` } @@ -64,7 +83,9 @@ func (w *Weather) Observe(at time.Time, pv, best float64, unthrottled bool) { if !unthrottled || !finite(pv) || !finite(best) || best <= 0 { return } - w.push(weatherSample{at: at, k: clampK(pv / best)}) + k := clampK(pv / best) + w.push(weatherSample{at: at, k: k}) + w.record(at, k) } // LiftForLoad hebt k auf (pv + jump) / best, wenn eine zugeschaltete Last @@ -79,6 +100,64 @@ func (w *Weather) LiftForLoad(at time.Time, pv, jump, best float64) { return } w.push(weatherSample{at: at, k: k}) + w.record(at, k) +} + +// record zaehlt k in das Fach des Tages von at, haelt hoechstens weatherHistDays +// Tage und setzt danach das Saisonmedian neu. +func (w *Weather) record(at time.Time, k float64) { + loc := at.In(time.Local) + day := loc.Format("2006-01-02") + idx := -1 + for i := range w.days { + if w.days[i].Day == day { + idx = i + break + } + } + if idx < 0 { + w.days = append(w.days, WeatherDay{Day: day}) + idx = len(w.days) - 1 + } + bin := min(int(k/weatherHistStep+1e-9), weatherHistBins-1) + w.days[idx].Bins[bin]++ + + cutoff := time.Date(loc.Year(), loc.Month(), loc.Day()-(weatherHistDays-1), 0, 0, 0, 0, time.Local) + cutoffDay := cutoff.Format("2006-01-02") + kept := w.days[:0] + for _, d := range w.days { + if d.Day >= cutoffDay { + kept = append(kept, d) + } + } + w.days = kept + w.updateMedian() +} + +// updateMedian setzt das Saisonmedian auf die Mitte des Fachs, in dem die +// kumulierte Summe ueber alle gehaltenen Tage die Hälfte erreicht. Unter +// weatherMedianMin Messungen bleibt das Median unveraendert. +func (w *Weather) updateMedian() { + var hist [weatherHistBins]uint64 + var total uint64 + for _, d := range w.days { + for i, c := range d.Bins { + hist[i] += uint64(c) + total += uint64(c) + } + } + if total < weatherMedianMin { + return + } + var cum uint64 + for i, c := range hist { + cum += c + if cum*2 >= total { + w.median = (float64(i) + 0.5) * weatherHistStep + w.hasMedian = true + return + } + } } // K liefert den aktuellen Wetterfaktor k zur Zeit at, dazu das 25. Perzentil @@ -122,6 +201,7 @@ func (w *Weather) State() WeatherState { m := w.median st.Median = &m } + st.Days = append([]WeatherDay(nil), w.days...) start := w.start() for i := 0; i < w.n; i++ { s := w.ring[(start+i)%weatherRing] @@ -137,6 +217,13 @@ func LoadWeather(st WeatherState) *Weather { if st.Median != nil { w.SetSeasonMedian(*st.Median) } + for _, d := range st.Days { + if _, err := time.ParseInLocation("2006-01-02", d.Day, time.Local); err != nil { + continue + } + w.days = append(w.days, d) + } + w.updateMedian() samples := st.Samples if len(samples) > weatherRing { samples = samples[len(samples)-weatherRing:] diff --git a/dashboard/internal/autolearn/pvreserve_test.go b/dashboard/internal/autolearn/pvreserve_test.go index 98e96a21..832a8b8c 100644 --- a/dashboard/internal/autolearn/pvreserve_test.go +++ b/dashboard/internal/autolearn/pvreserve_test.go @@ -160,3 +160,85 @@ func TestWeatherLoadEmptyState(t *testing.T) { t.Errorf("empty state: K = %v, fresh = %v, want 0.5, false", k, fresh) } } + +// nearWithin meldet, ob a und b weniger als 0.001 auseinanderliegen. +func nearWithin(a, b float64) bool { + return math.Abs(a-b) < 0.001 +} + +func TestWeatherSeasonMedianFromMeasurements(t *testing.T) { + var w Weather + t0 := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + observeRun(&w, t0, 80, 3200, 4000) + + k, _, fresh := w.K(t0.Add(79*time.Minute + 3*time.Hour)) + if fresh || !nearWithin(k, 0.825) { + t.Errorf("K ohne frische Messung = %v, fresh = %v, want nahe 0.825, false", k, fresh) + } +} + +func TestWeatherSeasonMedianNeedsSixtySamples(t *testing.T) { + var w Weather + t0 := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + observeRun(&w, t0, 59, 3600, 4000) + + if s := w.season(); s != 0.5 { + t.Errorf("season after 59 samples = %v, want 0.5", s) + } + w.Observe(t0.Add(59*time.Minute), 3600, 4000, true) + if s := w.season(); s == 0.5 { + t.Errorf("season after 60 samples = %v, want measured median", s) + } +} + +func TestWeatherThrottledMinutesDoNotCount(t *testing.T) { + var w Weather + t0 := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + for i := 0; i < 100; i++ { + w.Observe(t0.Add(time.Duration(i)*time.Minute), 3600, 4000, false) + } + if s := w.season(); s != 0.5 { + t.Errorf("season = %v, want 0.5", s) + } +} + +func TestWeatherHistogramDropsOldDays(t *testing.T) { + var w Weather + day0 := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + observeRun(&w, day0, 70, 3600, 4000) + day30 := day0.AddDate(0, 0, 30) + observeRun(&w, day30, 70, 1200, 4000) + + if s := w.season(); !nearWithin(s, 0.325) { + t.Errorf("season = %v, want nahe 0.325", s) + } +} + +func TestWeatherStateRoundTripKeepsHistogram(t *testing.T) { + var w Weather + t0 := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + observeRun(&w, t0, 70, 3600, 4000) + + raw, err := json.Marshal(w.State()) + if err != nil { + t.Fatal(err) + } + var st WeatherState + if err := json.Unmarshal(raw, &st); err != nil { + t.Fatal(err) + } + back := LoadWeather(st) + if !nearly(back.season(), w.season()) { + t.Errorf("restored median = %v, want %v", back.season(), w.season()) + } +} + +func TestLoadWeatherWithoutDaysKeepsOldMedian(t *testing.T) { + var st WeatherState + if err := json.Unmarshal([]byte(`{"median":0.7}`), &st); err != nil { + t.Fatal(err) + } + if s := LoadWeather(st).season(); !nearly(s, 0.7) { + t.Errorf("season = %v, want 0.7", s) + } +} From d5ffb8e29d64fe35e2ff310a426acc65958452a7 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:08:40 +0100 Subject: [PATCH 02/20] fix(autolearn): count a load that the PV covers as a weather measurement Co-Authored-By: Claude Sonnet 5.5 --- .../internal/autolearn/pvreserve_runner.go | 92 +++++++++++++++++++ .../autolearn/pvreserve_runner_test.go | 78 ++++++++++++++++ 2 files changed, 170 insertions(+) diff --git a/dashboard/internal/autolearn/pvreserve_runner.go b/dashboard/internal/autolearn/pvreserve_runner.go index ce70bd24..26ca6e35 100644 --- a/dashboard/internal/autolearn/pvreserve_runner.go +++ b/dashboard/internal/autolearn/pvreserve_runner.go @@ -5,15 +5,29 @@ import ( "context" "encoding/json" "fmt" + "maps" "math" "os" "path/filepath" "sync" + "time" "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) +const ( + // liftMinJumpW is the smallest rise of a device's power in W that counts as + // a load switched on. Spec 15.10, decided by Claude. + liftMinJumpW = 100.0 + // liftPVShare is the share of the jump the PV must have risen by. Spec 15.10, + // decided by Claude. + liftPVShare = 0.8 + // liftImportShare is the share of the jump the grid import may rise by at + // most. Spec 15.10, decided by Claude. + liftImportShare = 0.2 +) + // PVReserveRunner turns each minute into the PV reserve and the weather factor // k. It runs after the PVTracker on the minute hub, so the tracker has already // observed the same minute. It owns the Weather and saves it to pvweather.json. @@ -29,6 +43,12 @@ type PVReserveRunner struct { have bool w float64 est bool + // Values of the previous minute for the lift check. + prevHave bool + prevMinute time.Time + prevPV float64 + prevImport float64 + prevDev map[string]learnrec.DeviceMinute } // NewPVReserveRunner creates the runner. location reports the site coordinates, @@ -67,6 +87,8 @@ func (r *PVReserveRunner) ObserveMinute(f learnrec.Frame) { defer r.mu.Unlock() r.have = false pv := f.Balance["pv"] + imp := f.Balance["grid_import"] + defer r.remember(f, pv, imp) model, ok := r.models.Model() if !ok || r.location == nil || pv <= 0 { return @@ -78,6 +100,15 @@ func (r *PVReserveRunner) ObserveMinute(f learnrec.Frame) { az, el := sun.Position(f.Minute, lat, lon) best := r.tracker.BestAt(model, az, el) r.weather.Observe(f.Minute, pv, best, r.tracker.LastUnthrottled()) + if r.prevHave && f.Minute.Sub(r.prevMinute) == time.Minute { + if jump, ok := liftFrameJump(r.prevDev, f.Devices); ok { + dPV := pv - r.prevPV + dImp := imp - r.prevImport + if dPV >= liftPVShare*jump && dImp < liftImportShare*jump { + r.weather.LiftForLoad(f.Minute, r.prevPV, dPV, best) + } + } + } k, kLow, fresh := r.weather.K(f.Minute) r.w, r.est = Reserve(best, pv, kLow, fresh) if !model.Safe { @@ -89,6 +120,65 @@ func (r *PVReserveRunner) ObserveMinute(f learnrec.Frame) { } } +// remember keeps the values of the minute for the lift check of the next minute. +// It runs at the end of every ObserveMinute call, also when that returns early, +// and the caller holds r.mu. The device maps are copied. +func (r *PVReserveRunner) remember(f learnrec.Frame, pv, imp float64) { + r.prevHave = pv > 0 + r.prevMinute = f.Minute + r.prevPV = pv + r.prevImport = imp + r.prevDev = make(map[string]learnrec.DeviceMinute, len(f.Devices)) + for _, d := range f.Devices { + r.prevDev[d.ID] = learnrec.DeviceMinute{ID: d.ID, Power: maps.Clone(d.Power), Switch: maps.Clone(d.Switch)} + } +} + +// liftFrameJump returns the largest liftJump over the devices of the minute. +// A device without a value in prev does not count. +func liftFrameJump(prev map[string]learnrec.DeviceMinute, cur []learnrec.DeviceMinute) (jump float64, ok bool) { + for _, d := range cur { + p, found := prev[d.ID] + if !found { + continue + } + if j, lifted := liftJump(p, d); lifted && (!ok || j > jump) { + jump, ok = j, true + } + } + return jump, ok +} + +// liftJump reports the rise of a device's summed power from prev to cur when one +// of its switches went from off to on and the rise is at least liftMinJumpW. +// A switch missing in prev counts as off. +func liftJump(prev, cur learnrec.DeviceMinute) (jump float64, ok bool) { + edge := false + for key, on := range cur.Switch { + if on && !prev.Switch[key] { + edge = true + break + } + } + if !edge { + return 0, false + } + rise := sumPowerW(cur.Power) - sumPowerW(prev.Power) + if rise < liftMinJumpW { + return 0, false + } + return rise, true +} + +// sumPowerW adds the power values of one device in W. +func sumPowerW(power map[string]float64) float64 { + var sum float64 + for _, w := range power { + sum += w + } + return sum +} + // Current returns the reserve of the last minute, whether it is an estimate, and // whether there is one. ok is false without model, location or before the first // minute. @@ -210,5 +300,7 @@ func (r *PVReserveRunner) Reset() error { r.have = false r.w = 0 r.est = false + r.prevHave = false + r.prevDev = nil return removeIfExists(r.path) } diff --git a/dashboard/internal/autolearn/pvreserve_runner_test.go b/dashboard/internal/autolearn/pvreserve_runner_test.go index 63b9a347..8c744928 100644 --- a/dashboard/internal/autolearn/pvreserve_runner_test.go +++ b/dashboard/internal/autolearn/pvreserve_runner_test.go @@ -235,3 +235,81 @@ func TestPVReserveNeedsDays(t *testing.T) { t.Fatalf("Current ok=%v est=%v with unsafe model, want ok true, est true", ok, est) } } + +// liftTestRunner builds a runner with a safe model, a location and a tracker +// with a regulator, so minutes without grid export count as throttled and +// only the lift can measure. The raster holds 4000 W at pvTestMinute. Weather +// starts empty, so k is 0.5. +func liftTestRunner(t *testing.T) (*PVReserveRunner, *Weather) { + t.Helper() + store := NewPVModelStore(filepath.Join(t.TempDir(), "pvmodel.json")) + store.Set(reserveTestModel()) + reg := &RegulatorView{Present: true, DeadbandW: 50} + tr := NewPVTracker(NewRaster(5, 3), pvTestLocation, func() *RegulatorView { return reg }, pvTestDayFunc, "") + seed := learnrec.Frame{Minute: pvTestMinute, Balance: map[string]float64{"pv": 4000, "grid_export": 200}} + tr.ObserveMinute(seed) + tr.ObserveMinute(seed) + w := &Weather{} + return NewPVReserveRunner(tr, store, pvTestLocation, w, ""), w +} + +// liftRunnerFrame is a minute with PV pv, grid import imp and one device heater +// at heaterW with its switch on or off. +func liftRunnerFrame(at time.Time, pv, imp, heaterW float64, on bool) learnrec.Frame { + return learnrec.Frame{ + Minute: at, + Balance: map[string]float64{"pv": pv, "grid_import": imp}, + Devices: []learnrec.DeviceMinute{{ + ID: "heater", + Power: map[string]float64{"power": heaterW}, + Switch: map[string]bool{"switch": on}, + }}, + } +} + +// liftRunnerObserve runs one minute through the hub order: tracker, then runner. +func liftRunnerObserve(tr *PVTracker, r *PVReserveRunner, f learnrec.Frame) { + tr.ObserveMinute(f) + r.ObserveMinute(f) +} + +func TestRunnerLiftsKWhenPVFollowsLoad(t *testing.T) { + r, w := liftTestRunner(t) + tr := r.tracker + liftRunnerObserve(tr, r, liftRunnerFrame(pvTestMinute.Add(-time.Minute), 1000, 0, 0, false)) + liftRunnerObserve(tr, r, liftRunnerFrame(pvTestMinute, 2450, 50, 1500, true)) + k, _, _ := w.K(pvTestMinute) + if k < 2450.0/4000.0 { + t.Fatalf("k = %v, want >= %v after the lift", k, 2450.0/4000.0) + } +} + +func TestRunnerNoLiftWhenGridCoversLoad(t *testing.T) { + r, w := liftTestRunner(t) + tr := r.tracker + liftRunnerObserve(tr, r, liftRunnerFrame(pvTestMinute.Add(-time.Minute), 1000, 0, 0, false)) + liftRunnerObserve(tr, r, liftRunnerFrame(pvTestMinute, 1100, 1400, 1500, true)) + if k, _, _ := w.K(pvTestMinute); k != 0.5 { + t.Fatalf("k = %v, want 0.5 unchanged", k) + } +} + +func TestRunnerNoLiftWithoutSwitchEdge(t *testing.T) { + r, w := liftTestRunner(t) + tr := r.tracker + liftRunnerObserve(tr, r, liftRunnerFrame(pvTestMinute.Add(-time.Minute), 1000, 0, 0, true)) + liftRunnerObserve(tr, r, liftRunnerFrame(pvTestMinute, 2450, 50, 1500, true)) + if k, _, _ := w.K(pvTestMinute); k != 0.5 { + t.Fatalf("k = %v, want 0.5 unchanged", k) + } +} + +func TestRunnerNoLiftAfterGap(t *testing.T) { + r, w := liftTestRunner(t) + tr := r.tracker + liftRunnerObserve(tr, r, liftRunnerFrame(pvTestMinute.Add(-5*time.Minute), 1000, 0, 0, false)) + liftRunnerObserve(tr, r, liftRunnerFrame(pvTestMinute, 2450, 50, 1500, true)) + if k, _, _ := w.K(pvTestMinute); k != 0.5 { + t.Fatalf("k = %v, want 0.5 unchanged", k) + } +} From 0ad88792e3049daf4901b8ebae604a51fff39989 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:10:03 +0100 Subject: [PATCH 03/20] fix(autolearn): need a known off state before a switch counts as turned on Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/pvreserve_runner.go | 5 +++-- .../internal/autolearn/pvreserve_runner_test.go | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/dashboard/internal/autolearn/pvreserve_runner.go b/dashboard/internal/autolearn/pvreserve_runner.go index 26ca6e35..ffe29444 100644 --- a/dashboard/internal/autolearn/pvreserve_runner.go +++ b/dashboard/internal/autolearn/pvreserve_runner.go @@ -151,11 +151,12 @@ func liftFrameJump(prev map[string]learnrec.DeviceMinute, cur []learnrec.DeviceM // liftJump reports the rise of a device's summed power from prev to cur when one // of its switches went from off to on and the rise is at least liftMinJumpW. -// A switch missing in prev counts as off. +// A switch missing in prev is not a known off state, so it does not count as +// an edge. func liftJump(prev, cur learnrec.DeviceMinute) (jump float64, ok bool) { edge := false for key, on := range cur.Switch { - if on && !prev.Switch[key] { + if was, known := prev.Switch[key]; on && known && !was { edge = true break } diff --git a/dashboard/internal/autolearn/pvreserve_runner_test.go b/dashboard/internal/autolearn/pvreserve_runner_test.go index 8c744928..7563ad65 100644 --- a/dashboard/internal/autolearn/pvreserve_runner_test.go +++ b/dashboard/internal/autolearn/pvreserve_runner_test.go @@ -313,3 +313,18 @@ func TestRunnerNoLiftAfterGap(t *testing.T) { t.Fatalf("k = %v, want 0.5 unchanged", k) } } + +func TestLiftJumpNeedsPreviousOffState(t *testing.T) { + cur := learnrec.DeviceMinute{ID: "heater", Power: map[string]float64{"power": 1500}, Switch: map[string]bool{"switch": true}} + + // Without a known off state in prev the switch does not count as turned on. + if _, ok := liftJump(learnrec.DeviceMinute{ID: "heater", Power: map[string]float64{"power": 0}}, cur); ok { + t.Fatal("ok = true without the switch in prev, want false") + } + + // A known off state gives the rise. + jump, ok := liftJump(learnrec.DeviceMinute{ID: "heater", Power: map[string]float64{"power": 0}, Switch: map[string]bool{"switch": false}}, cur) + if !ok || jump != 1500 { + t.Fatalf("liftJump = %v, %v; want 1500, true", jump, ok) + } +} From 53d5881c7ddc8b2616112dacb95a3240177f1e8e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:12:23 +0100 Subject: [PATCH 04/20] fix(autolearn): let a detected shade cap the best PV curve Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 2 +- dashboard/internal/autolearn/demo_test.go | 4 +- dashboard/internal/autolearn/detect_shade.go | 31 +++++---- .../internal/autolearn/detect_shade_test.go | 67 ++++++++++++++++++- dashboard/internal/autolearn/pvmodel.go | 22 +++++- dashboard/internal/autolearn/pvmodel_test.go | 25 +++++++ dashboard/internal/autolearn/pvmodelstore.go | 27 +++++++- .../internal/autolearn/pvmodelstore_test.go | 23 +++++++ 8 files changed, 182 insertions(+), 19 deletions(-) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 572bceab..069ea724 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -613,7 +613,7 @@ func main() { automationEngine.Register(autolearn.BaseLoadDetector) automationEngine.Register(autolearn.BatteryDetector) automationEngine.Register(autolearn.NewPVModelDetector(pvTracker.Snapshot, pvModelStore)) - automationEngine.Register(autolearn.NewShadeDetector(pvTracker.Snapshot, pvModelStore.Model)) + automationEngine.Register(autolearn.NewShadeDetector(pvTracker.Snapshot, pvModelStore)) // Modell und Himmelsraster fuer den Rest-Ueberschuss. Der Raster-Schnappschuss // entsteht nur, wenn ein Modell da ist. pvSource := func() (autolearn.PVModel, *autolearn.Raster, bool) { diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index aaa18bf8..5706653b 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -583,7 +583,7 @@ func TestDemoShadeCyclesAndSurplus(t *testing.T) { } ctx := context.Background() - shade := NewShadeDetector(func() *Raster { return raster }, func() (PVModel, bool) { return model, true }) + shade := NewShadeDetector(func() *Raster { return raster }, shadeStore(t, model)) var shades []string for _, c := range shade.Run(ctx, in, "") { shades = append(shades, c.Finding.ID) @@ -694,7 +694,7 @@ func TestDemoShadeCurveSkipsTheRunningDay(t *testing.T) { in.Days = days raster := DemoPVRaster(now, demoLat, demoLon) model := DemoPVModel(raster) - shade := NewShadeDetector(func() *Raster { return raster }, func() (PVModel, bool) { return model, true }) + shade := NewShadeDetector(func() *Raster { return raster }, shadeStore(t, model)) cands := shade.Run(context.Background(), in, "") if len(cands) == 0 { t.Fatal("demo shows no shade") diff --git a/dashboard/internal/autolearn/detect_shade.go b/dashboard/internal/autolearn/detect_shade.go index 0dd2aca8..a062db10 100644 --- a/dashboard/internal/autolearn/detect_shade.go +++ b/dashboard/internal/autolearn/detect_shade.go @@ -49,28 +49,30 @@ func isShadeCandidate(c *shadeCell) bool { } // NewShadeDetector creates the shade detector. raster returns a copy of the -// sky raster, model the stored roof model and whether one exists. The detector -// runs once per round for all devices and returns no fixes. -func NewShadeDetector(raster func() *Raster, model func() (PVModel, bool)) Detector { +// sky raster, store holds the roof model. A finished run writes the cells of +// all shades it finds to the store, so the best curve can use them. The +// detector runs once per round for all devices and returns no fixes. +func NewShadeDetector(raster func() *Raster, store *PVModelStore) Detector { return Detector{ Name: "shade", Group: "energy", Light: false, PerDevice: false, Run: func(ctx context.Context, in *Input, _ string) []Candidate { - return shadeRun(ctx, in, raster, model) + return shadeRun(ctx, in, raster, store) }, } } -// shadeRun finds the shades of the raster. Without a site location, a safe -// model or a raster it returns nothing. -func shadeRun(ctx context.Context, in *Input, raster func() *Raster, model func() (PVModel, bool)) []Candidate { - if ctx.Err() != nil || raster == nil || model == nil || in.Doc.Location == nil { +// shadeRun finds the shades of the raster and stores their cells. Without a +// site location, a safe model or a raster it returns nothing and stores +// nothing. A run cut off by ctx stores nothing. +func shadeRun(ctx context.Context, in *Input, raster func() *Raster, store *PVModelStore) []Candidate { + if ctx.Err() != nil || raster == nil || in.Doc.Location == nil { return nil } r := raster() - m, ok := model() + m, ok := store.Model() if r == nil || !ok || !m.Safe { return nil } @@ -80,21 +82,26 @@ func shadeRun(ctx context.Context, in *Input, raster func() *Raster, model func( } site := in.Doc.Location cells := shadeCells(r, m) - if len(cells) == 0 { - return nil - } clearDays := shadeClearDays(in.Days) shadeCountDays(cells, r, in.Days, clearDays, loc, site) var out []Candidate + var keys [][2]int for _, comp := range shadeComponents(r, cells) { if ctx.Err() != nil { return nil } if c, ok := shadeCandidate(r, m, cells, comp, in, clearDays, loc, site); ok { out = append(out, c) + for _, sc := range comp { + keys = append(keys, sc.key) + } } } + if ctx.Err() != nil { + return nil + } + store.SetShade(keys) return out } diff --git a/dashboard/internal/autolearn/detect_shade_test.go b/dashboard/internal/autolearn/detect_shade_test.go index 157e732e..7538614e 100644 --- a/dashboard/internal/autolearn/detect_shade_test.go +++ b/dashboard/internal/autolearn/detect_shade_test.go @@ -2,6 +2,7 @@ package autolearn import ( "context" + "path/filepath" "testing" "time" @@ -59,8 +60,22 @@ func shadeFixture(t *testing.T, m PVModel, factor func(i, j int) float64) (*Rast return r, days } +// shadeStore returns a store that holds the roof model m and no shade. +func shadeStore(t *testing.T, m PVModel) *PVModelStore { + t.Helper() + store := NewPVModelStore(filepath.Join(t.TempDir(), "pvmodel.json")) + store.Set(m) + return store +} + // runShade runs the shade detector over the fixture of the year 2026. func runShade(t *testing.T, r *Raster, m PVModel, days []DayFile) []Candidate { + t.Helper() + return runShadeStore(t, r, shadeStore(t, m), days) +} + +// runShadeStore runs the shade detector with the given store over the fixture of the year 2026. +func runShadeStore(t *testing.T, r *Raster, store *PVModelStore, days []DayFile) []Candidate { t.Helper() loc := berlinLoc(t) in := &Input{ @@ -69,7 +84,7 @@ func runShade(t *testing.T, r *Raster, m PVModel, days []DayFile) []Candidate { Days: days, Doc: Doc{Location: shadeSite}, } - det := NewShadeDetector(func() *Raster { return r }, func() (PVModel, bool) { return m, true }) + det := NewShadeDetector(func() *Raster { return r }, store) return det.Run(context.Background(), in, "") } @@ -144,3 +159,53 @@ func TestShadeUnsafeModelGivesNone(t *testing.T) { t.Fatalf("got %d candidates, want 0", len(cands)) } } + +func TestShadeRunStoresShadeCells(t *testing.T) { + m := shadeModel() + r, days := shadeFixture(t, m, func(i, j int) float64 { + if shadeInCell(i, j) { + return 0.4 + } + return 0.95 + }) + store := shadeStore(t, m) + if cands := runShadeStore(t, r, store, days); len(cands) != 1 { + t.Fatalf("got %d candidates, want 1", len(cands)) + } + got, _ := store.Model() + want := map[[2]int]bool{} + for i := 42; i <= 45; i++ { + for j := 4; j <= 5; j++ { + want[[2]int{i, j}] = true + } + } + if len(got.Shade) != len(want) { + t.Fatalf("Shade has %d cells %v, want %d", len(got.Shade), got.Shade, len(want)) + } + for _, k := range got.Shade { + if !want[k] { + t.Errorf("Shade cell %v is not in the shade", k) + } + } +} + +func TestShadeRunClearsVanishedShade(t *testing.T) { + m := shadeModel() + r, days := shadeFixture(t, m, func(i, j int) float64 { + if shadeInCell(i, j) { + return 0.4 + } + return 0.95 + }) + store := shadeStore(t, m) + runShadeStore(t, r, store, days) + if got, _ := store.Model(); len(got.Shade) == 0 { + t.Fatal("first run stored no shade cells") + } + + flat, flatDays := shadeFixture(t, m, func(i, j int) float64 { return 0.95 }) + runShadeStore(t, flat, store, flatDays) + if got, _ := store.Model(); len(got.Shade) != 0 { + t.Fatalf("Shade = %v after the shade vanished, want empty", got.Shade) + } +} diff --git a/dashboard/internal/autolearn/pvmodel.go b/dashboard/internal/autolearn/pvmodel.go index a630ed63..6df8d1fd 100644 --- a/dashboard/internal/autolearn/pvmodel.go +++ b/dashboard/internal/autolearn/pvmodel.go @@ -35,6 +35,9 @@ type PVModel struct { CapW float64 Safe bool FittedAt int64 + // Shade are the sky cells of detected shades. In these cells the raster + // value counts as the expected power, see Best. + Shade [][2]int `json:"shade,omitempty"` } // pvSky is one sky position with the values the fit needs precomputed. @@ -242,9 +245,21 @@ func FitPV(r *Raster, step float64, maxSurfaces int) (PVModel, bool) { return model, true } +// inShade reports whether the sky cell key is part of a detected shade. +func (m PVModel) inShade(key [2]int) bool { + for _, k := range m.Shade { + if k == key { + return true + } + } + return false +} + // Best returns the expected PV power in W at az/el: the larger of the raster -// cell value and the modelled surfaces, capped at CapW. Below 3 degrees of -// sun elevation it returns 0. +// cell value and the modelled surfaces, capped at CapW. A sky cell inside a +// detected shade with a raster value gives that value instead of the larger +// one, so the shade lowers the curve. Below 3 degrees of sun elevation it +// returns 0. func (m PVModel) Best(az, el float64, r *Raster) float64 { if el < pvRasterMinElDeg { return 0 @@ -253,6 +268,9 @@ func (m PVModel) Best(az, el float64, r *Raster) float64 { if r != nil { if w, ok := r.Cell(az, el); ok { cell = w + if m.inShade(r.index(az, el)) { + return math.Min(m.CapW, w) + } } } p := newPVSky(az, el, 0) diff --git a/dashboard/internal/autolearn/pvmodel_test.go b/dashboard/internal/autolearn/pvmodel_test.go index 339855e8..da55caff 100644 --- a/dashboard/internal/autolearn/pvmodel_test.go +++ b/dashboard/internal/autolearn/pvmodel_test.go @@ -150,3 +150,28 @@ func TestBestPrefersCellWhenHigher(t *testing.T) { t.Fatalf("Best = %v, want cell value 4000", got) } } + +func TestBestUsesCellInsideShade(t *testing.T) { + r := NewRaster(5, 3) + r.Add(180, 60, 1200, "2026-11-01") + r.Add(180, 60, 1200, "2026-11-02") + m := PVModel{Surfaces: []Surface{{PMax: 3000 / pvGeom(180, 60, 30, 180), TiltDeg: 30, AzimuthDeg: 180}}, CapW: 6000} + + if got := m.Best(180, 60, r); math.Abs(got-3000) > 1e-6 { + t.Fatalf("Best without shade = %v, want model 3000", got) + } + m.Shade = [][2]int{r.index(180, 60)} + if got := m.Best(180, 60, r); got != 1200 { + t.Fatalf("Best inside shade = %v, want cell value 1200", got) + } +} + +func TestBestShadeWithoutCellUsesModel(t *testing.T) { + m := PVModel{Surfaces: []Surface{{PMax: 5000, TiltDeg: 30, AzimuthDeg: 180}}, CapW: 6000} + r := NewRaster(5, 3) + m.Shade = [][2]int{r.index(180, 60)} + want := 5000 * pvGeom(180, 60, 30, 180) + if got := m.Best(180, 60, r); math.Abs(got-want) > 1e-6 { + t.Fatalf("Best in empty shade cell = %v, want model %v", got, want) + } +} diff --git a/dashboard/internal/autolearn/pvmodelstore.go b/dashboard/internal/autolearn/pvmodelstore.go index 190c357f..7951e9c2 100644 --- a/dashboard/internal/autolearn/pvmodelstore.go +++ b/dashboard/internal/autolearn/pvmodelstore.go @@ -45,15 +45,40 @@ func (s *PVModelStore) Model() (PVModel, bool) { return s.model, s.ok } -// Set replaces the stored model. The next Save writes it. +// Set replaces the stored model. The stored shade cells are kept, a new fit +// does not clear a shade. The next Save writes the model. func (s *PVModelStore) Set(m PVModel) { s.mu.Lock() defer s.mu.Unlock() + m.Shade = s.model.Shade s.model = m s.ok = true s.dirty = true } +// SetShade replaces the shade cells of the stored model with a copy of keys. +// An empty list clears them. The next Save writes the change. +func (s *PVModelStore) SetShade(keys [][2]int) { + s.mu.Lock() + defer s.mu.Unlock() + cp := append([][2]int(nil), keys...) + if len(cp) == len(s.model.Shade) && equalKeys(cp, s.model.Shade) { + return + } + s.model.Shade = cp + s.dirty = true +} + +// equalKeys reports whether a and b hold the same sky cell keys in the same order. +func equalKeys(a, b [][2]int) bool { + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + // Save writes the model atomically: a temporary file in the same directory, // then a rename over the target. Nothing is written when the model did not // change since the last save. diff --git a/dashboard/internal/autolearn/pvmodelstore_test.go b/dashboard/internal/autolearn/pvmodelstore_test.go index 10be373e..5fda1b89 100644 --- a/dashboard/internal/autolearn/pvmodelstore_test.go +++ b/dashboard/internal/autolearn/pvmodelstore_test.go @@ -123,3 +123,26 @@ func TestPVTrackerSnapshotIsCopy(t *testing.T) { t.Fatalf("snapshot changed with the live raster: %v -> %v", before, after) } } + +func TestModelStoreSetKeepsShade(t *testing.T) { + store := NewPVModelStore(filepath.Join(t.TempDir(), "pvmodel.json")) + want := [][2]int{{42, 4}, {43, 4}} + store.SetShade(want) + store.Set(PVModel{CapW: 1}) + m, ok := store.Model() + if !ok || len(m.Shade) != len(want) || m.Shade[0] != want[0] || m.Shade[1] != want[1] { + t.Fatalf("Shade = %v ok=%v, want %v", m.Shade, ok, want) + } +} + +func TestModelStoreLoadsOldFileWithoutShade(t *testing.T) { + path := filepath.Join(t.TempDir(), "pvmodel.json") + old := `{"Surfaces":[{"PMax":5000,"TiltDeg":30,"AzimuthDeg":180}],"CapW":6000,"Safe":true,"FittedAt":1}` + if err := os.WriteFile(path, []byte(old), 0o600); err != nil { + t.Fatal(err) + } + m, ok := NewPVModelStore(path).Model() + if !ok || len(m.Surfaces) != 1 || len(m.Shade) != 0 { + t.Fatalf("model = %+v ok=%v, want one surface and no shade", m, ok) + } +} From 839eae210c3e111cd6d799b209742df7d04ea615 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:16:48 +0100 Subject: [PATCH 05/20] fix(autolearn): expect the night base load from the outdoor temperature Co-Authored-By: Claude Sonnet 5.5 --- .../internal/autolearn/detect_baseload.go | 102 ++++++++++++++---- .../autolearn/detect_baseload_test.go | 101 +++++++++++++++++ dashboard/internal/webui/catalogs/de.json | 1 + dashboard/internal/webui/catalogs/en.json | 1 + 4 files changed, 187 insertions(+), 18 deletions(-) diff --git a/dashboard/internal/autolearn/detect_baseload.go b/dashboard/internal/autolearn/detect_baseload.go index 03fc72a4..c2e85f47 100644 --- a/dashboard/internal/autolearn/detect_baseload.go +++ b/dashboard/internal/autolearn/detect_baseload.go @@ -61,6 +61,10 @@ type baseloadNight struct { night float64 // dev is the average power of each device with a record in the night, W. dev map[string]float64 + // tempC is the mean outdoor temperature over the night quarters with a + // value, C. hasTemp is set from half of the night quarters on. + tempC float64 + hasTemp bool } // baseLoadRun returns the drift finding and the learned site/base_w. @@ -132,6 +136,8 @@ func baseloadNights(in *Input) []baseloadNight { } var quarters []int var load []float64 + var tempSum float64 + tempN := 0 seen := true for q := 0; q < dayQuarters; q++ { if !baseloadNightQuarter(q, ds, nr) { @@ -142,10 +148,18 @@ func baseloadNights(in *Input) []baseloadNight { seen = false } load = append(load, float64(f.Site.LoadTotal[q])) + if p := f.Site.TempC[q]; p != nil { + tempSum += float64(*p) + tempN++ + } } if !seen || len(load) == 0 { continue } + var tempC float64 + if tempN > 0 { + tempC = tempSum / float64(tempN) + } _, week := t.ISOWeek() dev := map[string]float64{} for id, dd := range f.Devices { @@ -163,7 +177,8 @@ func baseloadNights(in *Input) []baseloadNight { dev[id] = sum / float64(n) } } - out = append(out, baseloadNight{date: f.Day, week: week, at: t, group: g, night: basePercentile10(load), dev: dev}) + out = append(out, baseloadNight{date: f.Day, week: week, at: t, group: g, night: basePercentile10(load), dev: dev, + tempC: tempC, hasTemp: 2*tempN >= len(quarters)}) } return out } @@ -180,7 +195,7 @@ func baseloadNightQuarter(q int, dayStart, nightRest float64) bool { // of the same weeks of the earlier years when the season store has them, else // the reference of the window. The spread is the MAD of the nights. func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { - exp := baseloadExpect(in, ns) + exp, tempAdj := baseloadExpect(in, ns) loads := make([]float64, len(ns)) for i, n := range ns { loads[i] = n.night @@ -207,7 +222,7 @@ func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { return nil } if !rising { - return baseloadFall(ns, at, before, after, shift) + return baseloadFall(ns, at, before, after, shift, tempAdj) } device := baseloadDevice(in, ns, at, shift) date := ns[at].date @@ -231,6 +246,9 @@ func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { Device: device, Benefit: &benefit, } + if tempAdj { + finding.Facts = []Fact{{Code: "temp_adjusted", Value: true}} + } if device != "" && in.Devices[device].Switchable { finding.Apply = []Fix{{Code: "night_off", Template: "night_off", Prefill: withEntity(map[string]any{"device": device}, "entity", switchEntityOf(in, device))}} @@ -255,7 +273,7 @@ func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { // baseloadFall reports a sustained fall of the nights from before to after. It // names no device and suggests no rule: a lower base load is a notice for the // monitoring, with no saving to win back, so the benefit stays empty. -func baseloadFall(ns []baseloadNight, at int, before, after []float64, shift float64) []Candidate { +func baseloadFall(ns []baseloadNight, at int, before, after []float64, shift float64, tempAdj bool) []Candidate { w := baseloadRound(-shift, baseloadRoundW) after0, before0 := Median(after), Median(before) finding := Finding{ @@ -269,6 +287,9 @@ func baseloadFall(ns []baseloadNight, at int, before, after []float64, shift flo }}, Evidence: Evidence{Shape: "scale", Unit: "W", IstValue: &after0, SollValue: &before0}, } + if tempAdj { + finding.Facts = []Fact{{Code: "temp_adjusted", Value: true}} + } return []Candidate{{ Finding: finding, Detector: "baseload", @@ -280,32 +301,77 @@ func baseloadFall(ns []baseloadNight, at int, before, after []float64, shift flo }} } -// baseloadExpect returns the expected night load of each night. With the same -// weeks of baseloadMinYears earlier years in the season store that is their -// median, else the reference of the window. -func baseloadExpect(in *Input, ns []baseloadNight) []float64 { +// baseloadTempExpect returns the expected night load of each night from its +// outdoor temperature: a heating hinge fitted over the nights with a +// temperature. Nights without one get the median of the expectations. ok is +// false when fewer than baseloadMinNights nights have a temperature or the fit +// is not trustworthy. +func baseloadTempExpect(ns []baseloadNight) ([]float64, bool) { + var temp, y []float64 + for _, n := range ns { + if n.hasTemp { + temp = append(temp, n.tempC) + y = append(y, n.night) + } + } + if len(temp) < baseloadMinNights { + return nil, false + } + knee, a, b, _, ok := FitKnee(temp, y, false) + if !ok { + return nil, false + } + exp := make([]float64, len(ns)) + var known []float64 + for i, n := range ns { + if n.hasTemp { + exp[i] = a + b*math.Max(0, knee-n.tempC) + known = append(known, exp[i]) + } + } + fallback := Median(known) + for i, n := range ns { + if !n.hasTemp { + exp[i] = fallback + } + } + return exp, true +} + +// baseloadExpect returns the expected night load of each night and whether a +// night took its expectation from the temperature. Per night the order is: the +// median of the same weeks of baseloadMinYears earlier years in the season +// store, else the temperature expectation, else the reference of the window. +func baseloadExpect(in *Input, ns []baseloadNight) ([]float64, bool) { loads := make([]float64, 0, baseloadRefNights) for i := 0; i < len(ns) && i < baseloadRefNights; i++ { loads = append(loads, ns[i].night) } ref := Median(loads) + temp, tempOK := baseloadTempExpect(ns) exp := make([]float64, len(ns)) + usedTemp := false for i, n := range ns { exp[i] = ref - if in.Season == nil { - continue + fromTemp := tempOK + if tempOK { + exp[i] = temp[i] } - var vals []float64 - for _, w := range in.Season.Same(n.at, n.week, baseloadMinYears) { - if w.BaseW > 0 { - vals = append(vals, w.BaseW) + if in.Season != nil { + var vals []float64 + for _, w := range in.Season.Same(n.at, n.week, baseloadMinYears) { + if w.BaseW > 0 { + vals = append(vals, w.BaseW) + } + } + if len(vals) >= baseloadMinYears { + exp[i] = Median(vals) + fromTemp = false } } - if len(vals) >= baseloadMinYears { - exp[i] = Median(vals) - } + usedTemp = usedTemp || fromTemp } - return exp + return exp, usedTemp } // baseloadSeasonKnown reports whether every night has its expectation from the diff --git a/dashboard/internal/autolearn/detect_baseload_test.go b/dashboard/internal/autolearn/detect_baseload_test.go index c528ace8..7033e1cb 100644 --- a/dashboard/internal/autolearn/detect_baseload_test.go +++ b/dashboard/internal/autolearn/detect_baseload_test.go @@ -3,6 +3,7 @@ package autolearn import ( "context" "fmt" + "math" "testing" "time" ) @@ -273,3 +274,103 @@ func TestBaseLoadDriftWithSeasonNeedsOnlyFourteenNights(t *testing.T) { t.Fatalf("20 nights without a season gave %d findings, want none", len(findings)) } } + +// blWithTemp sets the outdoor temperature temp(i) in C on every night quarter +// of day i. +func blWithTemp(in *Input, temp func(i int) float64) *Input { + for i := range in.Days { + for q := 0; q < dayQuarters; q++ { + if blNight(q) { + v := float32(temp(i)) + in.Days[i].Site.TempC[q] = &v + } + } + } + return in +} + +// blHeatingLoad is the night load in W of a heating house at temp C. +func blHeatingLoad(temp float64) float64 { + return 150 + 20*math.Max(0, 12-temp) +} + +func TestBaseloadHeatingStartIsNoDrift(t *testing.T) { + // 60 nights, the temperature falls from 16 to 2 C, the night load follows it. + temp := func(i int) float64 { return 16 - 14*float64(i)/59 } + in := blWithTemp(blInput(60, func(i int) float64 { + return blHeatingLoad(temp(i)) + }, nil), temp) + if findings, _ := blSplit(in); len(findings) != 0 { + t.Fatalf("heating start gave %d findings, want none", len(findings)) + } +} + +func TestBaseloadDriftFoundDespiteTemperature(t *testing.T) { + // Nights 0 to 44 cycle through 14 to 6 C, so the reference nights cover + // temperatures around 8 C many times. From night 45 on the temperature + // stays at 8 C and a heater adds 120 W. + cycle := []float64{14, 12, 10, 9, 8, 7, 6} + temp := func(i int) float64 { + if i >= 45 { + return 8 + } + return cycle[i%len(cycle)] + } + in := blWithTemp(blInput(60, func(i int) float64 { + if i >= 45 { + return blHeatingLoad(temp(i)) + 120 + } + return blHeatingLoad(temp(i)) + }, func(i int) (float64, bool) { + if i >= 45 { + return 120, true + } + return 0, true + }), temp) + findings, _ := blSplit(in) + if len(findings) != 1 { + t.Fatalf("want one drift finding, got %d", len(findings)) + } + f := findings[0] + if f.Summary.Code != "baseload.drift" || f.Device != "plug.heater" { + t.Errorf("summary %q with device %q, want baseload.drift with plug.heater", f.Summary.Code, f.Device) + } + if !hasFact(f.Facts, "temp_adjusted", true) { + t.Errorf("Facts = %+v, want temp_adjusted true", f.Facts) + } +} + +func TestBaseloadWithoutTemperatureUnchanged(t *testing.T) { + in := blInput(60, func(i int) float64 { + if i < 20 { + return 180 + } + return 260 + }, func(i int) (float64, bool) { + if i < 20 { + return 0, true + } + return 80, true + }) + findings, _ := blSplit(in) + if len(findings) != 1 { + t.Fatalf("want one drift finding, got %d", len(findings)) + } + f := findings[0] + if w := f.Summary.Params["w"]; w != 80.0 { + t.Errorf("w = %v, want 80", w) + } + if hasFact(f.Facts, "temp_adjusted", true) || len(f.Facts) != 0 { + t.Errorf("Facts = %+v, want none without temperature", f.Facts) + } +} + +// hasFact reports whether facts holds the fact code with the value want. +func hasFact(facts []Fact, code string, want any) bool { + for _, f := range facts { + if f.Code == code && f.Value == want { + return true + } + } + return false +} diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index f08d4e8e..d49b912e 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -588,6 +588,7 @@ "automations.learn.fact.season_months": "Monate in der Saison", "automations.learn.fact.settle_s": "Ausregelzeit in Sekunden", "automations.learn.fact.spread_min": "Streuung", + "automations.learn.fact.temp_adjusted": "Außentemperatur berücksichtigt", "automations.learn.fact.window_s": "Zeitfenster", "automations.learn.fix.add_condition": "Bedingung ergänzen", "automations.learn.fix.disable_duplicate": "Diese Regel ausschalten", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 112135e3..f8d23da5 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -588,6 +588,7 @@ "automations.learn.fact.season_months": "Months in the season", "automations.learn.fact.settle_s": "Settling time in seconds", "automations.learn.fact.spread_min": "Spread", + "automations.learn.fact.temp_adjusted": "Outdoor temperature taken into account", "automations.learn.fact.window_s": "Time window", "automations.learn.fix.add_condition": "Add a condition", "automations.learn.fix.disable_duplicate": "Turn this rule off", From 5db0bd2abe5a9d7cc683c38cb8e71c28898578d2 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:18:54 +0100 Subject: [PATCH 06/20] fix(autolearn): ignore rule started runs when learning the day start Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/base.go | 44 +++++++++-- dashboard/internal/autolearn/base_test.go | 90 +++++++++++++++++++++++ 2 files changed, 128 insertions(+), 6 deletions(-) diff --git a/dashboard/internal/autolearn/base.go b/dashboard/internal/autolearn/base.go index fb10afc2..68c7d4d8 100644 --- a/dashboard/internal/autolearn/base.go +++ b/dashboard/internal/autolearn/base.go @@ -43,6 +43,7 @@ type baseRec struct { load [dayQuarters]float64 prof [dayQuarters]float64 // Last geteilt durch Tagessumme, nur bei full hand [dayQuarters]float64 // Handgriffe aller Geräte je Viertelstunde + ruleW [dayQuarters]float64 // Leistung der per Regel gestarteten Läufe je Viertelstunde group int // Tagestyp, -1 ohne Zuordnung } @@ -139,6 +140,10 @@ func baseRecords(days []DayFile, loc *time.Location, today string) []baseRec { for q := range dd.Hand { r.hand[q] += float64(dd.Hand[q]) } + rw := ruleRunW(dd) + for q := range rw { + r.ruleW[q] += rw[q] + } } r.full = allSeen && sum > 0 r.morn = morning && sumMorning > 0 @@ -554,6 +559,28 @@ func houseWindowOf(byDate map[string]*DayFile, day time.Time, q int) (baseMetric return baseMetricOver(load, hand), true } +// ruleRunW liefert je Viertelstunde die Leistung eines Laufs, den eine Regel +// gestartet hat. Ein Lauf beginnt in Viertelstunde q, wenn er dort läuft und +// vorher nicht. Er ist ein Regel-Lauf, wenn die Regel ihn in q gestartet hat +// und weder Handgriff noch Ext ihn berührt. Er zählt bis vor die nächste +// Viertelstunde ohne Lauf. Ein Lauf, der vor Mitternacht begann, ist kein +// Regel-Lauf, denn die Tagesdatei allein zeigt seinen Anfang nicht. +func ruleRunW(dd *DeviceDay) [dayQuarters]float64 { + var w [dayQuarters]float64 + for q := 0; q < dayQuarters; q++ { + if dd.OnMin[q] == 0 || q == 0 || dd.OnMin[q-1] != 0 { + continue + } + if dd.Rule[q] == 0 || dd.Hand[q] != 0 || dd.Ext[q] != 0 { + continue + } + for k := q; k < dayQuarters && dd.OnMin[k] > 0; k++ { + w[k] = float64(dd.AvgW[k]) + } + } + return w +} + // baseBounds setzt je Tagestyp den Kreismedian von Tagesbeginn und Nachtruhe. func baseBounds(recs []baseRec, base *Base) { starts := map[int][]float64{} @@ -579,20 +606,25 @@ func baseBounds(recs []baseRec, base *Base) { } // baseDayBounds findet Tagesbeginn und Nachtruhe eines Tages in Minuten. Die -// Last liegt für zwei Viertelstunden über Nachtlast + max(50 W, 3 Streuungen). -// Der Beginn ist die erste solche Viertelstunde oder der erste Handgriff, je -// nachdem was früher kommt. Die Nachtruhe spiegelt das vom Abend her. +// Last ohne die per Regel gestarteten Läufe liegt für zwei Viertelstunden über +// Nachtlast + max(50 W, 3 Streuungen). Der Beginn ist die erste solche +// Viertelstunde oder der erste Handgriff, je nachdem was früher kommt. Die +// Nachtruhe spiegelt das vom Abend her. func baseDayBounds(r *baseRec) (start, end float64, ok bool) { - night := r.load[:baseNight] + var load [dayQuarters]float64 + for q := range load { + load[q] = math.Max(0, r.load[q]-r.ruleW[q]) + } + night := load[:baseNight] thr := basePercentile10(night) + math.Max(50, 3*MADScale(night)) first, last := -1, -1 for q := 0; q+1 < dayQuarters && first < 0; q++ { - if r.load[q] > thr && r.load[q+1] > thr { + if load[q] > thr && load[q+1] > thr { first = q } } for q := dayQuarters - 1; q >= 1 && last < 0; q-- { - if r.load[q] > thr && r.load[q-1] > thr { + if load[q] > thr && load[q-1] > thr { last = q } } diff --git a/dashboard/internal/autolearn/base_test.go b/dashboard/internal/autolearn/base_test.go index b422b067..5c9baea0 100644 --- a/dashboard/internal/autolearn/base_test.go +++ b/dashboard/internal/autolearn/base_test.go @@ -177,3 +177,93 @@ func TestBaseQuietDaysWithoutManualSwitching(t *testing.T) { t.Errorf("away days = %v, want exactly the %d quiet days", base.Away, len(quiet)) } } + +// baseRuleDay baut einen vollständigen Tag. Die Last ist nachts 100 W, die +// Wärmepumpe läuft 05:00 bis 06:30 mit zusätzlich 2000 W, danach 600 W Haus. +// Gerät und Startart kommen von außen, damit Regel und Handgriff gleich aussehen. +func baseRuleDay(day time.Time, dev *DeviceDay) DayFile { + var load [dayQuarters]float32 + for q := range load { + switch { + case q >= 27: + load[q] = 600 + case q >= 20 && q <= 25: + load[q] = 2100 + default: + load[q] = 100 + } + } + f := DayFile{V: dayFileVersion, Day: day.Format(dayLayout), Devices: map[string]*DeviceDay{"heatpump": dev}, + Events: []EventRec{}, Actions: []ActionRec{}} + for q := range load { + f.Site.Seen[q] = 1 + f.Site.LoadTotal[q] = load[q] + } + return f +} + +// baseRuleDays sind 14 gleiche Tage ab Montag, 5. Januar 2026. +func baseRuleDays(t *testing.T, loc *time.Location, dev func() *DeviceDay) []DayFile { + t.Helper() + start := time.Date(2026, 1, 5, 0, 0, 0, 0, loc) + var days []DayFile + for i := 0; i < 14; i++ { + days = append(days, baseRuleDay(start.AddDate(0, 0, i), dev())) + } + return days +} + +func TestDayStartIgnoresRuleStartedHeatPump(t *testing.T) { + loc := berlinLoc(t) + days := baseRuleDays(t, loc, func() *DeviceDay { + dd := &DeviceDay{} + for q := 20; q <= 25; q++ { + dd.OnMin[q] = 15 + dd.AvgW[q] = 2000 + } + dd.Rule[20] = 1 + return dd + }) + now := time.Date(2026, 2, 1, 12, 0, 0, 0, loc) + base := BuildBaseAt(days, loc, now) + g := base.DayType["2026-01-06"] + if got := base.DayStart[g]; math.Abs(got-405) > 1 { + t.Errorf("day start = %.1f, want 405 (06:45), not the rule started 05:00", got) + } +} + +func TestDayStartKeepsHandStartedDevice(t *testing.T) { + loc := berlinLoc(t) + days := baseRuleDays(t, loc, func() *DeviceDay { + dd := &DeviceDay{} + for q := 20; q <= 25; q++ { + dd.OnMin[q] = 15 + dd.AvgW[q] = 2000 + } + dd.Hand[20] = 1 + return dd + }) + now := time.Date(2026, 2, 1, 12, 0, 0, 0, loc) + base := BuildBaseAt(days, loc, now) + g := base.DayType["2026-01-06"] + if got := base.DayStart[g]; math.Abs(got-300) > 1 { + t.Errorf("day start = %.1f, want 300 (05:00) for a hand started device", got) + } +} + +func TestRuleRunWStopsAtOff(t *testing.T) { + var dd DeviceDay + dd.OnMin[1], dd.OnMin[2] = 15, 15 + dd.Rule[1] = 1 + dd.AvgW[1], dd.AvgW[2] = 2000, 2000 + w := ruleRunW(&dd) + for q := range w { + want := 0.0 + if q == 1 || q == 2 { + want = 2000 + } + if w[q] != want { + t.Errorf("ruleW[%d] = %.0f, want %.0f", q, w[q], want) + } + } +} From 8b74a6e66becdae90388deae6506a9120850fc84 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:20:15 +0100 Subject: [PATCH 07/20] fix(autolearn): count a rule start in the first quarter of the day Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/base.go | 11 +++++----- dashboard/internal/autolearn/base_test.go | 26 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/dashboard/internal/autolearn/base.go b/dashboard/internal/autolearn/base.go index 68c7d4d8..184f7695 100644 --- a/dashboard/internal/autolearn/base.go +++ b/dashboard/internal/autolearn/base.go @@ -561,14 +561,15 @@ func houseWindowOf(byDate map[string]*DayFile, day time.Time, q int) (baseMetric // ruleRunW liefert je Viertelstunde die Leistung eines Laufs, den eine Regel // gestartet hat. Ein Lauf beginnt in Viertelstunde q, wenn er dort läuft und -// vorher nicht. Er ist ein Regel-Lauf, wenn die Regel ihn in q gestartet hat -// und weder Handgriff noch Ext ihn berührt. Er zählt bis vor die nächste -// Viertelstunde ohne Lauf. Ein Lauf, der vor Mitternacht begann, ist kein -// Regel-Lauf, denn die Tagesdatei allein zeigt seinen Anfang nicht. +// vorher nicht. Für q = 0 gilt die Viertelstunde davor als aus, ein Lauf in 0 +// startet also dort. Er ist ein Regel-Lauf, wenn die Regel ihn in q gestartet +// hat und weder Handgriff noch Ext ihn berührt. Er zählt bis vor die nächste +// Viertelstunde ohne Lauf. Ein Lauf, der vor Mitternacht begann, hat in 0 keine +// Regel (Rule[0] == 0) und zählt deshalb nicht. func ruleRunW(dd *DeviceDay) [dayQuarters]float64 { var w [dayQuarters]float64 for q := 0; q < dayQuarters; q++ { - if dd.OnMin[q] == 0 || q == 0 || dd.OnMin[q-1] != 0 { + if dd.OnMin[q] == 0 || (q > 0 && dd.OnMin[q-1] != 0) { continue } if dd.Rule[q] == 0 || dd.Hand[q] != 0 || dd.Ext[q] != 0 { diff --git a/dashboard/internal/autolearn/base_test.go b/dashboard/internal/autolearn/base_test.go index 5c9baea0..2b3a2a00 100644 --- a/dashboard/internal/autolearn/base_test.go +++ b/dashboard/internal/autolearn/base_test.go @@ -267,3 +267,29 @@ func TestRuleRunWStopsAtOff(t *testing.T) { } } } + +func TestRuleRunWStartsAtMidnight(t *testing.T) { + // Ein Lauf in Viertelstunde 0 startet dort. Eine Regel in 0 zählt. + var dd DeviceDay + dd.OnMin[0], dd.OnMin[1] = 15, 15 + dd.Rule[0] = 1 + dd.AvgW[0], dd.AvgW[1] = 2000, 2000 + w := ruleRunW(&dd) + for q := range w { + want := 0.0 + if q == 0 || q == 1 { + want = 2000 + } + if w[q] != want { + t.Errorf("with rule: ruleW[%d] = %.0f, want %.0f", q, w[q], want) + } + } + // Ohne Regel in Viertelstunde 0 ist der Lauf vor Mitternacht begonnen. + dd.Rule[0] = 0 + w = ruleRunW(&dd) + for q := range w { + if w[q] != 0 { + t.Errorf("without rule: ruleW[%d] = %.0f, want 0", q, w[q]) + } + } +} From da6fe78052952a56b32895b6b7690c28339b1897 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:22:55 +0100 Subject: [PATCH 08/20] fix(autolearn): suggest the threshold reached on three of the last 14 days The never fired suggestion used 0.75 times the largest value seen, which proposed thresholds no single day came close to. It now takes the third largest daily maximum (or the third smallest daily minimum for below) of the last 14 calendar days, rounded to 50 W for watts and to two significant digits otherwise. With fewer than three days it falls back to the overall extreme as before. The existing test that expected 0.75 times the maximum now expects the third largest daily maximum (500 W) instead. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/observed.go | 123 ++++++++++++++++-- dashboard/internal/autolearn/observed_test.go | 121 ++++++++++++++++- 2 files changed, 229 insertions(+), 15 deletions(-) diff --git a/dashboard/internal/autolearn/observed.go b/dashboard/internal/autolearn/observed.go index d1878b99..03b46604 100644 --- a/dashboard/internal/autolearn/observed.go +++ b/dashboard/internal/autolearn/observed.go @@ -22,6 +22,12 @@ const ( hysteresisStepW = 50.0 // cooldownFloorS is the shortest cooldown the frequent check proposes. cooldownFloorS = 300 + // neverFiredDays is how many calendar days the never fired suggestion looks at (Spec 15.4). + neverFiredDays = 14 + // neverFiredRank is which daily extreme the never fired suggestion takes, the third one (Spec 15.4). + neverFiredRank = 3 + // wattStepW is the step a watt threshold suggestion is rounded to (Festlegung). + wattStepW = 50.0 ) // PVSource returns the stored roof model, the sky raster and whether a model @@ -300,16 +306,16 @@ func neverFiredFinding(rule Rule, stats RuleStats, st ObserverState, season Seas lo, hi = min(lo, r.Min), max(hi, r.Max) } if c.Comparison == "above" && hi < x { - return aboveFinding(rule, i, c, x, lo, hi, season, pv, loc, now) + return aboveFinding(rule, i, c, x, lo, hi, ranges, season, pv, loc, now) } if c.Comparison == "below" && lo > x { - return belowFinding(rule, i, c, x, lo, hi) + return belowFinding(rule, i, c, x, lo, hi, ranges, now) } } return Finding{}, false } -func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season SeasonalSource, pv PVSource, loc *sun.Location, now time.Time) (Finding, bool) { +func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, ranges []DayRange, season SeasonalSource, pv PVSource, loc *sun.Location, now time.Time) (Finding, bool) { var seasonMax *float64 var months []int // unsure is a PV threshold the curve does not reach while the raster does @@ -317,7 +323,7 @@ func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season Seaso unsure := false if c.Type == "balance_threshold" && (c.Field == "pv" || c.Field == "grid_export") && pv != nil && loc != nil { if m, r, ok := pv(); ok && m.Safe { - if f, ok := pvAboveFinding(rule, i, c, x, lo, hi, m, r, *loc, now); ok { + if f, ok := pvAboveFinding(rule, i, c, x, lo, hi, ranges, m, r, *loc, now); ok { return f, true } unsure = true @@ -349,7 +355,7 @@ func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season Seaso return Finding{}, false } - s := math.Max(50, math.Floor(0.75*hi/50)*50) + s := suggestedAbove(ranges, hi, c, now) scale.SollValue = &s scale.Max = scaleMax(hi, x, s) return Finding{ @@ -363,7 +369,7 @@ func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season Seaso "rule": rule.Name, "threshold": x}}, Evidence: scale, Apply: []Fix{{Code: "set_threshold", RuleID: rule.ID, Ops: []Op{ - {Path: []any{"conditions", i, thresholdKey(c)}, Value: int(s)}}}}, + {Path: []any{"conditions", i, thresholdKey(c)}, Value: suggestionValue(s)}}}}, }, true } @@ -373,7 +379,7 @@ func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season Seaso // is never fired with the threshold fix, but only when the raster knows the // highest noon sun of the year. Otherwise ok is false and the caller falls back // to the seasonal maximum. -func pvAboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, m PVModel, r *Raster, loc sun.Location, now time.Time) (Finding, bool) { +func pvAboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, ranges []DayRange, m PVModel, r *Raster, loc sun.Location, now time.Time) (Finding, bool) { scale := Evidence{Shape: "scale", Seen: [2]float64{lo, hi}, IstValue: &x, Unit: unitOf(c)} if week, ok := SeasonWeekFor(x, m, r, loc, now); ok { scale.Max = scaleMax(hi, x) @@ -394,7 +400,7 @@ func pvAboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, m PVModel, return Finding{}, false } - s := math.Max(50, math.Floor(0.75*hi/50)*50) + s := suggestedAbove(ranges, hi, c, now) scale.SollValue = &s scale.Max = scaleMax(hi, x, s) return Finding{ @@ -408,7 +414,7 @@ func pvAboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, m PVModel, "rule": rule.Name, "threshold": x}}, Evidence: scale, Apply: []Fix{{Code: "set_threshold", RuleID: rule.ID, Ops: []Op{ - {Path: []any{"conditions", i, thresholdKey(c)}, Value: int(s)}}}}, + {Path: []any{"conditions", i, thresholdKey(c)}, Value: suggestionValue(s)}}}}, }, true } @@ -457,8 +463,8 @@ func SeasonWeekFor(threshold float64, m PVModel, r *Raster, loc sun.Location, no return 0, false } -func belowFinding(rule Rule, i int, c Condition, y, lo, hi float64) (Finding, bool) { - s := math.Ceil(1.25*lo/50) * 50 +func belowFinding(rule Rule, i int, c Condition, y, lo, hi float64, ranges []DayRange, now time.Time) (Finding, bool) { + s := suggestedBelow(ranges, lo, c, now) scale := Evidence{Shape: "scale", Seen: [2]float64{lo, hi}, IstValue: &y, SollValue: &s, Unit: unitOf(c), Max: scaleMax(hi, y, s)} return Finding{ @@ -472,10 +478,103 @@ func belowFinding(rule Rule, i int, c Condition, y, lo, hi float64) (Finding, bo "rule": rule.Name, "threshold": y}}, Evidence: scale, Apply: []Fix{{Code: "set_threshold", RuleID: rule.ID, Ops: []Op{ - {Path: []any{"conditions", i, thresholdKey(c)}, Value: int(s)}}}}, + {Path: []any{"conditions", i, thresholdKey(c)}, Value: suggestionValue(s)}}}}, }, true } +// suggestedAbove is the threshold a rule that never fired above should use: the +// third largest daily maximum of the last neverFiredDays days, rounded down. Without +// enough days it is the largest maximum hi of all days. +func suggestedAbove(ranges []DayRange, hi float64, c Condition, now time.Time) float64 { + ext, ok := rankedExtreme(ranges, now, true) + if !ok { + ext = hi + } + return roundThreshold(ext, unitOf(c), true) +} + +// suggestedBelow is the threshold a rule that never fired below should use: the +// third smallest daily minimum of the last neverFiredDays days, rounded up. Without +// enough days it is the smallest minimum lo of all days. +func suggestedBelow(ranges []DayRange, lo float64, c Condition, now time.Time) float64 { + ext, ok := rankedExtreme(ranges, now, false) + if !ok { + ext = lo + } + return roundThreshold(ext, unitOf(c), false) +} + +// rankedExtreme is the neverFiredRank-th daily maximum (high) or minimum of the +// last neverFiredDays calendar days up to and including the day of now, counted +// from the largest maximum or the smallest minimum. ok is false with fewer days. +func rankedExtreme(ranges []DayRange, now time.Time, high bool) (float64, bool) { + y, m, d := now.Date() + today := time.Date(y, m, d, 0, 0, 0, 0, time.UTC).Unix() / 86400 + var vals []float64 + for _, r := range ranges { + if r.Day > today-neverFiredDays && r.Day <= today { + if high { + vals = append(vals, r.Max) + } else { + vals = append(vals, r.Min) + } + } + } + if len(vals) < neverFiredRank { + return 0, false + } + if high { + sort.Sort(sort.Reverse(sort.Float64Slice(vals))) + } else { + sort.Float64s(vals) + } + return vals[neverFiredRank-1], true +} + +// roundThreshold rounds v to a threshold. Watts are rounded to wattStepW, at +// least to wattStepW. Other values are rounded to two significant digits without +// a lower limit. down picks the rounding towards the lower value, otherwise the +// higher one. +func roundThreshold(v float64, unit string, down bool) float64 { + if v == 0 { + return 0 + } + // roundEps absorbs floating point noise before Floor or Ceil. + const roundEps = 1e-9 + if unit == "W" { + n := math.Ceil(v/wattStepW - roundEps) + if down { + n = math.Floor(v/wattStepW + roundEps) + } + return max(wattStepW, n*wattStepW) + } + e := int(math.Floor(math.Log10(math.Abs(v))+roundEps)) - 1 + if e >= 0 { + step := math.Pow10(e) + n := math.Ceil(v/step - roundEps) + if down { + n = math.Floor(v/step + roundEps) + } + return n * step + } + // A step below 1 is divided, so 0.43 stays exactly 0.43. + p := math.Pow10(-e) + n := math.Ceil(v*p - roundEps) + if down { + n = math.Floor(v*p + roundEps) + } + return n / p +} + +// suggestionValue is the threshold as Op value: an int for whole numbers, so +// 0.43 is not cut to 0. +func suggestionValue(v float64) any { + if v == math.Trunc(v) { + return int(v) + } + return v +} + // firedSince reports whether the rule triggered in an hour from since on. func firedSince(stats RuleStats, since time.Time) bool { from := since.Unix() / 3600 diff --git a/dashboard/internal/autolearn/observed_test.go b/dashboard/internal/autolearn/observed_test.go index 1b3771d0..50bdc1ba 100644 --- a/dashboard/internal/autolearn/observed_test.go +++ b/dashboard/internal/autolearn/observed_test.go @@ -131,13 +131,13 @@ func TestObservedNeverFiredWarnWithThresholdFix(t *testing.T) { t.Fatalf("fixes = %+v, want one set_threshold", f.Apply) } op := f.Apply[0].Ops[0] - if op.Path[0] != "conditions" || op.Path[1] != 0 || op.Path[2] != "threshold" || op.Value != 1350 { - t.Errorf("op = %v -> %v, want conditions/0/threshold -> 1350", op.Path, op.Value) + if op.Path[0] != "conditions" || op.Path[1] != 0 || op.Path[2] != "threshold" || op.Value != 500 { + t.Errorf("op = %v -> %v, want conditions/0/threshold -> 500", op.Path, op.Value) } if f.Evidence.Shape != "scale" || f.Evidence.Unit != "W" { t.Errorf("Evidence shape/unit = %q/%q, want scale/W", f.Evidence.Shape, f.Evidence.Unit) } - if f.Evidence.Seen != [2]float64{100, 1850} || *f.Evidence.IstValue != 3000 || *f.Evidence.SollValue != 1350 { + if f.Evidence.Seen != [2]float64{100, 1850} || *f.Evidence.IstValue != 3000 || *f.Evidence.SollValue != 500 { t.Errorf("Evidence seen/ist/soll = %v/%v/%v", f.Evidence.Seen, *f.Evidence.IstValue, *f.Evidence.SollValue) } if f.Evidence.SeasonMax != nil { @@ -511,3 +511,118 @@ func TestObservedFrequentReplayReplacesIstSpan(t *testing.T) { t.Errorf("SollSpans = %v, want none beside the replayed Soll", got[0].Evidence.SollSpans) } } + +// neverFiredRanked is a rule known for 40 days with the given day ranges under key. +func neverFiredRanked(key string, ranges []DayRange) ObserverState { + return ObserverState{ + Rules: map[string]RuleStats{"heat": {FirstSeen: testNow.Add(-40 * 24 * time.Hour), Hours: map[int64]int{}}}, + Values: map[string][]DayRange{key: ranges}, + } +} + +// rankedDays returns one range per day back from testNow, newest first. +func rankedDays(mins, maxs []float64, rest DayRange) []DayRange { + today := testNow.Unix() / 86400 + var out []DayRange + for i := 0; i < 14; i++ { + r := DayRange{Day: today - int64(i), Min: rest.Min, Max: rest.Max} + if i < len(mins) { + r.Min = mins[i] + } + if i < len(maxs) { + r.Max = maxs[i] + } + out = append(out, r) + } + return out +} + +func TestNeverFiredSuggestsThirdLargestDailyMax(t *testing.T) { + doc := observedDoc(t, "3000", "0") + ranges := rankedDays(nil, []float64{2600, 2450, 2380}, DayRange{Min: 100, Max: 2000}) + st := neverFiredRanked("balance:grid_export", ranges) + + got := findKind(ObservedFindings(doc, st, nil, testNow), "never_fired") + if len(got) != 1 { + t.Fatalf("never_fired findings = %d, want 1", len(got)) + } + if op := got[0].Apply[0].Ops[0]; op.Value != 2350 { + t.Errorf("threshold = %v, want 2350", op.Value) + } +} + +func TestNeverFiredBelowSuggestsThirdSmallestDailyMin(t *testing.T) { + doc := ruleDoc(t, `{"type": "balance_threshold", "field": "grid_export", "comparison": "below", + "threshold": 100, "hysteresis": 0}`) + ranges := rankedDays([]float64{180, 210, 240}, nil, DayRange{Min: 300, Max: 500}) + st := neverFiredRanked("balance:grid_export", ranges) + + got := findKind(ObservedFindings(doc, st, nil, testNow), "never_fired") + if len(got) != 1 { + t.Fatalf("never_fired findings = %d, want 1", len(got)) + } + if op := got[0].Apply[0].Ops[0]; op.Value != 250 { + t.Errorf("threshold = %v, want 250", op.Value) + } +} + +func TestNeverFiredTemperatureRoundsToTwoDigits(t *testing.T) { + doc := ruleDoc(t, `{"type": "entity_value", "entity_id": "sensor.temp", "comparison": "above", + "value": 30}`) + ranges := rankedDays(nil, []float64{25.4, 24.8, 24.3}, DayRange{Min: 10, Max: 20}) + st := neverFiredRanked("entity:sensor.temp", ranges) + + got := findKind(ObservedFindings(doc, st, nil, testNow), "never_fired") + if len(got) != 1 { + t.Fatalf("never_fired findings = %d, want 1", len(got)) + } + if op := got[0].Apply[0].Ops[0]; op.Value != 24 { + t.Errorf("threshold = %v, want 24", op.Value) + } +} + +func TestNeverFiredFewDaysFallsBackToMax(t *testing.T) { + doc := observedDoc(t, "3000", "0") + ranges := rankedDays(nil, []float64{2600, 2400}, DayRange{Min: 100, Max: 100}) + ranges = ranges[:2] + st := neverFiredRanked("balance:grid_export", ranges) + th := DefaultThresholds() + th.MinRangeDays = 2 + + got := findKind(ObservedFindingsWith(doc, st, nil, testNow, th), "never_fired") + if len(got) != 1 { + t.Fatalf("never_fired findings = %d, want 1", len(got)) + } + if op := got[0].Apply[0].Ops[0]; op.Value != 2600 { + t.Errorf("threshold = %v, want 2600", op.Value) + } +} + +func TestRoundThreshold(t *testing.T) { + tests := []struct { + v float64 + unit string + down bool + want float64 + }{ + {2387, "W", true, 2350}, + {2387, "W", false, 2400}, + {24.3, "°C", true, 24}, + {0.437, "", true, 0.43}, + {30, "W", true, 50}, + } + for _, tc := range tests { + if got := roundThreshold(tc.v, tc.unit, tc.down); got != tc.want { + t.Errorf("roundThreshold(%v, %q, %v) = %v, want %v", tc.v, tc.unit, tc.down, got, tc.want) + } + } +} + +// ruleDoc is a static doc with one rule that has the given condition. +func ruleDoc(t *testing.T, cond string) Doc { + t.Helper() + return staticDoc(t, `{"rules": [{"id": "heat", "name": "Heater", "enabled": true, + "cooldown_seconds": 0, + "conditions": [`+cond+`], + "actions": [{"type": "publish", "topic": "heater/set", "payload_source": "constant", "payload": "1"}]}]}`) +} From d2a3351f1f3c1ae30fa4856f3d91aca09d8f10ae Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:25:17 +0100 Subject: [PATCH 09/20] refactor(autolearn): share the rounding step of the suggested threshold The earlier commit changed TestObservedNeverFiredWarnWithThresholdFix from 1350 to 500 because of the new rule. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/observed.go | 35 ++++++++++--------- dashboard/internal/autolearn/observed_test.go | 13 +++++++ 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/dashboard/internal/autolearn/observed.go b/dashboard/internal/autolearn/observed.go index 03b46604..b7265263 100644 --- a/dashboard/internal/autolearn/observed.go +++ b/dashboard/internal/autolearn/observed.go @@ -539,31 +539,32 @@ func roundThreshold(v float64, unit string, down bool) float64 { if v == 0 { return 0 } - // roundEps absorbs floating point noise before Floor or Ceil. - const roundEps = 1e-9 if unit == "W" { - n := math.Ceil(v/wattStepW - roundEps) - if down { - n = math.Floor(v/wattStepW + roundEps) - } - return max(wattStepW, n*wattStepW) + return max(wattStepW, roundStep(v, wattStepW, down)) } e := int(math.Floor(math.Log10(math.Abs(v))+roundEps)) - 1 - if e >= 0 { - step := math.Pow10(e) - n := math.Ceil(v/step - roundEps) + return roundStep(v, math.Pow10(e), down) +} + +// roundEps absorbs floating point noise before Floor or Ceil. +const roundEps = 1e-9 + +// roundStep rounds v to a multiple of step, down or up. A step below 1 is +// divided by its reciprocal, so 0.43 stays exactly 0.43. +func roundStep(v, step float64, down bool) float64 { + if step < 1 { + p := math.Round(1 / step) + n := math.Ceil(v*p - roundEps) if down { - n = math.Floor(v/step + roundEps) + n = math.Floor(v*p + roundEps) } - return n * step + return n / p } - // A step below 1 is divided, so 0.43 stays exactly 0.43. - p := math.Pow10(-e) - n := math.Ceil(v*p - roundEps) + n := math.Ceil(v/step - roundEps) if down { - n = math.Floor(v*p + roundEps) + n = math.Floor(v/step + roundEps) } - return n / p + return n * step } // suggestionValue is the threshold as Op value: an int for whole numbers, so diff --git a/dashboard/internal/autolearn/observed_test.go b/dashboard/internal/autolearn/observed_test.go index 50bdc1ba..3ae5794f 100644 --- a/dashboard/internal/autolearn/observed_test.go +++ b/dashboard/internal/autolearn/observed_test.go @@ -626,3 +626,16 @@ func ruleDoc(t *testing.T, cond string) Doc { "conditions": [`+cond+`], "actions": [{"type": "publish", "topic": "heater/set", "payload_source": "constant", "payload": "1"}]}]}`) } + +// The window is the 14 calendar days up to and including the day of now. The +// day before it has the largest maximum and must not count. +func TestRankedExtremeWindowEndsBeforeFourteenDays(t *testing.T) { + today := testNow.Unix() / 86400 + ranges := rankedDays(nil, []float64{2600, 2450, 2380}, DayRange{Min: 100, Max: 1000}) + ranges = append(ranges, DayRange{Day: today - 14, Min: 100, Max: 9000}) + + got, ok := rankedExtreme(ranges, testNow, true) + if !ok || got != 2380 { + t.Fatalf("rankedExtreme = %v, %v, want 2380, true", got, ok) + } +} From ea018f3158fadbeef9d862cb7be981a64f2910c2 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:07:48 +0100 Subject: [PATCH 10/20] fix(autolearn): find contradicting rules whose ranges meet Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/static.go | 24 ++- dashboard/internal/autolearn/static_region.go | 183 ++++++++++++++++++ .../internal/autolearn/static_region_test.go | 76 ++++++++ dashboard/internal/autolearn/static_test.go | 59 ++++++ dashboard/internal/webui/catalogs/de.json | 2 + dashboard/internal/webui/catalogs/en.json | 2 + 6 files changed, 340 insertions(+), 6 deletions(-) create mode 100644 dashboard/internal/autolearn/static_region.go create mode 100644 dashboard/internal/autolearn/static_region_test.go diff --git a/dashboard/internal/autolearn/static.go b/dashboard/internal/autolearn/static.go index 88fe85aa..d0a1844a 100644 --- a/dashboard/internal/autolearn/static.go +++ b/dashboard/internal/autolearn/static.go @@ -171,8 +171,10 @@ func orphans(rule Rule, entityExists func(entityID string) bool) []Finding { // pairFindings compares every pair of enabled rules in document order. Same // conditions and same actions is a duplicate, same conditions with a shared -// publish topic and another payload is a contradiction. Rules with a learned -// value are left out, since only fixed values are compared. +// publish topic and another payload is a contradiction. Different conditions +// with such a publish topic are a warning when their ranges meet, since both +// rules can then fire at the same time. Rules with a learned value are left +// out, since only fixed values are compared. func pairFindings(rules []Rule) []Finding { var out []Finding for i := range rules { @@ -182,6 +184,9 @@ func pairFindings(rules []Rule) []Finding { continue } if conditionsKey(a) != conditionsKey(b) { + if topic, ok := conflictingPublishTopic(a, b); ok && rangesMeet(a, b) { + out = append(out, contradictionFinding(a, b, topic, "warn")) + } continue } if actionsKey(a) == actionsKey(b) { @@ -189,7 +194,7 @@ func pairFindings(rules []Rule) []Finding { continue } if topic, ok := conflictingPublishTopic(a, b); ok { - out = append(out, contradictionFinding(a, b, topic)) + out = append(out, contradictionFinding(a, b, topic, "bad")) } } } @@ -213,15 +218,22 @@ func duplicateFinding(first, second Rule) Finding { } } -func contradictionFinding(a, b Rule, topic string) Finding { +// contradictionFinding reports two rules that send different payloads to one +// topic. A "warn" severity is a range overlap, where the conditions differ, and +// uses its own text, since the plain check text speaks of the same conditions. +func contradictionFinding(a, b Rule, topic, severity string) Finding { + code := "check.contradiction" + if severity == "warn" { + code = "check.contradiction_range" + } return Finding{ ID: FindingID("contradiction", a.ID, b.ID), Kind: "contradiction", Group: "check", RuleIDs: []string{a.ID, b.ID}, - Severity: "bad", + Severity: severity, Confidence: "high", - Summary: Text{Code: "check.contradiction", Params: map[string]any{ + Summary: Text{Code: code, Params: map[string]any{ "rule": a.Name, "other": b.Name, "topic": topic}}, Evidence: Evidence{Shape: "links", IstNames: []string{a.Name, b.Name}}, Apply: []Fix{ diff --git a/dashboard/internal/autolearn/static_region.go b/dashboard/internal/autolearn/static_region.go new file mode 100644 index 00000000..20ca52f4 --- /dev/null +++ b/dashboard/internal/autolearn/static_region.go @@ -0,0 +1,183 @@ +package autolearn + +import ( + "encoding/json" + "math" +) + +// Festlegung: a week is compared in quarter hours, the grid the rules run on. +// A quarter counts when a window touches it. +const ( + minutesPerQuarter = 15 + quartersPerDay = 24 * 60 / minutesPerQuarter + weekdaysPerWeek = 7 + weekQuarters = weekdaysPerWeek * quartersPerDay +) + +// region is the set of situations in which a rule can fire. iv holds the +// interval per signal (balance field, topic or entity), open bounds are +// infinities. week holds the quarter hours of the week, nil means every time. +type region struct { + iv map[string][2]float64 + week *[weekQuarters]bool +} + +// ruleRegion returns the region of a rule. Only numeric comparisons and +// time windows are read, other condition types and learned values are left +// out. Conditions on the same signal intersect, and so do time windows. It +// reports false when the region is empty, which unsatisfiable already reports. +func ruleRegion(r Rule) (region, bool) { + out := region{iv: map[string][2]float64{}} + for _, c := range r.Conditions { + switch c.Type { + case "balance_threshold", "topic_value", "entity_value": + number, ok := conditionNumber(c) + if !ok { + continue + } + key := signalKey(c) + bounds, seen := out.iv[key] + if !seen { + bounds = [2]float64{math.Inf(-1), math.Inf(1)} + } + switch c.Comparison { + case "above": + bounds[0] = math.Max(bounds[0], number) + case "below": + bounds[1] = math.Min(bounds[1], number) + default: + continue + } + out.iv[key] = bounds + case "time_window": + mask, ok := windowMask(c) + if !ok { + continue + } + if out.week == nil { + out.week = &mask + continue + } + for i := range out.week { + out.week[i] = out.week[i] && mask[i] + } + } + } + for _, bounds := range out.iv { + if bounds[0] > bounds[1] { + return region{}, false + } + } + if out.week != nil && !anyTrue(out.week) { + return region{}, false + } + return out, true +} + +// signalKey names the signal a numeric condition compares, so that only +// conditions on the same signal are intersected. +func signalKey(c Condition) string { + switch c.Type { + case "balance_threshold": + return "b:" + c.Field + case "topic_value": + return "t:" + c.Topic + default: + return "e:" + c.EntityID + } +} + +// windowMask marks the quarter hours of the week that a time_window covers. +// A window whose end is not after its start runs into the next day, and that +// part belongs to the day the window starts on. An empty weekday list means +// every day. +func windowMask(c Condition) ([weekQuarters]bool, bool) { + var mask [weekQuarters]bool + var fields struct { + Start string `json:"start"` + End string `json:"end"` + Weekdays []int `json:"weekdays"` + } + if err := json.Unmarshal(c.Raw, &fields); err != nil { + return mask, false + } + startH, startM, err := parseClock(fields.Start) + if err != nil { + return mask, false + } + endH, endM, err := parseClock(fields.End) + if err != nil { + return mask, false + } + start := startH*60 + startM + end := endH*60 + endM + days := fields.Weekdays + if len(days) == 0 { + for day := 0; day < weekdaysPerWeek; day++ { + days = append(days, day) + } + } + for _, day := range days { + if day < 0 || day >= weekdaysPerWeek { + continue + } + if end > start { + markSpan(&mask, day, start, end) + continue + } + markSpan(&mask, day, start, minutesPerDay) + markSpan(&mask, (day+1)%weekdaysPerWeek, 0, end) + } + return mask, true +} + +// markSpan marks the quarters of one day that the minutes from to to touch. +func markSpan(mask *[weekQuarters]bool, day, from, to int) { + for q := 0; q < quartersPerDay; q++ { + qFrom := q * minutesPerQuarter + if qFrom+minutesPerQuarter > from && qFrom < to { + mask[day*quartersPerDay+q] = true + } + } +} + +func anyTrue(mask *[weekQuarters]bool) bool { + for _, v := range mask { + if v { + return true + } + } + return false +} + +// rangesMeet reports whether two rules can fire at the same time. Regions +// that are empty never meet. +func rangesMeet(a, b Rule) bool { + ra, okA := ruleRegion(a) + rb, okB := ruleRegion(b) + return okA && okB && regionsMeet(ra, rb) +} + +// regionsMeet reports whether two regions share a situation. Intervals of the +// same signal overlap, where equal bounds count as overlapping. When both have +// a week, they share a quarter hour. +func regionsMeet(a, b region) bool { + for key, ai := range a.iv { + bi, ok := b.iv[key] + if !ok { + continue + } + if math.Max(ai[0], bi[0]) > math.Min(ai[1], bi[1]) { + return false + } + } + if a.week == nil || b.week == nil { + return true + } + for i := range a.week { + if a.week[i] && b.week[i] { + return true + } + } + return false +} diff --git a/dashboard/internal/autolearn/static_region_test.go b/dashboard/internal/autolearn/static_region_test.go new file mode 100644 index 00000000..c9747074 --- /dev/null +++ b/dashboard/internal/autolearn/static_region_test.go @@ -0,0 +1,76 @@ +package autolearn + +import ( + "strings" + "testing" +) + +// regionRule parses one enabled rule with the given conditions and a publish of +// "on" to x/set. +func regionRule(t *testing.T, id string, conditions ...string) Rule { + t.Helper() + raw := `{"id": "` + id + `", "name": "` + id + `", "enabled": true, "conditions": [` + + strings.Join(conditions, ",") + `], "actions": [{"type": "publish", "topic": "x/set", "payload_source": "constant", "payload": "on"}]}` + return staticDoc(t, `{"rules": [`+raw+`]}`).Rules[0] +} + +const ( + gridExportAbove500 = `{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 500}` + gridExportAbove800 = `{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 800}` + gridExportAbove1000 = `{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 1000}` + gridExportBelow500 = `{"type": "balance_threshold", "field": "grid_export", "comparison": "below", "threshold": 500}` + sunWindow = `{"type": "sun_window", "from": "sunrise", "to": "sunset"}` +) + +func TestRegionsMeetOnOverlappingThresholds(t *testing.T) { + a := regionRule(t, "a", gridExportAbove500) + b := regionRule(t, "b", gridExportAbove800) + ra, okA := ruleRegion(a) + rb, okB := ruleRegion(b) + if !okA || !okB { + t.Fatalf("ruleRegion ok = %v/%v, want true/true", okA, okB) + } + if !regionsMeet(ra, rb) { + t.Errorf("regionsMeet = false, want true") + } +} + +func TestRegionsApartOnDisjointThresholds(t *testing.T) { + a := regionRule(t, "a", gridExportAbove1000) + b := regionRule(t, "b", gridExportBelow500) + ra, _ := ruleRegion(a) + rb, _ := ruleRegion(b) + if regionsMeet(ra, rb) { + t.Errorf("regionsMeet = true, want false") + } +} + +func TestRegionsMeetAcrossMidnight(t *testing.T) { + a := regionRule(t, "a", `{"type": "time_window", "start": "22:00", "end": "06:00", "weekdays": []}`) + b := regionRule(t, "b", `{"type": "time_window", "start": "05:00", "end": "07:00", "weekdays": []}`) + ra, _ := ruleRegion(a) + rb, _ := ruleRegion(b) + if !regionsMeet(ra, rb) { + t.Errorf("regionsMeet = false, want true") + } +} + +func TestRegionsApartOnWeekdays(t *testing.T) { + a := regionRule(t, "a", `{"type": "time_window", "start": "08:00", "end": "09:00", "weekdays": [0, 1, 2, 3, 4]}`) + b := regionRule(t, "b", `{"type": "time_window", "start": "08:00", "end": "09:00", "weekdays": [5, 6]}`) + ra, _ := ruleRegion(a) + rb, _ := ruleRegion(b) + if regionsMeet(ra, rb) { + t.Errorf("regionsMeet = true, want false") + } +} + +func TestRegionsIgnoreOtherConditionTypes(t *testing.T) { + a := regionRule(t, "a", sunWindow, gridExportAbove500) + b := regionRule(t, "b", gridExportAbove800) + ra, _ := ruleRegion(a) + rb, _ := ruleRegion(b) + if !regionsMeet(ra, rb) { + t.Errorf("regionsMeet = false, want true") + } +} diff --git a/dashboard/internal/autolearn/static_test.go b/dashboard/internal/autolearn/static_test.go index 85496c57..bc0c55da 100644 --- a/dashboard/internal/autolearn/static_test.go +++ b/dashboard/internal/autolearn/static_test.go @@ -276,3 +276,62 @@ func TestStaticSkipsRulesWithLearnedValues(t *testing.T) { t.Errorf("findings = %+v, want none", findings) } } + +func TestPairFindingsRangeContradictionIsWarn(t *testing.T) { + doc := staticDoc(t, `{ + "rules": [ + {"id": "a", "name": "Wallbox on", "enabled": true, + "conditions": [{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 500}], + "actions": [{"type": "publish", "topic": "wallbox/set", "payload_source": "constant", "payload": "on"}]}, + {"id": "b", "name": "Wallbox off", "enabled": true, + "conditions": [{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 800}], + "actions": [{"type": "publish", "topic": "wallbox/set", "payload_source": "constant", "payload": "off"}]} + ] + }`) + f := expectSingleFinding(t, pairFindings(doc.Rules)) + if f.Kind != "contradiction" || f.ID != "contradiction:a:b" { + t.Errorf("Kind/ID = %q/%q", f.Kind, f.ID) + } + if f.Severity != "warn" { + t.Errorf("Severity = %q, want warn", f.Severity) + } + if f.Summary.Code != "check.contradiction_range" { + t.Errorf("Summary.Code = %q, want check.contradiction_range", f.Summary.Code) + } +} + +func TestPairFindingsSameConditionsStayBad(t *testing.T) { + doc := staticDoc(t, `{ + "rules": [ + {"id": "a", "name": "Wallbox on", "enabled": true, + "conditions": [{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 500}], + "actions": [{"type": "publish", "topic": "wallbox/set", "payload_source": "constant", "payload": "on"}]}, + {"id": "b", "name": "Wallbox off", "enabled": true, + "conditions": [{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 500}], + "actions": [{"type": "publish", "topic": "wallbox/set", "payload_source": "constant", "payload": "off"}]} + ] + }`) + f := expectSingleFinding(t, pairFindings(doc.Rules)) + if f.Kind != "contradiction" || f.Severity != "bad" { + t.Errorf("Kind/Severity = %q/%q, want contradiction/bad", f.Kind, f.Severity) + } + if f.Summary.Code != "check.contradiction" { + t.Errorf("Summary.Code = %q, want check.contradiction", f.Summary.Code) + } +} + +func TestPairFindingsLearnedRulesSkipped(t *testing.T) { + doc := staticDoc(t, `{ + "rules": [ + {"id": "a", "name": "Wallbox on", "enabled": true, + "conditions": [{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": {"learned": "device/wallbox_1/usual_runtime_s", "min": 60, "max": 14400, "fallback": 3600}}], + "actions": [{"type": "publish", "topic": "wallbox/set", "payload_source": "constant", "payload": "on"}]}, + {"id": "b", "name": "Wallbox off", "enabled": true, + "conditions": [{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 800}], + "actions": [{"type": "publish", "topic": "wallbox/set", "payload_source": "constant", "payload": "off"}]} + ] + }`) + if findings := pairFindings(doc.Rules); len(findings) != 0 { + t.Errorf("findings = %+v, want none", findings) + } +} diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index d49b912e..c12cb90b 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -507,6 +507,8 @@ "automations.learn.check.competition.title": "Regeln konkurrieren um denselben Überschuss", "automations.learn.check.contradiction.text": "„{rule}“ und „{other}“ haben dieselben Bedingungen, schicken aber verschiedene Befehle an {topic}.", "automations.learn.check.contradiction.title": "Widerspricht „{other}“", + "automations.learn.check.contradiction_range.text": "„{rule}“ und „{other}“ können gleichzeitig zutreffen und schicken dann verschiedene Befehle an {topic}.", + "automations.learn.check.contradiction_range.title": "Widerspricht „{other}“", "automations.learn.check.duplicate.text": "„{rule}“ macht genau dasselbe wie „{other}“. Eine der beiden Regeln reicht.", "automations.learn.check.duplicate.title": "Doppelt mit „{other}“", "automations.learn.check.feedback.text": "„{rule}“ schaltet {device} ein, und die Last zieht danach den Überschuss unter die Ausschaltgrenze. Die Regel schaltet sich deshalb selbst wieder aus.", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index f8d23da5..cde5746b 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -507,6 +507,8 @@ "automations.learn.check.competition.title": "Rules compete for the same surplus", "automations.learn.check.contradiction.text": "“{rule}” and “{other}” have the same conditions but send different commands to {topic}.", "automations.learn.check.contradiction.title": "Contradicts “{other}”", + "automations.learn.check.contradiction_range.text": "“{rule}” and “{other}” can apply at the same time and then send different commands to {topic}.", + "automations.learn.check.contradiction_range.title": "Contradicts “{other}”", "automations.learn.check.duplicate.text": "“{rule}” does exactly the same as “{other}”. One of the two rules is enough.", "automations.learn.check.duplicate.title": "Duplicate of “{other}”", "automations.learn.check.feedback.text": "“{rule}” switches {device} on, and the load then pulls the surplus below the switch-off limit. The rule therefore switches itself off again.", From e85cf0b218b9af5739ca8d9ee2793db1cccaa69a Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:08:56 +0100 Subject: [PATCH 11/20] feat(monitoring): add a notice for a missing site location Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 23 +++++++++++++------ dashboard/internal/monitoring/notice.go | 12 ++++++++++ dashboard/internal/monitoring/notice_test.go | 24 ++++++++++++++++++++ 3 files changed, 52 insertions(+), 7 deletions(-) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 069ea724..10425b09 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -711,16 +711,25 @@ func main() { if monitoringSuggestions != nil { in.Suggestions = monitoringSuggestions() } - if effectsOn() { - var doc autolearn.Doc - ok := false - if raw, err := configManager.Read("automation_rules"); err == nil { - if parsed, err := autolearn.ParseDoc(raw); err == nil { - doc, ok = parsed, true - } + var doc autolearn.Doc + ok := false + if raw, err := configManager.Read("automation_rules"); err == nil { + if parsed, err := autolearn.ParseDoc(raw); err == nil { + doc, ok = parsed, true } + } + if effectsOn() { in.Effects, in.RuleNames = monitoringEffects(effectStore.Measured(time.Now()), doc, ok) } + // Eine PV-Anlage ohne Standort in den Regeln: die Meldung bittet darum. + hasPV := false + for _, a := range in.Config.Assignments { + if a.Role == energy.RolePV { + hasPV = true + break + } + } + in.LocationMissing = ok && doc.Location == nil && hasPV return in } monitoringStore := monitoring.OpenStore(filepath.Join(autolearnDir, "monitoring.json"), log.Printf) diff --git a/dashboard/internal/monitoring/notice.go b/dashboard/internal/monitoring/notice.go index 79f420f6..6af2eb71 100644 --- a/dashboard/internal/monitoring/notice.go +++ b/dashboard/internal/monitoring/notice.go @@ -54,6 +54,9 @@ type Input struct { // the names of their rules and scenarios by ID. Effects []autolearn.Finding RuleNames map[string]string + // LocationMissing is set when the rules have no site location, although a + // PV plant is assigned. Then the location notice asks for it. + LocationMissing bool } // Collect baut die Meldungen in fester Reihenfolge: energy, chain, learn, @@ -63,6 +66,15 @@ func Collect(in Input) []Notice { out = append(out, energyNotices(in)...) out = append(out, chainNotices(in.Snapshot)...) out = append(out, learnNotices(in.Findings)...) + if in.LocationMissing { + out = append(out, Notice{ + ID: "learn:no_location", + Source: "learn", + Severity: "info", + Code: "no_location", + Steps: []Step{{Code: "set_location", Target: "location"}}, + }) + } out = append(out, effectNotices(in.Effects, in.RuleNames)...) out = append(out, suggestionNotices(in.Suggestions)...) return out diff --git a/dashboard/internal/monitoring/notice_test.go b/dashboard/internal/monitoring/notice_test.go index a7b28c4d..15858ee0 100644 --- a/dashboard/internal/monitoring/notice_test.go +++ b/dashboard/internal/monitoring/notice_test.go @@ -208,3 +208,27 @@ func TestMeasuredEffectsBecomeNoticesThatOpenTheRule(t *testing.T) { t.Error("Collect changed the params of the finding") } } + +func TestCollectAddsLocationNotice(t *testing.T) { + got := Collect(Input{LocationMissing: true}) + var n *Notice + for i := range got { + if got[i].ID == "learn:no_location" { + n = &got[i] + } + } + if n == nil { + t.Fatalf("got %v, want a learn:no_location notice", got) + } + if len(n.Steps) != 1 || n.Steps[0].Code != "set_location" || n.Steps[0].Target != "location" { + t.Errorf("steps = %+v, want set_location with target location", n.Steps) + } +} + +func TestCollectWithoutLocationFlagHasNoLocationNotice(t *testing.T) { + for _, n := range Collect(Input{}) { + if n.ID == "learn:no_location" { + t.Fatalf("got notice %v without LocationMissing", n) + } + } +} From ce30731576f1c7043f6018667695cb6e915da7cb Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:10:20 +0100 Subject: [PATCH 12/20] test(autolearn): prove the region tests against empty ranges Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/static_region.go | 7 +-- .../internal/autolearn/static_region_test.go | 51 ++++++++++++------- 2 files changed, 37 insertions(+), 21 deletions(-) diff --git a/dashboard/internal/autolearn/static_region.go b/dashboard/internal/autolearn/static_region.go index 20ca52f4..fd76ad30 100644 --- a/dashboard/internal/autolearn/static_region.go +++ b/dashboard/internal/autolearn/static_region.go @@ -8,8 +8,9 @@ import ( // Festlegung: a week is compared in quarter hours, the grid the rules run on. // A quarter counts when a window touches it. const ( + minutesPerHour = 60 minutesPerQuarter = 15 - quartersPerDay = 24 * 60 / minutesPerQuarter + quartersPerDay = 24 * minutesPerHour / minutesPerQuarter weekdaysPerWeek = 7 weekQuarters = weekdaysPerWeek * quartersPerDay ) @@ -109,8 +110,8 @@ func windowMask(c Condition) ([weekQuarters]bool, bool) { if err != nil { return mask, false } - start := startH*60 + startM - end := endH*60 + endM + start := startH*minutesPerHour + startM + end := endH*minutesPerHour + endM days := fields.Weekdays if len(days) == 0 { for day := 0; day < weekdaysPerWeek; day++ { diff --git a/dashboard/internal/autolearn/static_region_test.go b/dashboard/internal/autolearn/static_region_test.go index c9747074..de3c9866 100644 --- a/dashboard/internal/autolearn/static_region_test.go +++ b/dashboard/internal/autolearn/static_region_test.go @@ -22,15 +22,21 @@ const ( sunWindow = `{"type": "sun_window", "from": "sunrise", "to": "sunset"}` ) +// mustRegion returns the region of a rule and fails the test when the region +// is empty, so that a missing region cannot pass as meeting everything. +func mustRegion(t *testing.T, r Rule) region { + t.Helper() + reg, ok := ruleRegion(r) + if !ok { + t.Fatalf("ruleRegion(%s) ok = false, want true", r.ID) + } + return reg +} + func TestRegionsMeetOnOverlappingThresholds(t *testing.T) { a := regionRule(t, "a", gridExportAbove500) b := regionRule(t, "b", gridExportAbove800) - ra, okA := ruleRegion(a) - rb, okB := ruleRegion(b) - if !okA || !okB { - t.Fatalf("ruleRegion ok = %v/%v, want true/true", okA, okB) - } - if !regionsMeet(ra, rb) { + if !regionsMeet(mustRegion(t, a), mustRegion(t, b)) { t.Errorf("regionsMeet = false, want true") } } @@ -38,9 +44,7 @@ func TestRegionsMeetOnOverlappingThresholds(t *testing.T) { func TestRegionsApartOnDisjointThresholds(t *testing.T) { a := regionRule(t, "a", gridExportAbove1000) b := regionRule(t, "b", gridExportBelow500) - ra, _ := ruleRegion(a) - rb, _ := ruleRegion(b) - if regionsMeet(ra, rb) { + if regionsMeet(mustRegion(t, a), mustRegion(t, b)) { t.Errorf("regionsMeet = true, want false") } } @@ -48,19 +52,23 @@ func TestRegionsApartOnDisjointThresholds(t *testing.T) { func TestRegionsMeetAcrossMidnight(t *testing.T) { a := regionRule(t, "a", `{"type": "time_window", "start": "22:00", "end": "06:00", "weekdays": []}`) b := regionRule(t, "b", `{"type": "time_window", "start": "05:00", "end": "07:00", "weekdays": []}`) - ra, _ := ruleRegion(a) - rb, _ := ruleRegion(b) - if !regionsMeet(ra, rb) { + if !regionsMeet(mustRegion(t, a), mustRegion(t, b)) { t.Errorf("regionsMeet = false, want true") } } +func TestRegionsApartAcrossMidnight(t *testing.T) { + a := regionRule(t, "a", `{"type": "time_window", "start": "22:00", "end": "06:00", "weekdays": []}`) + b := regionRule(t, "b", `{"type": "time_window", "start": "06:30", "end": "07:00", "weekdays": []}`) + if regionsMeet(mustRegion(t, a), mustRegion(t, b)) { + t.Errorf("regionsMeet = true, want false") + } +} + func TestRegionsApartOnWeekdays(t *testing.T) { a := regionRule(t, "a", `{"type": "time_window", "start": "08:00", "end": "09:00", "weekdays": [0, 1, 2, 3, 4]}`) b := regionRule(t, "b", `{"type": "time_window", "start": "08:00", "end": "09:00", "weekdays": [5, 6]}`) - ra, _ := ruleRegion(a) - rb, _ := ruleRegion(b) - if regionsMeet(ra, rb) { + if regionsMeet(mustRegion(t, a), mustRegion(t, b)) { t.Errorf("regionsMeet = true, want false") } } @@ -68,9 +76,16 @@ func TestRegionsApartOnWeekdays(t *testing.T) { func TestRegionsIgnoreOtherConditionTypes(t *testing.T) { a := regionRule(t, "a", sunWindow, gridExportAbove500) b := regionRule(t, "b", gridExportAbove800) - ra, _ := ruleRegion(a) - rb, _ := ruleRegion(b) - if !regionsMeet(ra, rb) { + if !regionsMeet(mustRegion(t, a), mustRegion(t, b)) { t.Errorf("regionsMeet = false, want true") } } + +func TestRegionEmptyForDisjointTimeWindows(t *testing.T) { + r := regionRule(t, "a", + `{"type": "time_window", "start": "08:00", "end": "09:00", "weekdays": []}`, + `{"type": "time_window", "start": "10:00", "end": "11:00", "weekdays": []}`) + if _, ok := ruleRegion(r); ok { + t.Errorf("ruleRegion ok = true, want false for disjoint time windows") + } +} From 9300975e99f2c1cbf05dbb5c9de0d410b3947c34 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:14:41 +0100 Subject: [PATCH 13/20] feat(monitoring): ask for the site location when PV learning needs it Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 4 ++++ dashboard/internal/webui/catalogs/en.json | 4 ++++ .../webui/static/js/automations.page.js | 11 ++++++++++ .../webui/static/js/monitoring-model.js | 4 +++- .../webui/static/js/monitoring.page.js | 12 ++++++++++ dashboard/test/automations.page.test.mjs | 22 +++++++++++++++++++ dashboard/test/monitoring-model.test.mjs | 13 +++++++++++ dashboard/test/monitoring.page.test.mjs | 16 ++++++++++++++ 8 files changed, 85 insertions(+), 1 deletion(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index c12cb90b..c79a2666 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -3865,6 +3865,8 @@ "monitoring.load_failed": "Monitoring konnte nicht geladen werden.", "monitoring.notice.chain.title": "{chain}: Messkette auffällig", "monitoring.notice.measured_no_meter.title": "Hausverbrauch gemessen, aber kein Hauszähler", + "monitoring.notice.no_location.text": "Ohne Standort lernt die Node weder die PV-Bestkurve noch PV-Reserve und Rest-Überschuss.", + "monitoring.notice.no_location.title": "Standort fehlt", "monitoring.notice.role_needed.title": "Werte nach einer Messkette ohne Rolle", "monitoring.notice.soc_capacity.text": "Akkustände ohne Kapazität: {count}. Ohne die Kapazität in kWh fehlt der Energieinhalt des Akkus in der Bilanz.", "monitoring.notice.soc_capacity.title": "Akkustand ohne Kapazität", @@ -3930,6 +3932,8 @@ "monitoring.step.rule_open.button": "Regel öffnen", "monitoring.step.set_load_role": "Dem Hauszähler die Rolle Hauszähler geben", "monitoring.step.set_load_role.button": "Rolle setzen", + "monitoring.step.set_location": "Standort in den Einstellungen der Automationen eintragen", + "monitoring.step.set_location.button": "Standort eintragen", "monitoring.step.set_role": "Rolle der Werte neu setzen", "monitoring.step.set_role.button": "Rollen setzen", "monitoring.step.shade_accept": "Lässt sich der Schatten nicht beseitigen, ist nichts zu tun. Rest-Überschuss und Überschussfenster rechnen ihn schon heraus.", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index cde5746b..bf5de331 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -3865,6 +3865,8 @@ "monitoring.load_failed": "Monitoring could not be loaded.", "monitoring.notice.chain.title": "{chain}: measurement chain looks wrong", "monitoring.notice.measured_no_meter.title": "House load set to measured, but no house meter", + "monitoring.notice.no_location.text": "Without a location the node learns neither the best PV curve nor the PV reserve and the remaining surplus.", + "monitoring.notice.no_location.title": "Location missing", "monitoring.notice.role_needed.title": "Values left without a role by a measurement chain", "monitoring.notice.soc_capacity.text": "Battery levels without capacity: {count}. Without the capacity in kWh the battery energy is missing from the balance.", "monitoring.notice.soc_capacity.title": "Battery level without capacity", @@ -3930,6 +3932,8 @@ "monitoring.step.rule_open.button": "Open the rule", "monitoring.step.set_load_role": "Give the house meter the role house meter", "monitoring.step.set_load_role.button": "Set role", + "monitoring.step.set_location": "Enter the location in the automation settings", + "monitoring.step.set_location.button": "Enter location", "monitoring.step.set_role": "Set the role of the values again", "monitoring.step.set_role.button": "Set roles", "monitoring.step.shade_accept": "If the shade cannot be removed, there is nothing to do. The remaining surplus and the surplus window already leave it out.", diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index 6e4e3792..31cbd44e 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -545,6 +545,17 @@ this._focusRuleListener = true; window.addEventListener('automation-focus-rule', event => this.focusRule(event.detail && event.detail.id)); } + if (window.__automationLocationRequest__) { + window.__automationLocationRequest__ = null; + this.openLocationSettings(); + } + if (!this._openLocationListener) { + this._openLocationListener = true; + window.addEventListener('automation-open-location', () => { + window.__automationLocationRequest__ = null; + this.openLocationSettings(); + }); + } this.csrfToken = (session && session.csrf_token) || ''; // "automations" liefert der Sitzungsendpunkt seit Task 3; ohne die // Rolle werden die Test-Knoepfe gar nicht erst angeboten. diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index 40be7ced..f0792d4f 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -14,7 +14,9 @@ } // Lernbefunde, Vorschläge und Erfolgskontrolle teilen Texte und Belege der Automationen. + // Die Meldung "Standort fehlt" trägt source learn, hat aber keinen Lernbefund dahinter. function isLearned(notice) { + if (notice.code === 'no_location') return false; return sourceOf(notice) !== 'energy'; } @@ -179,7 +181,7 @@ if (target === 'efficiency') return !!can.view_efficiency; if (target === 'devicemap') return !!can.view_device_map; if (target === 'action.role_keep') return !!can.edit_energy; - if (target === 'suggestion' || target === 'rule') return !!can.view_automations; + if (target === 'suggestion' || target === 'rule' || target === 'location') return !!can.view_automations; return false; } diff --git a/dashboard/internal/webui/static/js/monitoring.page.js b/dashboard/internal/webui/static/js/monitoring.page.js index 05feb954..6b9c78df 100644 --- a/dashboard/internal/webui/static/js/monitoring.page.js +++ b/dashboard/internal/webui/static/js/monitoring.page.js @@ -236,6 +236,7 @@ if (step.target === 'learned') { this.goLearned(step.key); return; } if (step.target === 'suggestion') { this.goSuggestion((step.ids || [])[0]); return; } if (step.target === 'rule') { this.goRule((step.ids || [])[0]); return; } + if (step.target === 'location') { this.goLocation(); return; } if (step.target === 'action.role_keep') { this.roleKeep(step.ids); return; } const panel = panelFor(step.target); if (!panel) return; @@ -278,6 +279,17 @@ }); }, + // Sprung zu den Standort-Einstellungen der Automationen. Wie goRule: Reiter zuerst, + // die Seite nimmt die Anfrage beim Laden oder über das Ereignis entgegen. + goLocation() { + window.__automationLocationRequest__ = true; + openTab('automations-panel'); + this.$nextTick(() => { + if (!window.__automationLocationRequest__) return; + window.dispatchEvent(new CustomEvent('automation-open-location')); + }); + }, + // Sprung zum aufgeklappten Vorschlag. Ist die Automationen-Seite noch nicht // geladen, nimmt ihr Band die Anfrage in load() entgegen. goSuggestion(id) { diff --git a/dashboard/test/automations.page.test.mjs b/dashboard/test/automations.page.test.mjs index 1900daeb..cefb658a 100644 --- a/dashboard/test/automations.page.test.mjs +++ b/dashboard/test/automations.page.test.mjs @@ -4643,3 +4643,25 @@ test('night_off and quiet_off prefer the entity of the prefill over the device', assert.equal(prefillToAnswers(id, { entity: 5 }), null); } }); + +test('the location request opens the location settings on load and on the event', async () => { + const { component, window } = createAutomationsPanel(); + window.fetch = async (url) => { + if (url.endsWith('/api/v1/configurations/automation_rules')) { + return { ok: true, json: async () => ({ version: 1, settings: {}, rules: [] }) }; + } + if (url.endsWith('/api/v1/devices')) return { ok: true, json: async () => [] }; + if (url.endsWith('/api/v1/auth/session')) return { ok: true, json: async () => ({ csrf_token: 'tok', automations: true }) }; + throw new Error(`unexpected fetch ${url}`); + }; + window.__automationLocationRequest__ = true; + await component.load(); + assert.equal(component.settingsOpen, true); + assert.equal(window.__automationLocationRequest__, null); + component.settingsOpen = false; + window.__automationLocationRequest__ = true; + window.dispatchEvent(new window.CustomEvent('automation-open-location')); + assert.equal(component.settingsOpen, true); + assert.equal(window.__automationLocationRequest__, null); + window.close(); +}); diff --git a/dashboard/test/monitoring-model.test.mjs b/dashboard/test/monitoring-model.test.mjs index 9f694f57..68b2898e 100644 --- a/dashboard/test/monitoring-model.test.mjs +++ b/dashboard/test/monitoring-model.test.mjs @@ -196,3 +196,16 @@ test('the rule step needs the right to view automations', () => { assert.equal(withRight.label, 'monitoring.step.rule_open.button'); assert.equal(M.steps(notice, {}, t)[0].target, ''); }); + +test('the location step needs the view_automations right and the notice reads its own texts', () => { + const notice = { id: 'learn:no_location', source: 'learn', severity: 'warn', code: 'no_location', steps: [{ code: 'set_location', target: 'location', ids: [] }] }; + const withRight = M.steps(notice, { view_automations: true }, t)[0]; + assert.equal(withRight.target, 'location'); + assert.equal(withRight.label, 'monitoring.step.set_location.button'); + assert.equal(M.steps(notice, {}, t)[0].target, ''); + assert.equal(M.steps(notice, {}, t)[0].label, ''); + assert.equal(M.isLearned(notice), false); + assert.equal(M.title(notice, t), 'monitoring.notice.no_location.title'); + assert.equal(M.text(notice, t), 'monitoring.notice.no_location.text'); + assert.equal(M.sourceOf(notice), 'learn'); +}); diff --git a/dashboard/test/monitoring.page.test.mjs b/dashboard/test/monitoring.page.test.mjs index bffff2eb..f70d3cd1 100644 --- a/dashboard/test/monitoring.page.test.mjs +++ b/dashboard/test/monitoring.page.test.mjs @@ -160,3 +160,19 @@ test('the rule step opens the automations tab and asks it to show the rule', asy assert.deepEqual(seen, ['tab', 'rule r1']); assert.equal(window.__automationFocusRequest__, 'r1'); }); + +test('the location step opens the automations tab and asks it to open the location settings', async () => { + const notices = [{ id: 'learn:no_location', source: 'learn', severity: 'warn', code: 'no_location', params: {}, steps: [{ code: 'set_location', target: 'location' }], first_seen: NOW, ack: null }]; + const { component, window } = createPanel({ roles: ['view_automations'], notices }); + await component.load(); + const seen = []; + const tab = window.document.createElement('button'); + tab.setAttribute('role', 'tab'); + tab.setAttribute('aria-controls', 'automations-panel'); + tab.addEventListener('click', () => seen.push('tab')); + window.document.body.appendChild(tab); + window.addEventListener('automation-open-location', () => seen.push('location')); + component.runStep(component.notices[0], 0); + assert.deepEqual(seen, ['tab', 'location']); + assert.equal(window.__automationLocationRequest__, true); +}); From a7315a27071df40d27a078c8ea5e6b62bf41dfe4 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:15:43 +0100 Subject: [PATCH 14/20] docs(dashboard): describe the corrected learning methods Co-Authored-By: Claude Sonnet 5.5 --- docs/dashboard/automations-rules.md | 35 +++++++++++++++++++++++------ docs/dashboard/monitoring.md | 3 ++- docs/dashboard/settings.md | 4 +++- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/docs/dashboard/automations-rules.md b/docs/dashboard/automations-rules.md index f2bd258c..c677b533 100644 --- a/docs/dashboard/automations-rules.md +++ b/docs/dashboard/automations-rules.md @@ -183,7 +183,8 @@ which is 7 days. Older values count as missing, and the fallback applies. - the usual switch on time, the usual switch off time and the usual runtime of each device, -- the start of the day and the night rest of the house, +- the start of the day and the night rest of the house, without the power of + devices that a rule switched on, - the house state, **House is active** or **House is quiet**, from the consumption of the last hours, - the typical operating power and the typical cycle energy of a device, once @@ -232,8 +233,10 @@ from the energy statistics. A week with fewer than four days of data does not count. The sun needs a location in the automation settings. Without one, the node -learns by calendar week and shows the hint **Location missing** on the -[learning features](settings.md#automations) page. The sun times are then not +learns neither the best PV curve nor the PV reserve, the remaining surplus or +shade. It shows the hint **Location missing** on the +[learning features](settings.md#automations) page, and for a plant with a PV +role also on the [Monitoring](monitoring.md) page. The sun times are then not used, and every switching time stays a clock time. **Switch times** can follow the clock or the sun. A habit that follows sunset @@ -308,7 +311,10 @@ value. - **PV reserve**, in W. It is the power the solar system could deliver right now and does not, for example because a regulator holds it back. The node learns what the system can deliver on a clear sky from the few moments when it ran - unthrottled, and scales that with the weather of the day. The value prefers to + unthrottled, and scales that with the weather of the day. A load that switches + on and is covered by the solar power counts as a measurement too. Without a + recent measurement the weather factor returns to the usual value of the last + 28 days. The value prefers to promise too little. Without an unthrottled moment for two hours it is halved and marked **Estimate**. - **Surplus left today**, in Wh. It is the solar energy that the house will not @@ -331,7 +337,10 @@ If the solar system is shaded by a tree or a building at the same place in the sky on many clear days, the node reports **A fixed shadow is pulling down PV power**. The note names the time of day, the weeks of the year and a rough yearly loss in kWh, and it draws the day curve with the best possible curve -dashed. It is only information and has no fix. +dashed. It is only information and has no fix. In the shaded part of the sky the +best possible curve follows the measured power, so the PV reserve and the +surplus values leave the shade out. When the shade disappears, the next check +removes it again. The data for this lives in `autolearn/pvraster.json`, `autolearn/pvmodel.json`, `autolearn/pvweather.json`, `autolearn/cycles.json` and @@ -414,7 +423,7 @@ The check reports eleven kinds of findings. Each one names the rules involved. | Finding | What it means | Based on | |---|---|---| | Competes with a regulator | The rule publishes to the topic of an enabled scenario regulator, so the device gets two commands in turn. | Rules and scenarios | -| Contradicts another rule | Two rules have the same conditions but send different commands to the same topic. | Rules | +| Contradicts another rule | Two rules send different commands to the same topic, and their conditions are the same or can apply at the same time. | Rules | | Duplicate | Two rules do exactly the same. One of the two is enough. | Rules | | Can never be met | The conditions rule each other out, for example above 500 W and below 300 W on the same value. | Rules | | Device missing | The rule uses an entity that is no longer in the device registry. | Rules and registry | @@ -425,6 +434,15 @@ The check reports eleven kinds of findings. Each one names the rules involved. | Often overridden | The device is switched back by hand or from outside soon after the rule switched it. | Rules and observed switching | | Runs while offline | The start of the rule's time window falls into the usual offline time of the device. | Rules and observed switching | +A contradiction between rules with the same conditions is a fault. When the +rules only overlap, it is a warning, because they may never actually meet there. +The check compares thresholds on the same value and time windows with their +weekdays. All other conditions count as open. Rules with a learned value are not +compared. + +**Never triggers** suggests the value that was reached on three of the last 14 +days. Watt values are rounded to 50 W, other values to two significant digits. + A threshold that was reached in earlier months of the last year does not count as a fault. Such a rule gets the note **Resting for the season** instead, which is only information and has no fix. @@ -485,7 +503,10 @@ house. They are shown as soon as the data is there. None of them adds a load. curve reaches again in a later calendar week shows that week. A threshold the plant never reaches stays **Never triggers**. - **Base load rises**: The night load of the house stays higher than expected - for several weeks. The finding names a device that explains at least half of + for several weeks. With an outdoor temperature sensor the expectation follows + the temperature when the night load depends on it, so the start of the heating + season is not reported. A real rise that comes together with falling + temperatures can then stay hidden. The finding names a device that explains at least half of the rise and, for a switchable device, offers the template **Night off**. Without a switchable device the finding appears as a notice on the [Monitoring](monitoring.md) page. - **Battery full early**: The battery reaches 97 % before the sun is highest, on most of the last days. This is information only and appears as a notice on diff --git a/docs/dashboard/monitoring.md b/docs/dashboard/monitoring.md index 0c5d7cc3..d19b5a3a 100644 --- a/docs/dashboard/monitoring.md +++ b/docs/dashboard/monitoring.md @@ -35,7 +35,7 @@ Notices come from five sources: |---|---| | Energy balance | The house load is set to measured, but no meter has the role house meter. A battery level exists without a capacity in kWh. Power values have no role. Values were left without a role by a measurement chain. | | Measurement chains | A finding of a [measurement chain](energy.md#measurement-chains), such as a unit error, a frozen value, a contradiction or a sign error. The card shows the time since the finding started. | -| Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power, a battery that is full early or empty before morning, or a rising base load without a switchable device. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | +| Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power, a battery that is full early or empty before morning, or a rising base load without a switchable device. For a plant with a PV role, a missing location is reported here too. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | | Suggestions | Every suggestion of the [suggestion band](automations-rules.md#suggestions). **Open suggestion** opens it on the Automations page. The chip **Suggestions** lists only these, **All** includes them. | | Results check | The measured [result](automations-learning.md#results-check) of an adopted suggestion, with the value before and since and its confidence, for eight weeks after the change. **Open the rule** shows the rule or scenario on the Automations page. | @@ -64,6 +64,7 @@ a button leads to the place for it: - **Measurement chain** opens the dialog of the chain on the Energy tab. - **Efficiency** and **Device map** open their tabs. - **Learned values** switches the tab to the learned values. +- **Enter location** opens the settings of the Automations page. - **Open the rule** shows the checked rule or scenario on the Automations page. A step that leads to a place you may not see is hidden, and its text stays. A diff --git a/docs/dashboard/settings.md b/docs/dashboard/settings.md index 6e8ac827..c2954614 100644 --- a/docs/dashboard/settings.md +++ b/docs/dashboard/settings.md @@ -44,7 +44,9 @@ last state, so a rule falls back to its default value after 7 days. **Location missing** appears on this page while **Learn patterns** is on and no location is set. Without a location the patterns have no sun times. **Enter location** opens the -automation settings. Learning goes on by calendar week meanwhile. +automation settings. Meanwhile the node learns neither the best PV curve nor the +PV reserve, the remaining surplus or shade. For a plant with a PV role the +[Monitoring](monitoring.md) page asks for the location too. **Outdoor temperature** takes a temperature sensor. The node stores its value in the daily profiles and uses it for the heating season, see From 556b5ae475f14b24227eb6993fa1794e0025f3e4 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:16:50 +0100 Subject: [PATCH 15/20] chore(webui): bump cache marks for the learning follow-up Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/cache-bust-history.csv | 3 +++ dashboard/internal/webui/templates/base.html | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index 20442b46..c53e5d42 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,4 +1,7 @@ version,date,asset,v,note +v0.11.23-pre.41,2026-11-30,js/automations.page.js,34, +v0.11.23-pre.41,2026-11-30,js/monitoring-model.js,7, +v0.11.23-pre.41,2026-11-30,js/monitoring.page.js,6, v0.11.22-pre.40,2026-11-30,css/manager.css,54, v0.11.22-pre.40,2026-11-30,js/energy.page.js,19, v0.11.22-pre.40,2026-11-30,js/monitoring-model.js,6, diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index fb4bed72..0215b70c 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -237,14 +237,14 @@

{{t "no_access.title"}}

{{if index .Can "view_history"}}

{{t "panel.history_loading"}}

{{end}} {{if index .Can "view_stats"}}

{{t "panel.stats_loading"}}

{{end}} {{if and .Manager (index .Can "view_efficiency")}}

{{t "panel.efficiency_loading"}}

{{end}} -{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} +{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} {{if .Manager}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} {{if index .Can "view_energy"}}

{{t "panel.energy_loading"}}

{{end}} {{if index .Can "view_device_map"}}

{{t "panel.devicemap_loading"}}

{{end}}

{{t "panel.settings_loading"}}

-{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} +{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} {{else}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{end}} From 8ab46e3c14924fc68c7992bfa87f7762ab45023b Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:25:34 +0100 Subject: [PATCH 16/20] docs(dashboard): match the learning docs to the reviewed behaviour Co-Authored-By: Claude Sonnet 5.5 --- docs/dashboard/automations-rules.md | 13 +++++++------ docs/dashboard/monitoring.md | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/dashboard/automations-rules.md b/docs/dashboard/automations-rules.md index c677b533..0598160e 100644 --- a/docs/dashboard/automations-rules.md +++ b/docs/dashboard/automations-rules.md @@ -234,8 +234,8 @@ count. The sun needs a location in the automation settings. Without one, the node learns neither the best PV curve nor the PV reserve, the remaining surplus or -shade. It shows the hint **Location missing** on the -[learning features](settings.md#automations) page, and for a plant with a PV +shade. While **Learn patterns** is on, it shows the hint **Location missing** on +the [learning features](settings.md#automations) page, and for a plant with a PV role also on the [Monitoring](monitoring.md) page. The sun times are then not used, and every switching time stays a clock time. @@ -313,9 +313,9 @@ value. what the system can deliver on a clear sky from the few moments when it ran unthrottled, and scales that with the weather of the day. A load that switches on and is covered by the solar power counts as a measurement too. Without a - recent measurement the weather factor returns to the usual value of the last - 28 days. The value prefers to - promise too little. Without an unthrottled moment for two hours it is halved + recent measurement the weather factor returns to a usual value. Once 60 + measured minutes exist within 28 days, that is their median. The value prefers + to promise too little. Without an unthrottled moment for two hours it is halved and marked **Estimate**. - **Surplus left today**, in Wh. It is the solar energy that the house will not use for the rest of the day. The node looks for the days that behaved like @@ -441,7 +441,8 @@ weekdays. All other conditions count as open. Rules with a learned value are not compared. **Never triggers** suggests the value that was reached on three of the last 14 -days. Watt values are rounded to 50 W, other values to two significant digits. +days. Thresholds on the energy balance are rounded to 50 W, all other +thresholds to two significant digits. A threshold that was reached in earlier months of the last year does not count as a fault. Such a rule gets the note **Resting for the season** instead, which diff --git a/docs/dashboard/monitoring.md b/docs/dashboard/monitoring.md index d19b5a3a..5bf5d82c 100644 --- a/docs/dashboard/monitoring.md +++ b/docs/dashboard/monitoring.md @@ -35,7 +35,7 @@ Notices come from five sources: |---|---| | Energy balance | The house load is set to measured, but no meter has the role house meter. A battery level exists without a capacity in kWh. Power values have no role. Values were left without a role by a measurement chain. | | Measurement chains | A finding of a [measurement chain](energy.md#measurement-chains), such as a unit error, a frozen value, a contradiction or a sign error. The card shows the time since the finding started. | -| Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power, a battery that is full early or empty before morning, or a rising base load without a switchable device. For a plant with a PV role, a missing location is reported here too. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | +| Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power, a battery that is full early or empty before morning, or a rising base load without a switchable device. For a plant with a PV role, a missing location is reported here too while **Learn patterns** is on. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | | Suggestions | Every suggestion of the [suggestion band](automations-rules.md#suggestions). **Open suggestion** opens it on the Automations page. The chip **Suggestions** lists only these, **All** includes them. | | Results check | The measured [result](automations-learning.md#results-check) of an adopted suggestion, with the value before and since and its confidence, for eight weeks after the change. **Open the rule** shows the rule or scenario on the Automations page. | From ee702d3120bdb7be76ea5191e3f23ae8189f4380 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:29:43 +0100 Subject: [PATCH 17/20] fix(autolearn): correct the findings of the branch review - Shade evidence: the best curve ignores the shade cells of an earlier run. - Regions: a shared bound is no overlap, above 500 and below 500 are apart. - Location notice only while pattern learning is on. - Stored shade cells are not written without a model after a reset. - Tests for the season median, midnight windows and the cleared shade. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 25 ++++--- dashboard/cmd/dashboard/main_test.go | 31 +++++++++ dashboard/internal/autolearn/detect_shade.go | 6 +- .../internal/autolearn/detect_shade_test.go | 68 ++++++++++++++++++- dashboard/internal/autolearn/pvmodelstore.go | 7 +- .../internal/autolearn/pvmodelstore_test.go | 17 +++++ .../internal/autolearn/pvreserve_test.go | 13 ++++ dashboard/internal/autolearn/static_region.go | 15 ++-- .../internal/autolearn/static_region_test.go | 17 +++++ dashboard/internal/autolearn/static_test.go | 22 ++++++ 10 files changed, 203 insertions(+), 18 deletions(-) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 10425b09..313f4756 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -721,15 +721,7 @@ func main() { if effectsOn() { in.Effects, in.RuleNames = monitoringEffects(effectStore.Measured(time.Now()), doc, ok) } - // Eine PV-Anlage ohne Standort in den Regeln: die Meldung bittet darum. - hasPV := false - for _, a := range in.Config.Assignments { - if a.Role == energy.RolePV { - hasPV = true - break - } - } - in.LocationMissing = ok && doc.Location == nil && hasPV + in.LocationMissing = locationMissing(effectsOn(), ok, doc, in.Config.Assignments) return in } monitoringStore := monitoring.OpenStore(filepath.Join(autolearnDir, "monitoring.json"), log.Printf) @@ -2057,3 +2049,18 @@ func performanceBusy(jobDir string) func() bool { return progress.State == "pending" || progress.State == "running" } } + +// locationMissing reports whether the notice asks for the site location: the +// pattern learning is on, the rules document could be read, it has no location +// and a PV plant is assigned. +func locationMissing(patternsOn, docOK bool, doc autolearn.Doc, assignments map[string]energy.Assignment) bool { + if !patternsOn || !docOK || doc.Location != nil { + return false + } + for _, a := range assignments { + if a.Role == energy.RolePV { + return true + } + } + return false +} diff --git a/dashboard/cmd/dashboard/main_test.go b/dashboard/cmd/dashboard/main_test.go index 1da87f03..15d4c90a 100644 --- a/dashboard/cmd/dashboard/main_test.go +++ b/dashboard/cmd/dashboard/main_test.go @@ -8,11 +8,13 @@ import ( "time" "github.com/Developer-Simon/energy-node-dashboard/internal/appconfig" + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" "github.com/Developer-Simon/energy-node-dashboard/internal/chainwatch" "github.com/Developer-Simon/energy-node-dashboard/internal/energy" "github.com/Developer-Simon/energy-node-dashboard/internal/nodeagent" "github.com/Developer-Simon/energy-node-dashboard/internal/registry" "github.com/Developer-Simon/energy-node-dashboard/internal/settings" + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) func TestValidateNodeDeviceID(t *testing.T) { @@ -184,3 +186,32 @@ func TestHoldsFromEnv(t *testing.T) { t.Fatalf("30 s: got %+v, want all five at 30 s", got) } } + +// The location notice needs learning switched on, a readable rules document, +// no location in it and a PV plant. +func TestLocationMissing(t *testing.T) { + pv := map[string]energy.Assignment{"pv": {Role: energy.RolePV}} + grid := map[string]energy.Assignment{"grid": {Role: energy.RoleGridImport}} + withLocation := autolearn.Doc{Location: &sun.Location{Lat: 52.52, Lon: 13.405}} + tests := []struct { + name string + patternsOn bool + docOK bool + doc autolearn.Doc + assignments map[string]energy.Assignment + want bool + }{ + {"all conditions hold", true, true, autolearn.Doc{}, pv, true}, + {"learning switched off", false, true, autolearn.Doc{}, pv, false}, + {"rules unreadable", true, false, autolearn.Doc{}, pv, false}, + {"location set", true, true, withLocation, pv, false}, + {"no PV plant", true, true, autolearn.Doc{}, grid, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := locationMissing(tt.patternsOn, tt.docOK, tt.doc, tt.assignments); got != tt.want { + t.Errorf("locationMissing = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/dashboard/internal/autolearn/detect_shade.go b/dashboard/internal/autolearn/detect_shade.go index a062db10..bd33b04e 100644 --- a/dashboard/internal/autolearn/detect_shade.go +++ b/dashboard/internal/autolearn/detect_shade.go @@ -335,6 +335,10 @@ func shadeEvidence(r *Raster, m PVModel, days []DayFile, clearDays map[string]bo if err != nil { return Evidence{}, false } + // The best curve is the model without the shade cells of an earlier run, + // so the dashed line shows the best possible curve on the measurement. + unshaded := m + unshaded.Shade = nil ev := Evidence{ Shape: "curve", Quarters: make([]float32, dayQuarters), @@ -345,7 +349,7 @@ func shadeEvidence(r *Raster, m PVModel, days []DayFile, clearDays map[string]bo ev.Quarters[q] = pick.Site.PV[q] az, el := sun.Position(shadeQuarterTime(midnight, q), site.Lat, site.Lon) ev.SollQ[q] = float32(m.Best(az, el, nil)) - ev.BestQ[q] = float32(m.Best(az, el, r)) + ev.BestQ[q] = float32(unshaded.Best(az, el, r)) } return ev, true } diff --git a/dashboard/internal/autolearn/detect_shade_test.go b/dashboard/internal/autolearn/detect_shade_test.go index 7538614e..15553ee3 100644 --- a/dashboard/internal/autolearn/detect_shade_test.go +++ b/dashboard/internal/autolearn/detect_shade_test.go @@ -205,7 +205,73 @@ func TestShadeRunClearsVanishedShade(t *testing.T) { flat, flatDays := shadeFixture(t, m, func(i, j int) float64 { return 0.95 }) runShadeStore(t, flat, store, flatDays) - if got, _ := store.Model(); len(got.Shade) != 0 { + got, _ := store.Model() + if len(got.Shade) != 0 { t.Fatalf("Shade = %v after the shade vanished, want empty", got.Shade) } + // A cell that was shaded before now gives the larger of its raster value and the model. + az, el := 212.5, 13.5 + w, ok := flat.Cell(az, el) + if !ok { + t.Fatal("flat raster has no value in the former shade") + } + want := got.Best(az, el, nil) + if w > want { + want = w + } + if best := got.Best(az, el, flat); !nearly(best, want) { + t.Errorf("Best in the former shade = %v, want %v", best, want) + } +} + +// The second run must show the same best curve as the first one. The model +// keeps the shade cells of the first run, so the best curve must not use them. +// Today is 2026-02-01, so the evidence day is 2026-01-31, the last clear day +// before today. Its afternoon sun crosses the shade in quarters of the day. +func TestShadeEvidenceSecondRunKeepsBest(t *testing.T) { + m := shadeModel() + r, days := shadeFixture(t, m, func(i, j int) float64 { + if shadeInCell(i, j) { + return 0.4 + } + return 0.95 + }) + store := shadeStore(t, m) + loc := berlinLoc(t) + now := time.Date(2026, 2, 1, 12, 0, 0, 0, loc) + in := &Input{Now: now, Loc: loc, Days: days, Doc: Doc{Location: shadeSite}} + det := NewShadeDetector(func() *Raster { return r }, store) + first := det.Run(context.Background(), in, "") + second := det.Run(context.Background(), in, "") + if len(first) != 1 || len(second) != 1 { + t.Fatalf("got %d and %d candidates, want 1 and 1", len(first), len(second)) + } + a := first[0].Finding.Evidence + b := second[0].Finding.Evidence + for q := range b.BestQ { + if a.BestQ[q] != b.BestQ[q] { + t.Errorf("quarter %d: second run BestQ = %v, first run %v", q, b.BestQ[q], a.BestQ[q]) + } + } + + midnight, err := time.ParseInLocation(dayLayout, "2026-01-31", loc) + if err != nil { + t.Fatal(err) + } + shaded := false + for q := range b.BestQ { + az, el := sun.Position(shadeQuarterTime(midnight, q), shadeSite.Lat, shadeSite.Lon) + w, ok := r.Cell(az, el) + key := r.index(az, el) + if !ok || !shadeInCell(key[0], key[1]) { + continue + } + shaded = true + if float64(b.BestQ[q]) <= w { + t.Errorf("quarter %d in the shade: BestQ = %v, want above the cell value %v", q, b.BestQ[q], w) + } + } + if !shaded { + t.Fatal("no quarter of the evidence day lies in a shade cell") + } } diff --git a/dashboard/internal/autolearn/pvmodelstore.go b/dashboard/internal/autolearn/pvmodelstore.go index 7951e9c2..b8262cc9 100644 --- a/dashboard/internal/autolearn/pvmodelstore.go +++ b/dashboard/internal/autolearn/pvmodelstore.go @@ -57,10 +57,15 @@ func (s *PVModelStore) Set(m PVModel) { } // SetShade replaces the shade cells of the stored model with a copy of keys. -// An empty list clears them. The next Save writes the change. +// An empty list clears them. Without a stored model it does nothing, so a run +// that ends after a reset cannot leave shade cells for a later model. The next +// Save writes the change. func (s *PVModelStore) SetShade(keys [][2]int) { s.mu.Lock() defer s.mu.Unlock() + if !s.ok { + return + } cp := append([][2]int(nil), keys...) if len(cp) == len(s.model.Shade) && equalKeys(cp, s.model.Shade) { return diff --git a/dashboard/internal/autolearn/pvmodelstore_test.go b/dashboard/internal/autolearn/pvmodelstore_test.go index 5fda1b89..a4138cde 100644 --- a/dashboard/internal/autolearn/pvmodelstore_test.go +++ b/dashboard/internal/autolearn/pvmodelstore_test.go @@ -127,6 +127,7 @@ func TestPVTrackerSnapshotIsCopy(t *testing.T) { func TestModelStoreSetKeepsShade(t *testing.T) { store := NewPVModelStore(filepath.Join(t.TempDir(), "pvmodel.json")) want := [][2]int{{42, 4}, {43, 4}} + store.Set(PVModel{CapW: 1}) store.SetShade(want) store.Set(PVModel{CapW: 1}) m, ok := store.Model() @@ -135,6 +136,22 @@ func TestModelStoreSetKeepsShade(t *testing.T) { } } +// A run that ends after "delete learned values" must not put shade cells +// into the store that is empty, so the next fitted model has no shade. +func TestModelStoreSetShadeAfterResetIgnored(t *testing.T) { + store := NewPVModelStore(filepath.Join(t.TempDir(), "pvmodel.json")) + store.Set(PVModel{CapW: 1}) + if err := store.Reset(); err != nil { + t.Fatal(err) + } + store.SetShade([][2]int{{42, 4}, {43, 4}}) + store.Set(PVModel{CapW: 2}) + m, ok := store.Model() + if !ok || len(m.Shade) != 0 { + t.Fatalf("Shade = %v ok=%v, want empty after reset", m.Shade, ok) + } +} + func TestModelStoreLoadsOldFileWithoutShade(t *testing.T) { path := filepath.Join(t.TempDir(), "pvmodel.json") old := `{"Surfaces":[{"PMax":5000,"TiltDeg":30,"AzimuthDeg":180}],"CapW":6000,"Safe":true,"FittedAt":1}` diff --git a/dashboard/internal/autolearn/pvreserve_test.go b/dashboard/internal/autolearn/pvreserve_test.go index 832a8b8c..299d1d29 100644 --- a/dashboard/internal/autolearn/pvreserve_test.go +++ b/dashboard/internal/autolearn/pvreserve_test.go @@ -242,3 +242,16 @@ func TestLoadWeatherWithoutDaysKeepsOldMedian(t *testing.T) { t.Errorf("season = %v, want 0.7", s) } } + +// Twenty lifts on one day are fewer than sixty samples, so the season median +// stays at its default. The weather factor of the lifts is (3000+600)/4000 = 0.9. +func TestWeatherFewLiftsKeepMedian(t *testing.T) { + var w Weather + t0 := time.Date(2026, 11, 21, 1, 0, 0, 0, time.Local) + for i := 0; i < 20; i++ { + w.LiftForLoad(t0.Add(time.Duration(i)*time.Hour), 3000, 600, 4000) + } + if s := w.season(); s != 0.5 { + t.Errorf("season after 20 lifts = %v, want 0.5", s) + } +} diff --git a/dashboard/internal/autolearn/static_region.go b/dashboard/internal/autolearn/static_region.go index fd76ad30..5f1a10be 100644 --- a/dashboard/internal/autolearn/static_region.go +++ b/dashboard/internal/autolearn/static_region.go @@ -25,8 +25,10 @@ type region struct { // ruleRegion returns the region of a rule. Only numeric comparisons and // time windows are read, other condition types and learned values are left -// out. Conditions on the same signal intersect, and so do time windows. It -// reports false when the region is empty, which unsatisfiable already reports. +// out. Conditions on the same signal intersect, and so do time windows. An +// interval whose lower bound is not below its upper bound is empty, so above +// 500 with below 500 is empty. It reports false when the region is empty, +// which unsatisfiable already reports. func ruleRegion(r Rule) (region, bool) { out := region{iv: map[string][2]float64{}} for _, c := range r.Conditions { @@ -65,7 +67,7 @@ func ruleRegion(r Rule) (region, bool) { } } for _, bounds := range out.iv { - if bounds[0] > bounds[1] { + if bounds[0] >= bounds[1] { return region{}, false } } @@ -160,15 +162,16 @@ func rangesMeet(a, b Rule) bool { } // regionsMeet reports whether two regions share a situation. Intervals of the -// same signal overlap, where equal bounds count as overlapping. When both have -// a week, they share a quarter hour. +// same signal overlap only when the larger lower bound lies below the smaller +// upper bound, so above 500 and below 500 are apart. When both have a week, +// they share a quarter hour. func regionsMeet(a, b region) bool { for key, ai := range a.iv { bi, ok := b.iv[key] if !ok { continue } - if math.Max(ai[0], bi[0]) > math.Min(ai[1], bi[1]) { + if math.Max(ai[0], bi[0]) >= math.Min(ai[1], bi[1]) { return false } } diff --git a/dashboard/internal/autolearn/static_region_test.go b/dashboard/internal/autolearn/static_region_test.go index de3c9866..d13cc978 100644 --- a/dashboard/internal/autolearn/static_region_test.go +++ b/dashboard/internal/autolearn/static_region_test.go @@ -89,3 +89,20 @@ func TestRegionEmptyForDisjointTimeWindows(t *testing.T) { t.Errorf("ruleRegion ok = true, want false for disjoint time windows") } } + +// A shared bound is no common situation: above 500 and below 500 never hold together. +func TestRegionsApartOnSharedBound(t *testing.T) { + a := regionRule(t, "a", gridExportAbove500) + b := regionRule(t, "b", gridExportBelow500) + if regionsMeet(mustRegion(t, a), mustRegion(t, b)) { + t.Errorf("regionsMeet = true, want false") + } +} + +func TestRegionsMeetOnSameLowerBound(t *testing.T) { + a := regionRule(t, "a", gridExportAbove500) + b := regionRule(t, "b", gridExportAbove500) + if !regionsMeet(mustRegion(t, a), mustRegion(t, b)) { + t.Errorf("regionsMeet = false, want true") + } +} diff --git a/dashboard/internal/autolearn/static_test.go b/dashboard/internal/autolearn/static_test.go index bc0c55da..db54f41a 100644 --- a/dashboard/internal/autolearn/static_test.go +++ b/dashboard/internal/autolearn/static_test.go @@ -335,3 +335,25 @@ func TestPairFindingsLearnedRulesSkipped(t *testing.T) { t.Errorf("findings = %+v, want none", findings) } } + +// The windows 22:00 to 06:00 and 05:00 to 07:00 share 05:00 to 06:00, so the +// two rules can fire together, and the pair is a warning contradiction. +func TestPairFindingsMidnightWindows(t *testing.T) { + doc := staticDoc(t, `{ + "rules": [ + {"id": "a", "name": "Wallbox on", "enabled": true, + "conditions": [{"type": "time_window", "start": "22:00", "end": "06:00", "weekdays": []}], + "actions": [{"type": "publish", "topic": "wallbox/set", "payload_source": "constant", "payload": "on"}]}, + {"id": "b", "name": "Wallbox off", "enabled": true, + "conditions": [{"type": "time_window", "start": "05:00", "end": "07:00", "weekdays": []}], + "actions": [{"type": "publish", "topic": "wallbox/set", "payload_source": "constant", "payload": "off"}]} + ] + }`) + f := expectSingleFinding(t, pairFindings(doc.Rules)) + if f.Kind != "contradiction" { + t.Errorf("Kind = %q, want contradiction", f.Kind) + } + if f.Severity != "warn" { + t.Errorf("Severity = %q, want warn", f.Severity) + } +} From dc430cb10b130986074dc14df80858180ea5f0ab Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Mon, 30 Nov 2026 19:37:13 +0000 Subject: [PATCH 18/20] chore(release): bump component versions --- dashboard/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/VERSION b/dashboard/VERSION index 5cfebf85..bb196294 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.11.23-pre.40 +v0.11.23-pre.41 From c410fb3b88f9963813bd89a809e870953d17a2e8 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Mon, 30 Nov 2026 19:38:18 +0000 Subject: [PATCH 19/20] docs(changelog): update changelogs --- changelog/highlights/306.json | 8 ++++++++ dashboard/CHANGELOG.md | 18 +++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 changelog/highlights/306.json diff --git a/changelog/highlights/306.json b/changelog/highlights/306.json new file mode 100644 index 00000000..1793c0b9 --- /dev/null +++ b/changelog/highlights/306.json @@ -0,0 +1,8 @@ +{ + "de": { + "*": "Das Lernen rechnet genauer und bittet um den Standort, wenn er für PV fehlt" + }, + "en": { + "*": "Correct the learning methods after the spec check" + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 6bf6207f..d48aa7c0 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.11.23-pre.40 (2026-11-06) +## v0.11.23-pre.41 (2026-11-06) ### Features @@ -38,6 +38,8 @@ - **monitoring:** Monitoring shows the forecast check, a year comparison and the learned values as a usual day (#297) (4f93975) - **dashboard:** show system versions on the versions page (#299) (18a2b0b) - **automations:** Monitoring checks the results of adopted suggestions and rules report a season drift (#300) (d9e023b) +- **monitoring:** add a notice for a missing site location (e85cf0b) +- **monitoring:** ask for the site location when PV learning needs it (9300975) - **automations:** mark rules that came from a learned suggestion (f85130f) - **webui:** record which suggestion a saved rule came from (ae2baed) - **autolearn:** measure the effect of an adopted suggestion against the season (a1e9dc6) @@ -368,6 +370,17 @@ - **storage:** set up, back up and replug the additional drive reliably (#247) (b668394) - **automations:** correct the learning feature after the full review (#296) (88f3c75) - Monitoring names values without a role and links to the learning settings (#303) (29450b8) +- **autolearn:** learn the season median of the weather factor from measured minutes (ca31a44) +- **autolearn:** count a load that the PV covers as a weather measurement (d5ffb8e) +- **autolearn:** need a known off state before a switch counts as turned on (0ad8879) +- **autolearn:** let a detected shade cap the best PV curve (53d5881) +- **autolearn:** expect the night base load from the outdoor temperature (839eae2) +- **autolearn:** ignore rule started runs when learning the day start (5db0bd2) +- **autolearn:** count a rule start in the first quarter of the day (8b74a6e) +- **autolearn:** suggest the threshold reached on three of the last 14 days (da6fe78) +- **autolearn:** find contradicting rules whose ranges meet (ea018f3) +- **autolearn:** correct the findings of the branch review (ee702d3) +- **automations:** correct the learning methods after the spec check (#306) - **history:** keep proxies from compressing the event streams (#304) (0298760) - **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **monitoring:** add the text for the learning settings button (50b5e84) @@ -533,6 +546,7 @@ ### Refactors +- **autolearn:** share the rounding step of the suggested threshold (d2a3351) - **devicemap:** call the saved chains chains like the energy page (6974b1b) - **chainsuggest:** read minute means from the shared collector (f1f3c68) - **dashboard:** feed chain learning and the rule observer through the shared collector (5b8386f) @@ -551,6 +565,7 @@ ### Tests +- **autolearn:** prove the region tests against empty ranges (ce30731) - **smoke:** split the main run into four independent runs (fa7e3df) - **demo:** expect a sure effect beside the estimates (aa987aa) - **demo:** fake the system packages for the versions page (ca2dc1e) @@ -576,6 +591,7 @@ ### Chores +- **webui:** bump cache marks for the learning follow-up (556b5ae) - **energy:** drop the styles and getter of the old energy notices (a864af2) - **monitoring:** drop the old notice keys, bump the changed assets, describe the button (c99833b) - **webui:** bump the cache marks of the changed automation assets (fa93e53) From 05b07be2fe05c83c422811026e9f8e9f29bb6ba9 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:38:31 +0100 Subject: [PATCH 20/20] chore(changelog): fold the learning follow-up into #279 Co-Authored-By: Claude Sonnet 5.5 --- changelog/highlights/306.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/changelog/highlights/306.json b/changelog/highlights/306.json index 1793c0b9..a002c428 100644 --- a/changelog/highlights/306.json +++ b/changelog/highlights/306.json @@ -4,5 +4,6 @@ }, "en": { "*": "Correct the learning methods after the spec check" - } + }, + "folded_into": 279 }