From 1a6a35c4984c1726f90f334be249e40791da72b0 Mon Sep 17 00:00:00 2001 From: hannesb90 <279736760+hannesb90@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:14:27 +0100 Subject: [PATCH 1/3] feat(heatplan): propose a zone's heat from prices and the site's plan A dynamic program over a zone's predicted temperature. It costs heat as electricity divided by the source's efficiency, so direct electric heat, air-to-air, air-to-water, a hot-water tank, a spa and a pool are the same problem with different inertia, band and COP. The site's energy plan comes first. Heat is costed at the import price, takes only what the plan still exports and only the headroom it leaves under the import limit, and leaves its band before it proposes a value that draws through that limit. Battery energy costs what the site buys back in the cheapest later slot the battery was to cover, never what the battery was charged at. Two owner rules sit beside the plan, both off until the owner sets them: PriceComfort moves a zone's target with the day's mean price, linearly between the owner's cheap, normal and dear levels, inside the zone's hard band; SavingsGate leaves every zone on its target unless the plans together save the owner's least amount in a day. A `thermal` config section carries the owner's numbers as plain values with their own checks, and cmd/ftw turns them into the planner's rules, so no control package depends on heatplan. Nothing calls the package yet: the service and dispatch are separate changes. ADR 0012 gains the proposal under "What the owner sets". Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: hannesb90 <279736760+hannesb90@users.noreply.github.com> --- .changeset/heat-comfort-day-price.md | 9 + .changeset/heat-planner-package.md | 7 + config.example.yaml | 17 + docs/adr/0012-heat-control.md | 48 ++ go/cmd/ftw/thermal_comfort.go | 35 ++ go/cmd/ftw/thermal_comfort_test.go | 55 ++ go/internal/config/config.go | 4 + go/internal/config/thermal.go | 123 +++++ go/internal/config/thermal_test.go | 103 ++++ go/internal/heatplan/archetypes_test.go | 148 +++++ go/internal/heatplan/comfort.go | 185 +++++++ go/internal/heatplan/comfort_test.go | 209 +++++++ go/internal/heatplan/plan.go | 690 ++++++++++++++++++++++++ go/internal/heatplan/plan_test.go | 677 +++++++++++++++++++++++ go/internal/heatplan/site.go | 156 ++++++ go/internal/heatplan/source.go | 208 +++++++ go/internal/heatplan/source_test.go | 121 +++++ 17 files changed, 2795 insertions(+) create mode 100644 .changeset/heat-comfort-day-price.md create mode 100644 .changeset/heat-planner-package.md create mode 100644 go/cmd/ftw/thermal_comfort.go create mode 100644 go/cmd/ftw/thermal_comfort_test.go create mode 100644 go/internal/config/thermal.go create mode 100644 go/internal/config/thermal_test.go create mode 100644 go/internal/heatplan/archetypes_test.go create mode 100644 go/internal/heatplan/comfort.go create mode 100644 go/internal/heatplan/comfort_test.go create mode 100644 go/internal/heatplan/plan.go create mode 100644 go/internal/heatplan/plan_test.go create mode 100644 go/internal/heatplan/site.go create mode 100644 go/internal/heatplan/source.go create mode 100644 go/internal/heatplan/source_test.go 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/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/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) + } +} From 7ffe9319d75f99412b7e53a9f0fc3c7031885048 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 15 Nov 2026 17:39:18 +0100 Subject: [PATCH 2/3] fix(heatplan): offer battery energy once and by the draw, no savings gate - Site offers battery power by the electricity the device draws at full output, not by its heat: a 6 kW pump at COP 3 is offered about 2 kW. - After takes the battery energy a zone used off what the next zone is offered, and moves it on the meter to the slot that gave it up. - A comfort shift rounded to the control's step never passes the owner's raise or lower limit. - The savings gate and the thermal config section are taken out. The planner runs in shadow first and shows what it would save; config comes with the change that acts on it (ADR 0012, decision 9). - Tests: run time across the plan start in both directions, a 25-hour day, the step limit, the pump's draw and two zones sharing a battery. Co-Authored-By: Claude Opus 5.5 --- .changeset/heat-comfort-day-price.md | 9 -- config.example.yaml | 17 ---- docs/adr/0012-heat-control.md | 59 +++++++------ go/cmd/ftw/thermal_comfort.go | 35 -------- go/cmd/ftw/thermal_comfort_test.go | 55 ------------ go/internal/config/config.go | 4 - go/internal/config/thermal.go | 123 --------------------------- go/internal/config/thermal_test.go | 103 ---------------------- go/internal/heatplan/comfort.go | 90 ++++++-------------- go/internal/heatplan/comfort_test.go | 86 ++++++------------- go/internal/heatplan/plan.go | 8 ++ go/internal/heatplan/plan_test.go | 120 +++++++++++++++++++++++++- go/internal/heatplan/site.go | 107 ++++++++++++++++++++--- 13 files changed, 307 insertions(+), 509 deletions(-) delete mode 100644 .changeset/heat-comfort-day-price.md delete mode 100644 go/cmd/ftw/thermal_comfort.go delete mode 100644 go/cmd/ftw/thermal_comfort_test.go delete mode 100644 go/internal/config/thermal.go delete mode 100644 go/internal/config/thermal_test.go diff --git a/.changeset/heat-comfort-day-price.md b/.changeset/heat-comfort-day-price.md deleted file mode 100644 index c39ba5c07..000000000 --- a/.changeset/heat-comfort-day-price.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -"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/config.example.yaml b/config.example.yaml index 6698b7e00..c9073eea6 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -280,23 +280,6 @@ 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 95b8d49e0..a4d1e0b55 100644 --- a/docs/adr/0012-heat-control.md +++ b/docs/adr/0012-heat-control.md @@ -2,14 +2,17 @@ - Status: accepted. - Implementation: the declaration - ([#1995](https://github.com/srcfl/ftw/pull/1995)) and the twin in shadow - ([#1996](https://github.com/srcfl/ftw/pull/1996)) are proposed as PRs. - Planned control has not shipped. + ([#1995](https://github.com/srcfl/ftw/pull/1995)), the twin in shadow + ([#1996](https://github.com/srcfl/ftw/pull/1996)) and the planner package + (`go/internal/heatplan`, from + [#2013](https://github.com/srcfl/ftw/pull/2013)) are merged. Nothing + calls the planner yet, and planned control has not shipped. - Date: 2026-11-10 - Decided by: Fredrik on 10 November 2026, in his [answers on #1994](https://github.com/srcfl/ftw/pull/1994#issuecomment-6763083595), and on the hot-water floor on 12 November 2026 - ([answer](https://github.com/srcfl/ftw/pull/1994#issuecomment-6832196178)). + ([answer](https://github.com/srcfl/ftw/pull/1994#issuecomment-6832196178)), + and on comfort that follows the day's price on 15 November 2026. See [Decisions](#decisions). - Builds on: [#520](https://github.com/srcfl/ftw/issues/520), the [`thermal`](../../go/internal/thermal/model.go) contract, driver @@ -142,7 +145,8 @@ thermal: #### Comfort follows the day's price -Proposed; see [Open](#open). What a degree is worth to the owner depends on +Decided on 15 November 2026; see [Decisions](#decisions), point 9. 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: @@ -152,7 +156,6 @@ 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 @@ -169,17 +172,20 @@ thermal: - 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. +- A shift rounded to the control's step never passes the owner's limit: a + raise of 2.5 K in steps of 1 K is 2 K. +- **The comfort rule comes first.** It moves the target, and 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. +- **It is the owner's target, not planned control.** It needs no trusted + twin. It still sends a value to the device, so decision 2 holds: a + device-side timed hold, or a small step from the device's own value. +- **There is no least saving.** A limit on what the plans must save before + they act was proposed and is not taken. In the one house that ran it, + with 5 kr a day, the plans saved 0.1–4.9 kr and the limit was never + reached, so it only turned the planner off. Instead the planner runs in + shadow first and the owner sees what it would have saved per day, then + turns planned control on with that number in view. ### 2. Declaration by the driver @@ -401,15 +407,20 @@ Fredrik answered on the hot-water floor on 12 November 2026: wins and Core does not reject it. Core holds the owner's floor and timer, with these three numbers as defaults when nothing is set. +Fredrik answered on comfort that follows the day's price on 15 November 2026: + +9. **Comfort that follows the day's price** is taken, as section 1 + describes, as the owner's own rule. It needs no trusted twin, and + decision 2 applies to what it sends. **There is no least daily saving.** + The planner runs in shadow first, and the box shows the owner what it + would have saved before planned control is turned on. + ## 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. +- **What makes a day cheap or dear.** Comfort that follows the price uses + the day's mean against the owner's fixed levels. Whether a longer + reference, such as the month, serves better is open until it has run in + more than one house. - **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 deleted file mode 100644 index 3f48b7336..000000000 --- a/go/cmd/ftw/thermal_comfort.go +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 17e222fb7..000000000 --- a/go/cmd/ftw/thermal_comfort_test.go +++ /dev/null @@ -1,55 +0,0 @@ -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/config/config.go b/go/internal/config/config.go index 4784ea678..0b8e473f0 100644 --- a/go/internal/config/config.go +++ b/go/internal/config/config.go @@ -46,7 +46,6 @@ 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 @@ -1985,9 +1984,6 @@ 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 deleted file mode 100644 index 83d859617..000000000 --- a/go/internal/config/thermal.go +++ /dev/null @@ -1,123 +0,0 @@ -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 deleted file mode 100644 index 7a86a137e..000000000 --- a/go/internal/config/thermal_test.go +++ /dev/null @@ -1,103 +0,0 @@ -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/heatplan/comfort.go b/go/internal/heatplan/comfort.go index 028e50dc6..c617e86f6 100644 --- a/go/internal/heatplan/comfort.go +++ b/go/internal/heatplan/comfort.go @@ -5,21 +5,20 @@ import ( "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. +// This file holds the owner's rule for what heat is worth, beside the plan +// itself, and what a plan saves. The rule has no default in code: every +// number in it is the owner's, its zero value 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. +// 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. PriceComfort +// moves the target before planning, so the plan and its baseline both stand +// on the comfort that day is worth. It needs no model of the zone and holds +// from the first day. // -// 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. +// There is no least saving before a plan may act. What a plan saves is shown +// to the owner from the shadow run, and the owner decides with that number +// in view (ADR 0012, decision 9). // PriceComfort moves a zone's target with the day's mean price. All prices // are in the unit of Request.Price. @@ -78,8 +77,18 @@ func (c PriceComfort) ShiftK(dayMean float64) float64 { } 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. + // thermostat's half-degree step should do in both directions. It + // never rounds past the owner's own limit: a raise of 2.5 K in + // steps of 1 K is at most 2 K, not 3. + // The small margin keeps 0.3 K in steps of 0.1 K at 0.3. + const eps = 1e-9 shift = math.Round(shift/c.StepK) * c.StepK + if shift > c.RaiseK+eps { + shift = math.Floor(c.RaiseK/c.StepK+eps) * c.StepK + } + if shift < -c.LowerK-eps { + shift = -math.Floor(c.LowerK/c.StepK+eps) * c.StepK + } } return shift } @@ -126,60 +135,13 @@ func DayMean(price []float64, slotH, minHours float64) (mean float64, ok bool) { 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. +// target, in the unit of Request.Price times kWh, over the plan's horizon. +// 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 index 11166a55a..11b40e991 100644 --- a/go/internal/heatplan/comfort_test.go +++ b/go/internal/heatplan/comfort_test.go @@ -118,6 +118,12 @@ func TestDayMeanNeedsMostOfTheDay(t *testing.T) { 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) } + // A day the clocks go back has 25 hours; its mean is still the mean of + // every slot in it, not of 24 hours. + long := append(flat(96, 100), flat(4, 200)...) + if m, ok := DayMean(long, slotH, 22); !ok || math.Abs(m-104) > 1e-9 { + t.Errorf("25 hours (a day the clocks go back) = %v, %v; want 104", m, ok) + } if _, ok := DayMean([]float64{100, math.NaN()}, 12, 22); ok { t.Error("a price that is not a number passed") } @@ -128,44 +134,6 @@ func TestDayMeanNeedsMostOfTheDay(t *testing.T) { 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. @@ -177,33 +145,29 @@ func TestSavingCountsOnlyWhatAFeasiblePlanSaves(t *testing.T) { 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()}, +// A step never takes the target past what the owner allowed: 2.5 K in +// whole steps is 2 K, and a step larger than the limit moves nothing. +func TestPriceComfortStepNeverPassesTheOwnersLimit(t *testing.T) { + for _, tc := range []struct { + name string + c PriceComfort + mean float64 + want float64 + }{ + {"2.5 K up in 1 K steps", PriceComfort{CheapPrice: 150, NormalPrice: 260, RaiseK: 2.5, StepK: 1}, 100, 2}, + {"1 K up in 2 K steps", PriceComfort{CheapPrice: 150, NormalPrice: 260, RaiseK: 1, StepK: 2}, 100, 0}, + {"1.5 K down in 1 K steps", PriceComfort{NormalPrice: 260, DearPrice: 400, LowerK: 1.5, StepK: 1}, 500, -1}, + {"0.3 K up in 0.1 K steps", PriceComfort{CheapPrice: 150, NormalPrice: 260, RaiseK: 0.3, StepK: 0.1}, 100, 0.3}, + {"a step that fits is kept", PriceComfort{CheapPrice: 150, NormalPrice: 260, RaiseK: 2, StepK: 0.5}, 100, 2}, } { - if g.Validate() == nil { - t.Errorf("%s: Validate accepted it", name) + got := tc.c.ShiftK(tc.mean) + if math.Abs(got-tc.want) > 1e-9 { + t.Errorf("%s: shift = %v K, want %v", tc.name, got, tc.want) } - 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) + if got > tc.c.RaiseK+1e-9 || got < -tc.c.LowerK-1e-9 { + t.Errorf("%s: shift %v K is past the owner's limit", tc.name, got) } } } diff --git a/go/internal/heatplan/plan.go b/go/internal/heatplan/plan.go index 5b5dd2bb6..c7abb0d3c 100644 --- a/go/internal/heatplan/plan.go +++ b/go/internal/heatplan/plan.go @@ -131,6 +131,10 @@ type Actuator struct { // 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. + // A RunSlots of 0 is a run time the caller does not know. It is read as + // a switch just made, so the device keeps its state for its whole + // minimum time: safe for the device, at the cost of heat held back or + // spent for up to that long. On bool RunSlots int } @@ -162,6 +166,10 @@ type Request struct { SurplusKW, SurplusPrice []float64 Zone Zone Actuator Actuator + + // battery is what Site offered from the battery, slot by slot, for + // After to take off before the next zone. + battery []batteryGift } // Slot is the proposal for one slot. diff --git a/go/internal/heatplan/plan_test.go b/go/internal/heatplan/plan_test.go index b559c2685..bba9cff5b 100644 --- a/go/internal/heatplan/plan_test.go +++ b/go/internal/heatplan/plan_test.go @@ -280,6 +280,52 @@ func TestMinimumOnAndOffTimesAreKept(t *testing.T) { } } +// The run time the device reports carries across the plan's start in both +// directions: a device off for 2 of its 6 slots waits 4 more however cheap +// the first hours are, and a device on for longer than its minimum may stop at +// once when the first hours are dear. +func TestRunTimeCarriesAcrossThePlanStart(t *testing.T) { + firstOn := func(p Plan) int { + for i, s := range p.Slots { + if s.Value == 1 { + return i + } + } + return -1 + } + cheapFirst := hours(day, func(h float64) float64 { + if h < 2 { + return -50 + } + return 100 + }) + r := pool(day, cheapFirst, summerDay(day)) + r.Zone.StartC = 27 + r.Actuator.MinOnSlots, r.Actuator.MinOffSlots = 4, 6 + r.Actuator.On, r.Actuator.RunSlots = false, 2 + p := propose(t, r) + checkRuns(t, p, r.Actuator) + if got := firstOn(p); got != 4 { + t.Fatalf("an off device 2 slots into its 6 first runs in slot %d, want 4", got) + } + + dearFirst := hours(day, func(h float64) float64 { + if h < 2 { + return 500 + } + return 100 + }) + r = pool(day, dearFirst, summerDay(day)) + r.Zone.StartC = 28 + r.Actuator.MinOnSlots, r.Actuator.MinOffSlots = 4, 6 + r.Actuator.On, r.Actuator.RunSlots = true, 8 + p = propose(t, r) + checkRuns(t, p, r.Actuator) + if p.Slots[0].Value != 0 { + t.Fatal("a device on for 8 slots, past its minimum of 4, kept running into two dear hours") + } +} + func TestAnUndersizedHeaterIsReportedNotHidden(t *testing.T) { r := radiatorHouse(day, flat(day, 100)) r.Actuator.MaxHeatKW = 2 // the house loses 4.2 kW at target @@ -550,7 +596,7 @@ func TestAfterHandsTheNextZoneWhatIsLeft(t *testing.T) { tank.Site(site, limit) first := propose(t, tank) second := spa(day, nil) - second.Site(After(site, first, slotH), limit) + second.Site(After(site, tank, first), limit) next := propose(t, second) for k := range site { total := site[k].GridKW + (first.Slots[k].ElecKWh+next.Slots[k].ElecKWh)/slotH @@ -637,6 +683,78 @@ func TestBatteryEnergyCostsWhatTheSiteBuysBack(t *testing.T) { } } +// A heat pump is offered battery power by the electricity it draws, not by +// the heat it gives: 6 kW of heat at a COP near 3 is about 2 kW, and the +// import headroom grows by no more than that. +func TestBatteryIsOfferedByTheElectricityAPumpDraws(t *testing.T) { + 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, BatteryDischargeKW: 4, BatterySpareKW: 10} + case between(h, 20, 23): + site[k] = SiteSlot{ImportPrice: 150, ExportPrice: 30, BatteryDischargeKW: 4, BatterySpareKW: 10} + } + } + r := airToAirHouse(day, nil, flat(day, 7)) + r.Actuator.MaxHeatKW = 6 + r.Site(site, 5) + for k := range site { + if !between(float64(k)*slotH, 17, 20) { + continue + } + draw := r.maxDrawKW(k) + if !(draw > 1 && draw < 3) { + t.Fatalf("slot %d: a 6 kW pump draws %.2f kW by the model, want about 2", k, draw) + } + if math.Abs(r.SurplusKW[k]-draw) > 1e-9 { + t.Fatalf("slot %d: offered %.2f kW from the battery, want the pump's draw %.2f", k, r.SurplusKW[k], draw) + } + if math.Abs(r.MaxElecKW[k]-(5+draw)) > 1e-9 { + t.Fatalf("slot %d: headroom %.2f kW, want the 5 kW limit plus %.2f", k, r.MaxElecKW[k], draw) + } + } +} + +// Two zones planned one after the other share the battery's energy once. +// What the first was carried by is taken off what the second is offered, +// and the slot that gave it up imports it instead. +func TestAfterOffersBatteryEnergyOnce(t *testing.T) { + site := batterySite(true) + offeredTotal := func(r Request) (kw float64) { + for _, v := range r.SurplusKW { + kw += v + } + return kw + } + first := airToAirHouse(day, nil, flat(day, 0)) + first.Site(site, 0) + p := propose(t, first) + var used float64 + for k, s := range p.Slots { + used += math.Min(s.ElecKWh/slotH, first.SurplusKW[k]) + } + if used < 0.5 { + t.Fatalf("the first room used %.2f kW-slots of battery power; the test needs it to use some", used) + } + next := After(site, first, p) + second := airToAirHouse(day, nil, flat(day, 0)) + second.Site(next, 0) + if got, want := offeredTotal(second), offeredTotal(first)-used; got > want+1e-6 { + t.Fatalf("the second room is offered %.2f kW-slots of battery power, want at most the %.2f the first left", got, want) + } + var before, after float64 + for k := range site { + before += site[k].GridKW*slotH + p.Slots[k].ElecKWh + after += next[k].GridKW * slotH + } + if math.Abs(before-after) > 1e-6 { + t.Fatalf("the meter shows %.3f kWh with the first room, want the %.3f the site and the room draw together", after, before) + } +} + // 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) { diff --git a/go/internal/heatplan/site.go b/go/internal/heatplan/site.go index 43a26124f..f8cd88e45 100644 --- a/go/internal/heatplan/site.go +++ b/go/internal/heatplan/site.go @@ -3,6 +3,8 @@ package heatplan import ( "math" "sort" + + "github.com/srcfl/ftw/go/internal/thermal" ) // SiteSlot is what the site's own plan says about one slot, before this @@ -22,7 +24,9 @@ type SiteSlot struct { // 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. +// limit. Set the Actuator, the Zone's band and OutdoorC first: the +// electricity the device draws at full output bounds what the zone is +// offered. // // 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 @@ -43,7 +47,12 @@ func (r *Request) Site(site []SiteSlot, importLimitKW float64) { if importLimitKW > 0 { r.MaxElecKW = make([]float64, n) } - fromBattery, buyBack := batteryOffer(site, r.Actuator.MaxHeatKW) + draw := make([]float64, n) + for k := range draw { + draw[k] = r.maxDrawKW(k) + } + fromBattery, buyBack, given := batteryOffer(site, draw) + r.battery = given for k, s := range site { r.Price[k] = s.ImportPrice r.SurplusPrice[k] = s.ImportPrice @@ -74,13 +83,53 @@ func (r *Request) Site(site []SiteSlot, importLimitKW float64) { // load into the dearest slots at the import price. const batteryShare = 0.5 +// maxDrawKW is the most electricity the zone's device can draw in slot k: +// full output at the worst efficiency the plan could run it at, with the +// sink at its hottest. A heat pump of 6 kW heat at COP 3 draws 2 kW. Without +// the outdoor forecast or the band for the slot it is full output at COP 1, +// which no source draws more than. Zero means no bound. +func (r *Request) maxDrawKW(k int) float64 { + a := r.Actuator + if !(a.MaxHeatKW > 0) { + return 0 + } + if a.Source.Kind != SourceHeatPump || k >= len(r.OutdoorC) || k >= len(r.Zone.MaxC) { + return a.MaxHeatKW + } + sink := math.Max(r.Zone.MaxC[k], r.Zone.StartC) + if c := a.Source.Supply; c != nil { + supplyK := 0.0 + if a.Strategy == thermal.InfluenceCurveOffset { + for i, v := range a.Values { + if i == 0 || v*a.SupplyKPerUnit > supplyK { + supplyK = v * a.SupplyKPerUnit + } + } + } + sink = c.At(r.OutdoorC[k]) + supplyK + } + cop := a.Source.COP(r.OutdoorC[k], sink) + if !(cop >= 1) || !finite(cop) { + return a.MaxHeatKW + } + return a.MaxHeatKW / cop +} + +// batteryGift is battery power one slot was offered from a cheaper, later +// slot whose cover the battery gives up for it. +type batteryGift struct { + to, from int + kw float64 +} + // 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) { +// their price. A slot that gives is not also offered energy. zoneKW is the +// most electricity the zone can draw in each slot; zero means no bound. +func batteryOffer(site []SiteSlot, zoneKW []float64) (kw, price []float64, given []batteryGift) { kw, price = make([]float64, len(site)), make([]float64, len(site)) type covered struct { slot int @@ -93,8 +142,8 @@ func batteryOffer(site []SiteSlot, zoneKW float64) (kw, price []float64) { continue } want := math.Max(0, s.BatterySpareKW) - if zoneKW > 0 { - want = math.Min(want, zoneKW) + if k < len(zoneKW) && zoneKW[k] > 0 { + want = math.Min(want, zoneKW[k]) } c = append(c, covered{slot: k, price: s.ImportPrice, give: batteryShare * s.BatteryDischargeKW, want: want}) } @@ -133,24 +182,56 @@ func batteryOffer(site []SiteSlot, zoneKW float64) (kw, price []float64) { 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 + given = append(given, batteryGift{to: t.slot, from: g.slot, kw: x}) } left -= part * room g.gave = true } } - return kw, price + return kw, price, given } // 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 { +// planning the next zone: surplus one zone takes, headroom it fills and +// battery energy it is carried by are not offered twice. r is the request +// the proposal was planned from, after its Site. Zones planned this way +// share the site in the order they are planned; they are not optimised +// together. +// +// Battery energy the zone used moves on the meter as the site will see it +// when it plans again: the slot it was used in does not import it, and the +// cheaper, later slot that gave it up does, with its cover for heat reduced +// by the same amount, so that all zones together are never offered more of +// it than one zone would be. +func After(site []SiteSlot, r Request, p Plan) []SiteSlot { out := append([]SiteSlot(nil), site...) + h := r.SlotH + if !(h > 0) { + return out + } for k := range out { - if k < len(p.Slots) && slotH > 0 { - out[k].GridKW += p.Slots[k].ElecKWh / slotH + if k < len(p.Slots) { + out[k].GridKW += p.Slots[k].ElecKWh / h + } + } + offered := make(map[int]float64, len(r.battery)) + for _, b := range r.battery { + offered[b.to] += b.kw + } + for _, b := range r.battery { + if b.to >= len(p.Slots) || b.to >= len(out) || b.from >= len(out) || !(offered[b.to] > 0) { + continue + } + used := math.Min(p.Slots[b.to].ElecKWh/h, offered[b.to]) + taken := b.kw * used / offered[b.to] + if !(taken > 0) { + continue } + to, from := &out[b.to], &out[b.from] + to.GridKW -= taken + to.BatterySpareKW = math.Max(0, to.BatterySpareKW-taken) + from.GridKW += taken + from.BatteryDischargeKW = math.Max(0, from.BatteryDischargeKW-taken/batteryShare) } return out } From 72e9020e55ba9d39e36406050144d7fa83d9b636 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 15 Nov 2026 17:46:56 +0100 Subject: [PATCH 3/3] fix(heatplan): bound a slot's draw by the warmest value a control holds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - maxDrawKW takes the highest setpoint or offset a control can regulate to, so no slot draws more than its battery offer and headroom allow. - A shift too small for one step is 0, not −0. - Tests: exact meter and offer accounting in After, and a check that no slot in three houses draws more than its bound. - ADR 0012: the PR that merged the planner, the config shape as future, and battery energy among what zones share in turn. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0012-heat-control.md | 12 ++++--- go/internal/heatplan/comfort.go | 3 ++ go/internal/heatplan/plan_test.go | 52 ++++++++++++++++++++++++++----- go/internal/heatplan/site.go | 14 ++++++++- 4 files changed, 69 insertions(+), 12 deletions(-) diff --git a/docs/adr/0012-heat-control.md b/docs/adr/0012-heat-control.md index a4d1e0b55..f98704f94 100644 --- a/docs/adr/0012-heat-control.md +++ b/docs/adr/0012-heat-control.md @@ -5,7 +5,8 @@ ([#1995](https://github.com/srcfl/ftw/pull/1995)), the twin in shadow ([#1996](https://github.com/srcfl/ftw/pull/1996)) and the planner package (`go/internal/heatplan`, from - [#2013](https://github.com/srcfl/ftw/pull/2013)) are merged. Nothing + [#2013](https://github.com/srcfl/ftw/pull/2013) in + [#2022](https://github.com/srcfl/ftw/pull/2022)) are merged. Nothing calls the planner yet, and planned control has not shipped. - Date: 2026-11-10 - Decided by: Fredrik on 10 November 2026, in his @@ -149,7 +150,9 @@ Decided on 15 November 2026; see [Decisions](#decisions), point 9. 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: +about comfort, not about timing, and it needs no model of the house. The +rule is in `heatplan.PriceComfort`; the configuration below is the shape it +will take, and comes with the change that acts on it: ```yaml thermal: @@ -466,8 +469,9 @@ Fredrik answered on comfort that follows the day's price on 15 November 2026: learns, as the car's is. This touches the load model and the plan's inputs, so it needs the owner's decision. - **Zones share the site in the order they are planned.** A zone gets - the surplus and headroom the zones before it left. This is less than - section 4 asks: zones on a shared source are not yet planned together. + the surplus, headroom and battery energy the zones before it left. This + is less than section 4 asks: zones on a shared source are not yet + planned together. The battery rule comes from a simulation with synthetic houses and prices, not from hardware. A planner that took battery energy for cheap diff --git a/go/internal/heatplan/comfort.go b/go/internal/heatplan/comfort.go index c617e86f6..035087c5a 100644 --- a/go/internal/heatplan/comfort.go +++ b/go/internal/heatplan/comfort.go @@ -90,6 +90,9 @@ func (c PriceComfort) ShiftK(dayMean float64) float64 { shift = -math.Floor(c.LowerK/c.StepK+eps) * c.StepK } } + if shift == 0 { + return 0 // not −0 + } return shift } diff --git a/go/internal/heatplan/plan_test.go b/go/internal/heatplan/plan_test.go index bba9cff5b..126229bad 100644 --- a/go/internal/heatplan/plan_test.go +++ b/go/internal/heatplan/plan_test.go @@ -709,6 +709,9 @@ func TestBatteryIsOfferedByTheElectricityAPumpDraws(t *testing.T) { if !(draw > 1 && draw < 3) { t.Fatalf("slot %d: a 6 kW pump draws %.2f kW by the model, want about 2", k, draw) } + if math.Abs(draw-6/r.Actuator.Source.COP(7, r.Zone.MaxC[k])) > 1e-9 { + t.Fatalf("slot %d: bound %.3f kW, want full output at the band's top", k, draw) + } if math.Abs(r.SurplusKW[k]-draw) > 1e-9 { t.Fatalf("slot %d: offered %.2f kW from the battery, want the pump's draw %.2f", k, r.SurplusKW[k], draw) } @@ -742,16 +745,51 @@ func TestAfterOffersBatteryEnergyOnce(t *testing.T) { next := After(site, first, p) second := airToAirHouse(day, nil, flat(day, 0)) second.Site(next, 0) - if got, want := offeredTotal(second), offeredTotal(first)-used; got > want+1e-6 { - t.Fatalf("the second room is offered %.2f kW-slots of battery power, want at most the %.2f the first left", got, want) + // The shoulder had 6 kW-slots on offer for heat, half of what it was + // to cover, and the first room was offered all of it. + if got := offeredTotal(first); math.Abs(got-6) > 1e-9 { + t.Fatalf("the first room is offered %.3f kW-slots, want the shoulder's 6", got) + } + if got, want := offeredTotal(second), offeredTotal(first)-used; math.Abs(got-want) > 1e-6 { + t.Fatalf("the second room is offered %.3f kW-slots of battery power, want the %.3f the first left", got, want) } - var before, after float64 + var shoulder float64 for k := range site { - before += site[k].GridKW*slotH + p.Slots[k].ElecKWh - after += next[k].GridKW * slotH + h := float64(k) * slotH + drawKW := p.Slots[k].ElecKWh / slotH + fromBattery := math.Min(drawKW, first.SurplusKW[k]) + switch { + case between(h, 17, 20): + // The peak imports only what the battery did not carry. + if want := site[k].GridKW + drawKW - fromBattery; math.Abs(next[k].GridKW-want) > 1e-9 { + t.Fatalf("slot %d: the meter reads %.3f kW, want %.3f", k, next[k].GridKW, want) + } + case between(h, 20, 23): + shoulder += next[k].GridKW - site[k].GridKW - drawKW + } + } + // The shoulder imports what the battery carried in the peak instead. + if math.Abs(shoulder-used) > 1e-9 { + t.Fatalf("the shoulder imports %.3f kW-slots more, want the %.3f the battery carried in the peak", shoulder, used) } - if math.Abs(before-after) > 1e-6 { - t.Fatalf("the meter shows %.3f kWh with the first room, want the %.3f the site and the room draw together", after, before) +} + +// The bound on a slot's draw holds for every plan: no slot draws more than +// the device's full output at the worst efficiency the plan can run it at. +func TestNoSlotDrawsMoreThanItsBound(t *testing.T) { + outdoor := hours(day, func(h float64) float64 { return -5 + 8*math.Sin(h*math.Pi/24) }) + price := hours(day, func(h float64) float64 { return 100 + 150*math.Max(0, math.Sin((h-6)*math.Pi/12)) }) + for name, r := range map[string]Request{ + "air to air": airToAirHouse(day, price, outdoor), + "slab": slabHouse(day, price, outdoor), + "radiators": radiatorHouse(day, price), + } { + p := propose(t, r) + for k, s := range p.Slots { + if got, bound := s.ElecKWh/slotH, r.maxDrawKW(k); got > bound+1e-9 { + t.Fatalf("%s, slot %d: draws %.3f kW over its bound %.3f", name, k, got, bound) + } + } } } diff --git a/go/internal/heatplan/site.go b/go/internal/heatplan/site.go index f8cd88e45..bc37feae5 100644 --- a/go/internal/heatplan/site.go +++ b/go/internal/heatplan/site.go @@ -85,7 +85,9 @@ const batteryShare = 0.5 // maxDrawKW is the most electricity the zone's device can draw in slot k: // full output at the worst efficiency the plan could run it at, with the -// sink at its hottest. A heat pump of 6 kW heat at COP 3 draws 2 kW. Without +// sink at its hottest: the band's top, the start, or the highest value the +// control can regulate to, whichever is warmest. A heat pump of 6 kW heat at +// COP 3 draws 2 kW. Without // the outdoor forecast or the band for the slot it is full output at COP 1, // which no source draws more than. Zero means no bound. func (r *Request) maxDrawKW(k int) float64 { @@ -97,6 +99,16 @@ func (r *Request) maxDrawKW(k int) float64 { return a.MaxHeatKW } sink := math.Max(r.Zone.MaxC[k], r.Zone.StartC) + for _, v := range a.Values { + switch a.Strategy { + case thermal.InfluenceSetpoint: + sink = math.Max(sink, v) + case thermal.InfluenceCurveOffset: + if k < len(r.Zone.TargetC) { + sink = math.Max(sink, r.Zone.TargetC[k]+v*a.ZoneKPerUnit) + } + } + } if c := a.Source.Supply; c != nil { supplyK := 0.0 if a.Strategy == thermal.InfluenceCurveOffset {