diff --git a/.changeset/heat-comfort-day-price.md b/.changeset/heat-comfort-day-price.md new file mode 100644 index 000000000..c39ba5c07 --- /dev/null +++ b/.changeset/heat-comfort-day-price.md @@ -0,0 +1,9 @@ +--- +"ftw": patch +--- + +A `thermal` section in the configuration for heat comfort that follows the +day's price: your own cheap, normal and dear day levels, how far each zone +may move, and the least daily saving for planned heat to be acted on. It is +parsed and checked, and has no defaults. Nothing acts on it yet, so there +is no behaviour change. diff --git a/.changeset/heat-planner-package.md b/.changeset/heat-planner-package.md new file mode 100644 index 000000000..6737274ff --- /dev/null +++ b/.changeset/heat-planner-package.md @@ -0,0 +1,7 @@ +--- +"ftw": patch +--- + +Internal: a heat planner package (`heatplan`) that proposes control values +for one zone from prices, weather and the site's energy plan. Nothing calls +it yet. No behaviour change. diff --git a/config.example.yaml b/config.example.yaml index c9073eea6..6698b7e00 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -280,6 +280,23 @@ fleet_ping: # soc_min: 0.10 # soc_max: 0.95 +# Heat comfort that follows the day's price (docs/adr/0012). Optional, and +# nothing here has a default: every number is yours. Prices are the day's +# mean total price in öre/kWh. Between the levels the change is gradual. +# Parsed and checked today; heat control itself is not released yet. +# thermal: +# cheap_day_ore_kwh: 150 # at or below: all of cheap_day_raise_k +# normal_day_ore_kwh: 260 # your own target, unchanged +# dear_day_ore_kwh: 400 # at or above: all of dear_day_lower_k +# min_saving_ore_per_day: 500 # move heat in time only if all zones together +# # save this much in a day; 0 = no limit +# zones: +# - comfort_sensor: { driver: wiser, metric: bathroom_floor_c } +# cheap_day_raise_k: 2.5 # a warmer floor on a cheap day +# - comfort_sensor: { driver: wiser, metric: bathroom_air_c } +# dear_day_lower_k: 1.0 # cooler air on a dear day, never warmer +# step_k: 0.5 # the thermostat's step + # Peak-power tariff (weekday 06–20 local time). Same minor units as # grid_tariff_ore_kwh, per kW, excluding VAT. 0 disables it. # price: diff --git a/docs/adr/0012-heat-control.md b/docs/adr/0012-heat-control.md index db98b25ca..95b8d49e0 100644 --- a/docs/adr/0012-heat-control.md +++ b/docs/adr/0012-heat-control.md @@ -140,6 +140,47 @@ thermal: - Without a comfort sensor, a zone cannot be planned. The roadmap does not let Core assume indoor temperature. +#### Comfort follows the day's price + +Proposed; see [Open](#open). What a degree is worth to the owner depends on +what the day costs. A warm bathroom floor is cheap comfort on a cheap day, +and a slightly cooler room is an easy saving on a dear one. That is a choice +about comfort, not about timing, and it needs no model of the house: + +```yaml +thermal: + cheap_day_ore_kwh: 150 # at or below: all of cheap_day_raise_k + normal_day_ore_kwh: 260 # the owner's own target + dear_day_ore_kwh: 400 # at or above: all of dear_day_lower_k + min_saving_ore_per_day: 500 + zones: + - comfort_sensor: { driver: wiser, metric: bathroom_floor_c } + cheap_day_raise_k: 2.5 + - comfort_sensor: { driver: wiser, metric: bathroom_air_c } + dear_day_lower_k: 1.0 + step_k: 0.5 +``` + +- The price is the mean total consumer price of the day the comfort is for, + once at least 22 hours of it are known. Between the levels the target + moves linearly, so a day one öre over a level is not a different day. +- Each direction is per zone and off at zero. A floor may follow cheap days + up while the room air only follows dear days down. +- The moved target stays inside the zone's hard band. +- **Nothing has a default.** These numbers depend on the contract, the + price area and the household. A site that sets none is unchanged. +- `min_saving_ore_per_day` is the least the plans of all zones must save + together in a day before any planned value is sent. Below it, every zone + is left on its target for the day. Moving heat for a few öre costs device + writes and the owner's trust in what the house is doing, and the saving is + inside the twin's error. An open gate closes again at 80 % of the limit, + so a saving near the limit does not start and stop the planning. +- **The two are layered.** The day's comfort moves the target first. The + plan and the baseline it is measured against both stand on that target, + so the plan is never credited with what the comfort rule saved. The + comfort rule holds without a trusted twin; the gate weighs plans and so + applies only where a twin is trusted. + ### 2. Declaration by the driver Two optional fields on an existing control, an optional `sensors` list and @@ -362,6 +403,13 @@ Fredrik answered on the hot-water floor on 12 November 2026: ## Open +- **Comfort that follows the day's price, and the least daily saving.** + Proposed in section 1 and not yet answered. One household has run both + since November 2026 on three floor-heating zones: with a 5 kr limit, the + planned savings of 0.1–4.9 kr per day never opened the gate, so in + practice only the day's comfort level acted. Whether the day's mean is + the right measure of a cheap or dear day, against a longer reference such + as the month, is open. - **Holding off a reheat needs a control.** Many heat pumps start a hot-water charge by themselves at their own start temperature. The planner can only delay a reheat on a device whose driver declares a control that diff --git a/go/cmd/ftw/thermal_comfort.go b/go/cmd/ftw/thermal_comfort.go new file mode 100644 index 000000000..3f48b7336 --- /dev/null +++ b/go/cmd/ftw/thermal_comfort.go @@ -0,0 +1,35 @@ +package main + +import ( + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/heatplan" +) + +// thermalGateKeepShare keeps an open savings gate open down to this share +// of the owner's limit, so a saving near the limit does not start and stop +// the planning every quarter. It is not a setting: it changes no outcome +// the owner would choose between. +const thermalGateKeepShare = 0.8 + +// thermalComfort is the owner's comfort rule for one zone, by its sensor +// key. A zone the owner did not list, or a site with no thermal section, +// gets the zero value, which moves nothing. +func thermalComfort(cfg *config.Thermal, sensor string) heatplan.PriceComfort { + z, ok := cfg.Zone(sensor) + if !ok { + return heatplan.PriceComfort{} + } + return heatplan.PriceComfort{ + CheapPrice: cfg.CheapDayOreKWh, NormalPrice: cfg.NormalDayOreKWh, DearPrice: cfg.DearDayOreKWh, + RaiseK: z.CheapDayRaiseK, LowerK: z.DearDayLowerK, StepK: z.StepK, + } +} + +// thermalSavingsGate is the owner's least daily saving, in öre. No limit +// set is no gate. +func thermalSavingsGate(cfg *config.Thermal) heatplan.SavingsGate { + if cfg == nil || cfg.MinSavingOrePerDay <= 0 { + return heatplan.SavingsGate{} + } + return heatplan.SavingsGate{MinPerDay: cfg.MinSavingOrePerDay, KeepShare: thermalGateKeepShare} +} diff --git a/go/cmd/ftw/thermal_comfort_test.go b/go/cmd/ftw/thermal_comfort_test.go new file mode 100644 index 000000000..17e222fb7 --- /dev/null +++ b/go/cmd/ftw/thermal_comfort_test.go @@ -0,0 +1,55 @@ +package main + +import ( + "testing" + + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/heatplan" +) + +func TestThermalConfigBecomesThePlannersRules(t *testing.T) { + cfg := &config.Thermal{ + CheapDayOreKWh: 150, NormalDayOreKWh: 260, DearDayOreKWh: 400, MinSavingOrePerDay: 500, + Zones: []config.ThermalZone{ + {ComfortSensor: config.ThermalSensor{Driver: "wiser", Metric: "floor_c"}, CheapDayRaiseK: 2.5}, + {ComfortSensor: config.ThermalSensor{Driver: "wiser", Metric: "air_c"}, DearDayLowerK: 1, StepK: 0.5}, + }, + } + if err := cfg.Validate(); err != nil { + t.Fatalf("validate: %v", err) + } + floor := thermalComfort(cfg, "wiser/floor_c") + if want := (heatplan.PriceComfort{CheapPrice: 150, NormalPrice: 260, DearPrice: 400, RaiseK: 2.5}); floor != want { + t.Errorf("floor = %+v, want %+v", floor, want) + } + // What the configuration accepts, the planner's own check accepts. + for _, key := range []string{"wiser/floor_c", "wiser/air_c"} { + if err := thermalComfort(cfg, key).Validate(); err != nil { + t.Errorf("%s: %v", key, err) + } + } + if got := floor.ShiftK(205); got != 1.25 { + t.Errorf("floor on a half-cheap day = %v K, want 1.25", got) + } + if got := thermalComfort(cfg, "wiser/air_c").ShiftK(500); got != -1 { + t.Errorf("air on a dear day = %v K, want -1", got) + } + if thermalComfort(cfg, "wiser/hall_c").Enabled() { + t.Error("a zone with no rule got one") + } + if gate := thermalSavingsGate(cfg); gate.MinPerDay != 500 || gate.KeepShare != thermalGateKeepShare { + t.Errorf("gate = %+v", gate) + } +} + +func TestNoThermalConfigIsNoRuleAndNoGate(t *testing.T) { + if thermalComfort(nil, "a/b").Enabled() || thermalSavingsGate(nil) != (heatplan.SavingsGate{}) { + t.Error("a missing thermal section must change nothing") + } + if thermalSavingsGate(&config.Thermal{}) != (heatplan.SavingsGate{}) { + t.Error("no limit must be no gate") + } + if open, _ := thermalSavingsGate(nil).Open(nil, 24, false); !open { + t.Error("no limit closed the gate") + } +} diff --git a/go/internal/api/api.go b/go/internal/api/api.go index 0c85bf2bd..733cdbc29 100644 --- a/go/internal/api/api.go +++ b/go/internal/api/api.go @@ -309,13 +309,6 @@ type Server struct { // nil in production; SendWithGeneration still binds every real dispatch to // the selected running generation. beforeDriverControlSend func() - // beforeDriverControlStateLock is a package-test seam for the narrower - // lookup-to-lock lifecycle race. It runs after the state map lookup while - // the map lock is still held, before the per-driver state lock is taken. - beforeDriverControlStateLock func() - // beforeDriverDefaultStateLock is a package-test seam for the default path's - // lookup-to-lock lifecycle race. It is nil in production. - beforeDriverDefaultStateLock func() versionUpdateMu sync.Mutex driverUpdateMu sync.Mutex diff --git a/go/internal/api/api_driver_control.go b/go/internal/api/api_driver_control.go index 82006752f..aa8016746 100644 --- a/go/internal/api/api_driver_control.go +++ b/go/internal/api/api_driver_control.go @@ -129,7 +129,7 @@ func (s *Server) handleDriverControl(w http.ResponseWriter, r *http.Request) { // command. The response is written inside done, still under that lock, so // the status read that explains an error is the one that caused it. s.controlHolds.Send(r.Context(), name, control.ID, applied, body, - time.Duration(seconds)*time.Second, s.beforeDriverControlStateLock, + time.Duration(seconds)*time.Second, func(hold drivercontrol.Hold, err error) { if err != nil { s.writeControlSendError(w, name, err) @@ -254,5 +254,5 @@ func (s *Server) controlRegistry() drivercontrol.Registry { // it clears any hold under the per-driver lock and sends the driver's own // default. See drivercontrol.Holds.SendDefault. func (s *Server) SendDriverDefault(ctx context.Context, name string) error { - return s.controlHolds.SendDefault(ctx, name, s.beforeDriverDefaultStateLock) + return s.controlHolds.SendDefault(ctx, name) } diff --git a/go/internal/api/api_driver_control_test.go b/go/internal/api/api_driver_control_test.go index e96d26547..4f6e26ab2 100644 --- a/go/internal/api/api_driver_control_test.go +++ b/go/internal/api/api_driver_control_test.go @@ -493,12 +493,12 @@ func TestDriverControlBindsHoldToRestartedGeneration(t *testing.T) { t.Fatalf("hold generation = %d, want replacement generation %d", hold.Generation, newStatus.Generation) } - state := srv.controlHolds.Peek("heat") + state := srv.controlHolds.Seams().Peek("heat") if state == nil { t.Fatal("control state disappeared before expiry") } - fired := state.CurrentHold() - if err := srv.controlHolds.Expire("heat", state, fired); err != nil { + fired := srv.controlHolds.Seams().CurrentHold(state) + if err := srv.controlHolds.Seams().Expire("heat", state, fired); err != nil { t.Fatalf("expiry after generation-bound command = %v", err) } waitMetric(t, tel, "heat", "defaulted", 1) @@ -545,12 +545,12 @@ func TestDriverControlLookupRaceCannotOrphanStateOrTimer(t *testing.T) { var resumeOnce sync.Once resumeRequest := func() { resumeOnce.Do(func() { close(resume) }) } defer resumeRequest() - srv.beforeDriverControlStateLock = func() { + srv.controlHolds.Seams().BeforeStateLock(func() { pauseOnce.Do(func() { close(lookedUp) <-resume }) - } + }) postDone := make(chan *httptest.ResponseRecorder, 1) go func() { @@ -566,7 +566,7 @@ func TestDriverControlLookupRaceCannotOrphanStateOrTimer(t *testing.T) { lifecycleDone := make(chan error, 1) go func() { lifecycleDone <- test.lifecycle(srv, cfg) }() mapProbeDone := make(chan bool, 1) - go func() { mapProbeDone <- srv.controlHolds.Peek("heat") == nil }() + go func() { mapProbeDone <- srv.controlHolds.Seams().Peek("heat") == nil }() select { case removed := <-mapProbeDone: if removed { @@ -635,16 +635,16 @@ func TestDriverControlExpiryDefaultFailureBlocksUntilRecovery(t *testing.T) { `{"control":"set_offset","value":2,"duration_s":600}`); rec.Code != http.StatusOK { t.Fatalf("POST = %d, body %s", rec.Code, rec.Body.String()) } - state := srv.controlHolds.Peek("heat") + state := srv.controlHolds.Seams().Peek("heat") if state == nil { t.Fatal("missing control state") } - hold := state.CurrentHold() + hold := srv.controlHolds.Seams().CurrentHold(state) if hold == nil { t.Fatal("missing control hold") } - if err := srv.controlHolds.Expire("heat", state, hold); err == nil { + if err := srv.controlHolds.Seams().Expire("heat", state, hold); err == nil { t.Fatal("expiry hid a failed default") } if got := srv.controlHolds.Active("heat"); got != nil { @@ -750,7 +750,7 @@ func TestDriverControlDefaultPathClearsHold(t *testing.T) { if hold := srv.controlHolds.Active("heat"); hold != nil { t.Fatalf("default path left hold active: %+v", hold) } - if state := srv.controlHolds.Peek("heat"); state == nil { + if state := srv.controlHolds.Seams().Peek("heat"); state == nil { t.Fatal("default path removed the existing control state") } waitMetric(t, tel, "heat", "defaulted", 1) @@ -853,27 +853,27 @@ func TestSendDriverDefaultClearsOnlyHoldsArmedBeforeIt(t *testing.T) { if !ok { t.Fatal("driver not running") } - state := srv.controlHolds.State("heat") - state.Lock() // an operator request in flight + state := srv.controlHolds.Seams().State("heat") + srv.controlHolds.Seams().Lock(state) // an operator request in flight if tc.armBefore { - srv.controlHolds.ArmLocked("heat", state, "set_offset", 1.0, status.Generation, time.Hour) + srv.controlHolds.Seams().ArmLocked("heat", state, "set_offset", 1.0, status.Generation, time.Hour) } done := make(chan error, 1) go func() { done <- srv.SendDriverDefault(context.Background(), "heat") }() select { case err := <-done: if err != nil { - state.Unlock() + srv.controlHolds.Seams().Unlock(state) t.Fatalf("SendDriverDefault = %v", err) } case <-time.After(time.Second): - state.Unlock() + srv.controlHolds.Seams().Unlock(state) t.Fatal("SendDriverDefault waited for the operator request") } if !tc.armBefore { - srv.controlHolds.ArmLocked("heat", state, "set_offset", 2.0, status.Generation, time.Hour) + srv.controlHolds.Seams().ArmLocked("heat", state, "set_offset", 2.0, status.Generation, time.Hour) } - state.Unlock() + srv.controlHolds.Seams().Unlock(state) if tc.wantCleared { deadline := time.Now().Add(time.Second) @@ -896,14 +896,14 @@ func TestSendDriverDefaultClearsOnlyHoldsArmedBeforeIt(t *testing.T) { func TestSendDriverDefaultDoesNotRecreateStateAfterRemove(t *testing.T) { srv, _ := controlServer(t) - srv.controlHolds.State("heat") + srv.controlHolds.Seams().State("heat") paused := make(chan struct{}) resume := make(chan struct{}) - srv.beforeDriverDefaultStateLock = func() { + srv.controlHolds.Seams().BeforeDefaultStateLock(func() { close(paused) <-resume - } + }) result := make(chan error, 1) go func() { @@ -926,7 +926,7 @@ func TestSendDriverDefaultDoesNotRecreateStateAfterRemove(t *testing.T) { close(resume) t.Fatal("RemoveProbe deadlocked behind SendDriverDefault") } - if state := srv.controlHolds.Peek("heat"); state != nil { + if state := srv.controlHolds.Seams().Peek("heat"); state != nil { t.Fatalf("removed driver still has control state before default resumes: %p", state) } close(resume) @@ -939,14 +939,14 @@ func TestSendDriverDefaultDoesNotRecreateStateAfterRemove(t *testing.T) { case <-time.After(time.Second): t.Fatal("SendDriverDefault did not finish after lifecycle removal") } - if state := srv.controlHolds.Peek("heat"); state != nil { + if state := srv.controlHolds.Seams().Peek("heat"); state != nil { t.Fatalf("default path recreated removed control state: %p", state) } } func TestSendDriverDefaultDoesNotAccumulateRemovedStates(t *testing.T) { srv, _ := controlServer(t) - srv.controlHolds.State("heat") + srv.controlHolds.Seams().State("heat") base := srv.deps.Cfg.Drivers[0] for i := 0; i < 64; i++ { @@ -956,14 +956,14 @@ func TestSendDriverDefaultDoesNotAccumulateRemovedStates(t *testing.T) { if err := srv.deps.Registry.Add(context.Background(), cfg); err != nil { t.Fatalf("add %s: %v", name, err) } - srv.controlHolds.State(name) + srv.controlHolds.Seams().State(name) paused := make(chan struct{}) resume := make(chan struct{}) - srv.beforeDriverDefaultStateLock = func() { + srv.controlHolds.Seams().BeforeDefaultStateLock(func() { close(paused) <-resume - } + }) result := make(chan error, 1) go func() { result <- srv.SendDriverDefault(context.Background(), name) @@ -984,13 +984,13 @@ func TestSendDriverDefaultDoesNotAccumulateRemovedStates(t *testing.T) { case <-time.After(time.Second): t.Fatalf("SendDriverDefault(%s) did not finish", name) } - srv.beforeDriverDefaultStateLock = nil - if state := srv.controlHolds.Peek(name); state != nil { + srv.controlHolds.Seams().BeforeDefaultStateLock(nil) + if state := srv.controlHolds.Seams().Peek(name); state != nil { t.Fatalf("removed driver %s left a control state", name) } } - if got := srv.controlHolds.Len(); got != 1 { + if got := srv.controlHolds.Seams().Len(); got != 1 { t.Fatalf("control state map has %d entries after removed names, want only heat", got) } } @@ -1005,15 +1005,15 @@ func TestDriverControlSerializesExpiryAndReplacement(t *testing.T) { `{"control":"set_offset","value":1,"duration_s":600}`); rec.Code != http.StatusOK { t.Fatalf("POST = %d, body %s", rec.Code, rec.Body.String()) } - state := srv.controlHolds.State("heat") - hold := state.CurrentHold() + state := srv.controlHolds.Seams().State("heat") + hold := srv.controlHolds.Seams().CurrentHold(state) if hold == nil { t.Fatal("missing hold") } done := make(chan struct{}) go func() { - srv.controlHolds.Expire("heat", state, hold) + srv.controlHolds.Seams().Expire("heat", state, hold) close(done) }() waitMetric(t, tel, "heat", "default_started", 1) @@ -1116,11 +1116,11 @@ func TestDriverControlClearsHoldAcrossLifecycle(t *testing.T) { t.Fatalf("initial POST = %d, body %s", rec.Code, rec.Body.String()) } waitMetric(t, tel, "heat", "applied", 2) - oldState := srv.controlHolds.Peek("heat") + oldState := srv.controlHolds.Seams().Peek("heat") if oldState == nil { t.Fatal("initial control state is missing") } - oldHold := oldState.CurrentHold() + oldHold := srv.controlHolds.Seams().CurrentHold(oldState) if oldHold == nil { t.Fatal("initial control hold is missing") } @@ -1131,7 +1131,7 @@ func TestDriverControlClearsHoldAcrossLifecycle(t *testing.T) { if got := srv.controlHolds.Active("heat"); got != nil { t.Fatalf("hold survived restart: %+v", got) } - if got := srv.controlHolds.Peek("heat"); got != nil { + if got := srv.controlHolds.Seams().Peek("heat"); got != nil { t.Fatal("control state map entry survived restart") } if got := driverDetail(t, srv, "heat"); got.Hold != nil { @@ -1146,7 +1146,7 @@ func TestDriverControlClearsHoldAcrossLifecycle(t *testing.T) { waitMetric(t, tel, "heat", "applied", -2) // Simulate a timer callback that was already in flight when the old // generation was removed. It must not default the new instance. - srv.controlHolds.Expire("heat", oldState, oldHold) + srv.controlHolds.Seams().Expire("heat", oldState, oldHold) time.Sleep(250 * time.Millisecond) if got, _, ok := tel.LatestMetric("heat", "defaulted"); !ok || got != 0 { t.Fatalf("old timer changed the replacement: defaulted=%v/%v", got, ok) @@ -1158,7 +1158,7 @@ func TestDriverControlClearsHoldAcrossLifecycle(t *testing.T) { disabled := cfg disabled.Disabled = true srv.deps.Registry.Reload(context.Background(), []config.Driver{disabled}, false) - if got := srv.controlHolds.Peek("heat"); got != nil { + if got := srv.controlHolds.Seams().Peek("heat"); got != nil { t.Fatal("control state map entry survived disable") } if got := driverDetail(t, srv, "heat"); got.Hold != nil { @@ -1166,7 +1166,7 @@ func TestDriverControlClearsHoldAcrossLifecycle(t *testing.T) { } srv.deps.Registry.Reload(context.Background(), []config.Driver{cfg}, false) - if got := srv.controlHolds.Peek("heat"); got != nil { + if got := srv.controlHolds.Seams().Peek("heat"); got != nil { t.Fatal("control state map entry survived re-add") } if got := driverDetail(t, srv, "heat"); got.Hold != nil { @@ -1184,7 +1184,7 @@ func TestDriverDetailUnknownNamesDoNotCreateControlState(t *testing.T) { t.Fatalf("GET %s = %d, body %s", name, rec.Code, rec.Body.String()) } } - if got := srv.controlHolds.Len(); got != 0 { + if got := srv.controlHolds.Seams().Len(); got != 0 { t.Fatalf("unknown GETs created %d control states", got) } } diff --git a/go/internal/config/config.go b/go/internal/config/config.go index 0b8e473f0..4784ea678 100644 --- a/go/internal/config/config.go +++ b/go/internal/config/config.go @@ -46,6 +46,7 @@ type Config struct { OCPP *OCPP `yaml:"ocpp,omitempty" json:"ocpp,omitempty"` Setup *Setup `yaml:"setup,omitempty" json:"setup,omitempty"` ForecastPriors *ForecastPriors `yaml:"forecast_priors,omitempty" json:"forecast_priors,omitempty"` + Thermal *Thermal `yaml:"thermal,omitempty" json:"thermal,omitempty"` // LoadWarnings collects recoverable problems Parse repaired instead of // refusing the file: an on-disk config an older version accepted must @@ -1984,6 +1985,9 @@ func (c *Config) Validate() error { if err := c.Price.Validate(); err != nil { return err } + if err := c.Thermal.Validate(); err != nil { + return err + } if c.Site.TimeZone != "" { if _, err := localzone.Load(c.Site.TimeZone); err != nil { return fmt.Errorf("site.time_zone: %w", err) diff --git a/go/internal/config/thermal.go b/go/internal/config/thermal.go new file mode 100644 index 000000000..83d859617 --- /dev/null +++ b/go/internal/config/thermal.go @@ -0,0 +1,123 @@ +package config + +import ( + "fmt" + "math" + "strings" +) + +// Thermal is the owner's say over what heat is worth (docs/adr/0012, +// "Comfort follows the day's price"). Every number is the owner's: nothing +// here has a default, and a site without the section runs exactly as +// before. The zone's target, band and controls of the ADR are not here yet. +// +// The section is plain numbers. What turns them into the planner's rules +// lives beside the planner's caller, so the configuration does not pull the +// planner onto the control path. +// +// Prices are the day's mean of the total consumer price, öre/kWh, the same +// figure the price view shows. +type Thermal struct { + // Day price levels. On a day at or below cheap_day_ore_kwh a zone gets + // all of its cheap_day_raise_k; at normal_day_ore_kwh its target is the owner's + // own; at or above dear_day_ore_kwh it loses all of its dear_day_lower_k. The + // change between them is linear. + CheapDayOreKWh float64 `yaml:"cheap_day_ore_kwh,omitempty" json:"cheap_day_ore_kwh,omitempty"` + NormalDayOreKWh float64 `yaml:"normal_day_ore_kwh,omitempty" json:"normal_day_ore_kwh,omitempty"` + DearDayOreKWh float64 `yaml:"dear_day_ore_kwh,omitempty" json:"dear_day_ore_kwh,omitempty"` + // MinSavingOrePerDay is what moving heat in time must save across all + // zones in a day before any of it is acted on. Below it every zone is + // left on its target for the day. 0 means no limit. + MinSavingOrePerDay float64 `yaml:"min_saving_ore_per_day,omitempty" json:"min_saving_ore_per_day,omitempty"` + // Zones lists the comfort each zone gives and takes. A zone not listed + // keeps its target whatever the day costs. + Zones []ThermalZone `yaml:"zones,omitempty" json:"zones,omitempty"` +} + +// ThermalSensor names one driver's metric. +type ThermalSensor struct { + Driver string `yaml:"driver" json:"driver"` + Metric string `yaml:"metric" json:"metric"` +} + +// Key is the name the thermal twin lists the sensor under. +func (s ThermalSensor) Key() string { return s.Driver + "/" + s.Metric } + +// ThermalZone is one zone's comfort rule. +type ThermalZone struct { + // ComfortSensor is the zone: the sensor whose temperature the owner + // cares about, as in the ADR. + ComfortSensor ThermalSensor `yaml:"comfort_sensor" json:"comfort_sensor"` + // CheapDayRaiseK is how much warmer the zone is wanted on a cheap day, + // DearDayLowerK how much cooler it may be on a dear one, in kelvin. + // Zero leaves that direction off. + CheapDayRaiseK float64 `yaml:"cheap_day_raise_k,omitempty" json:"cheap_day_raise_k,omitempty"` + DearDayLowerK float64 `yaml:"dear_day_lower_k,omitempty" json:"dear_day_lower_k,omitempty"` + // StepK rounds the change to the thermostat's step. 0 leaves it + // unrounded. + StepK float64 `yaml:"step_k,omitempty" json:"step_k,omitempty"` +} + +// Zone is the rule for one comfort sensor, by its key, and whether the +// owner listed it. +func (h *Thermal) Zone(sensor string) (ThermalZone, bool) { + if h == nil { + return ThermalZone{}, false + } + for _, z := range h.Zones { + if z.ComfortSensor.Key() == sensor { + return z, true + } + } + return ThermalZone{}, false +} + +// Validate refuses a section that cannot be read one way, so a typo is told +// to the owner instead of silently moving nothing. +func (h *Thermal) Validate() error { + if h == nil { + return nil + } + if h.CheapDayOreKWh < 0 || h.NormalDayOreKWh < 0 || h.DearDayOreKWh < 0 { + return fmt.Errorf("thermal: day price levels must be >= 0") + } + if h.MinSavingOrePerDay < 0 { + return fmt.Errorf("thermal.min_saving_ore_per_day must be >= 0") + } + if !thermalFinite(h.CheapDayOreKWh, h.NormalDayOreKWh, h.DearDayOreKWh, h.MinSavingOrePerDay) { + return fmt.Errorf("thermal: prices and the least saving must be finite") + } + seen := map[string]bool{} + for i, z := range h.Zones { + at := fmt.Sprintf("thermal.zones[%d]", i) + key := z.ComfortSensor.Key() + if z.ComfortSensor.Driver == "" || z.ComfortSensor.Metric == "" || strings.Contains(z.ComfortSensor.Driver, "/") { + return fmt.Errorf("%s.comfort_sensor needs a driver name and a metric", at) + } + if seen[key] { + return fmt.Errorf("%s.comfort_sensor %s is listed twice", at, key) + } + seen[key] = true + if !thermalFinite(z.CheapDayRaiseK, z.DearDayLowerK, z.StepK) || + z.CheapDayRaiseK < 0 || z.DearDayLowerK < 0 || z.CheapDayRaiseK > 10 || z.DearDayLowerK > 10 || + z.StepK < 0 || z.StepK > 5 { + return fmt.Errorf("%s (%s): a target moves 0 to 10 K, in steps of at most 5 K", at, key) + } + if z.CheapDayRaiseK > 0 && !(h.CheapDayOreKWh < h.NormalDayOreKWh) { + return fmt.Errorf("%s (%s): cheap_day_raise_k needs thermal.cheap_day_ore_kwh below normal_day_ore_kwh", at, key) + } + if z.DearDayLowerK > 0 && !(h.NormalDayOreKWh < h.DearDayOreKWh) { + return fmt.Errorf("%s (%s): dear_day_lower_k needs thermal.dear_day_ore_kwh above normal_day_ore_kwh", at, key) + } + } + return nil +} + +func thermalFinite(vs ...float64) bool { + for _, v := range vs { + if math.IsNaN(v) || math.IsInf(v, 0) { + return false + } + } + return true +} diff --git a/go/internal/config/thermal_test.go b/go/internal/config/thermal_test.go new file mode 100644 index 000000000..7a86a137e --- /dev/null +++ b/go/internal/config/thermal_test.go @@ -0,0 +1,103 @@ +package config + +import ( + "math" + "strings" + "testing" +) + +const thermalYAML = ` +site: + name: test +fuse: + max_amps: 16 +thermal: + cheap_day_ore_kwh: 150 + normal_day_ore_kwh: 260 + dear_day_ore_kwh: 400 + min_saving_ore_per_day: 500 + zones: + - comfort_sensor: { driver: wiser, metric: bathroom_floor_c } + cheap_day_raise_k: 2.5 + - comfort_sensor: { driver: wiser, metric: bathroom_air_c } + dear_day_lower_k: 1 + step_k: 0.5 +` + +func TestThermalSectionCarriesTheOwnersNumbers(t *testing.T) { + c, err := Parse([]byte(thermalYAML), ".") + if err != nil { + t.Fatalf("parse: %v", err) + } + if err := c.Thermal.Validate(); err != nil { + t.Fatalf("validate: %v", err) + } + h := c.Thermal + if h.CheapDayOreKWh != 150 || h.NormalDayOreKWh != 260 || h.DearDayOreKWh != 400 || h.MinSavingOrePerDay != 500 { + t.Errorf("levels = %+v", h) + } + floor, ok := h.Zone("wiser/bathroom_floor_c") + if !ok || floor.CheapDayRaiseK != 2.5 || floor.DearDayLowerK != 0 { + t.Errorf("floor = %+v, %v", floor, ok) + } + air, ok := h.Zone("wiser/bathroom_air_c") + if !ok || air.DearDayLowerK != 1 || air.StepK != 0.5 || air.CheapDayRaiseK != 0 { + t.Errorf("air = %+v, %v", air, ok) + } + if _, ok := h.Zone("wiser/hall_c"); ok { + t.Error("a zone with no rule got one") + } +} + +func TestThermalSectionIsOffUntilTheOwnerSetsIt(t *testing.T) { + var none *Thermal + if _, ok := none.Zone("a/b"); ok || none.Validate() != nil { + t.Error("a missing thermal section must change nothing") + } + if (&Thermal{}).Validate() != nil { + t.Error("an empty thermal section must be valid") + } +} + +func TestThermalSectionRefusesWhatCannotBeReadOneWay(t *testing.T) { + ok := func() *Thermal { + return &Thermal{CheapDayOreKWh: 150, NormalDayOreKWh: 260, DearDayOreKWh: 400, + Zones: []ThermalZone{{ComfortSensor: ThermalSensor{Driver: "wiser", Metric: "floor_c"}, CheapDayRaiseK: 2, DearDayLowerK: 1}}} + } + for name, tc := range map[string]struct { + change func(*Thermal) + want string + }{ + "cheap above normal": {func(h *Thermal) { h.CheapDayOreKWh = 300 }, "cheap_day_ore_kwh below"}, + "dear below normal": {func(h *Thermal) { h.DearDayOreKWh = 200 }, "dear_day_ore_kwh above"}, + "no price levels": {func(h *Thermal) { h.CheapDayOreKWh, h.NormalDayOreKWh, h.DearDayOreKWh = 0, 0, 0 }, "cheap_day_ore_kwh below"}, + "negative level": {func(h *Thermal) { h.CheapDayOreKWh = -5 }, "day price levels"}, + "level not a number": {func(h *Thermal) { h.DearDayOreKWh = math.Inf(1) }, "finite"}, + "negative saving": {func(h *Thermal) { h.MinSavingOrePerDay = -1 }, "min_saving_ore_per_day"}, + "negative raise": {func(h *Thermal) { h.Zones[0].CheapDayRaiseK = -1 }, "0 to 10 K"}, + "a raise of 20 K": {func(h *Thermal) { h.Zones[0].CheapDayRaiseK = 20 }, "0 to 10 K"}, + "sensor not named": {func(h *Thermal) { h.Zones[0].ComfortSensor.Metric = "" }, "needs a driver name and a metric"}, + "sensor twice": {func(h *Thermal) { h.Zones = append(h.Zones, h.Zones[0]) }, "listed twice"}, + } { + h := ok() + tc.change(h) + err := h.Validate() + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: err = %v, want one naming %q", name, err, tc.want) + } + } + if err := ok().Validate(); err != nil { + t.Fatalf("the valid section: %v", err) + } + // A direction that is off needs no price level. + only := &Thermal{NormalDayOreKWh: 260, DearDayOreKWh: 400, + Zones: []ThermalZone{{ComfortSensor: ThermalSensor{Driver: "a", Metric: "b"}, DearDayLowerK: 1}}} + if err := only.Validate(); err != nil { + t.Errorf("lower only, no cheap level: %v", err) + } + c := &Config{Thermal: ok()} + c.Thermal.DearDayOreKWh = 100 + if err := c.Validate(); err == nil || !strings.Contains(err.Error(), "thermal.zones[0]") { + t.Errorf("Config.Validate let a bad thermal section through: %v", err) + } +} diff --git a/go/internal/drivercontrol/holds.go b/go/internal/drivercontrol/holds.go index c4c572719..d9088f73b 100644 --- a/go/internal/drivercontrol/holds.go +++ b/go/internal/drivercontrol/holds.go @@ -46,33 +46,24 @@ type Hold struct { } // State serializes command dispatch, default dispatch and hold transitions -// for one driver. +// for one driver. It is opaque outside this package: callers go through +// Holds' methods, which take and release its lock themselves. type State struct { mu sync.Mutex hold *Hold } -// Lock takes the per-driver lock. Exported for tests that stand in for a -// command in flight; production callers use Holds' methods. -func (st *State) Lock() { st.mu.Lock() } - -// Unlock releases the per-driver lock. -func (st *State) Unlock() { st.mu.Unlock() } - -// CurrentHold returns the held setting itself, not a copy, or nil. Its -// identity is what Expire compares. -func (st *State) CurrentHold() *Hold { - st.mu.Lock() - defer st.mu.Unlock() - return st.hold -} - // Holds is every driver's State. type Holds struct { registry func() Registry mu sync.Mutex states map[string]*State + + // Test seams, nil in production and set only through Seams. Guarded by + // mu. + beforeStateLock func() + beforeDefaultStateLock func() } // New returns empty holds. registry is read at each use, so a caller whose @@ -97,10 +88,7 @@ func (h *Holds) reg() Registry { // done runs with the outcome while the lock is still held, so a caller that // reads registry status to explain an error sees it before any lifecycle // change waiting on this driver can proceed. -// -// beforeStateLock is a test seam, run after the state lookup and before the -// per-driver lock; nil in production. -func (h *Holds) Send(ctx context.Context, name, controlID string, value any, body []byte, d time.Duration, beforeStateLock func(), done func(Hold, error)) { +func (h *Holds) Send(ctx context.Context, name, controlID string, value any, body []byte, d time.Duration, done func(Hold, error)) { reg := h.reg() if reg == nil { done(Hold{}, errors.New("driver registry not available")) @@ -112,7 +100,7 @@ func (h *Holds) Send(ctx context.Context, name, controlID string, value any, bod // old status snapshot. The state lookup and lock are also one lifecycle // transaction: clearState takes the same locks in the same order, so it // cannot remove the map entry between these operations. - state := h.lock(name, beforeStateLock) + state := h.lock(name) defer state.mu.Unlock() sendCtx, cancel := context.WithTimeout(ctx, DefaultTimeout) defer cancel() @@ -122,19 +110,12 @@ func (h *Holds) Send(ctx context.Context, name, controlID string, value any, bod done(Hold{}, err) return } - hold := h.ArmLocked(name, state, controlID, value, generation, d) + hold := h.armLocked(name, state, controlID, value, generation, d) out := *hold out.timer = nil done(out, nil) } -// State returns the driver's state, creating it. -func (h *Holds) State(name string) *State { - h.mu.Lock() - defer h.mu.Unlock() - return h.stateLocked(name) -} - func (h *Holds) stateLocked(name string) *State { if h.states == nil { h.states = make(map[string]*State) @@ -152,11 +133,11 @@ func (h *Holds) stateLocked(name string) *State { // can either own the state before removal starts or see a removed state // after removal finishes; it cannot keep a pointer that was deleted in // between. -func (h *Holds) lock(name string, beforeStateLock func()) *State { +func (h *Holds) lock(name string) *State { h.mu.Lock() state := h.stateLocked(name) - if beforeStateLock != nil { - beforeStateLock() + if h.beforeStateLock != nil { + h.beforeStateLock() } state.mu.Lock() h.mu.Unlock() @@ -177,11 +158,11 @@ func (h *Holds) tryLockExisting(name string) (state *State, locked bool) { return state, state.mu.TryLock() } -// ArmLocked replaces any existing hold for the driver; the caller holds +// armLocked replaces any existing hold for the driver; the caller holds // state's lock. One driver holds one control at a time: two overlapping // holds on the same device would each expire into a default that undoes the // other. -func (h *Holds) ArmLocked(name string, state *State, control string, value any, generation uint64, d time.Duration) *Hold { +func (h *Holds) armLocked(name string, state *State, control string, value any, generation uint64, d time.Duration) *Hold { h.clearLocked(state) now := time.Now() hold := &Hold{ @@ -192,7 +173,7 @@ func (h *Holds) ArmLocked(name string, state *State, control string, value any, armedAt: now, } hold.timer = time.AfterFunc(d, func() { - if err := h.Expire(name, state, hold); err != nil { + if err := h.expire(name, state, hold); err != nil { slog.Error("control hold expiry default failed; registry recovery gate remains active", "driver", name, "err", err) } }) @@ -207,11 +188,11 @@ func (h *Holds) clearLocked(state *State) { state.hold = nil } -// Expire hands the device back to itself. It checks identity first: a hold +// expire hands the device back to itself. It checks identity first: a hold // that was replaced or released already had its timer stopped, but a timer // that had begun firing cannot be stopped, and defaulting a driver that an // operator has just set again is the one wrong answer here. -func (h *Holds) Expire(name string, state *State, fired *Hold) error { +func (h *Holds) expire(name string, state *State, fired *Hold) error { state.mu.Lock() defer state.mu.Unlock() if state.hold != fired { @@ -245,9 +226,7 @@ func (h *Holds) Expire(name string, state *State, fired *Hold) error { // cleared once the lock is free, but only a hold armed before the default // returned. A later one belongs to a command sent after the default and // keeps its own expiry. -// -// beforeDefaultStateLock is a test seam; nil in production. -func (h *Holds) SendDefault(ctx context.Context, name string, beforeDefaultStateLock func()) error { +func (h *Holds) SendDefault(ctx context.Context, name string) error { reg := h.reg() if reg == nil { return errors.New("driver registry not available") @@ -255,8 +234,11 @@ func (h *Holds) SendDefault(ctx context.Context, name string, beforeDefaultState if _, ok := reg.ControlStatus(name); !ok { return fmt.Errorf("driver %q not found", name) } - if beforeDefaultStateLock != nil { - beforeDefaultStateLock() + h.mu.Lock() + before := h.beforeDefaultStateLock + h.mu.Unlock() + if before != nil { + before() } state, locked := h.tryLockExisting(name) if locked { @@ -296,13 +278,36 @@ func (h *Holds) sendDefaultLocked(ctx context.Context, name string) error { // Active returns a copy of the driver's hold, or nil. A hold bound to a // generation that is no longer running is cleared, not returned. +// +// It takes the per-driver lock, so it waits for a command in flight, up to +// DefaultTimeout. That suits a request. The control tick must use TryActive. func (h *Holds) Active(name string) *Hold { - state := h.Peek(name) + state := h.peek(name) if state == nil { return nil } state.mu.Lock() defer state.mu.Unlock() + return h.activeLocked(name, state) +} + +// TryActive is Active for a caller that must not wait, as the control tick +// must not. known is false when a command or a default holds the driver's +// lock: the hold is then changing, and the caller should treat the driver as +// held and look again on its next tick rather than send anything. +func (h *Holds) TryActive(name string) (hold *Hold, known bool) { + state, locked := h.tryLockExisting(name) + if state == nil { + return nil, true + } + if !locked { + return nil, false + } + defer state.mu.Unlock() + return h.activeLocked(name, state), true +} + +func (h *Holds) activeLocked(name string, state *State) *Hold { if state.hold == nil { return nil } @@ -321,21 +326,14 @@ func (h *Holds) Active(name string) *Hold { return &hold } -// Peek returns the driver's state without creating one. -func (h *Holds) Peek(name string) *State { +// peek returns the driver's state without creating one. +func (h *Holds) peek(name string) *State { h.mu.Lock() state := h.states[name] h.mu.Unlock() return state } -// Len is how many drivers have state. For tests of lifecycle cleanup. -func (h *Holds) Len() int { - h.mu.Lock() - defer h.mu.Unlock() - return len(h.states) -} - // Clear is called by the registry before a driver generation is removed. It // stops the old timer and drops the map entry so a re-added driver cannot // inherit a hold from the previous instance. diff --git a/go/internal/drivercontrol/holds_test.go b/go/internal/drivercontrol/holds_test.go index 4c6654911..d01c0da36 100644 --- a/go/internal/drivercontrol/holds_test.go +++ b/go/internal/drivercontrol/holds_test.go @@ -56,7 +56,7 @@ func send(t *testing.T, h *Holds, value any, d time.Duration) (Hold, error) { t.Helper() var hold Hold var err error - h.Send(context.Background(), "heat", "set_offset", value, []byte(`{}`), d, nil, func(got Hold, e error) { + h.Send(context.Background(), "heat", "set_offset", value, []byte(`{}`), d, func(got Hold, e error) { hold, err = got, e }) return hold, err @@ -122,12 +122,12 @@ func TestExpiryOfAnOldGenerationSendsNoDefault(t *testing.T) { if _, err := send(t, h, 1.0, time.Hour); err != nil { t.Fatal(err) } - state := h.Peek("heat") - fired := state.CurrentHold() + state := h.peek("heat") + fired := h.Seams().CurrentHold(state) reg.mu.Lock() reg.generation = 2 reg.mu.Unlock() - if err := h.Expire("heat", state, fired); err != nil { + if err := h.expire("heat", state, fired); err != nil { t.Fatal(err) } if _, d := reg.counts(); d != 0 { @@ -142,12 +142,12 @@ func TestExpiryOfAReplacedHoldIsANoOp(t *testing.T) { if _, err := send(t, h, 1.0, time.Hour); err != nil { t.Fatal(err) } - state := h.Peek("heat") - old := state.CurrentHold() + state := h.peek("heat") + old := h.Seams().CurrentHold(state) if _, err := send(t, h, 2.0, time.Hour); err != nil { t.Fatal(err) } - if err := h.Expire("heat", state, old); err != nil { + if err := h.expire("heat", state, old); err != nil { t.Fatal(err) } if _, d := reg.counts(); d != 0 { @@ -164,7 +164,7 @@ func TestSendDefaultClearsTheHold(t *testing.T) { if _, err := send(t, h, 1.0, time.Hour); err != nil { t.Fatal(err) } - if err := h.SendDefault(context.Background(), "heat", nil); err != nil { + if err := h.SendDefault(context.Background(), "heat"); err != nil { t.Fatal(err) } if _, d := reg.counts(); d != 1 { @@ -177,7 +177,7 @@ func TestSendDefaultClearsTheHold(t *testing.T) { func TestSendDefaultForAnUnknownDriverFails(t *testing.T) { h := newHolds(&fakeRegistry{}) - if err := h.SendDefault(context.Background(), "heat", nil); err == nil { + if err := h.SendDefault(context.Background(), "heat"); err == nil { t.Fatal("default to a driver that is not running succeeded") } } @@ -189,8 +189,8 @@ func TestClearDropsStateAndTimer(t *testing.T) { t.Fatal(err) } h.Clear("heat") - if h.Len() != 0 || h.Peek("heat") != nil { - t.Fatalf("Clear left state: len=%d", h.Len()) + if len(h.states) != 0 || h.peek("heat") != nil { + t.Fatalf("Clear left state: len=%d", len(h.states)) } time.Sleep(60 * time.Millisecond) if _, d := reg.counts(); d != 0 { @@ -204,10 +204,45 @@ func TestNoRegistry(t *testing.T) { if _, err := send(t, h, 1.0, time.Hour); err == nil { t.Fatal("send without a registry succeeded") } - if err := h.SendDefault(context.Background(), "heat", nil); err == nil { + if err := h.SendDefault(context.Background(), "heat"); err == nil { t.Fatal("default without a registry succeeded") } if h.Active("heat") != nil { t.Fatal("hold without a registry") } } + +// The control tick reads a hold without waiting. While a command or a +// default holds the driver's lock it is told so, not kept waiting and not +// told there is no hold. +func TestTryActiveDoesNotWaitForACommandInFlight(t *testing.T) { + reg := &fakeRegistry{generation: 1, running: true} + h := newHolds(reg) + if hold, known := h.TryActive("heat"); hold != nil || !known { + t.Fatalf("TryActive without state = %+v, known %v; want nil, known", hold, known) + } + if _, err := send(t, h, 1.0, time.Hour); err != nil { + t.Fatal(err) + } + if hold, known := h.TryActive("heat"); !known || hold == nil || hold.Value != 1.0 { + t.Fatalf("TryActive = %+v, known %v; want the hold", hold, known) + } + + seams := h.Seams() + state := seams.Peek("heat") + seams.Lock(state) // a command in flight + done := make(chan bool, 1) + go func() { + hold, known := h.TryActive("heat") + done <- hold == nil && !known + }() + select { + case unknown := <-done: + if !unknown { + t.Error("TryActive behind a command in flight claimed to know the hold") + } + case <-time.After(time.Second): + t.Error("TryActive waited for the command in flight") + } + seams.Unlock(state) +} diff --git a/go/internal/drivercontrol/seams.go b/go/internal/drivercontrol/seams.go new file mode 100644 index 000000000..5d57329fb --- /dev/null +++ b/go/internal/drivercontrol/seams.go @@ -0,0 +1,84 @@ +package drivercontrol + +import ( + "testing" + "time" +) + +// Seams is what tests need to stand in for a request in flight, a timer +// that fired, or a lifecycle change between two steps. It reaches under the +// per-driver lock, which no production caller may do: a planned-value +// caller that held that lock itself could keep an operator's command, or +// the tick's safety default, waiting on it. +// +// The API package's race tests need it as well as this package's own, so it +// cannot live in a _test file. Seams panics outside a test binary instead. +type Seams struct{ h *Holds } + +// Seams returns the test access. It panics outside a test binary. +func (h *Holds) Seams() Seams { + if !testing.Testing() { + panic("drivercontrol: Seams is for tests only") + } + return Seams{h} +} + +// State returns the driver's state, creating it. +func (s Seams) State(name string) *State { + s.h.mu.Lock() + defer s.h.mu.Unlock() + return s.h.stateLocked(name) +} + +// Peek returns the driver's state without creating one. +func (s Seams) Peek(name string) *State { return s.h.peek(name) } + +// Len is how many drivers have state. +func (s Seams) Len() int { + s.h.mu.Lock() + defer s.h.mu.Unlock() + return len(s.h.states) +} + +// Lock takes the per-driver lock, as a command in flight does. +func (s Seams) Lock(st *State) { st.mu.Lock() } + +// Unlock releases the per-driver lock. +func (s Seams) Unlock(st *State) { st.mu.Unlock() } + +// CurrentHold returns the held setting itself, not a copy, or nil. Its +// identity is what Expire compares. +func (s Seams) CurrentHold(st *State) *Hold { + st.mu.Lock() + defer st.mu.Unlock() + return st.hold +} + +// ArmLocked arms a hold as Send does after its command; the caller holds +// st's lock. +func (s Seams) ArmLocked(name string, st *State, control string, value any, generation uint64, d time.Duration) *Hold { + return s.h.armLocked(name, st, control, value, generation, d) +} + +// Expire runs what a hold's timer runs. +func (s Seams) Expire(name string, st *State, fired *Hold) error { + return s.h.expire(name, st, fired) +} + +// BeforeStateLock sets a function Send runs after the state lookup, while +// the map lock is held and before the per-driver lock is taken. nil clears +// it. +func (s Seams) BeforeStateLock(fn func()) { + s.h.mu.Lock() + defer s.h.mu.Unlock() + s.h.beforeStateLock = fn +} + +// BeforeDefaultStateLock sets a function SendDefault runs after it has +// found the driver and before it looks for the driver's state. nil clears +// it. +func (s Seams) BeforeDefaultStateLock(fn func()) { + s.h.mu.Lock() + defer s.h.mu.Unlock() + s.h.beforeDefaultStateLock = fn +} diff --git a/go/internal/heatplan/archetypes_test.go b/go/internal/heatplan/archetypes_test.go new file mode 100644 index 000000000..9157f8a91 --- /dev/null +++ b/go/internal/heatplan/archetypes_test.go @@ -0,0 +1,148 @@ +package heatplan + +import ( + "math" + + "github.com/srcfl/ftw/go/internal/thermal" +) + +// Seven heated things with round, plausible numbers. They are fixtures for +// the tests, not defaults: a real zone's numbers come from its twin. + +const ( + slotH = 0.25 + day = 96 +) + +func flat(n int, v float64) []float64 { + out := make([]float64, n) + for i := range out { + out[i] = v + } + return out +} + +// hours builds a per-slot series from a value per hour of day. +func hours(n int, f func(hour float64) float64) []float64 { + out := make([]float64, n) + for i := range out { + out[i] = f(math.Mod(float64(i)*slotH, 24)) + } + return out +} + +func between(h, from, to float64) bool { return h >= from && h < to } + +// eveningPeak is a flat price with one expensive evening. +func eveningPeak(n int, base, peak float64) []float64 { + return hours(n, func(h float64) float64 { + if between(h, 17, 20) { + return peak + } + return base + }) +} + +func room(n int, tauH, capacity, outdoorC float64) Zone { + return Zone{ + TauH: tauH, CapacityKWhPerK: capacity, StartC: 21, + BoundaryC: flat(n, outdoorC), TargetC: flat(n, 21), MinC: flat(n, 20), MaxC: flat(n, 22), + ComfortWeight: 2, + } +} + +// A timber house on panel radiators. +func radiatorHouse(n int, price []float64) Request { + return Request{SlotH: slotH, Price: price, OutdoorC: flat(n, 0), + Zone: room(n, 40, 8, 0), + Actuator: Actuator{Strategy: thermal.InfluenceSetpoint, Values: Values(20, 22, 0.5, 21, 8), + MaxHeatKW: 8, Source: Source{Kind: SourceDirectElectric}}} +} + +// The same house behind one air-to-air unit. The unit heats the air, and the +// air is what its sensor sees, so the zone is light and quick. +func airToAirHouse(n int, price, outdoor []float64) Request { + z := room(n, 20, 3, 0) + z.BoundaryC = outdoor + return Request{SlotH: slotH, Price: price, OutdoorC: outdoor, Zone: z, + Actuator: Actuator{Strategy: thermal.InfluenceSetpoint, Values: Values(20, 22, 0.5, 21, 8), + MaxHeatKW: 5, Source: Source{Kind: SourceHeatPump, SinkApproachK: 18, FrostLoss: 0.1}}} +} + +// A concrete slab fed by an air-to-water pump on a heating curve. +func slabHouse(n int, price, outdoor []float64) Request { + z := room(n, 100, 20, 0) + z.BoundaryC = outdoor + return Request{SlotH: slotH, Price: price, OutdoorC: outdoor, Zone: z, + Actuator: Actuator{Strategy: thermal.InfluenceCurveOffset, Values: Values(-3, 3, 1, 0, 8), + ZoneKPerUnit: 0.4, SupplyKPerUnit: 2, MaxHeatKW: 8, + Source: Source{Kind: SourceHeatPump, Supply: &SupplyCurve{ColdOutdoorC: -15, ColdSupplyC: 45, MildOutdoorC: 15, MildSupplyC: 25}}}} +} + +// A tiled bathroom floor on a heating cable. hpCOP above zero puts it inside +// a house a heat pump keeps at 21 °C. +func bathroomFloor(n int, price []float64, hpCOP float64) Request { + z := Zone{TauH: 12, CapacityKWhPerK: 0.6, StartC: 23, + BoundaryC: flat(n, 21), TargetC: flat(n, 23), MinC: flat(n, 21.5), MaxC: flat(n, 26), + ComfortWeight: 2} + if hpCOP > 0 { + z.LossCreditCOP = flat(n, hpCOP) + } + return Request{SlotH: slotH, Price: price, OutdoorC: flat(n, 0), Zone: z, + Actuator: Actuator{Strategy: thermal.InfluenceSetpoint, Values: Values(21.5, 26, 0.5, 23, 12), + MaxHeatKW: 0.8, Source: Source{Kind: SourceDirectElectric}}} +} + +// A 300 l hot-water tank in a 20 °C utility room, drawn from morning and +// evening. +func hotWaterTank(n int, price []float64, src Source) Request { + draws := hours(n, func(h float64) float64 { + switch { + case between(h, 7, 7.5): + return -4 + case between(h, 19, 19.5): + return -5 + } + return 0 + }) + return Request{SlotH: slotH, Price: price, OutdoorC: flat(n, 0), + Zone: Zone{TauH: 200, CapacityKWhPerK: 0.35, StartC: 55, + BoundaryC: flat(n, 20), TargetC: flat(n, 55), MinC: flat(n, 50), MaxC: flat(n, 65), + DisturbanceK: draws}, + Actuator: Actuator{Strategy: thermal.InfluenceSetpoint, Values: Values(50, 65, 2.5, 55, 8), + MaxHeatKW: 3, Source: src}} +} + +// A 1500 l covered spa outdoors, used 19–22 and let down in between. +func spa(n int, price []float64) Request { + use := func(h float64) bool { return between(h, 19, 22) } + return Request{SlotH: slotH, Price: price, OutdoorC: flat(n, 0), + Zone: Zone{TauH: 200, CapacityKWhPerK: 1.74, StartC: 34, + BoundaryC: flat(n, 0), + TargetC: hours(n, func(h float64) float64 { return map[bool]float64{true: 38, false: 34}[use(h)] }), + MinC: hours(n, func(h float64) float64 { return map[bool]float64{true: 37.5, false: 30}[use(h)] }), + MaxC: flat(n, 40)}, + Actuator: Actuator{Strategy: thermal.InfluenceSetpoint, Values: Values(30, 40, 1, 34, 12), + MaxHeatKW: 3, Source: Source{Kind: SourceDirectElectric}}} +} + +// A 40 m³ covered pool on its own air-source pump, which only starts and +// stops. +func pool(n int, price, outdoor []float64) Request { + return Request{SlotH: slotH, Price: price, OutdoorC: outdoor, + Zone: Zone{TauH: 300, CapacityKWhPerK: 46, StartC: 27, + BoundaryC: outdoor, TargetC: flat(n, 27), MinC: flat(n, 26), MaxC: flat(n, 29)}, + Actuator: Actuator{Strategy: thermal.InfluenceOnOff, MaxHeatKW: 10, + MinOnSlots: 2, MinOffSlots: 2, + Source: Source{Kind: SourceHeatPump, CarnotFraction: 0.3, MaxCOP: 7}}} +} + +// A summer day: 12 °C at dawn, 24 °C mid-afternoon. +func summerDay(n int) []float64 { + return hours(n, func(h float64) float64 { return 18 - 6*math.Cos((h-3)*math.Pi/12) }) +} + +// A winter day: −6 °C at dawn, 2 °C mid-afternoon. +func winterDay(n int) []float64 { + return hours(n, func(h float64) float64 { return -2 - 4*math.Cos((h-3)*math.Pi/12) }) +} diff --git a/go/internal/heatplan/comfort.go b/go/internal/heatplan/comfort.go new file mode 100644 index 000000000..028e50dc6 --- /dev/null +++ b/go/internal/heatplan/comfort.go @@ -0,0 +1,185 @@ +package heatplan + +import ( + "errors" + "math" +) + +// This file holds the owner's two rules for what heat is worth, beside the +// plan itself. Neither has a default in code: every number in them is the +// owner's, the zero value of each rule changes nothing, and a caller must +// not invent one. +// +// - PriceComfort: how warm the owner wants a zone depends on what the day +// costs. A cheap day may buy a warmer floor; a dear day may cost a +// cooler room. It moves the target before planning, so the plan and its +// baseline both stand on the comfort that day is worth. +// - SavingsGate: moving heat in time is only worth a device's writes and +// the owner's attention when the plans together save enough in a day. +// Below that the devices are left on their targets. +// +// PriceComfort needs no model of the zone and holds from the first day. +// SavingsGate weighs plans, so it is only as good as the twins behind them. + +// PriceComfort moves a zone's target with the day's mean price. All prices +// are in the unit of Request.Price. +type PriceComfort struct { + // CheapPrice is the day's mean price at or below which the target is + // raised by all of RaiseK. NormalPrice is where the target is the + // owner's own, and DearPrice the mean at or above which it is lowered by + // all of LowerK. Between them the shift is linear, never a step. + CheapPrice float64 `json:"cheap_price"` + NormalPrice float64 `json:"normal_price"` + DearPrice float64 `json:"dear_price"` + // RaiseK and LowerK are how far the target moves, in kelvin. Zero turns + // that direction off: a floor may follow cheap days up while the room + // air only follows dear days down. + RaiseK float64 `json:"raise_k"` + LowerK float64 `json:"lower_k"` + // StepK rounds the shift to the control's step, halves away from zero. + // Zero leaves it unrounded. + StepK float64 `json:"step_k,omitempty"` +} + +// Enabled reports whether the rule moves anything. +func (c PriceComfort) Enabled() bool { return c.RaiseK > 0 || c.LowerK > 0 } + +// Validate refuses a rule that cannot be read one way. A direction that is +// off needs no price. +func (c PriceComfort) Validate() error { + if !finite(c.CheapPrice, c.NormalPrice, c.DearPrice, c.RaiseK, c.LowerK, c.StepK) { + return errors.New("heatplan: price comfort must be finite") + } + if c.RaiseK < 0 || c.LowerK < 0 || c.RaiseK > 10 || c.LowerK > 10 || c.StepK < 0 || c.StepK > 5 { + return errors.New("heatplan: price comfort moves a target 0 to 10 K, in steps of at most 5 K") + } + if c.RaiseK > 0 && !(c.CheapPrice < c.NormalPrice) { + return errors.New("heatplan: the cheap price must be below the normal price") + } + if c.LowerK > 0 && !(c.NormalPrice < c.DearPrice) { + return errors.New("heatplan: the dear price must be above the normal price") + } + return nil +} + +// ShiftK is how far the target moves on a day whose mean price is dayMean: +// above zero on a cheap day, below on a dear one. An invalid rule, or a mean +// that is not a number, moves nothing. +func (c PriceComfort) ShiftK(dayMean float64) float64 { + if !finite(dayMean) || c.Validate() != nil { + return 0 + } + var shift float64 + switch { + case c.RaiseK > 0 && dayMean < c.NormalPrice: + shift = c.RaiseK * math.Min(1, (c.NormalPrice-dayMean)/(c.NormalPrice-c.CheapPrice)) + case c.LowerK > 0 && dayMean > c.NormalPrice: + shift = -c.LowerK * math.Min(1, (dayMean-c.NormalPrice)/(c.DearPrice-c.NormalPrice)) + } + if c.StepK > 0 { + // math.Round rounds halves away from zero, which is what a + // thermostat's half-degree step should do in both directions. + shift = math.Round(shift/c.StepK) * c.StepK + } + return shift +} + +// Apply returns the zone with its target moved for a day whose mean price is +// dayMean. The band is the owner's hard limit and stays where it is: a +// target is moved inside it and no further. The zone passed in is not +// changed. +func (c PriceComfort) Apply(z Zone, dayMean float64) Zone { + shift := c.ShiftK(dayMean) + if shift == 0 { + return z + } + target := make([]float64, len(z.TargetC)) + for i, t := range z.TargetC { + t += shift + if i < len(z.MinC) && t < z.MinC[i] { + t = z.MinC[i] + } + if i < len(z.MaxC) && t > z.MaxC[i] { + t = z.MaxC[i] + } + target[i] = t + } + z.TargetC = target + return z +} + +// DayMean is the mean of one day's prices, and whether enough of the day is +// known to call it that: at least minHours of slots of slotH hours each. A +// caller passes the slots of the day the comfort is for, the ones already +// past included, not the horizon from now. +func DayMean(price []float64, slotH, minHours float64) (mean float64, ok bool) { + if !(slotH > 0) || len(price) == 0 || float64(len(price))*slotH < minHours { + return 0, false + } + var sum float64 + for _, p := range price { + if !finite(p) { + return 0, false + } + sum += p + } + return sum / float64(len(price)), true +} + +// SavingsGate is the owner's least saving for planned heat to be acted on. +type SavingsGate struct { + // MinPerDay is what the plans must save together in a day, in the unit + // of Request.Price times kWh. Zero or less opens the gate always. + MinPerDay float64 `json:"min_per_day"` + // KeepShare is the share of MinPerDay below which an open gate closes + // again, so that a saving near the limit does not open and close it + // every slot. From above 0 to 1; zero means 1, no hysteresis. + KeepShare float64 `json:"keep_share,omitempty"` +} + +// Validate refuses a gate that cannot be read one way. +func (g SavingsGate) Validate() error { + if !finite(g.MinPerDay, g.KeepShare) || g.KeepShare < 0 || g.KeepShare > 1 { + return errors.New("heatplan: the savings gate keeps a share of 0 to 1 of a finite limit") + } + return nil +} + +// Saving is what the plan saves against the device left alone at the +// target. A plan that leaves its band saves nothing: it is not feasible, +// and what it seems to save is comfort it did not deliver. +func (p Plan) Saving() float64 { + if p.BandExcursionKh > 0 || !finite(p.Cost, p.BaselineCost) { + return 0 + } + return math.Max(0, p.BaselineCost-p.Cost) +} + +// Open reports whether the plans together save enough to act on, and what +// they save scaled to a day. horizonH is the horizon the plans cover; a +// horizon longer than a day is scaled down and a shorter one up, since a +// morning with half a day of prices would otherwise never reach a daily +// limit. wasOpen is the gate's last answer. +// +// A closed gate means every zone is left on its target, which with +// PriceComfort is the target that day is worth. An invalid gate, or a +// horizon that is not a length of time, is closed: the devices then run +// themselves, which is always safe. +func (g SavingsGate) Open(plans []Plan, horizonH float64, wasOpen bool) (open bool, perDay float64) { + if g.Validate() != nil || !(horizonH > 0) || !finite(horizonH) { + return false, 0 + } + var saved float64 + for _, p := range plans { + saved += p.Saving() + } + perDay = saved * 24 / horizonH + if g.MinPerDay <= 0 { + return true, perDay + } + limit := g.MinPerDay + if wasOpen && g.KeepShare > 0 { + limit *= g.KeepShare + } + return perDay >= limit, perDay +} diff --git a/go/internal/heatplan/comfort_test.go b/go/internal/heatplan/comfort_test.go new file mode 100644 index 000000000..11166a55a --- /dev/null +++ b/go/internal/heatplan/comfort_test.go @@ -0,0 +1,209 @@ +package heatplan + +import ( + "math" + "testing" +) + +// The rule one household runs today: a bathroom floor that follows cheap +// days up, and room air that only follows dear days down. Prices in öre. +var ( + floorComfort = PriceComfort{CheapPrice: 150, NormalPrice: 260, DearPrice: 400, RaiseK: 2.5} + airComfort = PriceComfort{CheapPrice: 150, NormalPrice: 260, DearPrice: 400, LowerK: 1, StepK: 0.5} +) + +func TestPriceComfortMovesGraduallyWithTheDaysPrice(t *testing.T) { + for _, tc := range []struct { + name string + c PriceComfort + mean float64 + want float64 + }{ + {"floor, cheaper than cheap", floorComfort, 90, 2.5}, + {"floor, at cheap", floorComfort, 150, 2.5}, + {"floor, halfway", floorComfort, 205, 1.25}, + {"floor, normal", floorComfort, 260, 0}, + {"floor never follows a dear day down", floorComfort, 480, 0}, + {"air never follows a cheap day up", airComfort, 90, 0}, + {"air, normal", airComfort, 260, 0}, + {"air, a little dear rounds to no step", airComfort, 290, 0}, + {"air, a quarter of the way is half a step up to 0.5", airComfort, 295, -0.5}, + {"air, most of the way", airComfort, 343, -0.5}, + {"air, three quarters rounds to the whole", airComfort, 365, -1}, + {"air, dearer than dear", airComfort, 480, -1}, + } { + if got := tc.c.ShiftK(tc.mean); math.Abs(got-tc.want) > 1e-9 { + t.Errorf("%s: shift at %v = %v K, want %v", tc.name, tc.mean, got, tc.want) + } + } +} + +// Nothing is built in: a rule nobody set, a rule that contradicts itself and +// a mean that is not a number all leave the owner's target alone. +func TestPriceComfortWithoutARuleChangesNothing(t *testing.T) { + z := room(day, 40, 8, 0) + for name, c := range map[string]PriceComfort{ + "zero value": {}, + "cheap above normal": {CheapPrice: 300, NormalPrice: 260, DearPrice: 400, RaiseK: 2}, + "dear below normal": {CheapPrice: 150, NormalPrice: 260, DearPrice: 200, LowerK: 1}, + "equal prices": {CheapPrice: 260, NormalPrice: 260, DearPrice: 260, RaiseK: 2, LowerK: 1}, + "negative shift": {CheapPrice: 150, NormalPrice: 260, DearPrice: 400, RaiseK: -1, LowerK: 1}, + "not a number": {CheapPrice: math.NaN(), NormalPrice: 260, DearPrice: 400, RaiseK: 2}, + "a step out of range": {CheapPrice: 150, NormalPrice: 260, DearPrice: 400, LowerK: 1, StepK: 9}, + } { + for _, mean := range []float64{50, 260, 900} { + if got := c.Apply(z, mean); &got.TargetC[0] != &z.TargetC[0] { + t.Errorf("%s: target moved at a mean of %v", name, mean) + } + } + if name != "zero value" && c.Validate() == nil { + t.Errorf("%s: Validate accepted it", name) + } + } + if (PriceComfort{}).Validate() != nil || (PriceComfort{}).Enabled() { + t.Error("the zero value must be valid and off") + } + if got := floorComfort.Apply(z, math.NaN()); &got.TargetC[0] != &z.TargetC[0] { + t.Error("a mean that is not a number moved the target") + } + if floorComfort.Validate() != nil || airComfort.Validate() != nil { + t.Error("the household's rules must be valid") + } +} + +// The band is the owner's hard limit. Comfort moves the target inside it, +// and leaves the zone it was given untouched. +func TestPriceComfortStaysInsideTheBand(t *testing.T) { + z := room(day, 40, 8, 0) // target 21, band 20 to 22 + up := floorComfort.Apply(z, 100) + down := PriceComfort{NormalPrice: 260, DearPrice: 400, LowerK: 3}.Apply(z, 500) + for i := range z.TargetC { + if up.TargetC[i] != 22 || down.TargetC[i] != 20 { + t.Fatalf("slot %d: target %v up and %v down, want the band's 22 and 20", i, up.TargetC[i], down.TargetC[i]) + } + if z.TargetC[i] != 21 { + t.Fatalf("slot %d: the caller's zone was changed to %v", i, z.TargetC[i]) + } + } +} + +// The baseline is the device left alone at the target, so on a dear day it +// is the cooler target the owner said that day is worth: the plan is not +// credited with the comfort rule's saving. +func TestBaselineFollowsTheDaysComfort(t *testing.T) { + price := flat(day, 450) + r := radiatorHouse(day, price) + mean, ok := DayMean(price, slotH, 22) + if !ok || mean != 450 { + t.Fatalf("DayMean = %v, %v", mean, ok) + } + usual := propose(t, r) + r.Zone = airComfort.Apply(r.Zone, mean) + if r.Zone.TargetC[0] != 20 { + t.Fatalf("target on a dear day = %v, want 20", r.Zone.TargetC[0]) + } + dear := propose(t, r) + if !(dear.BaselineCost < usual.BaselineCost) { + t.Errorf("baseline on a dear day = %v, want below the usual %v", dear.BaselineCost, usual.BaselineCost) + } + if s := dear.Saving(); s > 0.01*dear.BaselineCost { + t.Errorf("a flat price left %v to save against a baseline of %v", s, dear.BaselineCost) + } +} + +func TestDayMeanNeedsMostOfTheDay(t *testing.T) { + if _, ok := DayMean(flat(80, 100), slotH, 22); ok { + t.Error("20 hours passed for a day") + } + if m, ok := DayMean(flat(92, 100), slotH, 22); !ok || m != 100 { + t.Errorf("23 hours (a day the clocks go forward) = %v, %v", m, ok) + } + if _, ok := DayMean([]float64{100, math.NaN()}, 12, 22); ok { + t.Error("a price that is not a number passed") + } + if _, ok := DayMean(nil, slotH, 0); ok { + t.Error("no prices passed") + } +} + +func saves(v float64) Plan { return Plan{Cost: 1000 - v, BaselineCost: 1000} } + +// Five kronor a day, in öre, as the household set it. +func TestSavingsGateWeighsEveryPlanTogether(t *testing.T) { + gate := SavingsGate{MinPerDay: 500, KeepShare: 0.8} + if open, perDay := gate.Open([]Plan{saves(200), saves(250)}, 24, false); open || perDay != 450 { + t.Errorf("450 a day: open %v, per day %v", open, perDay) + } + if open, perDay := gate.Open([]Plan{saves(200), saves(250), saves(60)}, 24, false); !open || perDay != 510 { + t.Errorf("510 a day: open %v, per day %v", open, perDay) + } + // Half a day of prices: the same plans are worth twice as much a day. + if open, perDay := gate.Open([]Plan{saves(260)}, 12, false); !open || perDay != 520 { + t.Errorf("260 in 12 hours: open %v, per day %v", open, perDay) + } + // Two days of horizon are not two days of saving in one. + if open, perDay := gate.Open([]Plan{saves(900)}, 48, false); open || perDay != 450 { + t.Errorf("900 in 48 hours: open %v, per day %v", open, perDay) + } +} + +func TestSavingsGateDoesNotFlapAtTheLimit(t *testing.T) { + gate := SavingsGate{MinPerDay: 500, KeepShare: 0.8} + open := false + var got []bool + for _, v := range []float64{480, 510, 480, 410, 390, 480, 500} { + open, _ = gate.Open([]Plan{saves(v)}, 24, open) + got = append(got, open) + } + want := []bool{false, true, true, true, false, false, true} + for i := range want { + if got[i] != want[i] { + t.Fatalf("gate over time = %v, want %v", got, want) + } + } + if open, _ := (SavingsGate{MinPerDay: 500}).Open([]Plan{saves(480)}, 24, true); open { + t.Error("without a keep share an open gate stayed open below the limit") + } +} + +// What a plan seems to save by leaving its band is comfort it did not +// deliver, and a plan that costs more than leaving the device alone saves +// nothing rather than less than nothing. +func TestSavingCountsOnlyWhatAFeasiblePlanSaves(t *testing.T) { + out := saves(900) + out.BandExcursionKh = 0.5 + worse := Plan{Cost: 1100, BaselineCost: 1000} + broken := Plan{Cost: math.NaN(), BaselineCost: 1000} + if out.Saving() != 0 || worse.Saving() != 0 || broken.Saving() != 0 || saves(300).Saving() != 300 { + t.Errorf("savings = %v, %v, %v, %v; want 0, 0, 0, 300", out.Saving(), worse.Saving(), broken.Saving(), saves(300).Saving()) + } + gate := SavingsGate{MinPerDay: 500} + if open, perDay := gate.Open([]Plan{out, worse, saves(300)}, 24, false); open || perDay != 300 { + t.Errorf("open %v, per day %v; want closed at 300", open, perDay) + } +} + +// No limit set is no gate. A gate that cannot be read is closed, because +// leaving the devices to themselves is the safe answer. +func TestSavingsGateWithoutALimitIsOpenAndABrokenOneIsClosed(t *testing.T) { + if open, _ := (SavingsGate{}).Open(nil, 24, false); !open { + t.Error("the zero value closed the gate") + } + for name, g := range map[string]SavingsGate{ + "keep share above 1": {MinPerDay: 500, KeepShare: 1.5}, + "negative keep": {MinPerDay: 500, KeepShare: -0.1}, + "not a number": {MinPerDay: math.NaN()}, + } { + if g.Validate() == nil { + t.Errorf("%s: Validate accepted it", name) + } + if open, _ := g.Open([]Plan{saves(9000)}, 24, true); open { + t.Errorf("%s: gate open", name) + } + } + for _, h := range []float64{0, -3, math.NaN(), math.Inf(1)} { + if open, _ := (SavingsGate{MinPerDay: 500}).Open([]Plan{saves(9000)}, h, true); open { + t.Errorf("horizon %v: gate open", h) + } + } +} diff --git a/go/internal/heatplan/plan.go b/go/internal/heatplan/plan.go new file mode 100644 index 000000000..5b5dd2bb6 --- /dev/null +++ b/go/internal/heatplan/plan.go @@ -0,0 +1,690 @@ +// Package heatplan proposes when a heated zone should take its heat. +// +// It is the planner of docs/adr/0012: a dynamic program over the price and +// weather horizon whose state is the zone's predicted temperature and whose +// actions are the few values a declared control accepts. It proposes; it +// reads no device and sends nothing. Core checks every proposed value +// against the declared bounds, the lease and the minimum on and off times +// before anything is dispatched. +// +// One model covers every heated thing, because they differ in numbers and +// not in form: +// +// C · dT/dt = Q − UA · (T − T_boundary) + other +// +// What differs, and what decides whether moving heat in time pays: +// +// - What a kWh of heat costs. Direct electric heat costs the price. A heat +// pump's heat costs the price divided by a COP that moves with the +// outdoor air and with how hot the sink is (Source). Preheating through +// a heat pump raises the sink and so costs efficiency; heating a tank or +// a pool gets dearer the hotter it already is; an air-source pump is +// cheapest in the warmest hours whatever the price does. +// - How long the heat stays. τ = C/UA is hours for the air of a room +// behind an air-to-air unit, days for a slab or a covered pool. The +// planner preheats only as far ahead as the zone holds it. +// - Where lost heat goes. A room loses to outdoors and the heat is gone. +// A bathroom floor inside a house a heat pump keeps warm loses to the +// rooms around it, where it replaces heat the pump would have made at +// COP 3–4 (Zone.LossCreditCOP). Charging that floor with direct +// electricity therefore rarely pays, and letting it coast costs less +// than its own meter suggests. +// - What the band is for. A room has a target and comfort on both sides +// of it. A tank or a spa has no comfort inside its band, only a floor, +// a ceiling, and times it must be ready by (per-slot bands). +package heatplan + +import ( + "errors" + "math" + + "github.com/srcfl/ftw/go/internal/thermal" +) + +// ErrUnsupported is returned for a control the planner cannot yet reason +// about. The device then runs itself, as it does without a trusted twin. +var ErrUnsupported = errors.New("heatplan: control strategy not supported") + +const ( + maxSlots = 4 * 24 * 4 + maxValues = 16 + // The temperature grid. Fine enough that a 0.5 K setpoint step spans + // several points, coarse enough for a Raspberry Pi to plan every zone + // each quarter. + minGridStepK = 0.02 + gridPoints = 400 + // Being warmer than asked is a smaller fault than being colder, and the + // extra loss already charges for it. + overTargetShare = 0.25 + // Leaving the band is not a trade. The weight only has to dominate any + // energy saving; the plan reports the excursion and the caller decides. + bandWeightFactor = 1e3 + // A value other than the device's own must earn this share of the + // do-nothing cost per slot, so equal-cost plans do not chatter. + chatterShare = 1e-4 + // How far a kWh over the site's import limit outweighs the worst the + // band could charge for the heat it carries. Large, because a control + // offers few values: a sliver over the limit can buy a whole slot of + // heat, and must still lose. + limitWeightFactor = 1e3 +) + +// Zone is one heated thing as its twin describes it, in thermal terms. +type Zone struct { + // TauH is the inertia C/UA: how long the zone coasts. + TauH float64 + // CapacityKWhPerK is C: the heat one kelvin holds. + CapacityKWhPerK float64 + // OtherGainKPerH is what neither loss nor the control explains: sun, + // people, other heat. The twin's constant term. + OtherGainKPerH float64 + // StartC is the measured temperature now. + StartC float64 + + // Per slot, each as long as the horizon. + + // BoundaryC is what the zone loses heat to: the outdoor forecast for a + // house or an outdoor pool, the room a tank stands in, the rooms around + // a bathroom floor. + BoundaryC []float64 + // TargetC is what the owner asked for. MinC and MaxC are the hard band + // around it. They vary by slot so a spa can be let down between uses + // and a tank can have a floor. + TargetC, MinC, MaxC []float64 + // DisturbanceK is a forecast change no heating explains: a hot-water + // draw, a lid left open. Nil means none. + DisturbanceK []float64 + // LossCreditCOP is the efficiency of the other source that heats the + // space this zone loses to. Heat lost there is not lost: it saves that + // source the same heat. Zero in a slot means the loss is gone, as it is + // to outdoors or to a house nothing else is heating. Nil means zero. + LossCreditCOP []float64 + + // ComfortWeight prices distance from the target, as a multiple of what + // holding the zone one kelvin warmer costs. Above 1, sitting below the + // target never pays by itself and only moving heat between prices does. + // Zero is a store with no comfort inside its band. + ComfortWeight float64 +} + +// Actuator is the one declared control the plan moves, and the heat behind it. +type Actuator struct { + // Strategy is the control's declared lever. + // setpoint the value is the temperature the device regulates + // the zone to. + // curve_offset the device regulates the zone to its own target plus + // value × ZoneKPerUnit, and its flow runs + // value × SupplyKPerUnit hotter. + // on_off 1 runs the device at full output up to the band's + // ceiling, 0 stops it. + Strategy thermal.InfluenceStrategy + // Values are the candidates, rising. For on_off they are ignored. + Values []float64 + // MaxHeatKW is the heat at full output. + MaxHeatKW float64 + Source Source + + ZoneKPerUnit float64 + SupplyKPerUnit float64 + + // MinOnSlots and MinOffSlots are the declared protection times, in + // slots, rounded up by the caller. on_off only. + MinOnSlots, MinOffSlots int + // On and RunSlots say what the device is doing now and for how long. + On bool + RunSlots int +} + +// Request is one zone, one control and one horizon. +type Request struct { + // SlotH is the length of a slot in hours. + SlotH float64 + // Price is the marginal cost of a kWh of electricity in each slot, in + // any one currency: import price, or what export would have paid while + // the site has surplus. + Price []float64 + // OutdoorC is the outdoor forecast, for the heat pump's cold side and + // its supply curve. It is not the zone's boundary unless the caller + // says so in Zone.BoundaryC. + OutdoorC []float64 + // MaxElecKW is how much electricity the zone may draw in each slot + // before the site passes its import limit: a capacity tariff's peak, or + // the fuse. Heat is planned inside the site's energy plan and never + // through it, so this outranks the zone's own band: the plan lets the + // zone leave its band before it proposes a value that draws more. A + // control cannot enforce a power, so what the device's lowest value or + // a compressor's minimum run still draws is reported, not hidden. Nil + // means no limit. + MaxElecKW []float64 + // SurplusKW is power the site would otherwise export in each slot, and + // SurplusPrice what a kWh of it would have earned. The zone's first + // SurplusKW cost SurplusPrice; the rest costs Price. Nil means none. + SurplusKW, SurplusPrice []float64 + Zone Zone + Actuator Actuator +} + +// Slot is the proposal for one slot. +type Slot struct { + // Value is the control value to hold through the slot. + Value float64 `json:"value"` + // TempC is the predicted temperature at the slot's end. + TempC float64 `json:"temp_c"` + HeatKWh float64 `json:"heat_kwh"` + ElecKWh float64 `json:"elec_kwh"` + // Cost is the electricity bought, less the credit for heat passed on. + Cost float64 `json:"cost"` +} + +// Plan is a proposal and what it was weighed against. +type Plan struct { + Slots []Slot `json:"slots"` + // Cost is the plan's energy cost over the horizon, credit included, with + // the heat missing or left over at the end valued at what it would cost + // to buy then. BaselineCost is the same for the device left alone at + // the target. + Cost float64 `json:"cost"` + BaselineCost float64 `json:"baseline_cost"` + // BandExcursionKh is how far and how long the prediction leaves the + // band. Above zero the zone cannot be held with this control and the + // caller must not treat the plan as feasible. + BandExcursionKh float64 `json:"band_excursion_kh"` + // OverLimitKWh is the electricity predicted above MaxElecKW that no + // declared value could avoid: the device's own regulation at its lowest + // value, or a compressor's minimum run. + OverLimitKWh float64 `json:"over_limit_kwh"` +} + +// Values returns the candidates a number control offers between lo and hi +// in whole steps from lo, thinned evenly to at most limit, and always +// keeping keep (the device's own value) when it lies on a step. +func Values(lo, hi, step, keep float64, limit int) []float64 { + if !(step > 0) || hi < lo || limit < 3 || !finite(lo, hi, step) { + return nil + } + n := int(math.Floor((hi-lo)/step+1e-9)) + 1 + stride := 1 + // Room for the far end and the kept value beside the even picks. + for n > limit && (n-1)/stride+1 > limit-2 { + stride++ + } + idx := map[int]bool{n - 1: true} + for i := 0; i < n; i += stride { + idx[i] = true + } + if k := math.Round((keep - lo) / step); k >= 0 && k < float64(n) && math.Abs(lo+k*step-keep) < 1e-6 { + idx[int(k)] = true + } + out := make([]float64, 0, len(idx)) + for i := 0; i < n; i++ { + if idx[i] { + out = append(out, lo+float64(i)*step) + } + } + return out +} + +func (r Request) validate() error { + n := len(r.Price) + z, a := r.Zone, r.Actuator + if n == 0 || n > maxSlots { + return errors.New("heatplan: horizon must be 1 to 384 slots") + } + if !(r.SlotH > 0) || r.SlotH > 1 { + return errors.New("heatplan: slot length must be within an hour") + } + for _, s := range [][]float64{r.OutdoorC, z.BoundaryC, z.TargetC, z.MinC, z.MaxC} { + if len(s) != n { + return errors.New("heatplan: every series must cover the horizon") + } + } + for _, s := range [][]float64{z.DisturbanceK, z.LossCreditCOP, r.MaxElecKW, r.SurplusKW} { + if s != nil && len(s) != n { + return errors.New("heatplan: every series must cover the horizon") + } + } + if (r.SurplusKW == nil) != (r.SurplusPrice == nil) || len(r.SurplusKW) != len(r.SurplusPrice) { + return errors.New("heatplan: surplus needs both its power and its price") + } + for i := 0; i < n; i++ { + if !finite(r.Price[i], r.OutdoorC[i], z.BoundaryC[i], z.TargetC[i], z.MinC[i], z.MaxC[i]) { + return errors.New("heatplan: series must be finite") + } + if z.MinC[i] > z.TargetC[i] || z.TargetC[i] > z.MaxC[i] || z.MinC[i] < -30 || z.MaxC[i] > 100 { + return errors.New("heatplan: target must lie inside its band") + } + if r.OutdoorC[i] < -60 || r.OutdoorC[i] > 60 || z.BoundaryC[i] < -60 || z.BoundaryC[i] > 100 { + return errors.New("heatplan: temperature out of range") + } + if r.MaxElecKW != nil && (!finite(r.MaxElecKW[i]) || r.MaxElecKW[i] < 0) { + return errors.New("heatplan: the electricity limit must be zero or more") + } + if r.SurplusKW != nil && (!finite(r.SurplusKW[i], r.SurplusPrice[i]) || r.SurplusKW[i] < 0) { + return errors.New("heatplan: surplus must be zero or more") + } + if z.DisturbanceK != nil && !finite(z.DisturbanceK[i]) { + return errors.New("heatplan: series must be finite") + } + if z.LossCreditCOP != nil && (!finite(z.LossCreditCOP[i]) || z.LossCreditCOP[i] < 0 || + (z.LossCreditCOP[i] > 0 && z.LossCreditCOP[i] < 1)) { + return errors.New("heatplan: loss credit must be a COP of 1 or more, or zero") + } + } + // The same envelope the twin calls physical, widened for a tank and a + // pool: a spa holds 2 kWh/K, a pool 60. + if !finite(z.TauH, z.CapacityKWhPerK, z.OtherGainKPerH, z.StartC, z.ComfortWeight) || + z.TauH < 1 || z.TauH > 5000 || z.CapacityKWhPerK < 0.05 || z.CapacityKWhPerK > 1000 || + math.Abs(z.OtherGainKPerH) > 3 || z.StartC < -30 || z.StartC > 100 || + z.ComfortWeight < 0 || z.ComfortWeight > 100 { + return errors.New("heatplan: zone model is not physical") + } + if !finite(a.MaxHeatKW) || a.MaxHeatKW <= 0 || a.MaxHeatKW > 500 { + return errors.New("heatplan: heat output out of range") + } + if err := a.Source.validate(); err != nil { + return err + } + switch a.Strategy { + case thermal.InfluenceOnOff: + if a.MinOnSlots < 0 || a.MinOffSlots < 0 || a.MinOnSlots > 48 || a.MinOffSlots > 48 || a.RunSlots < 0 { + return errors.New("heatplan: minimum on and off times out of range") + } + case thermal.InfluenceSetpoint, thermal.InfluenceCurveOffset: + if len(a.Values) == 0 || len(a.Values) > maxValues { + return errors.New("heatplan: a control needs 1 to 16 candidate values") + } + for i, v := range a.Values { + if !finite(v) || (i > 0 && v <= a.Values[i-1]) { + return errors.New("heatplan: candidate values must be finite and rising") + } + } + if a.Strategy == thermal.InfluenceCurveOffset { + if !finite(a.ZoneKPerUnit, a.SupplyKPerUnit) || a.ZoneKPerUnit <= 0 || a.ZoneKPerUnit > 5 || + a.SupplyKPerUnit < 0 || a.SupplyKPerUnit > 10 { + return errors.New("heatplan: a curve offset needs its learned effect on the zone") + } + } + default: + return ErrUnsupported + } + return nil +} + +// action is one thing the planner may ask for in a slot, reduced to what the +// device then does: regulate the zone toward a temperature, with its flow +// shifted. +type action struct { + value float64 + on bool // on_off only + supplyK float64 + // setpoint returns the temperature the device regulates to in slot k. + setpoint func(k int) float64 +} + +type solver struct { + r Request + n int + decay float64 // e^(−h/τ) + a float64 // 1/τ + acts []action + // neutral is the index of the action the device takes by itself in a + // slot: its own target. + neutral func(k int) int + + comfortPerKh float64 + bandPerKh float64 + limitPerKWh float64 + chatter float64 + + lo, step float64 + points int +} + +// Propose plans the horizon. An error means the request is not one the +// planner can answer; the device then runs itself. +func Propose(r Request) (Plan, error) { + if err := r.validate(); err != nil { + return Plan{}, err + } + s := newSolver(r) + plan := s.run(false) + base := s.run(true) + plan.BaselineCost = base.Cost + return plan, nil +} + +func newSolver(r Request) *solver { + z, a := r.Zone, r.Actuator + s := &solver{r: r, n: len(r.Price), a: 1 / z.TauH} + s.decay = math.Exp(-r.SlotH * s.a) + + switch a.Strategy { + case thermal.InfluenceOnOff: + s.acts = []action{ + {value: 0, setpoint: func(int) float64 { return math.Inf(-1) }}, + {value: 1, on: true, setpoint: func(k int) float64 { return z.MaxC[k] }}, + } + case thermal.InfluenceSetpoint: + for _, v := range a.Values { + v := v + s.acts = append(s.acts, action{value: v, setpoint: func(int) float64 { return v }}) + } + case thermal.InfluenceCurveOffset: + for _, v := range a.Values { + v := v + s.acts = append(s.acts, action{value: v, supplyK: v * a.SupplyKPerUnit, + setpoint: func(k int) float64 { return z.TargetC[k] + v*a.ZoneKPerUnit }}) + } + } + // The device's own choice: the candidate that regulates closest to the + // target. For on_off there is none; its thermostat is not a candidate. + s.neutral = func(k int) int { + if a.Strategy == thermal.InfluenceOnOff { + return -1 + } + best, bestD := 0, math.Inf(1) + for i, act := range s.acts { + if d := math.Abs(act.setpoint(k) - z.TargetC[k]); d < bestD { + best, bestD = i, d + } + } + return best + } + + // What a kWh of heat costs at the target, on average over the horizon. + var heatPrice float64 + for k := 0; k < s.n; k++ { + heatPrice += math.Max(0, r.Price[k]) / s.cop(k, z.TargetC[k], 0) + } + heatPrice /= float64(s.n) + holdPerKh := s.holdCost(heatPrice) + s.comfortPerKh = z.ComfortWeight * holdPerKh + s.bandPerKh = bandWeightFactor * (heatPrice*z.CapacityKWhPerK + holdPerKh + 1e-9) + s.chatter = chatterShare * holdPerKh * r.SlotH + // The site's import limit outranks the band. A kWh held back costs the + // zone at most 1/C kelvin outside its band for the rest of the horizon; + // a kWh over the limit must cost more than that. + s.limitPerKWh = limitWeightFactor * s.bandPerKh * float64(s.n) * r.SlotH / z.CapacityKWhPerK + + lo, hi := z.StartC, z.StartC + for k := 0; k < s.n; k++ { + lo, hi = math.Min(lo, z.MinC[k]), math.Max(hi, z.MaxC[k]) + } + margin := math.Max(1, 0.1*(hi-lo)) + lo, hi = lo-margin, hi+margin + s.step = math.Max(minGridStepK, (hi-lo)/gridPoints) + s.points = int(math.Ceil((hi-lo)/s.step)) + 1 + s.lo = lo + return s +} + +// holdCost is what regulating the zone one kelvin warmer for an hour costs, +// averaged over the horizon. Comfort is priced in multiples of it, so it has +// to count everything a warmer zone costs: the extra loss, the worse COP of a +// heat pump whose sink is hotter for all the heat it delivers, and, against +// those, the credit for loss that warms space another source heats. +func (s *solver) holdCost(heatPrice float64) float64 { + z, a := s.r.Zone, s.r.Actuator + supplyPerK := 0.0 + if a.Strategy == thermal.InfluenceCurveOffset { + supplyPerK = a.SupplyKPerUnit / a.ZoneKPerUnit + } + steady := func(k int, temp, supplyK float64) float64 { + loss := z.CapacityKWhPerK * s.a * (temp - z.BoundaryC[k]) + heat := math.Max(0, loss-z.CapacityKWhPerK*z.OtherGainKPerH) + cost := heat / s.cop(k, temp, supplyK) + if z.LossCreditCOP != nil && z.LossCreditCOP[k] > 0 { + cost -= loss / z.LossCreditCOP[k] + } + return cost * math.Max(0, s.r.Price[k]) + } + var hold float64 + for k := 0; k < s.n; k++ { + hold += steady(k, z.TargetC[k]+1, supplyPerK) - steady(k, z.TargetC[k], 0) + } + hold /= float64(s.n) + // A zone that costs nothing to hold, such as one warmed by other gains + // all day, still needs a scale for comfort. + return math.Max(hold, 0.1*heatPrice*z.CapacityKWhPerK*s.a) +} + +// cop is the source's efficiency in slot k with the zone at zoneC. +func (s *solver) cop(k int, zoneC, supplyK float64) float64 { + src := s.r.Actuator.Source + sink := zoneC + if src.Supply != nil { + sink = src.Supply.At(s.r.OutdoorC[k]) + supplyK + } + return src.COP(s.r.OutdoorC[k], sink) +} + +type step struct { + next, heatKWh, elecKWh, overKWh, cost, penalty float64 +} + +// advance moves the zone one slot from temp under an action. The first-order +// model is solved exactly over the slot, so a zone with little inertia does +// not overshoot the way a forward difference would. +func (s *solver) advance(k int, temp float64, act action) step { + z, h := s.r.Zone, s.r.SlotH + c := z.CapacityKWhPerK + // The heat that lands the zone on the setpoint at the slot's end, + // within what the device can give. + sp := act.setpoint(k) + var q float64 + if !math.IsInf(sp, -1) { + eq := (sp - temp*s.decay) / (1 - s.decay) + q = c * (s.a*(eq-z.BoundaryC[k]) - z.OtherGainKPerH) + q = math.Max(0, math.Min(s.r.Actuator.MaxHeatKW, q)) + } + eq := z.BoundaryC[k] + (q/c+z.OtherGainKPerH)/s.a + next := eq + (temp-eq)*s.decay + mid := (temp + next) / 2 + if z.DisturbanceK != nil { + next += z.DisturbanceK[k] + } + + out := step{next: next, heatKWh: q * h} + out.elecKWh = out.heatKWh / s.cop(k, mid, act.supplyK) + out.cost = out.elecKWh * s.r.Price[k] + if s.r.SurplusKW != nil { + // What the site would have exported is used first, at what it + // would have earned. + own := math.Min(out.elecKWh, s.r.SurplusKW[k]*h) + out.cost += own * (s.r.SurplusPrice[k] - s.r.Price[k]) + } + if s.r.MaxElecKW != nil { + out.overKWh = math.Max(0, out.elecKWh-s.r.MaxElecKW[k]*h) + out.penalty += s.limitPerKWh * out.overKWh + } + if z.LossCreditCOP != nil && z.LossCreditCOP[k] > 0 { + // Heat passed to the space around the zone saves the source that + // heats that space the same heat. A zone colder than its + // surroundings takes heat from that source instead, and pays. + lossKWh := c * s.a * (mid - z.BoundaryC[k]) * h + out.cost -= lossKWh * s.r.Price[k] / z.LossCreditCOP[k] + } + + switch { + case mid < z.TargetC[k]: + out.penalty += s.comfortPerKh * (z.TargetC[k] - mid) * h + default: + out.penalty += overTargetShare * s.comfortPerKh * (mid - z.TargetC[k]) * h + } + out.penalty += s.bandPerKh * s.excursion(k, next) * h + return out +} + +func (s *solver) excursion(k int, temp float64) float64 { + z := s.r.Zone + return math.Max(0, z.MinC[k]-temp) + math.Max(0, temp-z.MaxC[k]) +} + +// terminal values the heat missing or left over at the horizon's end, so a +// plan cannot profit by ending cold or lose by ending warm. Missing heat is +// bought at the mean of the last hours; heat left over is worth only the +// cheapest of them, since that is when it would otherwise have been bought. +func (s *solver) terminal(temp float64) float64 { + z := s.r.Zone + tail := s.n / 4 + if tail < 1 { + tail = 1 + } + mean, min := 0.0, math.Inf(1) + for k := s.n - tail; k < s.n; k++ { + p := math.Max(0, s.r.Price[k]) / s.cop(k, z.TargetC[k], 0) + mean += p + min = math.Min(min, p) + } + mean /= float64(tail) + d := z.TargetC[s.n-1] - temp + if d > 0 { + return d * z.CapacityKWhPerK * mean + } + return d * z.CapacityKWhPerK * min +} + +// Run state for on_off: index 0..MinOff−1 is off for that many slots plus +// one, capped; then MinOn states for on. Other strategies have one state. +func (s *solver) runStates() (off, on int) { + a := s.r.Actuator + if a.Strategy != thermal.InfluenceOnOff { + return 1, 0 + } + return max(1, a.MinOffSlots), max(1, a.MinOnSlots) +} + +// allowed says whether an action may follow run state rs, and the state it +// leads to. +func (s *solver) allowed(rs int, act action) (int, bool) { + off, on := s.runStates() + if on == 0 { + return 0, true + } + if rs < off { // off for rs+1 slots, capped at off + if !act.on { + return min(rs+1, off-1), true + } + return off, rs == off-1 + } + held := rs - off // on for held+1 slots, capped at on + if act.on { + return off + min(held+1, on-1), true + } + return 0, held == on-1 +} + +func (s *solver) startState() int { + off, on := s.runStates() + if on == 0 { + return 0 + } + a := s.r.Actuator + run := max(1, a.RunSlots) + if a.On { + return off + min(run, on) - 1 + } + return min(run, off) - 1 +} + +func (s *solver) interp(v []float64, temp float64) float64 { + x := (temp - s.lo) / s.step + i := int(math.Floor(x)) + if i < 0 { + i = 0 + } + if i > s.points-2 { + i = s.points - 2 + } + return v[i] + (v[i+1]-v[i])*(x-float64(i)) +} + +// run solves the horizon. With baseline set it follows the device's own +// choice in every slot instead of choosing. +func (s *solver) run(baseline bool) Plan { + off, on := s.runStates() + states := off + on + + pick := func(k, rs int, temp float64, value [][]float64) (int, step, int) { + if baseline { + i := s.neutral(k) + if i < 0 { + // A device with only start and stop keeps its own + // thermostat: it holds the target. + act := action{setpoint: func(k int) float64 { return s.r.Zone.TargetC[k] }} + return -1, s.advance(k, temp, act), rs + } + return i, s.advance(k, temp, s.acts[i]), rs + } + best, bestCost, bestStep, bestNext := -1, math.Inf(1), step{}, 0 + neutral := s.neutral(k) + for i, act := range s.acts { + next, ok := s.allowed(rs, act) + if !ok { + continue + } + st := s.advance(k, temp, act) + cost := st.cost + st.penalty + s.interp(value[next], st.next) + if i != neutral { + cost += s.chatter + } + if cost < bestCost { + best, bestCost, bestStep, bestNext = i, cost, st, next + } + } + return best, bestStep, bestNext + } + + var values [][][]float64 + if !baseline { + values = make([][][]float64, s.n+1) + last := make([][]float64, states) + for rs := range last { + last[rs] = make([]float64, s.points) + for i := range last[rs] { + last[rs][i] = s.terminal(s.lo + float64(i)*s.step) + } + } + values[s.n] = last + for k := s.n - 1; k >= 0; k-- { + cur := make([][]float64, states) + for rs := range cur { + cur[rs] = make([]float64, s.points) + for i := range cur[rs] { + temp := s.lo + float64(i)*s.step + j, st, next := pick(k, rs, temp, values[k+1]) + if j < 0 { + cur[rs][i] = math.Inf(1) + continue + } + cur[rs][i] = st.cost + st.penalty + s.interp(values[k+1][next], st.next) + if j != s.neutral(k) { + cur[rs][i] += s.chatter + } + } + } + values[k] = cur + } + } + + plan := Plan{Slots: make([]Slot, 0, s.n)} + temp, rs := s.r.Zone.StartC, s.startState() + for k := 0; k < s.n; k++ { + var next [][]float64 + if !baseline { + next = values[k+1] + } + j, st, nrs := pick(k, rs, temp, next) + value := s.r.Zone.TargetC[k] + if j >= 0 { + value = s.acts[j].value + } + temp, rs = st.next, nrs + plan.Slots = append(plan.Slots, Slot{Value: value, TempC: temp, HeatKWh: st.heatKWh, ElecKWh: st.elecKWh, Cost: st.cost}) + plan.Cost += st.cost + plan.BandExcursionKh += s.excursion(k, temp) * s.r.SlotH + plan.OverLimitKWh += st.overKWh + } + plan.Cost += s.terminal(temp) + return plan +} diff --git a/go/internal/heatplan/plan_test.go b/go/internal/heatplan/plan_test.go new file mode 100644 index 000000000..b559c2685 --- /dev/null +++ b/go/internal/heatplan/plan_test.go @@ -0,0 +1,677 @@ +package heatplan + +import ( + "errors" + "math" + "testing" + + "github.com/srcfl/ftw/go/internal/thermal" +) + +func propose(t *testing.T, r Request) Plan { + t.Helper() + p, err := Propose(r) + if err != nil { + t.Fatalf("Propose: %v", err) + } + if len(p.Slots) != len(r.Price) { + t.Fatalf("plan has %d slots for a horizon of %d", len(p.Slots), len(r.Price)) + } + for i, s := range p.Slots { + if !finite(s.Value, s.TempC, s.HeatKWh, s.ElecKWh, s.Cost) || s.HeatKWh < 0 || s.ElecKWh < 0 { + t.Fatalf("slot %d is not a finite, non-negative proposal: %+v", i, s) + } + } + return p +} + +// heat sums the heat bought in the hours [from, to) of every day. +func heat(p Plan, from, to float64) float64 { + var sum float64 + for i, s := range p.Slots { + if between(math.Mod(float64(i)*slotH, 24), from, to) { + sum += s.HeatKWh + } + } + return sum +} + +func tempRange(p Plan, from, to float64) (lo, hi float64) { + lo, hi = math.Inf(1), math.Inf(-1) + for i, s := range p.Slots { + if between(math.Mod(float64(i)*slotH, 24), from, to) { + lo, hi = math.Min(lo, s.TempC), math.Max(hi, s.TempC) + } + } + return lo, hi +} + +func cheapNight(n int, night float64) []float64 { + return hours(n, func(h float64) float64 { + if between(h, 1, 5) { + return night + } + return 100 + }) +} + +func TestFlatPriceLeavesTheDeviceAlone(t *testing.T) { + for name, r := range map[string]Request{ + "radiators": radiatorHouse(day, flat(day, 100)), + "air to air": airToAirHouse(day, flat(day, 100), flat(day, 0)), + "slab": slabHouse(day, flat(day, 100), flat(day, 0)), + "bathroom floor": bathroomFloor(day, flat(day, 100), 3.5), + } { + p := propose(t, r) + // The last slots may differ: the horizon's end is valued, not planned. + for i, s := range p.Slots[:day-8] { + want := r.Zone.TargetC[i] + if r.Actuator.Strategy == thermal.InfluenceCurveOffset { + want = 0 + } + if s.Value != want { + t.Fatalf("%s: slot %d proposes %v with nothing to gain; the device's own value is %v", name, i, s.Value, want) + } + } + if p.BandExcursionKh != 0 { + t.Fatalf("%s: left its band by %v Kh", name, p.BandExcursionKh) + } + } +} + +// Direct electric heat in a heavy house: buy before the peak, buy nothing +// during it. +func TestRadiatorsCoastThroughAPeak(t *testing.T) { + p := propose(t, radiatorHouse(day, eveningPeak(day, 100, 300))) + if got := heat(p, 17, 20); got > 0.1 { + t.Fatalf("bought %.1f kWh of heat at three times the price", got) + } + if lo, _ := tempRange(p, 0, 24); lo < 20 { + t.Fatalf("coasted to %.2f °C, under the 20 °C band", lo) + } + if _, hi := tempRange(p, 14, 17); hi < 21.5 { + t.Fatalf("preheated only to %.2f °C before the peak", hi) + } + if p.Cost > 0.85*p.BaselineCost { + t.Fatalf("cost %.0f against %.0f left alone: the peak was not avoided", p.Cost, p.BaselineCost) + } + if p.BandExcursionKh != 0 { + t.Fatalf("left the band by %v Kh", p.BandExcursionKh) + } +} + +// The same peak behind an air-to-air unit. The air it heats holds little, so +// the band runs out before the peak does and some heat is bought in it; a +// plan that pretended otherwise would leave the band. +func TestShortInertiaCannotCoastAWholePeak(t *testing.T) { + price := eveningPeak(day, 100, 300) + light := propose(t, airToAirHouse(day, price, flat(day, 0))) + heavy := propose(t, radiatorHouse(day, price)) + if light.BandExcursionKh != 0 { + t.Fatalf("left the band by %v Kh", light.BandExcursionKh) + } + if heat(light, 17, 20) < 1 { + t.Fatalf("a zone with τ = 20 h and 3 kWh/K bought only %.2f kWh through a three-hour peak", heat(light, 17, 20)) + } + if heat(light, 17, 20) <= heat(heavy, 17, 20) { + t.Fatal("the light zone should need more heat in the peak than the heavy one") + } + // It still starts the peak as warm as the band allows. + if _, hi := tempRange(light, 16, 17); hi < 21.8 { + t.Fatalf("entered the peak at %.2f °C with a 22 °C ceiling", hi) + } +} + +// A heat pump on a slab preheats through its curve offset, and pays for it: +// a hotter flow is a worse COP. With a long inertia it still pays at twice +// the price. +func TestSlabPreheatsThroughTheOffset(t *testing.T) { + r := slabHouse(day, eveningPeak(day, 100, 200), flat(day, 0)) + p := propose(t, r) + if got := heat(p, 17, 20); got > 0.1 { + t.Fatalf("bought %.1f kWh of heat in the peak", got) + } + raised := false + for i, s := range p.Slots { + if s.Value != math.Trunc(s.Value) || s.Value < -3 || s.Value > 3 { + t.Fatalf("slot %d proposes offset %v, not a declared step", i, s.Value) + } + if h := float64(i) * slotH; between(h, 14, 17) && s.Value > 0 { + raised = true + } + } + if !raised { + t.Fatal("never raised the offset ahead of the peak") + } + if p.Cost >= p.BaselineCost { + t.Fatalf("cost %.0f, no better than %.0f left alone", p.Cost, p.BaselineCost) + } +} + +// Heat a bathroom floor loses inside a heated house is not lost: it saves the +// heat pump the same heat. The floor is then cheaper to run than its own +// meter says, by the pump's COP. +func TestLossIntoAHeatedHouseIsCredited(t *testing.T) { + alone := propose(t, bathroomFloor(day, flat(day, 100), 0)) + inside := propose(t, bathroomFloor(day, flat(day, 100), 3.5)) + var elecAlone, elecInside float64 + for i := range alone.Slots { + elecAlone += alone.Slots[i].ElecKWh + elecInside += inside.Slots[i].ElecKWh + } + if math.Abs(elecAlone-elecInside) > 0.01 { + t.Fatalf("the floor draws %.2f kWh alone and %.2f kWh inside the house; the credit must not change the meter", elecAlone, elecInside) + } + want := alone.Cost * (1 - 1/3.5) + if math.Abs(inside.Cost-want) > 0.02*want { + t.Fatalf("cost inside the house %.1f, want %.1f: the floor's cost less what the pump is spared", inside.Cost, want) + } +} + +// A tank on an immersion heater stores a small price difference as hot as +// the band allows: its heat costs the same at any temperature. A heat pump +// does not, because the last kelvins cost it more than the night saves. +func TestHotWaterStoresOnlyWhatItsSourceMakesWorthwhile(t *testing.T) { + price := cheapNight(day, 88) + direct := propose(t, hotWaterTank(day, price, Source{Kind: SourceDirectElectric})) + pump := propose(t, hotWaterTank(day, price, Source{Kind: SourceHeatPump})) + if _, hi := tempRange(direct, 1, 5); hi < 64 { + t.Fatalf("the immersion heater charged only to %.1f °C on the cheap night", hi) + } + if _, hi := tempRange(pump, 1, 5); hi > 61 { + t.Fatalf("the heat pump charged to %.1f °C for a 12 %% saving", hi) + } + for name, p := range map[string]Plan{"direct": direct, "pump": pump} { + if lo, _ := tempRange(p, 0, 24); lo < 50-1e-6 { + t.Fatalf("%s: tank at %.2f °C, under its 50 °C floor", name, lo) + } + if p.BandExcursionKh != 0 { + t.Fatalf("%s: left the band by %v Kh", name, p.BandExcursionKh) + } + } + // A large difference is worth the worse COP. + deep := propose(t, hotWaterTank(day, cheapNight(day, 40), Source{Kind: SourceHeatPump})) + if _, hi := tempRange(deep, 1, 5); hi < 64 { + t.Fatalf("the heat pump charged only to %.1f °C at 40 %% of the price", hi) + } +} + +// A spa must be ready when it is used and has no comfort in between. Its +// heater takes hours to lift it, so the plan has to start early, and it +// starts where the heat is cheapest. +func TestSpaIsReadyForUseOnCheapHeat(t *testing.T) { + price := hours(day, func(h float64) float64 { + switch { + case between(h, 1, 5): + return 40 + case between(h, 17, 20): + return 300 + } + return 100 + }) + p := propose(t, spa(day, price)) + if lo, _ := tempRange(p, 19, 22); lo < 37.5-1e-6 { + t.Fatalf("spa at %.2f °C while in use, under 37.5 °C", lo) + } + if p.BandExcursionKh != 0 { + t.Fatalf("left the band by %v Kh", p.BandExcursionKh) + } + if got := heat(p, 17, 20); got > 0.1 { + t.Fatalf("bought %.1f kWh in the peak", got) + } + total := heat(p, 0, 24) + if night := heat(p, 1, 5); night < 0.8*total { + t.Fatalf("%.1f of %.1f kWh bought in the cheap night", night, total) + } +} + +// At one price all day, a pool's air-source pump still has a cheapest hour: +// the warmest one. +func TestPoolPumpRunsInTheWarmHours(t *testing.T) { + r := pool(day, flat(day, 100), summerDay(day)) + p := propose(t, r) + total := heat(p, 0, 24) + if total < 10 { + t.Fatalf("pool bought %.1f kWh in a day; the plan only deferred", total) + } + if warm := heat(p, 11, 19); warm < 0.95*total { + t.Fatalf("%.1f of %.1f kWh bought between 11 and 19", warm, total) + } + if p.Cost >= p.BaselineCost { + t.Fatalf("cost %.0f, no better than %.0f left alone", p.Cost, p.BaselineCost) + } + checkRuns(t, p, r.Actuator) +} + +func checkRuns(t *testing.T, p Plan, a Actuator) { + t.Helper() + run, on := max(1, a.RunSlots), a.On + for i, s := range p.Slots { + now := s.Value == 1 + if s.Value != 0 && s.Value != 1 { + t.Fatalf("slot %d proposes %v for a start/stop control", i, s.Value) + } + if now == on { + run++ + continue + } + if need := map[bool]int{true: a.MinOnSlots, false: a.MinOffSlots}[on]; run < need { + t.Fatalf("slot %d switches after %d slots; the device needs %d", i, run, need) + } + on, run = now, 1 + } +} + +func TestMinimumOnAndOffTimesAreKept(t *testing.T) { + // A jagged price that would have a free device switching every slot. + price := make([]float64, day) + for i := range price { + price[i] = 100 + 80*float64(i%2) + } + for _, c := range []struct { + on bool + run int + }{{false, 1}, {true, 1}, {true, 6}, {false, 6}} { + r := pool(day, price, summerDay(day)) + r.Zone.StartC = 26.2 + r.Actuator.MinOnSlots, r.Actuator.MinOffSlots = 4, 6 + r.Actuator.On, r.Actuator.RunSlots = c.on, c.run + checkRuns(t, propose(t, r), r.Actuator) + } +} + +func TestAnUndersizedHeaterIsReportedNotHidden(t *testing.T) { + r := radiatorHouse(day, flat(day, 100)) + r.Actuator.MaxHeatKW = 2 // the house loses 4.2 kW at target + p := propose(t, r) + if p.BandExcursionKh <= 0 { + t.Fatal("a house that cannot be held reported no excursion") + } + for i, s := range p.Slots { + if s.HeatKWh < 2*slotH-1e-9 { + t.Fatalf("slot %d holds back heat while the zone falls out of its band", i) + } + } +} + +func TestNegativePriceFillsTheBand(t *testing.T) { + price := hours(day, func(h float64) float64 { + if between(h, 12, 14) { + return -20 + } + return 100 + }) + p := propose(t, radiatorHouse(day, price)) + // It may arrive cooler to take more; what it must not do is hold back. + if got := heat(p, 12, 14); got < 2*8-0.01 { + t.Fatalf("took %.1f kWh in two hours of being paid to heat; the radiators give 16", got) + } + if p.BandExcursionKh != 0 { + t.Fatalf("left the band by %v Kh", p.BandExcursionKh) + } +} + +func TestProposeRefusesWhatItCannotAnswer(t *testing.T) { + bad := map[string]func(*Request){ + "no horizon": func(r *Request) { r.Price = nil }, + "short series": func(r *Request) { r.OutdoorC = r.OutdoorC[:10] }, + "nan price": func(r *Request) { r.Price[3] = math.NaN() }, + "target outside band": func(r *Request) { r.Zone.TargetC[5] = 25 }, + "no inertia": func(r *Request) { r.Zone.TauH = 0 }, + "negative capacity": func(r *Request) { r.Zone.CapacityKWhPerK = -1 }, + "no heat": func(r *Request) { r.Actuator.MaxHeatKW = 0 }, + "falling values": func(r *Request) { r.Actuator.Values = []float64{21, 20} }, + "too many values": func(r *Request) { r.Actuator.Values = Values(0, 40, 1, 0, 100) }, + "credit below one": func(r *Request) { r.Zone.LossCreditCOP = flat(day, 0.5) }, + "unknown source": func(r *Request) { r.Actuator.Source.Kind = "wood" }, + "hour-long slots": func(r *Request) { r.SlotH = 2 }, + } + for name, mutate := range bad { + r := radiatorHouse(day, flat(day, 100)) + mutate(&r) + if _, err := Propose(r); err == nil { + t.Errorf("%s: accepted", name) + } + } + + r := radiatorHouse(day, flat(day, 100)) + r.Actuator.Strategy = thermal.InfluenceDiscreteMode + if _, err := Propose(r); !errors.Is(err, ErrUnsupported) { + t.Fatalf("discrete mode: got %v, want ErrUnsupported", err) + } + offset := slabHouse(day, flat(day, 100), flat(day, 0)) + offset.Actuator.ZoneKPerUnit = 0 + if _, err := Propose(offset); err == nil { + t.Fatal("a curve offset with no learned effect on the zone was planned") + } +} + +func TestValues(t *testing.T) { + eq := func(got, want []float64) bool { + if len(got) != len(want) { + return false + } + for i := range got { + if math.Abs(got[i]-want[i]) > 1e-9 { + return false + } + } + return true + } + if got := Values(-3, 3, 1, 0, 16); !eq(got, []float64{-3, -2, -1, 0, 1, 2, 3}) { + t.Fatalf("whole range: %v", got) + } + // Thinned, with both ends and the device's own value kept. + got := Values(5, 30, 0.5, 21.5, 8) + if len(got) > 8 || got[0] != 5 || got[len(got)-1] != 30 { + t.Fatalf("thinned range lost an end or its limit: %v", got) + } + kept := false + for i, v := range got { + kept = kept || v == 21.5 + if i > 0 && v <= got[i-1] { + t.Fatalf("not rising: %v", got) + } + } + if !kept { + t.Fatalf("thinned range dropped the device's own value: %v", got) + } + for _, bad := range [][]float64{Values(1, 0, 1, 0, 8), Values(0, 1, 0, 0, 8), Values(0, 1, 1, 0, 2)} { + if bad != nil { + t.Fatalf("a range that is none returned %v", bad) + } + } +} + +// A thermostat cannot be told to draw less; it can only be told when. With +// the cheap hours taken by something else, the tank charges in the cheapest +// hours that have room for it. +func TestImportLimitMovesTheDraw(t *testing.T) { + price := hours(day, func(h float64) float64 { + switch { + case between(h, 2, 4): + return 40 + case between(h, 4, 6): + return 60 + } + return 100 + }) + free := hotWaterTank(day, price, Source{Kind: SourceDirectElectric}) + limited := hotWaterTank(day, price, Source{Kind: SourceDirectElectric}) + limited.MaxElecKW = hours(day, func(h float64) float64 { + if between(h, 2, 4) { + return 1 // the car is charging + } + return 5 + }) + pf, pl := propose(t, free), propose(t, limited) + if heat(pf, 2, 4) < 3 { + t.Fatalf("the free tank took %.1f kWh in the cheapest hours; the test needs it to want them", heat(pf, 2, 4)) + } + if pl.OverLimitKWh != 0 { + t.Fatalf("%.2f kWh over the limit with room elsewhere", pl.OverLimitKWh) + } + for k, s := range pl.Slots { + if kw := s.ElecKWh / slotH; kw > limited.MaxElecKW[k]+1e-6 { + t.Fatalf("slot %d draws %.2f kW against a limit of %.0f kW", k, kw, limited.MaxElecKW[k]) + } + } + if heat(pl, 4, 6) < 3 { + t.Fatalf("took %.1f kWh in the next cheapest hours", heat(pl, 4, 6)) + } + // To the planner's own resolution: its temperature grid is 0.1 K here. + if lo, _ := tempRange(pl, 0, 24); lo < 49.95 || pl.BandExcursionKh > 0.01 { + t.Fatalf("the limit cost the tank its floor: %.2f °C", lo) + } + if pf.OverLimitKWh != 0 { + t.Fatal("a plan without a limit reported being over one") + } +} + +// Heat is planned inside the site's energy plan, never through it. With the +// site's headroom taken for eight hours, the house coasts out of its band; +// the plan says so and does not draw the difference. +func TestImportLimitOutranksTheBand(t *testing.T) { + busy := func(h float64) bool { return between(h, 14, 22) } + r := radiatorHouse(day, flat(day, 100)) + r.Actuator.Values = Values(15, 22, 0.5, 21, 16) + r.MaxElecKW = hours(day, func(h float64) float64 { + if busy(h) { + return 1 // the house needs 4.2 kW to hold its target + } + return 10 + }) + p := propose(t, r) + for k, s := range p.Slots { + if kw := s.ElecKWh / slotH; kw > r.MaxElecKW[k]+1e-6 { + t.Fatalf("slot %d draws %.2f kW through a %.0f kW limit", k, kw, r.MaxElecKW[k]) + } + } + if p.OverLimitKWh != 0 { + t.Fatalf("reports %.2f kWh over the limit", p.OverLimitKWh) + } + if lo, _ := tempRange(p, 14, 22); lo >= 20 || p.BandExcursionKh <= 0 { + t.Fatalf("lowest %.2f °C, excursion %v Kh: eight hours on 1 kW must take the house under 20 °C, and be reported", lo, p.BandExcursionKh) + } + // It did what it could inside the plan: full before, and back after. + if _, hi := tempRange(p, 13, 14); hi < 21.9 { + t.Fatalf("entered the limited hours at %.2f °C with a 22 °C ceiling", hi) + } + if got := heat(p, 22, 24); got < 2*8-0.1 { + t.Fatalf("took %.1f kWh in the two hours after the limit lifted; the radiators give 16", got) + } +} + +// A thermostat regulates by itself at the lowest value it can be given. +// What that draws through the limit cannot be planned away, and is reported. +func TestWhatTheDeviceDrawsByItselfIsReported(t *testing.T) { + r := radiatorHouse(day, flat(day, 100)) // lowest value 20 °C: 4 kW + r.MaxElecKW = flat(day, 3) + p := propose(t, r) + if p.OverLimitKWh <= 0 { + t.Fatal("the thermostat's own draw through the limit was not reported") + } + for k, s := range p.Slots { + if s.Value > 21 { + t.Fatalf("slot %d raises the setpoint to %v under a limit the house already passes", k, s.Value) + } + } +} + +// Solar the site would have exported is the cheapest heat there is, as far +// as it goes and no further. +func TestSurplusIsUsedBeforeImport(t *testing.T) { + site := make([]SiteSlot, day) + for k := range site { + site[k] = SiteSlot{ImportPrice: 100, ExportPrice: 30, GridKW: 0.5} + if between(float64(k)*slotH, 11, 14) { + site[k].GridKW = -2 // exporting 2 kW + } + } + r := hotWaterTank(day, nil, Source{Kind: SourceDirectElectric}) + r.Site(site, 0) + p := propose(t, r) + if got := heat(p, 11, 14); got < 3 { + t.Fatalf("took %.1f kWh while the site exported", got) + } + // The same tank with no surplus has no reason to charge at midday. + plain := hotWaterTank(day, flat(day, 100), Source{Kind: SourceDirectElectric}) + if got := heat(propose(t, plain), 11, 14); got > 0.5 { + t.Fatalf("took %.1f kWh at midday with nothing to gain", got) + } + // Surplus is priced only as far as it goes: 3 kWh in an hour is 2 at the + // export price and 1 at the import price. + one := Request{SlotH: 1, OutdoorC: []float64{0}, + Zone: Zone{TauH: 200, CapacityKWhPerK: 0.35, StartC: 50, BoundaryC: []float64{20}, + TargetC: []float64{60}, MinC: []float64{50}, MaxC: []float64{65}}, + Actuator: Actuator{Strategy: thermal.InfluenceSetpoint, Values: []float64{65}, MaxHeatKW: 3, + Source: Source{Kind: SourceDirectElectric}}} + one.Site([]SiteSlot{{ImportPrice: 100, ExportPrice: 30, GridKW: -2}}, 0) + if got := propose(t, one).Slots[0]; math.Abs(got.ElecKWh-3) > 1e-9 || math.Abs(got.Cost-(2*30+1*100)) > 1e-6 { + t.Fatalf("3 kWh against a 2 kW surplus cost %.1f for %.2f kWh, want 160 for 3", got.Cost, got.ElecKWh) + } + if p.Cost >= p.BaselineCost { + t.Fatalf("cost %.0f, no better than %.0f left alone", p.Cost, p.BaselineCost) + } +} + +func TestSiteSetsHeadroomAndSurplus(t *testing.T) { + var r Request + r.Site([]SiteSlot{ + {ImportPrice: 100, ExportPrice: 30, GridKW: 3}, + {ImportPrice: 100, ExportPrice: 30, GridKW: -1.5}, + {ImportPrice: 100, ExportPrice: 30, GridKW: 7}, + {ImportPrice: 20, ExportPrice: 30, GridKW: -1}, + }, 5) + want := []struct{ max, surplus, surplusPrice float64 }{{2, 0, 100}, {6.5, 1.5, 30}, {0, 0, 100}, {6, 1, 20}} + for k, w := range want { + if r.MaxElecKW[k] != w.max || r.SurplusKW[k] != w.surplus || r.SurplusPrice[k] != w.surplusPrice { + t.Errorf("slot %d: limit %v surplus %v at %v, want %+v", k, r.MaxElecKW[k], r.SurplusKW[k], r.SurplusPrice[k], w) + } + } + r.Site([]SiteSlot{{ImportPrice: 100}}, 0) + if r.MaxElecKW != nil { + t.Fatal("no import limit must mean no limit, not a limit of zero") + } +} + +// Two zones planned one after the other must not both claim the same +// surplus or the same headroom. +func TestAfterHandsTheNextZoneWhatIsLeft(t *testing.T) { + site := make([]SiteSlot, day) + for k := range site { + site[k] = SiteSlot{ImportPrice: 100, ExportPrice: 30, GridKW: 1} + if between(float64(k)*slotH, 2, 4) { + site[k].ImportPrice = 40 + } + } + const limit = 5.0 + tank := hotWaterTank(day, nil, Source{Kind: SourceDirectElectric}) + tank.Site(site, limit) + first := propose(t, tank) + second := spa(day, nil) + second.Site(After(site, first, slotH), limit) + next := propose(t, second) + for k := range site { + total := site[k].GridKW + (first.Slots[k].ElecKWh+next.Slots[k].ElecKWh)/slotH + if total > limit+1e-6 { + t.Fatalf("slot %d: the site imports %.2f kW with both zones, over its %.0f kW limit", k, total, limit) + } + } + if first.OverLimitKWh != 0 || next.OverLimitKWh != 0 { + t.Fatal("a zone reported passing the limit") + } +} + +// batterySite is a day with an evening peak at 300 that the battery covers. +// With ample set it also covers the shoulder after it, at 150. +func batterySite(ample bool) []SiteSlot { + site := make([]SiteSlot, day) + for k := range site { + h := float64(k) * slotH + site[k] = SiteSlot{ImportPrice: 100, ExportPrice: 30, GridKW: 1} + switch { + case between(h, 17, 20): + site[k] = SiteSlot{ImportPrice: 300, ExportPrice: 30, GridKW: 0, BatteryDischargeKW: 1, BatterySpareKW: 2} + case between(h, 20, 23): + site[k].ImportPrice = 150 + if ample { + site[k] = SiteSlot{ImportPrice: 150, ExportPrice: 30, GridKW: 0, BatteryDischargeKW: 1, BatterySpareKW: 2} + } + } + } + return site +} + +// A battery that holds energy does not make the peak cheap. Heat it carries +// is bought back in the cheapest slot the battery was to cover, and only as +// much as half of what it was to spend there. +func TestBatteryEnergyCostsWhatTheSiteBuysBack(t *testing.T) { + var ample, scarce Request + ample.Site(batterySite(true), 5) + scarce.Site(batterySite(false), 5) + for k := range ample.Price { + h := float64(k) * slotH + if !between(h, 17, 20) { + if ample.SurplusKW[k] != 0 || scarce.SurplusKW[k] != 0 { + t.Fatalf("slot %d: battery energy offered outside the slots dearer than the one given up", k) + } + continue + } + // 3 kWh planned for the shoulder, half of it on offer, against + // 6 kWh of spare power in the peak: a quarter of each slot's 2 kW. + if math.Abs(ample.SurplusKW[k]-0.5) > 1e-9 || math.Abs(ample.SurplusPrice[k]-150) > 1e-9 { + t.Fatalf("slot %d: %.2f kW at %.0f, want 0.5 kW at the shoulder's 150", k, ample.SurplusKW[k], ample.SurplusPrice[k]) + } + if math.Abs(ample.MaxElecKW[k]-5.5) > 1e-9 { + t.Fatalf("slot %d: headroom %.2f kW, want the 5 kW limit plus the 0.5 kW the battery carries", k, ample.MaxElecKW[k]) + } + // A battery planned only into the peak has nothing to give up: + // every kWh heat took would be bought back at the peak's price. + if scarce.SurplusKW[k] != 0 || scarce.SurplusPrice[k] != 300 || scarce.MaxElecKW[k] != 5 { + t.Fatalf("slot %d: a battery planned only into the peak offered %.2f kW at %.0f", k, scarce.SurplusKW[k], scarce.SurplusPrice[k]) + } + } + // The battery cannot give back what it has already spent: a shoulder + // before the peak frees nothing for it. + early := batterySite(false) + for k := range early { + if between(float64(k)*slotH, 14, 17) { + early[k] = SiteSlot{ImportPrice: 150, ExportPrice: 30, GridKW: 0, BatteryDischargeKW: 1, BatterySpareKW: 2} + } + } + var before Request + before.Site(early, 5) + for k := range before.Price { + if before.SurplusKW[k] != 0 { + t.Fatalf("slot %d: offered %.2f kW from a shoulder that comes before the peak", k, before.SurplusKW[k]) + } + } + // A small zone is offered what it can take, not what the battery has. + small := Request{Actuator: Actuator{MaxHeatKW: 0.2}} + small.Site(batterySite(true), 0) + for k := range small.Price { + if between(float64(k)*slotH, 17, 20) && math.Abs(small.SurplusKW[k]-0.2) > 1e-9 { + t.Fatalf("slot %d: a 0.2 kW floor is offered %.2f kW", k, small.SurplusKW[k]) + } + } +} + +// The heat a light room must buy in the peak costs the shoulder's price for +// what the battery carries, and the import price for the rest. +func TestBatteryMakesAPeakCheaperToHeatThrough(t *testing.T) { + plan := func(ample bool) Plan { + r := airToAirHouse(day, nil, flat(day, 0)) + r.Site(batterySite(ample), 0) + return propose(t, r) + } + with, without := plan(true), plan(false) + peakCost := func(p Plan) (cost, elec float64) { + for k, s := range p.Slots { + if between(float64(k)*slotH, 17, 20) { + cost, elec = cost+s.Cost, elec+s.ElecKWh + } + } + return cost, elec + } + costWith, elecWith := peakCost(with) + costWithout, elecWithout := peakCost(without) + if elecWith < 0.2 || elecWithout < 0.2 { + t.Fatalf("the room bought %.2f and %.2f kWh in the peak; the test needs it to buy some", elecWith, elecWithout) + } + // 0.5 kW of the peak draw at the shoulder's 150, the rest at 300. + if got := costWith / elecWith; got < 150 || got > 290 { + t.Fatalf("peak electricity cost %.1f per kWh with the battery, want between the shoulder's 150 and the peak's 300", got) + } + if got := costWithout / elecWithout; math.Abs(got-300) > 1 { + t.Fatalf("peak electricity cost %.1f per kWh without, want the import price 300", got) + } + if with.Cost >= without.Cost { + t.Fatalf("cost %.0f with the battery, %.0f without", with.Cost, without.Cost) + } + for name, p := range map[string]Plan{"with": with, "without": without} { + if p.BandExcursionKh != 0 { + t.Fatalf("%s: left the band by %v Kh", name, p.BandExcursionKh) + } + } +} diff --git a/go/internal/heatplan/site.go b/go/internal/heatplan/site.go new file mode 100644 index 000000000..43a26124f --- /dev/null +++ b/go/internal/heatplan/site.go @@ -0,0 +1,156 @@ +package heatplan + +import ( + "math" + "sort" +) + +// SiteSlot is what the site's own plan says about one slot, before this +// zone's heat: what Core's battery and solar plan already decided. +type SiteSlot struct { + // ImportPrice is the full cost of a kWh from the grid; ExportPrice + // what a kWh sent to it earns. + ImportPrice, ExportPrice float64 + // GridKW is the planned exchange with the grid, positive into the + // site, after solar, the battery and the car. + GridKW float64 + // BatteryDischargeKW is what the battery is planned to give in the + // slot, zero or more. BatterySpareKW is how much more it could give: + // its power limit less the plan. + BatteryDischargeKW, BatterySpareKW float64 +} + +// Site sets the request's prices, surplus and import limit from the site's +// plan. importLimitKW is the most the site may import; zero or less means no +// limit. Set the Actuator first: its output bounds what the zone can take. +// +// The site's plan comes first and heat fits around it. Surplus is only what +// the plan still exports after the battery and the car, and headroom only +// what it leaves under the limit. +// +// A battery holding energy does not make a slot cheap. The battery follows +// the site's load, so heat moved into a slot where it discharges is carried +// by the battery, which then has less for later: the site buys that energy +// back in the cheapest slot the battery was still to cover. Heat is charged +// that price, not the price the battery was charged at. The energy on offer +// at it is only what the battery was to spend in those later, cheaper +// slots, kept by batteryShare for a forecast that runs short; past it, and +// wherever nothing cheaper follows, heat costs the import price. +func (r *Request) Site(site []SiteSlot, importLimitKW float64) { + n := len(site) + r.Price, r.SurplusKW, r.SurplusPrice = make([]float64, n), make([]float64, n), make([]float64, n) + r.MaxElecKW = nil + if importLimitKW > 0 { + r.MaxElecKW = make([]float64, n) + } + fromBattery, buyBack := batteryOffer(site, r.Actuator.MaxHeatKW) + for k, s := range site { + r.Price[k] = s.ImportPrice + r.SurplusPrice[k] = s.ImportPrice + headroom := importLimitKW - s.GridKW + switch { + case s.GridKW < 0: + r.SurplusKW[k] = -s.GridKW + // Export never earns more than import costs; a slot that + // claims so would be heated with imported power called + // surplus. + r.SurplusPrice[k] = math.Min(s.ExportPrice, s.ImportPrice) + case fromBattery[k] > 0: + r.SurplusKW[k] = fromBattery[k] + r.SurplusPrice[k] = buyBack[k] + // What the battery carries does not come through the meter. + headroom += fromBattery[k] + } + if r.MaxElecKW != nil { + r.MaxElecKW[k] = math.Max(0, headroom) + } + } +} + +// batteryShare is how much of the energy the battery was to spend in its +// cheapest covered slots heat may count on. The rest is left for a house +// that uses more, or a battery that holds less, than the site's plan +// forecast: heat that counts on energy which is then not there has moved +// load into the dearest slots at the import price. +const batteryShare = 0.5 + +// batteryOffer finds the power heat may take from the battery in each slot, +// and the price it pays for it. The battery's energy is finite: what heat +// takes in one slot the battery cannot give in a later one, and when the +// site plans again it drops the cheapest slot it still meant to cover. So a +// slot is offered energy only from cheaper slots that come after it, at +// their price. A slot that gives is not also offered energy. +func batteryOffer(site []SiteSlot, zoneKW float64) (kw, price []float64) { + kw, price = make([]float64, len(site)), make([]float64, len(site)) + type covered struct { + slot int + price, give, want float64 + gave bool + } + var c []covered + for k, s := range site { + if s.GridKW < 0 || !(s.BatteryDischargeKW > 0) { + continue + } + want := math.Max(0, s.BatterySpareKW) + if zoneKW > 0 { + want = math.Min(want, zoneKW) + } + c = append(c, covered{slot: k, price: s.ImportPrice, give: batteryShare * s.BatteryDischargeKW, want: want}) + } + givers := make([]int, len(c)) + for i := range givers { + givers[i] = i + } + sort.SliceStable(givers, func(i, j int) bool { return c[givers[i]].price < c[givers[j]].price }) + for _, gi := range givers { + g := &c[gi] + if kw[g.slot] > 0 { + continue + } + // The dearest earlier slots first, a price level at a time. + for left := g.give; left > 1e-12; { + level, room := g.price, 0.0 + for _, t := range c[:gi] { + if t.gave || t.price <= g.price || t.want-kw[t.slot] <= 1e-12 { + continue + } + switch { + case t.price > level: + level, room = t.price, t.want-kw[t.slot] + case t.price == level: + room += t.want - kw[t.slot] + } + } + if room <= 0 { + break + } + part := math.Min(1, left/room) + for _, t := range c[:gi] { + if t.gave || t.price != level || t.want-kw[t.slot] <= 1e-12 { + continue + } + x := part * (t.want - kw[t.slot]) + price[t.slot] = (price[t.slot]*kw[t.slot] + g.price*x) / (kw[t.slot] + x) + kw[t.slot] += x + } + left -= part * room + g.gave = true + } + } + return kw, price +} + +// After returns the site's plan with a zone's proposal added to it, for +// planning the next zone: surplus one zone takes and headroom it fills are +// not offered twice. Zones planned this way share the site in the order +// they are planned; they are not optimised together. +func After(site []SiteSlot, p Plan, slotH float64) []SiteSlot { + out := append([]SiteSlot(nil), site...) + for k := range out { + if k < len(p.Slots) && slotH > 0 { + out[k].GridKW += p.Slots[k].ElecKWh / slotH + } + } + return out +} diff --git a/go/internal/heatplan/source.go b/go/internal/heatplan/source.go new file mode 100644 index 000000000..138bd4368 --- /dev/null +++ b/go/internal/heatplan/source.go @@ -0,0 +1,208 @@ +package heatplan + +import ( + "errors" + "math" + "sort" +) + +// SourceKind says how a device turns electricity into heat. +type SourceKind string + +const ( + // SourceDirectElectric is a resistive heater: a floor cable, a panel + // radiator, an immersion heater, a spa heater. One kWh in, one kWh out, + // whatever the weather and whatever it heats. + SourceDirectElectric SourceKind = "direct_electric" + // SourceHeatPump moves heat. What a kWh of electricity delivers depends + // on how far the heat is lifted: from the cold side (outdoor air, ground) + // to the sink (a room, a flow temperature, a tank, a pool). + SourceHeatPump SourceKind = "heat_pump" +) + +// Defaults for a heat pump whose driver declares nothing more than its kind. +// They are a starting point, not a claim about any device: 50 % of the Carnot +// limit and 5 K across each heat exchanger give 3.5 at 0 °C outdoor and 35 °C +// flow, 2.3 at −15/45 and 2.6 for hot water at 55 °C, the range the +// manufacturers' own tables sit in. +const ( + defaultCarnotFraction = 0.5 + defaultApproachK = 5.0 + defaultMaxCOP = 6.0 + minLiftK = 8.0 +) + +// COPPoint is one declared operating point: the COP at an outdoor +// temperature, with the sink at Source.CurveSinkC. +type COPPoint struct { + OutdoorC float64 + COP float64 +} + +// SupplyCurve is a hydronic heat pump's weather compensation: the flow +// temperature it runs at for an outdoor temperature, linear between two +// points and held flat outside them. +type SupplyCurve struct { + ColdOutdoorC float64 // e.g. −15 + ColdSupplyC float64 // e.g. 45 + MildOutdoorC float64 // e.g. 15 + MildSupplyC float64 // e.g. 25 +} + +// At is the flow temperature at an outdoor temperature. +func (c SupplyCurve) At(outdoorC float64) float64 { + if outdoorC <= c.ColdOutdoorC { + return c.ColdSupplyC + } + if outdoorC >= c.MildOutdoorC { + return c.MildSupplyC + } + f := (outdoorC - c.ColdOutdoorC) / (c.MildOutdoorC - c.ColdOutdoorC) + return c.ColdSupplyC + f*(c.MildSupplyC-c.ColdSupplyC) +} + +// Source is the efficiency of one heat input. +type Source struct { + Kind SourceKind + + // The rest describes a heat pump and is ignored for direct electric. + + // ColdSideC is the temperature the pump takes heat from when that is + // not outdoor air: brine from the ground, exhaust air. Nil means + // outdoor air, which moves with the forecast and frosts. + ColdSideC *float64 + // Supply is the flow temperature of a hydronic pump. Nil means the + // pump heats the zone itself and the sink is the zone's own + // temperature: the room for air-to-air, the water for a tank or a pool. + Supply *SupplyCurve + // SinkApproachK is how much hotter the condenser runs than the sink. + // Zero means 5 K, right for water. An air-to-air unit blows room air + // over its coil and needs 15–20 K. + SinkApproachK float64 + // CarnotFraction is the share of the ideal COP the pump reaches. Zero + // means 0.5. Unused when Curve is declared. + CarnotFraction float64 + // Curve is the pump's declared COP by outdoor temperature, measured + // with the sink at CurveSinkC. It replaces CarnotFraction; a sink at + // another temperature scales it by the ratio of the ideal COPs. + Curve []COPPoint + CurveSinkC float64 + // FrostLoss is the share of output an air-source pump loses to + // defrosting at its worst, around +1 °C in damp air. It fades to + // nothing at −7 and +6 °C. Zero means the curve already includes it. + FrostLoss float64 + // MaxCOP caps the result. Zero means 6. + MaxCOP float64 +} + +func (s Source) validate() error { + switch s.Kind { + case SourceDirectElectric: + return nil + case SourceHeatPump: + default: + return errors.New("heatplan: unknown source kind") + } + if s.SinkApproachK < 0 || s.SinkApproachK > 40 || s.CarnotFraction < 0 || s.CarnotFraction > 1 || + s.FrostLoss < 0 || s.FrostLoss > 0.5 || s.MaxCOP < 0 || !finite(s.SinkApproachK, s.CarnotFraction, s.FrostLoss, s.MaxCOP) { + return errors.New("heatplan: heat pump efficiency out of range") + } + if s.ColdSideC != nil && (!finite(*s.ColdSideC) || *s.ColdSideC < -30 || *s.ColdSideC > 40) { + return errors.New("heatplan: cold side temperature out of range") + } + if c := s.Supply; c != nil { + if !finite(c.ColdOutdoorC, c.ColdSupplyC, c.MildOutdoorC, c.MildSupplyC) || + c.MildOutdoorC <= c.ColdOutdoorC || c.ColdSupplyC < c.MildSupplyC || c.MildSupplyC < 15 || c.ColdSupplyC > 80 { + return errors.New("heatplan: supply curve is not a heating curve") + } + } + for i, p := range s.Curve { + if !finite(p.OutdoorC, p.COP) || p.COP < 1 || p.COP > 10 { + return errors.New("heatplan: declared COP out of range") + } + if i > 0 && p.OutdoorC <= s.Curve[i-1].OutdoorC { + return errors.New("heatplan: declared COP points must rise in outdoor temperature") + } + } + if len(s.Curve) > 0 && (!finite(s.CurveSinkC) || s.CurveSinkC < 5 || s.CurveSinkC > 80) { + return errors.New("heatplan: declared COP needs the sink temperature it was measured at") + } + return nil +} + +// COP is the heat delivered per unit of electricity with the outdoor air at +// outdoorC and the sink at sinkC. It is never below 1: a pump that cannot +// beat its own backup heater is running on it. +func (s Source) COP(outdoorC, sinkC float64) float64 { + if s.Kind != SourceHeatPump { + return 1 + } + cold := outdoorC + if s.ColdSideC != nil { + cold = *s.ColdSideC + } + var cop float64 + if len(s.Curve) > 0 { + cop = interpCOP(s.Curve, outdoorC) * s.ideal(sinkC, cold) / s.ideal(s.CurveSinkC, cold) + } else { + frac := s.CarnotFraction + if frac == 0 { + frac = defaultCarnotFraction + } + cop = frac * s.ideal(sinkC, cold) + } + if s.ColdSideC == nil && s.FrostLoss > 0 { + cop *= 1 - s.FrostLoss*frostWeight(outdoorC) + } + max := s.MaxCOP + if max == 0 { + max = defaultMaxCOP + } + return math.Max(1, math.Min(max, cop)) +} + +// ideal is the Carnot COP between the evaporator and the condenser, each a +// heat exchanger's approach away from what it exchanges with. +func (s Source) ideal(sinkC, coldC float64) float64 { + approach := s.SinkApproachK + if approach == 0 { + approach = defaultApproachK + } + condenser := sinkC + approach + evaporator := coldC - defaultApproachK + return (condenser + 273.15) / math.Max(minLiftK, condenser-evaporator) +} + +// frostWeight is 1 where an air coil ices fastest and 0 where it does not: +// below −7 °C the air is too dry, above +6 °C the coil stays above freezing. +func frostWeight(outdoorC float64) float64 { + switch { + case outdoorC <= -7 || outdoorC >= 6: + return 0 + case outdoorC < 1: + return (outdoorC + 7) / 8 + default: + return (6 - outdoorC) / 5 + } +} + +func interpCOP(curve []COPPoint, outdoorC float64) float64 { + i := sort.Search(len(curve), func(i int) bool { return curve[i].OutdoorC >= outdoorC }) + switch { + case i == 0: + return curve[0].COP + case i == len(curve): + return curve[len(curve)-1].COP + } + a, b := curve[i-1], curve[i] + return a.COP + (b.COP-a.COP)*(outdoorC-a.OutdoorC)/(b.OutdoorC-a.OutdoorC) +} + +func finite(vs ...float64) bool { + for _, v := range vs { + if math.IsNaN(v) || math.IsInf(v, 0) { + return false + } + } + return true +} diff --git a/go/internal/heatplan/source_test.go b/go/internal/heatplan/source_test.go new file mode 100644 index 000000000..5442917de --- /dev/null +++ b/go/internal/heatplan/source_test.go @@ -0,0 +1,121 @@ +package heatplan + +import ( + "math" + "testing" +) + +func TestDirectElectricIsOneEverywhere(t *testing.T) { + s := Source{Kind: SourceDirectElectric} + for _, c := range [][2]float64{{-20, 20}, {0, 65}, {25, 38}} { + if got := s.COP(c[0], c[1]); got != 1 { + t.Fatalf("COP(%v, %v) = %v", c[0], c[1], got) + } + } +} + +// The undeclared pump has to land where real ones do, or every plan built on +// it is wrong by the same factor. +func TestDefaultHeatPumpIsInTheRangeOfRealOnes(t *testing.T) { + water := Source{Kind: SourceHeatPump} + air := Source{Kind: SourceHeatPump, SinkApproachK: 18} + for _, c := range []struct { + name string + src Source + outdoor, sink float64 + atLeast, atMost float64 + }{ + {"air to water, 0 °C, 35 °C flow", water, 0, 35, 3.0, 4.0}, + {"air to water, −15 °C, 45 °C flow", water, -15, 45, 2.0, 2.7}, + {"hot water at 55 °C, 0 °C", water, 0, 55, 2.2, 3.0}, + {"air to air, 0 °C, 21 °C room", air, 0, 21, 3.0, 4.2}, + {"air to air, −15 °C, 21 °C room", air, -15, 21, 2.2, 3.0}, + } { + if got := c.src.COP(c.outdoor, c.sink); got < c.atLeast || got > c.atMost { + t.Errorf("%s: COP %.2f, want %.1f–%.1f", c.name, got, c.atLeast, c.atMost) + } + } +} + +func TestHeatPumpCOPFollowsTheLift(t *testing.T) { + s := Source{Kind: SourceHeatPump} + if !(s.COP(5, 35) > s.COP(-5, 35)) { + t.Fatal("warmer outdoor air must raise the COP") + } + if !(s.COP(0, 30) > s.COP(0, 40) && s.COP(0, 40) > s.COP(0, 60)) { + t.Fatal("a hotter sink must lower the COP") + } + poor := Source{Kind: SourceHeatPump, CarnotFraction: 0.1} + if got := poor.COP(-30, 70); got != 1 { + t.Fatalf("COP %.2f; a pump never does worse than its backup heater", got) + } + if got := s.COP(30, 20); got != defaultMaxCOP { + t.Fatalf("COP %.2f with no lift, want the cap %v", got, defaultMaxCOP) + } + brine := 2.0 + ground := Source{Kind: SourceHeatPump, ColdSideC: &brine, FrostLoss: 0.2} + if ground.COP(-20, 35) != ground.COP(10, 35) { + t.Fatal("a ground-source pump must not follow the outdoor air, or frost") + } +} + +func TestDeclaredCurveIsUsedAndScaledToTheSink(t *testing.T) { + s := Source{Kind: SourceHeatPump, CurveSinkC: 35, + Curve: []COPPoint{{-15, 2.2}, {-7, 2.8}, {2, 3.6}, {7, 4.6}}} + for outdoor, want := range map[float64]float64{-20: 2.2, -7: 2.8, -2.5: 3.2, 7: 4.6, 15: 4.6} { + if got := s.COP(outdoor, 35); math.Abs(got-want) > 1e-9 { + t.Errorf("COP at %v °C and the curve's own sink = %v, want %v", outdoor, got, want) + } + } + // 20 K hotter costs roughly a quarter to a third at this lift. + if ratio := s.COP(2, 55) / s.COP(2, 35); ratio < 0.6 || ratio > 0.8 { + t.Fatalf("COP at 55 °C is %.2f of the COP at 35 °C", ratio) + } +} + +func TestFrostCostsMostJustAboveFreezing(t *testing.T) { + s := Source{Kind: SourceHeatPump, FrostLoss: 0.15} + dry := Source{Kind: SourceHeatPump} + loss := func(outdoor float64) float64 { return 1 - s.COP(outdoor, 35)/dry.COP(outdoor, 35) } + if math.Abs(loss(1)-0.15) > 1e-9 { + t.Fatalf("loss at +1 °C = %.3f, want 0.15", loss(1)) + } + for _, outdoor := range []float64{-15, -7, 6, 12} { + if loss(outdoor) != 0 { + t.Errorf("loss at %v °C = %.3f, want none", outdoor, loss(outdoor)) + } + } + if !(loss(-3) > 0 && loss(-3) < 0.15 && loss(4) > 0 && loss(4) < 0.15) { + t.Fatal("the loss must fade on both sides of +1 °C") + } +} + +func TestSupplyCurve(t *testing.T) { + c := SupplyCurve{ColdOutdoorC: -15, ColdSupplyC: 45, MildOutdoorC: 15, MildSupplyC: 25} + for outdoor, want := range map[float64]float64{-30: 45, -15: 45, 0: 35, 15: 25, 25: 25} { + if got := c.At(outdoor); math.Abs(got-want) > 1e-9 { + t.Errorf("flow at %v °C = %v, want %v", outdoor, got, want) + } + } +} + +func TestSourceValidation(t *testing.T) { + hot := 60.0 + for name, s := range map[string]Source{ + "unknown kind": {Kind: "district"}, + "carnot above one": {Kind: SourceHeatPump, CarnotFraction: 1.2}, + "cold side too hot": {Kind: SourceHeatPump, ColdSideC: &hot}, + "cooling curve": {Kind: SourceHeatPump, Supply: &SupplyCurve{ColdOutdoorC: -15, ColdSupplyC: 25, MildOutdoorC: 15, MildSupplyC: 45}}, + "cop below one": {Kind: SourceHeatPump, CurveSinkC: 35, Curve: []COPPoint{{0, 0.8}}}, + "unordered curve": {Kind: SourceHeatPump, CurveSinkC: 35, Curve: []COPPoint{{5, 4}, {0, 3}}}, + "curve with no sink": {Kind: SourceHeatPump, Curve: []COPPoint{{0, 3}}}, + "frost loss too high": {Kind: SourceHeatPump, FrostLoss: 0.9}, + } { + if s.validate() == nil { + t.Errorf("%s: accepted", name) + } + } + if err := (Source{Kind: SourceDirectElectric, CarnotFraction: 9}).validate(); err != nil { + t.Fatalf("direct electric must ignore heat pump fields: %v", err) + } +}