Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/planner-learned-battery-limits.md
Original file line number Diff line number Diff line change
@@ -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.
26 changes: 21 additions & 5 deletions docs/energyplan-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.

Expand Down
10 changes: 10 additions & 0 deletions go/cmd/ftw/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
3 changes: 2 additions & 1 deletion go/internal/battery/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}

Expand Down
19 changes: 17 additions & 2 deletions go/internal/battery/plateau.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
41 changes: 41 additions & 0 deletions go/internal/battery/plateau_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
147 changes: 147 additions & 0 deletions go/internal/control/sitesim_learned_limits_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
})
}
}
5 changes: 5 additions & 0 deletions go/internal/mpc/charging_periods.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion go/internal/mpc/energyplan_fault_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion go/internal/mpc/energyplan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions go/internal/mpc/external_optimizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading