diff --git a/.changeset/planner-learned-battery-limits.md b/.changeset/planner-learned-battery-limits.md new file mode 100644 index 000000000..8194d3df2 --- /dev/null +++ b/.changeset/planner-learned-battery-limits.md @@ -0,0 +1,12 @@ +--- +"ftw": minor +--- + +The planner now plans each battery within what it has shown it can do. When +the battery model has learned that the inverter holds grid import while the +battery charges, or that the battery stops at a DC current or power, each +slot of the plan stays inside that limit, at the battery's temperature now. +At night the plan then charges over more hours at what the battery can +take, instead of expecting its full power and falling short every quarter. +Bundles Energyplan 0.9.0, which takes these per-slot limits; Core's own +planner holds them too. A battery with nothing learned plans as before. diff --git a/docs/energyplan-contract.md b/docs/energyplan-contract.md index 3451019b3..27cbaeec9 100644 --- a/docs/energyplan-contract.md +++ b/docs/energyplan-contract.md @@ -37,10 +37,12 @@ The handshake identifies the worker, its version, protocol range and features. Protocol compatibility and supported features govern use, not matching Core and Energyplan release numbers. Current features are `champion`, `forecast_reset`, `partial_slots`, `demand_charges`, `ev_duty`, -`charging_periods`, `published_prices`, `hourly_import_caps` and -`demand_elapsed_hours`; the worker also reports `forecast_protocol_version`. -Core negotiates `charging_periods` before sending its optional fields, and -`hourly_import_caps` before sending `hourly_import_caps`. +`charging_periods`, `published_prices`, `hourly_import_caps`, +`demand_elapsed_hours` and `storage_slot_limits`; the worker also reports +`forecast_protocol_version`. Core negotiates `charging_periods` before +sending its optional fields, `hourly_import_caps` before sending +`hourly_import_caps`, and `storage_slot_limits` before sending a storage's +per-slot limits. Core negotiates `demand_elapsed_hours` before sending a demand hour that starts before the first slot or ended by its execution start. @@ -93,7 +95,21 @@ Physical zero and capacity remain hard limits throughout. Default wear cost is zero; charge/discharge efficiency remains in the physical model. Multiple batteries keep their own limits. Current execution requires a common -charge/discharge direction in each slot. Demand-charge windows use explicit +charge/discharge direction in each slot. + +A storage may carry `max_charge_w_by_slot` and `max_discharge_w_by_slot`: +what it can charge or discharge in each slot, in W, when that is less than +its `max_charge_w` or `max_discharge_w`. Each array is absent, or has one +finite, nonnegative entry per slot in slot order. Core omits a field it does +not send; `[]` and `null` are invalid. An entry above the scalar limit is +held to it, so an array never raises a limit, and a request without the +arrays plans as before. Every solver path holds each slot's battery power +to these limits as hard limits, as it holds the scalars. Core derives them +from what the battery has shown it can do, such as an inverter that holds +grid import while it charges from the grid; they are planning limits, not +commands. A worker without `storage_slot_limits` gets none of them, and Core +checks its plan against the scalar limits only; Core's own planner still +holds them. Core rejects a plan more than 2 W past a slot limit it sent. Demand-charge windows use explicit UTC intervals and elapsed import from Core; Core owns local calendar and daylight-saving conversion. diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index eb6c4c2d4..68bc12f18 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -1737,6 +1737,16 @@ func main() { defer ctrlMu.Unlock() return control.MeasuredHourImport(ctrl) } + // The planner plans each battery within the limits its model has + // learned and trusts (srcfl/ftw#2068), at the temperature it has now. + mpcSvc.LearnedBatteryLimits = func(driver string, tempC *float64) []battery.Plateau { + modelsMu.Lock() + defer modelsMu.Unlock() + if m := models[driver]; m != nil { + return m.Plateaus.KnownAt(tempC) + } + return nil + } // Cap planned export below the fuse when the operator set a site // export ceiling, so the DP never schedules a discharge that would // over-export and trip an inverter (the Ferroamp 0x8030 fault). diff --git a/go/internal/battery/model.go b/go/internal/battery/model.go index ee8fe8c2f..a17acbf67 100644 --- a/go/internal/battery/model.go +++ b/go/internal/battery/model.go @@ -69,7 +69,8 @@ type Model struct { ForgettingFactor float64 `json:"forgetting_factor"` // Plateaus are the limits this battery has shown when short of an order. - // They explain Core's verdict only; nothing in control reads them. + // They explain Core's verdict and bound what the planner plans for the + // battery; nothing in control reads them. Plateaus *Plateaus `json:"plateaus,omitempty"` } diff --git a/go/internal/battery/plateau.go b/go/internal/battery/plateau.go index 4226ca901..22bb587e9 100644 --- a/go/internal/battery/plateau.go +++ b/go/internal/battery/plateau.go @@ -13,8 +13,9 @@ import ( // A flat run that comes back on more than one day is what this device does, // so a later shortfall that sits on it is a limit, not lost control. // -// It only explains Core's verdict. Dispatch, fuse protection, clamps and -// commands never read it. The caller holds the model lock. +// It explains Core's verdict, and the planner plans within the limits it +// trusts (KnownAt). Dispatch, fuse protection, clamps and commands never +// read it. The caller holds the model lock. type Plateaus struct { Series []PlateauSeries `json:"series"` // open is the shortfall run under way. It is not stored: a restart @@ -339,6 +340,20 @@ func (p *Plateaus) Known() []Plateau { return out } +// KnownAt lists the trusted plateaus of the temperature band tempC is in, or +// of no band when tempC is nil, as Explain matches them. The planner reads +// them; a battery's temperature moves slowly over a plan. +func (p *Plateaus) KnownAt(tempC *float64) []Plateau { + band := tempBand(tempC) + out := []Plateau{} + for _, known := range p.Known() { + if sameBand(known.TempBandC, band) { + out = append(out, known) + } + } + return out +} + // plateau is the series' trusted plateau: of the groups of runs that agree, // the newest one seen at least plateauTrustRuns times on two days. A lower // level becomes normal only once it repeats like that; until then the old diff --git a/go/internal/battery/plateau_test.go b/go/internal/battery/plateau_test.go index e6b80a1b3..281c62bd7 100644 --- a/go/internal/battery/plateau_test.go +++ b/go/internal/battery/plateau_test.go @@ -357,3 +357,44 @@ func TestSlowMeterCapIsTrusted(t *testing.T) { } } } + +// The planner plans with the limits of the band the battery is in now: a +// cold-weather limit never holds a warm battery, and a battery that reports +// no temperature takes only the limits learned without one. +func TestKnownAtKeepsTheBandOfTheTemperatureNow(t *testing.T) { + p := &Plateaus{} + at := day0 + cold, warm := f(4), f(14) + for day := range 3 { + start := day0.Add(time.Duration(day) * 24 * time.Hour) + at = feed(p, start, 60, shortfall{a: f(22.4), tempC: cold, batteryW: func(int) float64 { return 4300 }}) + at = feed(p, at.Add(time.Hour), 60, shortfall{a: f(18), tempC: warm, batteryW: func(int) float64 { return 3500 }}) + at = feed(p, at.Add(time.Hour), 60, shortfall{a: f(25), batteryW: func(int) float64 { return 4800 }}) + } + p.Tick(at, nil) + byValue := func(known []Plateau, kind string) []float64 { + var out []float64 + for _, k := range known { + if k.Kind == kind { + out = append(out, k.Value) + } + } + return out + } + for _, c := range []struct { + tempC *float64 + want float64 + }{{f(7.5), 22.4}, {f(10), 18}, {f(19.9), 18}, {nil, 25}} { + got := byValue(p.KnownAt(c.tempC), LimitBatteryCurrent) + if len(got) != 1 || math.Abs(got[0]-c.want) > 0.5 { + t.Fatalf("at %v: current limits %v, want one near %v", c.tempC, got, c.want) + } + } + if got := p.KnownAt(f(31)); len(got) != 0 { + t.Fatalf("a band with no runs has limits: %+v", got) + } + var none *Plateaus + if got := none.KnownAt(cold); len(got) != 0 { + t.Fatalf("no model has limits: %+v", got) + } +} diff --git a/go/internal/control/sitesim_learned_limits_test.go b/go/internal/control/sitesim_learned_limits_test.go new file mode 100644 index 000000000..36e310736 --- /dev/null +++ b/go/internal/control/sitesim_learned_limits_test.go @@ -0,0 +1,147 @@ +package control + +import ( + "context" + "fmt" + "math" + "path/filepath" + "strings" + "testing" + "testing/synctest" + "time" + + "github.com/srcfl/ftw/go/internal/battery" + "github.com/srcfl/ftw/go/internal/mpc" + "github.com/srcfl/ftw/go/internal/sitesim" + "github.com/srcfl/ftw/go/internal/state" +) + +// learnedNightQuarter is one quarter of the night: the battery energy the +// plan in force wanted from it and what the battery gave. +type learnedNightQuarter struct { + start time.Time + plannedWh, givenWh float64 +} + +// runLearnedNight runs the owner's home box at night closed-loop: a 9.6 kWh +// battery at 10 % behind an inverter that holds grid import at 4.32 kW while +// it charges, 1.2 kW of house, two cheap hours and two dear ones. Core's +// planner replans every quarter and Core runs the plan. learned gives the +// planner the import hold the battery model has learned. +func runLearnedNight(t *testing.T, learned bool) []learnedNightQuarter { + t.Helper() + start := time.Date(2026, 11, 20, 1, 0, 0, 0, time.UTC) + time.Sleep(start.Sub(time.Now())) // The bubble's clock becomes the plant's. + st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + prices := make([]state.PricePoint, 32) + for i := range prices { + total := 30. + if i >= 8 { + total = 300 + } + prices[i] = state.PricePoint{Zone: "SE3", SlotTsMs: start.Add(time.Duration(i) * 15 * time.Minute).UnixMilli(), SlotLenMin: 15, + SpotOreKwh: total - 50, TotalOreKwh: total, Source: "test", FetchedAtMs: start.UnixMilli()} + } + if err := st.SavePrices(prices); err != nil { + t.Fatal(err) + } + svc := mpc.New(st, nil, "SE3", mpc.Params{Mode: mpc.ModeArbitrage, SoCLevels: 21, ActionLevels: 21, + CapacityWh: 9600, InitialSoC: .1, SoCMin: .05, SoCMax: .95, MaxChargeW: 5000, MaxDischargeW: 5000, + ChargeEfficiency: .95, DischargeEfficiency: .95}) + svc.Horizon, svc.BaseLoad = 4*time.Hour, 1200 + svc.UpdateBatteryFleet([]mpc.BatteryFleetMember{{Driver: "battery", CapacityWh: 9600, MaxChargeW: 5000, MaxDischargeW: 5000}}, 9600, 5000, 5000) + svc.UpdateSiteEconomics(mpc.SiteEconomics{FuseMaxW: 17250, Timezone: "UTC"}) + if learned { + svc.LearnedBatteryLimits = func(driver string, _ *float64) []battery.Plateau { + if driver != "battery" { + return nil + } + return []battery.Plateau{{Direction: "charge", Kind: battery.LimitGridImport, Value: 4320, Unit: "W", Seen: 9}} + } + } + + p := sitesim.New(start, 25) + p.EVSE = &sitesim.EVSE{Phases: 3, MinA: 6, MaxA: 16, Delay: 5 * time.Second, ReadbackLag: 10 * time.Second} + p.Car = &sitesim.Car{Phases: 3, MaxW: 11040} + p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 5000, MaxDischargeW: 5000, CapacityWh: 9600, SoC: .1, + Latency: 2 * time.Second, GridImportCapW: 4320} + p.HouseW = [3]float64{400, 400, 400} + s := &simSite{p: p, lp: simLoadpoint()} + s.setup = func(s *simSite) { + s.state.Mode, s.state.UseEnergyDispatch = ModePlannerArbitrage, true + s.state.SlotDirective = func(now time.Time) (SlotDirective, bool) { + d, ok := svc.SlotDirectiveAt(now) + if !ok { + return SlotDirective{}, false + } + return SlotDirectiveFromMPC(d), true + } + } + s.boot() + + var quarters []learnedNightQuarter + end := start.Add(2 * time.Hour) + nextReplan := start.Add(10 * time.Second) // Telemetry first. + for s.p.Now.Before(end) { + time.Sleep(sitesim.Step) + s.step() + now := s.p.Now + if !now.Before(nextReplan) { + svc.Tele = s.store + plan := svc.ReplanWithReason(context.Background(), "slot_elapsed") + if plan == nil { + t.Fatalf("%s: no plan: %+v", now.Format("15:04:05"), svc.PlanSnapshot()) + } + q := now.Truncate(15 * time.Minute) + if len(quarters) == 0 || !quarters[len(quarters)-1].start.Equal(q) { + var wh float64 + for _, a := range plan.Actions { + begin, end := max(a.ExecutionStart(), now.UnixMilli()), a.SlotStartMs+int64(a.SlotLenMin)*60_000 + if a.SlotStartMs == q.UnixMilli() && end > begin { + wh = math.Max(0, a.BatteryW) * float64(end-begin) / 3.6e6 + } + } + quarters = append(quarters, learnedNightQuarter{start: q, plannedWh: wh}) + } + nextReplan = q.Add(15*time.Minute + time.Second) + } + if len(quarters) > 0 { + quarters[len(quarters)-1].givenWh += math.Max(0, p.Battery.W) * sitesim.Step.Hours() + } + if s.failure != "" && !strings.Contains(s.failure, "idle") { + t.Fatal(s.failure) + } + } + return quarters +} + +// The planner that knows the inverter's import hold plans the night charge +// the battery can take, so every cheap quarter gives what its plan wanted. +// The planner without it plans 5 kW and every cheap quarter falls short. +func TestSiteSimNightChargeWithinTheLearnedImportHold(t *testing.T) { + for _, learned := range []bool{false, true} { + t.Run(fmt.Sprintf("learned=%v", learned), func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + quarters := runLearnedNight(t, learned) + short, line := 0, "" + for _, q := range quarters { + line += fmt.Sprintf(" %s plan %.0f gave %.0f;", q.start.Format("15:04"), q.plannedWh, q.givenWh) + if q.plannedWh-q.givenWh > 50 { + short++ + } + } + t.Logf("%d of %d quarters short:%s", short, len(quarters), line) + if learned && short > 0 { + t.Errorf("%d quarters gave less than their plan, with the learned hold", short) + } + if !learned && short < 4 { + t.Errorf("only %d quarters short without the learned hold: the case shows nothing", short) + } + }) + }) + } +} diff --git a/go/internal/mpc/charging_periods.go b/go/internal/mpc/charging_periods.go index e0079e727..f4d32457c 100644 --- a/go/internal/mpc/charging_periods.go +++ b/go/internal/mpc/charging_periods.go @@ -83,6 +83,11 @@ func (o *EnergyplanOptimizer) prepareEnergyplanRequest(ctx context.Context, requ request.Settings.TimeLimitS = math.Min(o.cfg.Timeout.Seconds()*0.8, energyplanBudget(slots, p, true).Seconds()) } } + // A worker without the feature plans each slot at the configured + // limits, as before; Core's own planner still holds the learned ones. + if optimizerHasFeature(info, "storage_slot_limits") { + addStorageSlotLimits(request, slots, p) + } loads := p.activeLoadpoints() needed := false for _, lp := range loads { diff --git a/go/internal/mpc/energyplan_fault_test.go b/go/internal/mpc/energyplan_fault_test.go index b718baff8..c434b19f6 100644 --- a/go/internal/mpc/energyplan_fault_test.go +++ b/go/internal/mpc/energyplan_fault_test.go @@ -57,7 +57,7 @@ func TestNativeEnergyplanEVRecoveryFallbackFaults(t *testing.T) { t.Cleanup(func() { _ = external.Close() }) wrapper := &EnergyplanOptimizer{ExternalOptimizer: external} health, err := wrapper.Health(context.Background()) - if err != nil || health.Version != "0.8.0" { + if err != nil || health.Version != "0.9.0" { t.Fatalf("bundle health=%+v err=%v", health, err) } svc := shadowTestService(t) diff --git a/go/internal/mpc/energyplan_test.go b/go/internal/mpc/energyplan_test.go index 6c4258023..c9fadc07b 100644 --- a/go/internal/mpc/energyplan_test.go +++ b/go/internal/mpc/energyplan_test.go @@ -95,7 +95,7 @@ func TestNativeEnergyplanDownsideAndAsyncShadow(t *testing.T) { svc := shadowTestService(t) svc.Optimizer = o info, err := svc.Optimizer.(*EnergyplanOptimizer).Health(context.Background()) - if err != nil || info.Name != "ftw-solver" || info.Version != "0.8.0" { + if err != nil || info.Name != "ftw-solver" || info.Version != "0.9.0" { t.Fatalf("bundled worker health: %+v %v", info, err) } start := time.Now().UTC().Truncate(time.Hour) diff --git a/go/internal/mpc/external_optimizer.go b/go/internal/mpc/external_optimizer.go index 90af8d0bf..1a5d513de 100644 --- a/go/internal/mpc/external_optimizer.go +++ b/go/internal/mpc/external_optimizer.go @@ -123,6 +123,11 @@ type externalStorage struct { DischargeEfficiency float64 `json:"discharge_efficiency"` TerminalPriceOreKWh float64 `json:"terminal_price_per_kwh"` CycleCostOreKWh float64 `json:"cycle_cost_per_kwh"` + // What the battery can do in each slot, sent only to a worker that + // announces storage_slot_limits and only where it has shown less than + // its configured limit (storageSlotLimits). + MaxChargeWBySlot []float64 `json:"max_charge_w_by_slot,omitempty"` + MaxDischargeWBySlot []float64 `json:"max_discharge_w_by_slot,omitempty"` } type externalDemandCharge struct { @@ -272,6 +277,9 @@ func (o *ExternalOptimizer) Optimize(ctx context.Context, slots []Slot, p Params if err := validateExternalAssets(request, response.Plan); err != nil { return Plan{}, fmt.Errorf("optimizer contract rejected: %w", err) } + if err := validateStorageSlotLimits(request, response.Plan); err != nil { + return Plan{}, fmt.Errorf("optimizer plan rejected: %w", err) + } plan = response.toPlan(slots, p) plan.OptimizerInput = append(json.RawMessage(nil), payload...) if err := ValidatePlan(slots, p, &plan); err != nil { diff --git a/go/internal/mpc/mpc.go b/go/internal/mpc/mpc.go index bbbd067e3..1b4c2cadc 100644 --- a/go/internal/mpc/mpc.go +++ b/go/internal/mpc/mpc.go @@ -271,6 +271,9 @@ type StorageAssetSpec struct { MaxDischargeW float64 ChargeEfficiency float64 DischargeEfficiency float64 + // Learned is what this battery has shown it can do. Both planners plan + // each slot within it (slotLimits); it never raises the limits above. + Learned LearnedLimits } func (p Params) activeLoadpoints() []*LoadpointSpec { @@ -698,7 +701,17 @@ func OptimizeContext(ctx context.Context, slots []Slot, p Params) (Plan, error) idleActionIdx = i } } - actionAt := func(j int) float64 { return actionGrid[j] } + // What the batteries have shown they can do holds each slot's actions: + // an action past a slot's limit runs at that limit. Without learned + // limits every slot keeps the grid above. + chargeLimitW, dischargeLimitW := fleetSlotLimitsW(slots, p) + actionAt := func(t, j int) float64 { + w := actionGrid[j] + if chargeLimitW != nil { + w = max(-dischargeLimitW[t], min(w, chargeLimitW[t])) + } + return w + } // EV dimensions. When no loadpoint is active, EL=EA=1 and the // EV loops degenerate to a single pass that adds zero power / @@ -786,7 +799,7 @@ func OptimizeContext(ctx context.Context, slots []Slot, p Params) (Plan, error) bestV := math.Inf(1) bestPolicy := 0 for ba := 0; ba < A; ba++ { - battW := actionAt(ba) + battW := actionAt(t, ba) // Battery SoC transition (independent of EV). dBattWh := loadpoint.BatteryEnergyDeltaWh(battW, dtH, p.ChargeEfficiency, p.DischargeEfficiency) @@ -1100,7 +1113,7 @@ func OptimizeContext(ctx context.Context, slots []Slot, p Params) (Plan, error) pol := Policy[t][si][ei] ba := pol / EA ea := pol % EA - actW := clipBatteryPowerToBand(soc, actionAt(ba), dtH, p.CapacityWh, + actW := clipBatteryPowerToBand(soc, actionAt(t, ba), dtH, p.CapacityWh, p.ChargeEfficiency, p.DischargeEfficiency, p.SoCMin, p.SoCMax) evW := evActionW(ea) soc2 := soc + loadpoint.BatteryEnergyDeltaWh(actW, dtH, p.ChargeEfficiency, p.DischargeEfficiency)/p.CapacityWh diff --git a/go/internal/mpc/params_validation.go b/go/internal/mpc/params_validation.go index cb587802f..909046250 100644 --- a/go/internal/mpc/params_validation.go +++ b/go/internal/mpc/params_validation.go @@ -290,6 +290,15 @@ func validateStorageSpecs(p Params, assetIDs map[string]string) error { if err := requireNonNegativePlanningValue(field+".max_discharge_w", storage.MaxDischargeW); err != nil { return err } + learned := storage.Learned + for _, l := range []struct { + name string + w float64 + }{{"charge_w", learned.ChargeW}, {"discharge_w", learned.DischargeW}, {"grid_import_w", learned.GridImportW}} { + if err := requireNonNegativePlanningValue(field+".learned."+l.name, l.w); err != nil { + return err + } + } if err := requirePlanningEfficiency(field+".charge_efficiency", storage.ChargeEfficiency, false); err != nil { return err } diff --git a/go/internal/mpc/params_validation_test.go b/go/internal/mpc/params_validation_test.go index 5d069378c..49968da0a 100644 --- a/go/internal/mpc/params_validation_test.go +++ b/go/internal/mpc/params_validation_test.go @@ -258,6 +258,8 @@ func TestValidatePlanningParamsRejectsInvalidStoragePhysics(t *testing.T) { {"initial above physical", "initial_energy_wh", func(p *Params) { p.Storages[0].InitialEnergyWh = 10001 }}, {"negative charge power", ".max_charge_w", func(p *Params) { p.Storages[0].MaxChargeW = -1 }}, {"nan discharge power", ".max_discharge_w", func(p *Params) { p.Storages[0].MaxDischargeW = math.NaN() }}, + {"nan learned import hold", ".learned.grid_import_w", func(p *Params) { p.Storages[0].Learned.GridImportW = math.NaN() }}, + {"negative learned discharge", ".learned.discharge_w", func(p *Params) { p.Storages[0].Learned.DischargeW = -1 }}, {"zero efficiency", ".charge_efficiency", func(p *Params) { p.Storages[0].ChargeEfficiency = 0 }}, {"nan efficiency", ".charge_efficiency", func(p *Params) { p.Storages[0].ChargeEfficiency = math.NaN() }}, {"high efficiency", ".discharge_efficiency", func(p *Params) { p.Storages[0].DischargeEfficiency = 1.01 }}, diff --git a/go/internal/mpc/service.go b/go/internal/mpc/service.go index abef59fba..173a78e79 100644 --- a/go/internal/mpc/service.go +++ b/go/internal/mpc/service.go @@ -14,6 +14,7 @@ import ( "time" "github.com/google/uuid" + "github.com/srcfl/ftw/go/internal/battery" "github.com/srcfl/ftw/go/internal/loadpoint" "github.com/srcfl/ftw/go/internal/state" "github.com/srcfl/ftw/go/internal/telemetry" @@ -144,7 +145,13 @@ type Service struct { HourImport func() HourImport // Set before Start. Called without s.mu; must not acquire the control lock. PVExecutionAllowed func(PVCurtailment) bool - Load LoadPredictor // optional — overrides flat BaseLoad + // LearnedBatteryLimits returns the trusted limits a battery's model has + // learned (battery.Plateaus.KnownAt) for the temperature band it is in + // now. Both planners plan each slot within them. Nil plans with the + // configured limits alone. Called without s.mu; it takes the battery + // models' lock. + LearnedBatteryLimits func(driver string, tempC *float64) []battery.Plateau + Load LoadPredictor // optional — overrides flat BaseLoad // Optimizer is the external mathematical planning engine. Nil — the // default since #1020 — makes the in-process Go DP the champion. When // non-nil, any engine/process/validation failure falls back to the DP for @@ -2863,6 +2870,11 @@ func (s *Service) onlineFleetParams(p Params, fleet []BatteryFleetMember, fuseMa sumSoCWh += initialEnergyWh maxCharge += b.MaxChargeW maxDischarge += b.MaxDischargeW + var learned LearnedLimits + if s.LearnedBatteryLimits != nil { + tempC, voltageV := batteryPackNow(r.Data) + learned = learnedLimits(s.LearnedBatteryLimits(b.Driver, tempC), voltageV) + } storages = append(storages, StorageAssetSpec{ ID: b.Driver, CapacityWh: b.CapacityWh, @@ -2873,6 +2885,7 @@ func (s *Service) onlineFleetParams(p Params, fleet []BatteryFleetMember, fuseMa MaxDischargeW: b.MaxDischargeW, ChargeEfficiency: p.ChargeEfficiency, DischargeEfficiency: p.DischargeEfficiency, + Learned: learned, }) } if totalCap <= 0 { diff --git a/go/internal/mpc/storage_limits.go b/go/internal/mpc/storage_limits.go new file mode 100644 index 000000000..7b1841f5b --- /dev/null +++ b/go/internal/mpc/storage_limits.go @@ -0,0 +1,231 @@ +package mpc + +import ( + "encoding/json" + "fmt" + "math" + + "github.com/srcfl/ftw/go/internal/battery" +) + +// LearnedLimits are what a battery has shown it can do, from the limits its +// model trusts (battery.Plateaus). A battery that gives less than the plan +// asks ends its slots under-delivered and makes Core replan; planning within +// these limits keeps the plan to what the battery does. They only lower the +// configured limits, and zero means none is known. +type LearnedLimits struct { + // ChargeW and DischargeW are the most the battery gives itself: a DC + // current limit at the pack's voltage now, or a power limit. + ChargeW float64 + DischargeW float64 + // GridImportW is the grid import the inverter holds while the battery + // charges. The battery then gets that import plus PV less the house. + GridImportW float64 +} + +func (l LearnedLimits) known() bool { + return l.ChargeW > 0 || l.DischargeW > 0 || l.GridImportW > 0 +} + +// learnedLimits reads the trusted plateaus of the temperature band the +// battery is in now. A current limit becomes watts at the pack's voltage now; +// without a voltage it is left out. Under discharge the pack's voltage sags +// below what it reads at rest, so a discharge limit read at rest is a little +// optimistic: the battery may give slightly less than planned. A limit below the least power the learner +// samples (battery.PlateauMinShortfallW) cannot be one it learned, so it is +// left out too. Where a current and a power limit both hold, the lower wins. +func learnedLimits(known []battery.Plateau, voltageV *float64) LearnedLimits { + var l LearnedLimits + lower := func(have *float64, w float64) { + if !finite(w) || w < battery.PlateauMinShortfallW { + return + } + if *have == 0 || w < *have { + *have = w + } + } + for _, k := range known { + var w float64 + switch k.Kind { + case battery.LimitBatteryPower: + w = k.Value + case battery.LimitBatteryCurrent: + if voltageV == nil { + continue + } + w = k.Value * *voltageV + case battery.LimitGridImport: + if k.Direction == "charge" { + lower(&l.GridImportW, k.Value) + } + continue + default: + // A grid export limit says what the site may export, not what + // the battery can discharge. + continue + } + switch k.Direction { + case "charge": + lower(&l.ChargeW, w) + case "discharge": + lower(&l.DischargeW, w) + } + } + return l +} + +// batteryPackNow is the pack temperature and DC voltage a battery's driver +// reports now (srcfl/device-drivers docs/WRITING-A-DRIVER.md, "What a battery +// can do now"), with the legacy names. A missing or implausible value is nil, +// by the same rules as the control verdict. +func batteryPackNow(data json.RawMessage) (tempC, voltageV *float64) { + var b struct { + TemperatureC *float64 `json:"temperature_C"` + LegacyTempC *float64 `json:"temp_c"` + V *float64 `json:"V"` + LegacyV *float64 `json:"v"` + } + if len(data) == 0 || json.Unmarshal(data, &b) != nil { + return nil, nil + } + tempC, voltageV = b.TemperatureC, b.V + if tempC == nil { + tempC = b.LegacyTempC + } + if voltageV == nil { + voltageV = b.LegacyV + } + if tempC != nil && (!finite(*tempC) || *tempC < -40 || *tempC > 100) { + tempC = nil + } + if voltageV != nil && (!finite(*voltageV) || *voltageV <= 0) { + voltageV = nil + } + return tempC, voltageV +} + +// slotLimits is what each storage can charge and discharge in each slot, in +// W: its configured limits, lowered by what it has shown it can do. The +// grid import hold belongs to the site, so the batteries that learned one +// share its room, in proportion to their configured charge limits, rather +// than each counting all of it. The room is the least hold any of them +// learned plus the slot's PV less its house load, the forecasts the plan +// uses for the slot. A car charging in the same slot takes import the +// batteries then cannot get; the limits leave it out, so they can only be +// optimistic there, and Core's own grid and fuse limits still hold. +func slotLimits(slots []Slot, storages []StorageAssetSpec) (charge, discharge [][]float64) { + holdW, holdChargeW := math.Inf(1), 0.0 + for _, s := range storages { + if s.Learned.GridImportW > 0 { + holdW = min(holdW, s.Learned.GridImportW) + holdChargeW += s.MaxChargeW + } + } + charge, discharge = make([][]float64, len(storages)), make([][]float64, len(storages)) + for i, s := range storages { + charge[i], discharge[i] = make([]float64, len(slots)), make([]float64, len(slots)) + share := 0.0 + if s.Learned.GridImportW > 0 && holdChargeW > 0 { + share = s.MaxChargeW / holdChargeW + } + for t, slot := range slots { + c, d := s.MaxChargeW, s.MaxDischargeW + if l := s.Learned.ChargeW; l > 0 { + c = min(c, l) + } + if l := s.Learned.DischargeW; l > 0 { + d = min(d, l) + } + if s.Learned.GridImportW > 0 { + c = min(c, max(0, holdW-slot.LoadW-slot.PVW)*share) + } + charge[i][t], discharge[i][t] = c, d + } + } + return charge, discharge +} + +// storageSlotLimits is each storage's charge and discharge limit per slot +// for the worker. A side whose limits never fall below the configured one is +// nil, so a storage with nothing learned keeps today's request. +func storageSlotLimits(slots []Slot, storages []StorageAssetSpec) (charge, discharge [][]float64) { + charge, discharge = slotLimits(slots, storages) + below := func(limits []float64, configured float64) bool { + for _, w := range limits { + if w < configured { + return true + } + } + return false + } + for i, s := range storages { + if !s.Learned.known() || !below(charge[i], s.MaxChargeW) { + charge[i] = nil + } + if !s.Learned.known() || !below(discharge[i], s.MaxDischargeW) { + discharge[i] = nil + } + } + return charge, discharge +} + +// fleetSlotLimitsW is the batteries' summed charge and discharge limit per +// slot, within the aggregate limits, for Core's own planner. Nil when no +// battery has a learned limit: the planner then keeps the aggregate limits. +func fleetSlotLimitsW(slots []Slot, p Params) (charge, discharge []float64) { + known := false + for _, s := range p.Storages { + known = known || s.Learned.known() + } + if !known { + return nil, nil + } + perCharge, perDischarge := slotLimits(slots, p.Storages) + charge, discharge = make([]float64, len(slots)), make([]float64, len(slots)) + for i := range p.Storages { + for t := range slots { + charge[t] += perCharge[i][t] + discharge[t] += perDischarge[i][t] + } + } + for t := range slots { + charge[t] = min(charge[t], p.MaxChargeW) + discharge[t] = min(discharge[t], p.MaxDischargeW) + } + return charge, discharge +} + +// addStorageSlotLimits puts each storage's learned per-slot limits on the +// wire of a worker that announces storage_slot_limits. +func addStorageSlotLimits(request *externalRequest, slots []Slot, p Params) { + charge, discharge := storageSlotLimits(slots, p.Storages) + byID := make(map[string]int, len(p.Storages)) + for i, s := range p.Storages { + byID[s.ID] = i + } + for i := range request.Storages { + if j, ok := byID[request.Storages[i].ID]; ok { + request.Storages[i].MaxChargeWBySlot, request.Storages[i].MaxDischargeWBySlot = charge[j], discharge[j] + } + } +} + +// validateStorageSlotLimits holds a worker's plan to the per-slot limits Core +// sent it, with the same 2 W as the configured limits. +func validateStorageSlotLimits(request externalRequest, plan externalPlan) error { + for _, s := range request.Storages { + for i, a := range plan.Actions { + w, ok := a.StoragePowerW[s.ID] + if !ok { + continue + } + if i < len(s.MaxChargeWBySlot) && w > s.MaxChargeWBySlot[i]+2 { + return fmt.Errorf("slot %d storage %s power %.3f exceeds its slot charge limit %.3f", i, s.ID, w, s.MaxChargeWBySlot[i]) + } + if i < len(s.MaxDischargeWBySlot) && w < -s.MaxDischargeWBySlot[i]-2 { + return fmt.Errorf("slot %d storage %s power %.3f exceeds its slot discharge limit %.3f", i, s.ID, w, s.MaxDischargeWBySlot[i]) + } + } + } + return nil +} diff --git a/go/internal/mpc/storage_limits_test.go b/go/internal/mpc/storage_limits_test.go new file mode 100644 index 000000000..345223d35 --- /dev/null +++ b/go/internal/mpc/storage_limits_test.go @@ -0,0 +1,514 @@ +package mpc + +import ( + "bytes" + "context" + "encoding/json" + "math" + "os" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/battery" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +func ptr(v float64) *float64 { return &v } + +// The owner's home box (Sungrow SH8.0RT with an SBR096): the inverter holds +// grid import at 4.32 kW while the battery charges from the grid, and the +// battery's DC current stops near 22.4 A when it discharges. +func homeBoxPlateaus() []battery.Plateau { + return []battery.Plateau{ + {Direction: "charge", Kind: battery.LimitGridImport, Value: 4320, Unit: "W", Seen: 9}, + {Direction: "discharge", Kind: battery.LimitBatteryCurrent, Value: 22.4, Unit: "A", Seen: 12}, + } +} + +func TestLearnedLimitsReadTrustedPlateaus(t *testing.T) { + got := learnedLimits(homeBoxPlateaus(), ptr(188)) + want := LearnedLimits{DischargeW: 22.4 * 188, GridImportW: 4320} + if got != want { + t.Fatalf("home box limits %+v, want %+v", got, want) + } + // Without the pack's voltage the current limit has no watts. + if got := learnedLimits(homeBoxPlateaus(), nil); got != (LearnedLimits{GridImportW: 4320}) { + t.Fatalf("no voltage: %+v", got) + } + // A power limit beside the current one: the lower holds. + both := append(homeBoxPlateaus(), battery.Plateau{Direction: "discharge", Kind: battery.LimitBatteryPower, Value: 4000, Unit: "W"}) + if got := learnedLimits(both, ptr(188)); got.DischargeW != 4000 { + t.Fatalf("current and power limits: %+v, want 4000 W", got) + } + // An export limit is the site's, not the battery's; a limit below what + // the learner samples, from a wrong voltage, is not one it learned. + odd := []battery.Plateau{ + {Direction: "discharge", Kind: battery.LimitGridExport, Value: 3000}, + {Direction: "charge", Kind: battery.LimitBatteryCurrent, Value: 20}, + {Direction: "charge", Kind: battery.LimitBatteryPower, Value: 4600}, + } + if got := learnedLimits(odd, ptr(0.19)); got != (LearnedLimits{ChargeW: 4600}) { + t.Fatalf("odd plateaus: %+v", got) + } + if got := learnedLimits(nil, ptr(188)); got.known() { + t.Fatalf("no plateaus learned %+v", got) + } +} + +func TestBatteryPackNowReadsTemperatureAndVoltage(t *testing.T) { + for _, c := range []struct { + data string + tempC, voltsV *float64 + }{ + {`{"temperature_C":12.5,"V":191.2}`, ptr(12.5), ptr(191.2)}, + {`{"temp_c":-3,"v":52}`, ptr(-3), ptr(52)}, + {`{"temperature_C":140,"V":-1}`, nil, nil}, + {`{}`, nil, nil}, + {``, nil, nil}, + {`not json`, nil, nil}, + } { + tempC, voltsV := batteryPackNow(json.RawMessage(c.data)) + same := func(a, b *float64) bool { return a == nil && b == nil || a != nil && b != nil && *a == *b } + if !same(tempC, c.tempC) || !same(voltsV, c.voltsV) { + t.Fatalf("%s: %v %v", c.data, tempC, voltsV) + } + } +} + +func TestSlotLimitsFollowTheSlotsLoadAndPV(t *testing.T) { + s := StorageAssetSpec{ID: "sungrow", MaxChargeW: 5000, MaxDischargeW: 5000, + Learned: LearnedLimits{GridImportW: 4320, DischargeW: 4200}} + for _, c := range []struct { + loadW, pvW, charge float64 + }{ + {600, 0, 3720}, // a quiet night + {1500, 0, 2820}, // a busy night + {1000, -3000, 5000}, // PV gives the battery its full power + {5000, 0, 0}, // the house alone takes the import limit + } { + charge, discharge := slotLimits([]Slot{{LoadW: c.loadW, PVW: c.pvW}}, []StorageAssetSpec{s}) + if charge[0][0] != c.charge || discharge[0][0] != 4200 { + t.Fatalf("load %v pv %v: %v / %v, want %v / 4200", c.loadW, c.pvW, charge, discharge, c.charge) + } + } + // A learned limit never raises the configured one. + s.MaxDischargeW, s.Learned.ChargeW = 3000, 9000 + if charge, discharge := slotLimits([]Slot{{PVW: -9000}}, []StorageAssetSpec{s}); charge[0][0] != 5000 || discharge[0][0] != 3000 { + t.Fatalf("raised: %v / %v", charge, discharge) + } +} + +// Two batteries behind one site that both learned its grid hold share the +// hold's room by their configured charge limits; together they never get +// more than the room. A battery without a hold keeps its own limits. +func TestBatteriesShareTheSitesGridHold(t *testing.T) { + storages := []StorageAssetSpec{ + {ID: "a", MaxChargeW: 5000, MaxDischargeW: 5000, Learned: LearnedLimits{GridImportW: 4320}}, + {ID: "b", MaxChargeW: 3000, MaxDischargeW: 3000, Learned: LearnedLimits{GridImportW: 4400}}, + {ID: "c", MaxChargeW: 2000, MaxDischargeW: 2000}, + } + slots := []Slot{{LoadW: 1000}, {LoadW: 600, PVW: -4000}, {LoadW: 5000}} + charge, _ := slotLimits(slots, storages) + // The room is the least hold, 4320 W, less the house: 3320 W, then + // 7720 W with PV, then nothing. + for i, room := range []float64{3320, 7720, 0} { + a, b := charge[0][i], charge[1][i] + if math.Abs(a-min(5000, room*5/8)) > 1e-9 || math.Abs(b-min(3000, room*3/8)) > 1e-9 || a+b > room+1e-9 { + t.Fatalf("slot %d: a %v b %v, room %v", i, a, b, room) + } + if charge[2][i] != 2000 { + t.Fatalf("slot %d: the battery without a hold got %v", i, charge[2][i]) + } + } + // The fleet's limit for Core's own planner is the shared room too. + fleet, _ := fleetSlotLimitsW(slots, Params{MaxChargeW: 10000, MaxDischargeW: 10000, Storages: storages}) + if math.Abs(fleet[0]-(3320+2000)) > 1e-9 { + t.Fatalf("fleet night charge %v, want the room plus the third battery", fleet[0]) + } + // One battery gets the whole room, exactly. + one, _ := slotLimits(slots[:1], storages[:1]) + if one[0][0] != 3320 { + t.Fatalf("one battery: %v", one[0][0]) + } +} + +type slotLimitTransport struct{ feature bool } + +func (c *slotLimitTransport) RoundTrip(context.Context, []byte) ([]byte, error) { + features := []string{"champion", "ev_duty", "published_prices"} + if c.feature { + features = append(features, "storage_slot_limits") + } + return json.Marshal(map[string]any{"name": "ftw-solver", "version": "test", "protocol_version": 1, "features": features}) +} +func (*slotLimitTransport) Close() error { return nil } + +func preparedRequest(t *testing.T, feature bool, slots []Slot, p Params) []byte { + t.Helper() + external := &ExternalOptimizer{cfg: ExternalOptimizerConfig{Timeout: time.Second}, transport: &slotLimitTransport{feature: feature}} + o := &EnergyplanOptimizer{ExternalOptimizer: external} + r := external.buildRequest(slots, p) + if err := o.prepareEnergyplanRequest(context.Background(), &r, slots, p); err != nil { + t.Fatal(err) + } + r.RequestID = "fixed" + out, err := json.Marshal(r) + if err != nil { + t.Fatal(err) + } + return out +} + +func TestEnergyplanRequestCarriesSlotLimitsOnlyWhenLearned(t *testing.T) { + slots, p := homeBoxNight() + baseline := preparedRequest(t, false, slots, p) + // Nothing learned: the request is the same, whatever the worker takes. + if got := preparedRequest(t, true, slots, p); !bytes.Equal(got, baseline) { + t.Fatalf("request changed without learned limits:\n%s\n%s", got, baseline) + } + if bytes.Contains(baseline, []byte("_by_slot")) { + t.Fatalf("unlearned request carries slot limits: %s", baseline) + } + learned := p + learned.Storages = append([]StorageAssetSpec(nil), p.Storages...) + learned.Storages[0].Learned = LearnedLimits{GridImportW: 4320, DischargeW: 4200} + // A worker without the feature gets today's request; Core's own + // planner still holds the limits. + if got := preparedRequest(t, false, slots, learned); !bytes.Equal(got, baseline) { + t.Fatalf("an old worker got new fields:\n%s", got) + } + var req externalRequest + if err := json.Unmarshal(preparedRequest(t, true, slots, learned), &req); err != nil { + t.Fatal(err) + } + s := req.Storages[0] + if len(s.MaxChargeWBySlot) != len(slots) || len(s.MaxDischargeWBySlot) != len(slots) { + t.Fatalf("slot limits %+v", s) + } + for i, slot := range slots { + want := min(5000, max(0, 4320-slot.LoadW-slot.PVW)) + if math.Abs(s.MaxChargeWBySlot[i]-want) > 1e-9 || s.MaxDischargeWBySlot[i] != 4200 { + t.Fatalf("slot %d: %v / %v, want %v / 4200", i, s.MaxChargeWBySlot[i], s.MaxDischargeWBySlot[i], want) + } + } + if s.MaxChargeW != 5000 || s.MaxDischargeW != 5000 { + t.Fatalf("scalar limits changed: %+v", s) + } +} + +func TestOnlineFleetParamsReadsLearnedLimitsAtTheBatteryTemperature(t *testing.T) { + tel := telemetry.NewStore() + soc := 0.3 + tel.Update("sungrow", telemetry.DerBattery, 0, &soc, json.RawMessage(`{"temperature_C":14,"V":190}`)) + tel.DriverHealthMut("sungrow").RecordSuccess() + var asked *float64 + s := &Service{Tele: tel, LearnedBatteryLimits: func(driver string, tempC *float64) []battery.Plateau { + if driver != "sungrow" { + t.Fatalf("asked for %q", driver) + } + asked = tempC + return homeBoxPlateaus() + }} + p, ok := s.onlineFleetParams(Params{}, []BatteryFleetMember{{Driver: "sungrow", CapacityWh: 9600, MaxChargeW: 5000, MaxDischargeW: 5000}}, 0) + if !ok || len(p.Storages) != 1 { + t.Fatalf("params %+v", p) + } + if asked == nil || *asked != 14 { + t.Fatalf("asked at %v, want 14 °C", asked) + } + if got := p.Storages[0].Learned; got != (LearnedLimits{DischargeW: 22.4 * 190, GridImportW: 4320}) { + t.Fatalf("learned %+v", got) + } + // Without the hook the planner keeps the configured limits alone. + s.LearnedBatteryLimits = nil + if p, _ := s.onlineFleetParams(Params{}, []BatteryFleetMember{{Driver: "sungrow", CapacityWh: 9600, MaxChargeW: 5000, MaxDischargeW: 5000}}, 0); p.Storages[0].Learned.known() { + t.Fatalf("learned without a model: %+v", p.Storages[0].Learned) + } +} + +func TestWorkerPlanPastItsSlotLimitsIsRejected(t *testing.T) { + request := externalRequest{Storages: []externalStorage{{ID: "b", MaxChargeW: 5000, MaxDischargeW: 5000, + MaxChargeWBySlot: []float64{3000, 3000}, MaxDischargeWBySlot: []float64{4200, 4200}}}} + plan := func(w ...float64) externalPlan { + var p externalPlan + for _, v := range w { + p.Actions = append(p.Actions, externalAction{StoragePowerW: map[string]float64{"b": v}}) + } + return p + } + if err := validateStorageSlotLimits(request, plan(3001.5, -4201.5)); err != nil { + t.Fatalf("within 2 W: %v", err) + } + if err := validateStorageSlotLimits(request, plan(3003, 0)); err == nil { + t.Fatal("accepted a charge past its slot limit") + } + if err := validateStorageSlotLimits(request, plan(0, -4203)); err == nil { + t.Fatal("accepted a discharge past its slot limit") + } + request.Storages[0].MaxChargeWBySlot, request.Storages[0].MaxDischargeWBySlot = nil, nil + if err := validateStorageSlotLimits(request, plan(5000, -5000)); err != nil { + t.Fatalf("no slot limits: %v", err) + } +} + +// homeBoxNight is eight cheap night hours with 0.6-1.5 kW of house load, +// cheapest at three to five, then eight dear evening hours of 2 kW with a +// peak at the third, on the home box's 9.6 kWh battery at 10 %. Its +// configured limits are 5 kW both ways. +func homeBoxNight() ([]Slot, Params) { + start := time.Now().Truncate(time.Hour).Add(time.Hour).UnixMilli() + nightLoad := []float64{600, 800, 1500, 1200, 700, 900, 1400, 1000} + nightPrice := []float64{40, 35, 30, 12, 10, 14, 32, 38} + slots := make([]Slot, 16) + for i := range slots { + slots[i] = Slot{StartMs: start + int64(i)*3600000, LenMin: 60, PriceOre: 300, SpotOre: 200, LoadW: 2000, + Limits: PowerLimits{MaxImportW: 17000, MaxExportW: 17000}} + if i < len(nightLoad) { + slots[i].PriceOre, slots[i].SpotOre, slots[i].LoadW = nightPrice[i], nightPrice[i]-10, nightLoad[i] + } + if i == 10 { + slots[i].PriceOre, slots[i].SpotOre = 600, 500 + } + } + p := Params{Mode: ModeArbitrage, CapacityWh: 9600, SoCMin: 0.05, SoCMax: 0.95, InitialSoC: 0.1, + MaxChargeW: 5000, MaxDischargeW: 5000, ChargeEfficiency: 0.95, DischargeEfficiency: 0.95, + SoCLevels: 49, ActionLevels: 21, + Storages: []StorageAssetSpec{{ID: "sungrow", CapacityWh: 9600, InitialEnergyWh: 960, MinEnergyWh: 480, + MaxEnergyWh: 9120, MaxChargeW: 5000, MaxDischargeW: 5000, ChargeEfficiency: 0.95, DischargeEfficiency: 0.95}}} + return slots, p +} + +// checkHomeBoxNight holds a plan of homeBoxNight to the box's learned +// limits and returns how many night hours charge. +func checkHomeBoxNight(t *testing.T, slots []Slot, p Params, plan Plan, limited bool) int { + t.Helper() + if err := ValidatePlan(slots, p, &plan); err != nil { + t.Fatal(err) + } + hours, nightWh := 0, 0.0 + powers := make([]float64, len(plan.Actions)) + limitsC, limitsD := slotLimits(slots, p.Storages) + for i, a := range plan.Actions { + charge, discharge := limitsC[0][i], limitsD[0][i] + if limited && (a.BatteryW > charge+2 || a.BatteryW < -discharge-2) { + t.Fatalf("slot %d: battery %.0f W outside -%.0f..%.0f W", i, a.BatteryW, discharge, charge) + } + if i < 8 && a.BatteryW > 1 { + hours++ + nightWh += a.BatteryW * slots[i].DurationHours() + } + powers[i] = math.Round(a.BatteryW) + } + t.Logf("learned limits %v: %d night hours charge %.0f Wh; battery W %v; cost %.1f ore", limited, hours, nightWh, powers, plan.TotalCostOre) + return hours +} + +// On the home box the inverter holds grid import at 4.32 kW while the +// battery charges, so a night hour gives the battery 4.32 kW less the house: +// 2.8-3.7 kW, not 5 kW. Core's planner then charges over more night hours, +// never past what the battery can take, and discharges at most 4.2 kW. +func TestCoreDPPlansTheHomeBoxNightWithinItsLearnedLimits(t *testing.T) { + slots, p := homeBoxNight() + free := Optimize(slots, p) + freeHours := checkHomeBoxNight(t, slots, p, free, false) + learned := p + learned.Storages = append([]StorageAssetSpec(nil), p.Storages...) + learned.Storages[0].Learned = LearnedLimits{GridImportW: 4320, DischargeW: 4200} + limited := Optimize(slots, learned) + hours := checkHomeBoxNight(t, slots, learned, limited, true) + if hours <= freeHours { + t.Fatalf("charges in %d night hours with the limits, %d without", hours, freeHours) + } + if !planExceedsLearnedLimits(slots, learned, free) { + t.Fatal("the plan without the limits fits them: the test proves nothing") + } +} + +func planExceedsLearnedLimits(slots []Slot, p Params, plan Plan) bool { + limitsC, limitsD := slotLimits(slots, p.Storages) + for i, a := range plan.Actions { + charge, discharge := limitsC[0][i], limitsD[0][i] + if a.BatteryW > charge+2 || a.BatteryW < -discharge-2 { + return true + } + } + return false +} + +// The same night through the worker: it gets the slot limits, plans within +// them, and Core accepts its plan. +func TestNativeEnergyplanPlansTheHomeBoxNightWithinItsLearnedLimits(t *testing.T) { + binary := os.Getenv("FTW_NATIVE_SOLVER") + if binary == "" { + t.Skip("run make native-solver-test to include the Rust worker") + } + o, err := NewEnergyplanOptimizer(binary) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = o.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + info, err := o.Health(ctx) + if err != nil { + t.Fatal(err) + } + if !optimizerHasFeature(info, "storage_slot_limits") { + t.Fatalf("the bundled worker %s does not take storage_slot_limits", info.Version) + } + slots, p := homeBoxNight() + free, err := o.Optimize(context.Background(), slots, p) + if err != nil { + t.Fatal(err) + } + freeHours := checkHomeBoxNight(t, slots, p, free, false) + learned := p + learned.Storages = append([]StorageAssetSpec(nil), p.Storages...) + learned.Storages[0].Learned = LearnedLimits{GridImportW: 4320, DischargeW: 4200} + limited, err := o.Optimize(context.Background(), slots, learned) + if err != nil { + t.Fatal(err) + } + if limited.Solver == nil || limited.Solver.Fallback { + t.Fatalf("solver %+v; want the worker's own plan", limited.Solver) + } + var req externalRequest + if err := json.Unmarshal(limited.OptimizerInput, &req); err != nil { + t.Fatal(err) + } + if len(req.Storages[0].MaxChargeWBySlot) != len(slots) { + t.Fatalf("the worker got no slot limits: %+v", req.Storages[0]) + } + hours := checkHomeBoxNight(t, slots, learned, limited, true) + if hours <= freeHours || !planExceedsLearnedLimits(slots, learned, free) { + t.Fatalf("charges in %d night hours with the limits, %d without", hours, freeHours) + } +} + +// A car charging in the same night slot takes import the battery then cannot +// get, and the slot limits leave the car out. That makes the plan +// optimistic for the battery only: the plan still keeps the site's import +// limit and the owner's hourly import ceiling, which ValidatePlan holds it to. +func TestACarBesideTheGridHoldKeepsCoresImportLimits(t *testing.T) { + slots, p := homeBoxNight() + for i := range slots { + slots[i].Limits.MaxImportW = 11000 + } + p.Storages[0].Learned = LearnedLimits{GridImportW: 4320, DischargeW: 4200} + p.Loadpoint = &LoadpointSpec{ID: "car", CapacityWh: 60000, Levels: 21, SoCMax: 1, InitialSoC: .3, PluggedIn: true, + TargetSoC: .5, TargetSlotIdx: 7, MaxChargeW: 11000, AllowedStepsW: []float64{0, 4140, 6900}, ChargeEfficiency: .9} + p.ImportMeanW = 9000 + for _, s := range slots { + p.ImportHours = append(p.ImportHours, ImportHour{StartMs: s.StartMs, EndMs: s.StartMs + 3600000}) + } + plan := Optimize(slots, p) + if err := ValidatePlan(slots, p, &plan); err != nil { + t.Fatalf("Core's limits rejected the plan: %v", err) + } + charge, discharge := slotLimits(slots, p.Storages) + both := 0 + for i, a := range plan.Actions { + if a.BatteryW > charge[0][i]+2 || a.BatteryW < -discharge[0][i]-2 { + t.Fatalf("slot %d: battery %.0f W outside its slot limits", i, a.BatteryW) + } + if a.GridW > slots[i].Limits.MaxImportW+solverGridLimitToleranceW || a.GridW > p.ImportMeanW+solverGridLimitToleranceW { + t.Fatalf("slot %d: grid %.0f W past the import limits", i, a.GridW) + } + if a.BatteryW > 1 && a.LoadpointW > 1 { + both++ + } + } + t.Logf("%d night slots charge the car and the battery together; battery W %v", both, func() []float64 { + out := make([]float64, len(plan.Actions)) + for i, a := range plan.Actions { + out[i] = math.Round(a.BatteryW) + } + return out + }()) + if both == 0 { + t.Fatal("no slot charges the car and the battery together: the case is not covered") + } + if plan.Actions[7].LoadpointSoC+1e-9 < .5 { + t.Fatalf("the car missed its goal: %.3f", plan.Actions[7].LoadpointSoC) + } +} + +// failingWorker announces storage_slot_limits, keeps each request and +// answers it with an error code. +type failingWorker struct { + code string + requests []externalRequest +} + +func (f *failingWorker) RoundTrip(_ context.Context, payload []byte) ([]byte, error) { + var head struct { + Type string `json:"type"` + } + _ = json.Unmarshal(payload, &head) + if head.Type == "handshake" { + return json.Marshal(map[string]any{"name": "ftw-solver", "version": "test", "protocol_version": 1, + "features": []string{"champion", "ev_duty", "published_prices", "storage_slot_limits"}}) + } + var request externalRequest + if err := json.Unmarshal(payload, &request); err != nil { + return nil, err + } + f.requests = append(f.requests, request) + return json.Marshal(map[string]any{"schema_version": 1, "request_id": request.RequestID, "ok": false, + "error": map[string]string{"code": f.code, "message": "test"}}) +} +func (*failingWorker) Close() error { return nil } + +// When the worker fails on a request with slot limits, Core's own planner +// takes over within the same limits: the battery never gets a plan the +// worker was told it cannot do. +func TestWorkerFailureFallsBackWithinTheSameSlotLimits(t *testing.T) { + for _, code := range []string{"numerical_failure", "deadline_exceeded"} { + t.Run(code, func(t *testing.T) { + svc := shadowTestService(t) + svc.Defaults.Mode = ModeArbitrage + svc.Defaults.SoCLevels, svc.Defaults.ActionLevels = 21, 21 + svc.UpdateBatteryFleet([]BatteryFleetMember{{Driver: "battery", CapacityWh: 10000, MaxChargeW: 5000, MaxDischargeW: 5000}}, 10000, 5000, 5000) + svc.Tele = telemetry.NewStore() + soc := .2 + svc.Tele.Update("battery", telemetry.DerBattery, 0, &soc, json.RawMessage(`{"V":190}`)) + svc.Tele.DriverHealthMut("battery").RecordSuccess() + svc.LearnedBatteryLimits = func(string, *float64) []battery.Plateau { + return []battery.Plateau{ + {Direction: "charge", Kind: battery.LimitGridImport, Value: 2000, Unit: "W"}, + {Direction: "discharge", Kind: battery.LimitBatteryCurrent, Value: 12, Unit: "A"}, + } + } + worker := &failingWorker{code: code} + external := &ExternalOptimizer{cfg: ExternalOptimizerConfig{Timeout: 2 * time.Second}, transport: worker, timeBudget: energyplanTimeBudget} + o := &EnergyplanOptimizer{ExternalOptimizer: external} + external.prepareRequest = o.prepareEnergyplanRequest + svc.Optimizer = o + plan := svc.Replan(context.Background()) + if plan == nil || plan.Solver == nil || !plan.Solver.Fallback { + t.Fatalf("no Core fallback: %+v", plan) + } + if len(worker.requests) != 1 || len(worker.requests[0].Storages[0].MaxChargeWBySlot) == 0 || + len(worker.requests[0].Storages[0].MaxDischargeWBySlot) == 0 { + t.Fatalf("the worker got no slot limits: %+v", worker.requests) + } + sent := worker.requests[0].Storages[0] + if err := ValidatePlan(svc.lastSlots, svc.lastParams, plan); err != nil { + t.Fatal(err) + } + atLimit := false + for i, a := range plan.Actions { + if a.BatteryW > sent.MaxChargeWBySlot[i]+2 || a.BatteryW < -sent.MaxDischargeWBySlot[i]-2 { + t.Fatalf("slot %d: fallback battery %.0f W outside the limits sent, -%.0f..%.0f W", + i, a.BatteryW, sent.MaxDischargeWBySlot[i], sent.MaxChargeWBySlot[i]) + } + atLimit = atLimit || math.Abs(a.BatteryW-sent.MaxChargeWBySlot[i]) < 2 && a.BatteryW > 1 || + math.Abs(a.BatteryW+sent.MaxDischargeWBySlot[i]) < 2 && a.BatteryW < -1 + } + if !atLimit { + t.Fatalf("the fallback never reached a slot limit, so the case shows nothing: %+v", plan.Actions) + } + svc.shadowWG.Wait() + }) + } +} diff --git a/go/internal/sitesim/sitesim.go b/go/internal/sitesim/sitesim.go index 9e4a58642..e7f5db123 100644 --- a/go/internal/sitesim/sitesim.go +++ b/go/internal/sitesim/sitesim.go @@ -109,7 +109,13 @@ func (p *Plant) Step() Tick { } var batW [3]float64 if b := p.Battery; b != nil { - b.step(p.Now) + // What the rest of the site imports, for an inverter that holds + // grid import: the house, PV and the car's draw a second ago. + restW := p.HouseW[0] + p.HouseW[1] + p.HouseW[2] + p.PVW + if p.EVSE != nil { + restW += p.EVSE.DrawW + } + b.step(p.Now, restW) batW = spread(b.W, b.Phases) } for i := range p.A { @@ -181,8 +187,14 @@ type Battery struct { MaxChargeW, MaxDischargeW float64 CapacityWh, SoC float64 Latency time.Duration - W float64 // power now, positive charging - queue []timedW + // GridImportCapW > 0 is a hybrid inverter that holds grid import there + // while it charges the battery from the grid: the battery gets that + // import less what the rest of the site imports. The home box's Sungrow + // holds 4.32 kW. Discharge is not held. + GridImportCapW float64 + W float64 // power now, positive charging + ordered float64 // the command in force; W follows it within the limits + queue []timedW } // Command asks for w from now + Latency. @@ -190,11 +202,20 @@ func (b *Battery) Command(now time.Time, w float64) { b.queue = append(b.queue, timedW{now.Add(b.Latency), w}) } -func (b *Battery) step(now time.Time) { +func (b *Battery) step(now time.Time, restW float64) { for len(b.queue) > 0 && !b.queue[0].at.After(now) { b.W, b.queue = b.queue[0].w, b.queue[1:] + b.ordered = b.W + } + if b.GridImportCapW > 0 { + // The inverter gives what it can of the order in force, and more + // as room comes back. + b.W = b.ordered } b.W = math.Max(-b.MaxDischargeW, math.Min(b.MaxChargeW, b.W)) + if b.GridImportCapW > 0 && b.W > 0 { + b.W = math.Min(b.W, math.Max(0, b.GridImportCapW-restW)) + } if (b.W > 0 && b.SoC >= 1) || (b.W < 0 && b.SoC <= 0) { b.W = 0 } diff --git a/go/internal/sitesim/sitesim_test.go b/go/internal/sitesim/sitesim_test.go index b9eda6300..276d5456c 100644 --- a/go/internal/sitesim/sitesim_test.go +++ b/go/internal/sitesim/sitesim_test.go @@ -89,3 +89,35 @@ func TestPlantSignsAndDelays(t *testing.T) { t.Fatalf("readback %v, want the draw from 6 s at 16 s", heard) } } + +// A hybrid inverter that holds grid import while its battery charges, as +// the home box's Sungrow does at 4.32 kW: the battery gets that import plus +// PV less the house and the car, and no more; discharge is not held. +func TestBatteryChargeHoldsTheInverterGridImport(t *testing.T) { + p := New(t0, 25) + p.HouseW = [3]float64{400, 400, 400} + p.Battery = &Battery{Phases: 3, MaxChargeW: 5000, MaxDischargeW: 5000, CapacityWh: 9600, SoC: .1, GridImportCapW: 4320} + p.Battery.Command(p.Now, 5000) + p.Step() + if p.Battery.W != 4320-1200 { + t.Fatalf("night charge %.0f W, want %.0f", p.Battery.W, 4320.-1200) + } + if grid := (p.A[0] + p.A[1] + p.A[2]) * p.Voltage; math.Abs(grid-4320) > 1e-6 { + t.Fatalf("grid import %.1f W, want the 4320 W the inverter holds", grid) + } + p.PVW = -3000 + p.Step() + if p.Battery.W != 5000 { + t.Fatalf("with PV %.0f W, want the full 5000", p.Battery.W) + } + p.PVW, p.HouseW = 0, [3]float64{1600, 1600, 1600} + p.Step() + if p.Battery.W != 0 { + t.Fatalf("house over the import hold: %.0f W, want 0", p.Battery.W) + } + p.Battery.Command(p.Now, -5000) + p.Step() + if p.Battery.W != -5000 { + t.Fatalf("discharge %.0f W, want -5000", p.Battery.W) + } +} diff --git a/go/test/site/runner/runner.go b/go/test/site/runner/runner.go index 821a8f3fc..9a3411037 100644 --- a/go/test/site/runner/runner.go +++ b/go/test/site/runner/runner.go @@ -23,7 +23,7 @@ var watchedPaths = []string{ "go/internal/control/", "go/internal/loadpoint/", "go/internal/ocpp/", "go/internal/telemetry/", "go/internal/drivers/", "go/internal/mdnsresolve/", // driver host, command deadlines "go/internal/mpc/", "go/internal/optimizercontract/", // plans - "go/internal/gridcost/", "go/internal/forecasting/", "go/internal/sunpos/", // plan inputs + "go/internal/battery/", "go/internal/gridcost/", "go/internal/forecasting/", "go/internal/sunpos/", // plan inputs "go/internal/config/", "go/internal/configreload/", // limits "go/internal/units/", // charge steps "go/internal/localzone/", // household clock: goal deadlines, import hour diff --git a/optimizer/native/bundle/ftw-solver-linux-amd64 b/optimizer/native/bundle/ftw-solver-linux-amd64 index 3ac729f03..6d3ee8c5c 100755 Binary files a/optimizer/native/bundle/ftw-solver-linux-amd64 and b/optimizer/native/bundle/ftw-solver-linux-amd64 differ diff --git a/optimizer/native/bundle/ftw-solver-linux-arm64 b/optimizer/native/bundle/ftw-solver-linux-arm64 index 46c674ee3..d9f759762 100755 Binary files a/optimizer/native/bundle/ftw-solver-linux-arm64 and b/optimizer/native/bundle/ftw-solver-linux-arm64 differ diff --git a/optimizer/native/bundle/manifest.json b/optimizer/native/bundle/manifest.json index 72efab35d..c9ab595d9 100644 --- a/optimizer/native/bundle/manifest.json +++ b/optimizer/native/bundle/manifest.json @@ -1,9 +1,9 @@ { "schema_version": 1, "product": "energyplan", - "version": "0.8.0", + "version": "0.9.0", "source_repository": "srcfl/energyplan", - "source_commit": "51f0c2017e62cb11a05ce5f8dcb216dad60142bf", + "source_commit": "438aa26b469f812bdbe741a05a91a929124d7216", "rustc": "rustc 1.95.0 (59807616e 2026-04-14)", "protocol_version": 1, "forecast_protocol_version": 1, @@ -35,12 +35,12 @@ "bytes": 15377 }, "ftw-solver-linux-amd64": { - "sha256": "9e66bd4b7bc0ed70656328d06fec562963509935dbad7edf2361d2a4a719a32c", - "bytes": 2266240 + "sha256": "6f3e4cc3be30444c68dbac535544f6a096029a696e68eef0b2a62dfc560d2e5e", + "bytes": 2278792 }, "ftw-solver-linux-arm64": { - "sha256": "6d2e1e1e9dbb1d46684b41584b554d506ac3bbed796730c7ee0fb0c2aa0378ef", - "bytes": 1799728 + "sha256": "18ae7980242e582cd1b9a9c4968367370b43d2280d3b3bccec3303652c985067", + "bytes": 1806808 }, "rust-runtime/COPYRIGHT-library.html": { "sha256": "90567e2718bf7fd65a71a3a43c5596488e80e5f51ed02bfea6fec54458b5f3d1",